package resend import ( "encoding/json" "net/http" "strconv" "strings" "time" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/outbound" ) // Error names that change the outcome. Other known names are classified by // status alone. const ( errorNameValidation = "validation_error" errorNameInvalidIdempotent = "invalid_idempotent_request" errorNameResourceLocked = "resource_locked" errorNameDailyQuota = "daily_quota_exceeded" errorNameMonthlyQuota = "monthly_quota_exceeded" errorNameServiceUnavailable = "service_unavailable" ) // knownErrorNames is the fixed set of Resend error names that may become // SendResult.ProviderCode: the names on // https://resend.com/docs/api-reference/errors plus the older names that the // official Node SDK still lists (invalid_api_key, invalid_from_address, // invalid_access, invalid_region, security_error, internal_server_error). A // name outside the set is treated as no name, so provider text never leaves // the adapter. var knownErrorNames = map[string]struct{}{ "invalid_idempotency_key": {}, errorNameValidation: {}, "missing_api_key": {}, "restricted_api_key": {}, "invalid_api_key": {}, "suspended_api_key": {}, "invalid_permission": {}, "invalid_access": {}, "invalid_from_address": {}, "invalid_region": {}, "email_above_quota": {}, "not_found": {}, "method_not_allowed": {}, "concurrent_idempotent_requests": {}, errorNameInvalidIdempotent: {}, errorNameResourceLocked: {}, "invalid_attachment": {}, "invalid_parameter": {}, "missing_required_field": {}, "missing_required_parameter": {}, errorNameDailyQuota: {}, errorNameMonthlyQuota: {}, "rate_limit_exceeded": {}, "security_error": {}, "application_error": {}, "internal_server_error": {}, errorNameServiceUnavailable: {}, } const ( // maxProviderMessageIDLength bounds the stored ID. Resend returns UUIDs. maxProviderMessageIDLength = 128 // maxRetryAfter caps a provider wait hint so that a malformed header // cannot park a delivery for longer than a daily quota reset. maxRetryAfter = 24 * time.Hour ) // providerAnswer is an HTTP answer. body is set only when complete is true: // the body was read without error and within maxResponseBodyBytes. type providerAnswer struct { status int header http.Header body []byte complete bool } // classifyResponse maps an HTTP answer to the port outcome. The body is only // parsed for the message ID or the error name; neither the body nor the // provider's message is kept. A rejected or unknown result carries the error // name as ProviderCode when it is in knownErrorNames. // // - 2xx with a valid ID: accepted. Without one the request may still have // been accepted, so the outcome is unknown. // - 3xx: rejected invalid_request. The API documents no redirect, the // request did not reach the send handler, and repeating it gets the same // redirect. // - 403 validation_error (unverified sender domain; without one Resend // sends only testing emails to the account's own address): rejected // permanent. // - 408 and 409 resource_locked: rejected temporary. // - 409 concurrent_idempotent_requests: unknown. Another request with the // same key is in progress and may be accepted; a later retry with the // same key gets its result. // - 409 invalid_idempotent_request: unknown. The key was used with another // body in the last 24 hours, so an earlier request under this key may // have been accepted. Repeating cannot succeed and a new key could send // the message twice: the delivery layer stops and escalates on this code. // - 409 without a known name: unknown, since it may be either of the above. // - 429 daily_quota_exceeded: quota_exhausted with QuotaPeriod day until // the next midnight UTC; 429 monthly_quota_exceeded: quota_exhausted // with QuotaPeriod month and without a wait hint, the reset depends on // the billing cycle; other 429: rate_limited with // Retry-After or RateLimit-Reset. // - other 4xx (validation, key, permission, not found): invalid_request. // - 503 service_unavailable: rejected temporary; the API refused the // request as a whole. // - other 5xx, including 500 application_error and internal_server_error: // unknown. The API failed while handling the request, or a proxy or // gateway answered, so the message may have been accepted. func classifyResponse(answer providerAnswer, now time.Time) outbound.SendResult { status := answer.status switch { case status >= 200 && status < 300: if id, ok := parseMessageID(answer); ok { return outbound.SendResult{Outcome: outbound.MailOutcomeAccepted, ProviderMessageID: id} } return unknownResult(0) case status >= 300 && status < 400: return rejected(outbound.MailRejectionInvalidRequest, 0) } name := parseErrorName(answer) result := classifyError(status, name, answer.header, now) result.ProviderCode = outbound.MailProviderCode(name) return result } func classifyError(status int, name string, header http.Header, now time.Time) outbound.SendResult { if status >= 500 { if status == http.StatusServiceUnavailable && name == errorNameServiceUnavailable { return rejected(outbound.MailRejectionTemporary, retryAfter(header, now)) } return unknownResult(0) } switch status { case http.StatusForbidden: if name == errorNameValidation { return rejected(outbound.MailRejectionPermanent, 0) } case http.StatusRequestTimeout: return rejected(outbound.MailRejectionTemporary, retryAfter(header, now)) case http.StatusConflict: if name == errorNameResourceLocked { return rejected(outbound.MailRejectionTemporary, retryAfter(header, now)) } return unknownResult(retryAfter(header, now)) case http.StatusTooManyRequests: return classifyTooManyRequests(name, header, now) } return rejected(outbound.MailRejectionInvalidRequest, 0) } func classifyTooManyRequests(name string, header http.Header, now time.Time) outbound.SendResult { switch name { case errorNameDailyQuota: // The daily quota resets at midnight UTC, not after a rolling day. return quotaExhausted(domain.MailQuotaPeriodDay, untilNextUTCMidnight(now)) case errorNameMonthlyQuota: // The monthly reset follows the account's billing cycle, which the // API does not report. return quotaExhausted(domain.MailQuotaPeriodMonth, 0) default: return rejected(outbound.MailRejectionRateLimited, rateLimitWait(header, now)) } } func rejected(reason outbound.MailRejection, wait time.Duration) outbound.SendResult { return outbound.SendResult{Outcome: outbound.MailOutcomeRejected, Rejection: reason, RetryAfter: wait} } func quotaExhausted(period domain.MailQuotaPeriod, wait time.Duration) outbound.SendResult { result := rejected(outbound.MailRejectionQuotaExhausted, wait) result.QuotaPeriod = period return result } func unknownResult(wait time.Duration) outbound.SendResult { return outbound.SendResult{Outcome: outbound.MailOutcomeUnknown, RetryAfter: wait} } // parseMessageID reads {"id": "..."} and accepts only an ID that is safe to // store and log. func parseMessageID(answer providerAnswer) (string, bool) { if !answer.complete { return "", false } var success struct { ID string `json:"id"` } if err := json.Unmarshal(answer.body, &success); err != nil { return "", false } if len(success.ID) == 0 || len(success.ID) > maxProviderMessageIDLength || strings.ContainsFunc(success.ID, isNotIDCharacter) { return "", false } return success.ID, true } // parseErrorName reads the name of {"statusCode", "name", "message"}. It // returns "" for any name outside knownErrorNames, so provider text never // flows further. func parseErrorName(answer providerAnswer) string { if !answer.complete { return "" } var failure struct { Name string `json:"name"` } if err := json.Unmarshal(answer.body, &failure); err != nil { return "" } if _, known := knownErrorNames[failure.Name]; !known { return "" } return failure.Name } // rateLimitWait prefers Retry-After and falls back to RateLimit-Reset, the // seconds until the rate limit window resets. func rateLimitWait(header http.Header, now time.Time) time.Duration { if wait := retryAfter(header, now); wait > 0 { return wait } return parseSeconds(header.Get("Ratelimit-Reset")) } // retryAfter reads Retry-After as delta seconds or as an HTTP date. func retryAfter(header http.Header, now time.Time) time.Duration { value := strings.TrimSpace(header.Get("Retry-After")) if value == "" { return 0 } if wait := parseSeconds(value); wait > 0 { return wait } date, err := http.ParseTime(value) if err != nil { return 0 } return capWait(date.Sub(now)) } func parseSeconds(value string) time.Duration { seconds, err := strconv.ParseInt(strings.TrimSpace(value), 10, 64) if err != nil || seconds <= 0 { return 0 } if seconds > int64(maxRetryAfter/time.Second) { return maxRetryAfter } return time.Duration(seconds) * time.Second } func untilNextUTCMidnight(now time.Time) time.Duration { current := now.UTC() midnight := time.Date(current.Year(), current.Month(), current.Day()+1, 0, 0, 0, 0, time.UTC) return capWait(midnight.Sub(current)) } func capWait(wait time.Duration) time.Duration { switch { case wait <= 0: return 0 case wait > maxRetryAfter: return maxRetryAfter default: return wait } } func isNotIDCharacter(character rune) bool { isLetter := (character >= 'a' && character <= 'z') || (character >= 'A' && character <= 'Z') isDigit := character >= '0' && character <= '9' return !isLetter && !isDigit && character != '-' && character != '_' }