feat(mail): add MailSender port and explicit provider selection
This commit is contained in:
1 parent
e7d0d92ef9
commit
6153887eb5
26 files changed
+1253
-29
No files matched your search
@@ -0,0 +1,181 @@
|
||||
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 answered and refused the
|
||||
// request; it did not take the message. Rejection says why.
|
||||
MailOutcomeRejected MailOutcome = "rejected"
|
||||
|
||||
// MailOutcomeUnknown means the request may have reached the provider but
|
||||
// no conclusive answer came back, for example a timeout or a connection
|
||||
// lost after the request was written. The message may or may not have
|
||||
// been accepted (delivery_uncertain). It is not a failure: a retry must
|
||||
// reuse the same IdempotencyKey so a provider that supports keys can
|
||||
// deduplicate it.
|
||||
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 provider-side refusal, such as
|
||||
// a 5xx answer or an SMTP 4xx reply, that a later attempt may overcome.
|
||||
MailRejectionTemporary MailRejection = "temporary"
|
||||
)
|
||||
|
||||
// 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/<token id>". A transport that supports
|
||||
// provider-side deduplication sends it; others ignore it. It must not
|
||||
// contain personal data.
|
||||
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
|
||||
|
||||
// RetryAfter is the provider's requested wait for a rejected attempt, or
|
||||
// zero when the provider gave none.
|
||||
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.
|
||||
//
|
||||
// Errors and logs never include recipients, subjects, bodies, credentials, or
|
||||
// raw provider responses.
|
||||
type MailSender interface {
|
||||
Send(ctx context.Context, mail OutgoingMail) (SendResult, error)
|
||||
}
|
||||
Reference in new issue
Block a user