package outbound import ( "context" "errors" "fmt" "log/slog" "strings" "time" "lincodex/backend/internal/domain" ) const ( // maxMailIdempotencyKeyLength follows the Resend Idempotency-Key limit of // 256 characters; SMTP has no such key, so the strictest provider rule // applies. maxMailIdempotencyKeyLength = 256 redactedOutgoingMail = "[redacted outgoing mail]" ) var ( // ErrMailChannelUnavailable reports that no mail transport is active // (EMAIL_PROVIDER=disabled). Nothing was sent and nothing was handed to a // provider. Callers must record the message as not sent; it is never a // delivery, and it never confirms an email address or satisfies an // account check. ErrMailChannelUnavailable = errors.New("mail channel unavailable") // ErrInvalidOutgoingMail reports a message that fails // OutgoingMail.Validate. It is a caller bug, not a provider rejection, and // nothing was sent. ErrInvalidOutgoingMail = errors.New("invalid outgoing mail") ) // MailOutcome is what one transport attempt established about a message. The // zero value is not an outcome and must never be read as acceptance. type MailOutcome string const ( // MailOutcomeAccepted means the provider accepted the request and returned // a message ID. It does not mean the message was delivered or read. MailOutcomeAccepted MailOutcome = "accepted" // MailOutcomeRejected means the provider did not take the message: either // it answered and refused the request, or the transport failed before the // request was completely written (DNS, connect, or TLS failure), so no // complete request reached the provider. Rejection says why; the second case is // always MailRejectionTemporary. MailOutcomeRejected MailOutcome = "rejected" // MailOutcomeUnknown means the request may have reached the provider but // no conclusive answer came back, for example a timeout, a connection // lost after the request was written, or a provider error raised while // handling it. The message may or may not have been accepted // (delivery_uncertain). It is not a "not sent" result: a retry must reuse // the same IdempotencyKey and the same content so a provider that // supports keys can deduplicate it. Deduplication has a window (24 hours // for Resend); after it a retry may send the message twice, so the // delivery layer must stop retrying and escalate to an operator instead. // // ProviderCode may name the reason. With Resend, // "concurrent_idempotent_requests" means another request with the same // key is still in progress: retry later with the same key. And // "invalid_idempotent_request" means the key was already used with // another body, so an earlier request under it may have been accepted; // repeating cannot succeed and a new key could send the message twice, so // the delivery layer must stop and escalate. MailOutcomeUnknown MailOutcome = "unknown" ) // MailRejection is a provider-independent reason for MailOutcomeRejected that // the delivery layer can map to its retry policy. It never carries provider // text, recipients, or message content. type MailRejection string const ( // MailRejectionPermanent means the provider will not accept this message, // for example an unverified sender domain or a suppressed recipient. MailRejectionPermanent MailRejection = "permanent" // MailRejectionInvalidRequest means the provider rejected the request // shape or credentials; retrying the same request cannot help. MailRejectionInvalidRequest MailRejection = "invalid_request" // MailRejectionRateLimited means a short-term rate limit; RetryAfter may // say when to try again. MailRejectionRateLimited MailRejection = "rate_limited" // MailRejectionQuotaExhausted means a daily or monthly sending quota is // used up; retrying before the quota resets cannot help. MailRejectionQuotaExhausted MailRejection = "quota_exhausted" // MailRejectionTemporary means a transient condition that a later attempt // may overcome: a provider-side refusal, such as a 5xx answer or an SMTP // 4xx reply, or a failure before the request was completely written. In // the second case no complete request reached the provider, so a retry // cannot duplicate the message. MailRejectionTemporary MailRejection = "temporary" ) // MailProviderCode is the provider's machine-readable error name for a // rejected or unknown attempt, for example Resend's // "invalid_idempotent_request" or "daily_quota_exceeded". A transport sets it only to a name from its own // fixed list of documented provider names and leaves it empty for anything // else, so it never carries free text from the provider and is safe to log, // store, and use as a metric label. Retry decisions follow Outcome and // Rejection; the code adds operator detail, such as telling a wrong API key // from a malformed request, or an idempotency key reused with another body. type MailProviderCode string // OutgoingMail is one rendered message. The sender address comes from the // transport configuration (EMAIL_FROM), so usecases and templates never choose // or depend on it, nor on the provider. // // String, GoString, Format, and LogValue redact the whole message, because the // recipient and the bodies are personal data and a body can carry a // verification link. Read the fields directly where they are needed. type OutgoingMail struct { To domain.EmailAddress Subject string TextBody string HTMLBody string // IdempotencyKey is stable for one logical delivery across every retry, // for example "email_verification/". A transport that supports // provider-side deduplication sends it; others ignore it. It must not // contain personal data. The provider keeps it only for a limited window // (24 hours for Resend); see MailOutcomeUnknown. IdempotencyKey string } // Validate reports a message that no transport could send. Errors wrap // ErrInvalidOutgoingMail and name only the field, never its value. func (mail OutgoingMail) Validate() error { if mail.To.IsZero() { return invalidOutgoingMail("recipient must be set") } if strings.TrimSpace(mail.Subject) == "" { return invalidOutgoingMail("subject must not be empty") } // A control character in the subject could inject header lines. if strings.ContainsFunc(mail.Subject, isControlCharacter) { return invalidOutgoingMail("subject must not contain control characters") } if strings.TrimSpace(mail.TextBody) == "" && strings.TrimSpace(mail.HTMLBody) == "" { return invalidOutgoingMail("text or HTML body must not be empty") } if length := len(mail.IdempotencyKey); length == 0 || length > maxMailIdempotencyKeyLength { return invalidOutgoingMail("idempotency key must have 1 to 256 characters") } for index := range len(mail.IdempotencyKey) { if character := mail.IdempotencyKey[index]; character <= ' ' || character > '~' { return invalidOutgoingMail("idempotency key must contain printable ASCII characters without spaces") } } return nil } func (mail OutgoingMail) String() string { return redactedOutgoingMail } func (mail OutgoingMail) GoString() string { return redactedOutgoingMail } // Format redacts every verb; without it %+v would print the fields. func (mail OutgoingMail) Format(state fmt.State, _ rune) { _, _ = state.Write([]byte(redactedOutgoingMail)) } func (mail OutgoingMail) LogValue() slog.Value { return slog.StringValue(redactedOutgoingMail) } func isControlCharacter(character rune) bool { return character < ' ' || character == 0x7f } func invalidOutgoingMail(reason string) error { return fmt.Errorf("OutgoingMail.Validate - %s: %w", reason, ErrInvalidOutgoingMail) } // SendResult is the outcome of one attempt that may have reached a provider. type SendResult struct { Outcome MailOutcome // ProviderMessageID is set only for MailOutcomeAccepted. ProviderMessageID string // Rejection is set only for MailOutcomeRejected. Rejection MailRejection // ProviderCode is set only for MailOutcomeRejected and MailOutcomeUnknown, // and only when the provider answered with a documented error name; see // MailProviderCode. ProviderCode MailProviderCode // RetryAfter is the wait before the next attempt for a rejected or // unknown result: the provider's own hint (for example Retry-After), or a // wait the transport derived from documented provider rules (for example // the next daily quota reset). It is zero when there is neither. RetryAfter time.Duration } // MailSender hands one message to the configured transport. // // Send makes exactly one attempt and never retries; retries, backoff, and // deduplication belong to the delivery layer, which also records outcomes. // A nil error comes with an Outcome of accepted, rejected, or unknown. A // non-nil error means the message certainly did not leave the process: it // wraps ErrMailChannelUnavailable when no transport is active, // ErrInvalidOutgoingMail for an invalid message, or the context error when // ctx ended before the request was sent. The returned SendResult is then // zero and must be ignored. A failure to reach the provider before the // request was written while ctx is still active is not an error: it is // MailOutcomeRejected with MailRejectionTemporary. A failure after the request // may have been written is MailOutcomeUnknown. // // Errors and logs never include recipients, subjects, bodies, credentials, or // raw provider responses. type MailSender interface { Send(ctx context.Context, mail OutgoingMail) (SendResult, error) }