Files
warmbly/internal/app/consumer/event_send_result.go
T

661 lines
26 KiB
Go

package jobs
import (
"context"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
"github.com/rs/zerolog/log"
"github.com/warmbly/warmbly/internal/config"
"github.com/warmbly/warmbly/internal/errx"
"github.com/warmbly/warmbly/internal/infrastructure/pubsub"
"github.com/warmbly/warmbly/internal/models"
"github.com/warmbly/warmbly/internal/pkg/dsn"
"github.com/warmbly/warmbly/internal/pkg/emailverify"
"github.com/warmbly/warmbly/internal/pkg/mailhdr"
"github.com/warmbly/warmbly/internal/repository"
)
// errSendResultEarly is returned when a worker result lands before the
// control plane has finished stamping the task it belongs to. The message is
// left for redelivery; the stamping finishes within milliseconds.
var errSendResultEarly = errors.New("send result arrived before the task was stamped; retrying")
// HandleEmailSent confirms a send the worker delivered to the provider. The
// control plane reserves the step before it hands the send over and stamps it
// right after, so this normally only persists the Message-ID the worker put on
// the wire. It is also the repair path: when the stamp was lost between the
// dispatch and the control plane's write (a crash, or a failed progress write),
// the delivered email would otherwise leave no sent_at for follow-up pacing to
// read, so a reserved step is stamped here from the worker's own confirmation.
func (s *JobsService) HandleEmailSent(ctx context.Context, result models.SendEmailResult) error {
result.Success = true
if recovery, ok := s.TaskRepo.(repository.SendResultRecovery); ok {
return recovery.ApplySendResult(ctx, result, func(ctx context.Context) error { return s.applyEmailSent(ctx, result) })
}
return s.applyEmailSent(ctx, result)
}
func (s *JobsService) applyEmailSent(ctx context.Context, result models.SendEmailResult) error {
if s.TaskRepo == nil || result.TaskID == uuid.Nil {
return nil
}
task, err := s.TaskRepo.GetTask(ctx, result.TaskID)
if err != nil {
return err
}
if task == nil {
log.Warn().Str("task_id", result.TaskID.String()).Msg("email sent result for unknown task")
return nil
}
if s.EmailAccountErrorRepository != nil && models.ValidMailTransportTime(result.SentAt, time.Now()) {
if err := s.EmailAccountErrorRepository.RecordTransportSuccess(ctx, task.EmailAccountID, models.MailTransportSend, result.SentAt, &result.TaskID, result.TransportGeneration); err != nil {
return err
}
}
// The worker reports the Message-ID the provider put on the wire, which is
// not always the one the control plane minted: Graph and Gmail re-stamp it. Take the
// worker's answer whenever it differs, because everything that matches a
// send back to us later (campaign reply threading, warmup reply candidates)
// keys on what the recipient actually received.
if result.MessageID != "" && result.MessageID != task.MessageID {
if err := s.TaskRepo.UpdateTaskMessageID(ctx, task.ID, result.MessageID); err != nil {
return err
}
}
// The provider-side conversation handle (Gmail only). Without it a
// follow-up can carry perfect In-Reply-To/References headers and Gmail
// still files it as a new thread in the sender's own mailbox, which is
// what made every campaign follow-up look like a second cold email
// (issue #472).
if result.ThreadID != "" {
if err := s.TaskRepo.UpdateTaskThreadID(ctx, task.ID, result.ThreadID); err != nil {
return err
}
}
switch task.TaskType {
case "email":
return s.fileSentForward(ctx, task.ID)
case "campaign":
s.repairCampaignSendStamp(ctx, task)
// Anchor the graduation ramp on the mailbox's first CONFIRMED cold
// send. Anchoring at dispatch would start the clock on a send the
// worker then failed, and the ramp is a proxy for days of proven
// sending. Idempotent in SQL, so every later send is a no-op.
if s.WarmupRepo != nil {
if err := s.WarmupRepo.StampColdRampStart(ctx, task.EmailAccountID); err != nil {
log.Warn().Err(err).Str("email_account_id", task.EmailAccountID.String()).Msg("could not anchor the cold ramp")
}
}
case "placement":
// The seed is searched for the Message-ID the provider actually sent.
if s.PlacementRepo != nil && result.MessageID != "" {
if err := s.PlacementRepo.SetProbeMessageIDByTask(ctx, task.ID, result.MessageID); err != nil {
log.Warn().Err(err).Str("task_id", task.ID.String()).Msg("could not record a placement probe's message id")
}
}
case "warmup":
// Without this the recipient has nothing to match a warmup email
// against when the verify header did not survive delivery.
if s.WarmupRepo != nil && result.MessageID != "" {
if err := s.WarmupRepo.RecordWarmupTokenDelivery(ctx, task.ID, result.MessageID); err != nil {
return err
}
}
}
return nil
}
// fileSentForward files a forward's sent copy that Sent sync stored before its
// Message-ID was known; a copy stored after is filed by the insert itself.
func (s *JobsService) fileSentForward(ctx context.Context, taskID uuid.UUID) error {
if s.UniboxRepository == nil {
return nil
}
filed, err := s.UniboxRepository.FileSentForward(ctx, taskID)
if err != nil {
return err
}
for i := range filed {
s.publishEmailUpdated(ctx, filed[i].UserID, &filed[i].Message)
}
return nil
}
// repairCampaignSendStamp completes a reserved campaign step the control plane
// never stamped. A no-op in the normal case, where the stamp is already there.
func (s *JobsService) repairCampaignSendStamp(ctx context.Context, task *repository.Task) {
if s.CampaignProgressRepo == nil {
return
}
ct, err := s.TaskRepo.GetCampaignTask(ctx, task.ID)
if err != nil || ct == nil || ct.CampaignID == nil || ct.ContactID == nil || ct.SequenceID == nil {
return
}
repaired, err := s.CampaignProgressRepo.StampDispatchedSend(ctx, *ct.CampaignID, *ct.ContactID, *ct.SequenceID)
if err != nil {
log.Warn().Err(err).Str("task_id", task.ID.String()).Msg("could not repair the campaign send stamp")
return
}
if repaired {
log.Warn().
Str("task_id", task.ID.String()).
Str("campaign_id", ct.CampaignID.String()).
Str("contact_id", ct.ContactID.String()).
Msg("stamped a delivered campaign send the control plane never recorded")
}
}
// HandleEmailFailed walks back a send the worker could not deliver. The
// control plane reserves a step and stamps it sent the moment it hands it to a
// worker, so without this the lead would sit at "processing" forever with no
// email ever leaving. For a campaign send the step's reservation and sent_at
// are cleared so the next tick retries it, the day's counters give the send
// back, the failure is written to the campaign's activity log, and a campaign
// that completed while the send was in flight is reopened. Once the retry cap
// is spent the lead is marked failed and routing drops it.
func (s *JobsService) HandleEmailFailed(ctx context.Context, result models.SendEmailResult) error {
result.Success = false
if recovery, ok := s.TaskRepo.(repository.SendResultRecovery); ok {
return recovery.ApplySendResult(ctx, result, func(ctx context.Context) error { return s.applyEmailFailed(ctx, result) })
}
if result.Error != nil && result.Error.Failure != nil && result.Error.Failure.Disposition == errx.SendAmbiguous {
return nil
}
return s.applyEmailFailed(ctx, result)
}
func (s *JobsService) applyEmailFailed(ctx context.Context, result models.SendEmailResult) error {
if s.TaskRepo == nil || result.TaskID == uuid.Nil {
return nil
}
task, err := s.TaskRepo.GetTask(ctx, result.TaskID)
if err != nil {
return err
}
if task == nil {
log.Warn().Str("task_id", result.TaskID.String()).Msg("email failed result for unknown task")
return nil
}
if task.Status == "active" {
// The worker answered before the control plane finished the tick; the
// stamping completes within milliseconds, so look once more before
// leaving the result for redelivery.
time.Sleep(300 * time.Millisecond)
if task, err = s.TaskRepo.GetTask(ctx, result.TaskID); err != nil || task == nil {
return err
}
}
switch task.Status {
case "completed", "dead_lettered":
// The normal case: stamped by the control plane, refused by the worker.
case "active":
return errSendResultEarly
default:
// Already walked back (duplicate delivery) or cancelled.
return nil
}
reason, code := sendFailureReason(result)
if kind := pauseOf(result); kind != errx.SendPauseNone && kind != errx.SendPauseRetry {
// The mailbox's sending just paused; open drawers and lists refetch.
accountID := task.EmailAccountID
repository.AfterSendResultCommit(ctx, func(ctx context.Context) { s.publishAccountSynced(ctx, accountID) })
}
if task.TaskType == "warmup" {
return s.failWarmupSend(ctx, task, reason)
}
if err := s.TaskRepo.RecordTaskFailure(ctx, task.ID, "Send failed", reason); err != nil {
return err
}
switch task.TaskType {
case "campaign":
return s.failCampaignSend(ctx, task, reason, code, refusedRecipient(result), nil)
case "email":
s.notifyUserSendFailed(ctx, task, reason)
case "placement":
if s.PlacementRepo != nil {
return s.PlacementRepo.FailProbeByTask(ctx, task.ID, reason)
}
}
return nil
}
// failWarmupSend leaves redelivery possible unless the task and refund both persist.
func (s *JobsService) failWarmupSend(ctx context.Context, task *repository.Task, reason string) error {
if s.WarmupRepo == nil {
return s.TaskRepo.RecordTaskFailure(ctx, task.ID, "Send failed", reason)
}
day := time.Now()
if task.CompletedAt != nil {
day = *task.CompletedAt
}
return s.WarmupRepo.FailWarmupSend(ctx, task.EmailAccountID, task.ID, day, "Send failed", reason)
}
// failCampaignSend is the campaign half of HandleEmailFailed. countedOn is the
// day the send was counted against, for giving the daily counters back; nil
// reads it off the task, which is right for a worker result but not for the
// reclaimer, whose sends can be counted on an earlier day.
func (s *JobsService) failCampaignSend(ctx context.Context, task *repository.Task, reason, code, refused string, countedOn *time.Time) error {
ct, err := s.TaskRepo.GetCampaignTask(ctx, task.ID)
if err != nil {
return err
}
if ct == nil || ct.CampaignID == nil {
return nil
}
campaignID := *ct.CampaignID
var campaign *models.Campaign
if s.CampaignRepo != nil {
campaign, _ = s.CampaignRepo.GetByID(ctx, campaignID)
}
recipient := ""
if ct.ContactID != nil && s.ContactRepo != nil {
if contact, cerr := s.ContactRepo.GetByID(ctx, *ct.ContactID); cerr == nil && contact != nil {
recipient = contact.Email
}
}
// A copy the server refused is not the lead's bounce: it is dropped from
// later emails and the lead's step is retried without it.
copyRefused := code == string(errx.MailErrorCodeRecipientRejected) && refused != "" &&
recipient != "" && !strings.EqualFold(mailhdr.Bare(refused), recipient)
// A refusal on the SENDING DOMAIN's authentication is not about this lead:
// the recipient received nothing, and every retry from that domain fails
// identically until its DNS is fixed. Give the reservation back without
// spending one of the lead's attempts, and bring the domain's re-check
// forward so the send gate stops choosing that mailbox. Another mailbox in
// the campaign's pool picks the lead up on the next tick.
if code == string(errx.MailErrorCodeDomainAuthRejected) {
s.recheckSendingDomainAuth(ctx, task.EmailAccountID)
if ct.ContactID != nil && ct.SequenceID != nil && s.CampaignProgressRepo != nil {
if relErr := s.CampaignProgressRepo.ReleaseSend(ctx, campaignID, *ct.ContactID, *ct.SequenceID, false); relErr != nil {
log.Warn().Err(relErr).Str("campaign_id", campaignID.String()).Msg("could not release a domain-auth refusal for retry")
}
}
s.logCampaignSendFailure(ctx, campaignID, ct, recipient, reason, code, 0, false, true, false)
return nil
}
// Only permanent recipient refusals are bounce evidence; deferrals may use the same wording.
if s.Evidence != nil && ct.ContactID != nil && ct.SequenceID != nil && !copyRefused &&
code != string(errx.MailErrorCodeServerUnreachable) && code != models.ServerPacingCode && code != models.SenderPausedCode && emailverify.NamesRecipient(reason) {
s.Evidence.RecordEvidence(ctx, *ct.ContactID, models.Step(&campaignID, ct.SequenceID), "bounced_recipient", "send:"+ct.SequenceID.String(), reason)
}
// A refused copy that the retry will leave off costs the lead no attempt;
// one that could not be recorded is counted, so it cannot loop forever.
copyExcluded := false
if copyRefused {
copyExcluded, err = s.recordRefusedCopy(ctx, task, ct, campaign, refused, reason)
if err != nil {
return err
}
}
attempts, exhausted, rolledBack := 0, false, false
if ct.ContactID != nil && ct.SequenceID != nil && s.CampaignProgressRepo != nil {
if copyExcluded || code == models.MailboxLoadingCode || code == models.ServerPacingCode || code == models.SenderPausedCode {
attempts, exhausted, rolledBack, err = s.CampaignProgressRepo.WalkBackSend(ctx, campaignID, *ct.ContactID, *ct.SequenceID, reason, false)
} else {
attempts, exhausted, rolledBack, err = s.CampaignProgressRepo.RecordSendFailure(ctx, campaignID, *ct.ContactID, *ct.SequenceID, reason)
}
if err != nil {
return err
}
}
if rolledBack && s.CampaignRepo != nil {
// With the step walked back, no other stamped step means this was the
// lead's first email, which the new-lead cap counted.
newLead := true
if has, herr := s.CampaignProgressRepo.HasSentSteps(ctx, campaignID, *ct.ContactID); herr == nil {
newLead = !has
}
day := time.Now()
switch {
case countedOn != nil:
day = *countedOn
case task.CompletedAt != nil:
day = *task.CompletedAt
}
if derr := s.CampaignRepo.DecrementCampaignDailySend(ctx, campaignID, day, newLead); derr != nil {
log.Warn().Err(derr).Str("campaign_id", campaignID.String()).Msg("could not give back the failed send's daily count")
}
}
// A recipient the mail server refused at RCPT is a bounce that simply
// arrived synchronously, so it goes through the bounce pipeline (progress,
// optional suppression, guardrails, warmup health, webhooks). The lead is
// dropped as bounced only when the refusal blames the address; a kept lead
// takes the retry path below, which reopens a campaign that completed.
if rolledBack && !copyRefused && code == string(errx.MailErrorCodeRecipientRejected) {
recorded, kept, err := s.recordSynchronousBounce(ctx, task, ct, campaign, recipient, reason)
if err != nil {
return err
}
if recorded && !kept {
s.logCampaignSendFailure(ctx, campaignID, ct, recipient, reason, code, attempts, false, false, false)
s.publishCampaignUpdated(ctx, campaign, campaignID, "")
log.Info().Str("task_id", task.ID.String()).Str("campaign_id", campaignID.String()).Msg("campaign send refused at RCPT; recorded as bounce")
return nil
}
}
reopened := false
if rolledBack && !exhausted && campaign != nil && campaign.Status == "completed" && s.CampaignRepo != nil {
if ok, rerr := s.CampaignRepo.ReopenAfterSendFailure(ctx, campaignID); rerr != nil {
log.Warn().Err(rerr).Str("campaign_id", campaignID.String()).Msg("could not reopen campaign after send failure")
} else {
reopened = ok
}
}
s.logCampaignSendFailure(ctx, campaignID, ct, recipient, reason, code, attempts, exhausted, rolledBack, reopened)
status := ""
if reopened {
status = "active"
}
s.publishCampaignUpdated(ctx, campaign, campaignID, status)
log.Info().
Str("task_id", task.ID.String()).
Str("campaign_id", campaignID.String()).
Str("code", code).
Int("attempts", attempts).
Bool("exhausted", exhausted).
Bool("rolled_back", rolledBack).
Bool("reopened", reopened).
Msg("campaign send failed in worker; step walked back")
return nil
}
// recordSynchronousBounce feeds a RCPT-refused send into the deliverability
// pipeline as a bounce, and reports whether ingestion kept the address.
// Returns false when the bounce could not be attributed (no org, no
// recipient), in which case the caller falls back to the retry path.
func (s *JobsService) recordSynchronousBounce(ctx context.Context, task *repository.Task, ct *repository.CampaignTask, campaign *models.Campaign, recipient, reason string) (recorded, kept bool, err error) {
if s.AdvancedService == nil || campaign == nil || campaign.OrganizationID == nil || recipient == "" {
return false, false, nil
}
taskID := task.ID
req := &models.IngestDeliverabilityEventRequest{
EventType: models.DeliverabilityEventBounce,
Provider: "smtp_reject",
TaskID: &taskID,
CampaignID: ct.CampaignID,
ContactID: ct.ContactID,
RecipientEmail: recipient,
Reason: reason,
IdempotencyKey: "reject:" + taskID.String(),
}
if xerr := s.AdvancedService.IngestDeliverabilityEvent(ctx, *campaign.OrganizationID, req); xerr != nil {
log.Warn().Str("task_id", taskID.String()).Str("error", xerr.Message).Msg("could not record refused recipient as a bounce")
return false, false, xerr
}
return true, req.AddressKept, nil
}
// recordRefusedCopy feeds a copied address the server refused at RCPT into
// the bounce pipeline under its own name, and reports whether the next send
// is sure to leave it off: a lead's copy through its bounced mark, a
// campaign-wide one through the recorded bounce the send path reads.
func (s *JobsService) recordRefusedCopy(ctx context.Context, task *repository.Task, ct *repository.CampaignTask, campaign *models.Campaign, refused, reason string) (bool, error) {
if campaign == nil || campaign.OrganizationID == nil || ct.CampaignID == nil || ct.ContactID == nil {
return false, nil
}
address := strings.ToLower(mailhdr.Bare(refused))
var owner *uuid.UUID
if s.CampaignProgressRepo != nil {
id, err := s.CampaignProgressRepo.MarkLeadCCBounced(ctx, *ct.CampaignID, *ct.ContactID, address)
if err != nil {
log.Warn().Err(err).Str("task_id", task.ID.String()).Msg("could not mark a refused copy bounced")
return false, err
}
owner = id
}
if s.AdvancedService == nil {
return owner != nil, nil
}
taskID := task.ID
req := &models.IngestDeliverabilityEventRequest{
EventType: models.DeliverabilityEventBounce,
Provider: "smtp_reject",
TaskID: &taskID,
CampaignID: ct.CampaignID,
ContactID: owner,
RecipientEmail: address,
Reason: reason,
IdempotencyKey: "reject:" + taskID.String() + ":" + address,
}
if xerr := s.AdvancedService.IngestDeliverabilityEvent(ctx, *campaign.OrganizationID, req); xerr != nil {
log.Warn().Str("task_id", taskID.String()).Str("error", xerr.Message).Msg("could not record a refused copy as a bounce")
return false, xerr
}
return true, nil
}
// refusedRecipient is the address the server refused, when the worker knew.
func refusedRecipient(result models.SendEmailResult) string {
if result.Error == nil {
return ""
}
return result.Error.Recipient
}
// publishCampaignUpdated pulses the campaign for every teammate (status "" keeps
// the dashboard's status as is).
func (s *JobsService) publishCampaignUpdated(ctx context.Context, campaign *models.Campaign, campaignID uuid.UUID, status string) {
if s.StreamingPublisher == nil || campaign == nil {
return
}
repository.AfterSendResultCommit(ctx, func(ctx context.Context) {
s.StreamingPublisher.PublishCampaignEvent(ctx, &pubsub.CampaignEvent{
BaseEvent: pubsub.BaseEvent{EventType: pubsub.EventCampaignUpdated, UserID: campaign.UserID},
OrgID: campaignOrgID(campaign),
CampaignID: campaignID.String(),
Name: campaign.Name,
Status: status,
})
})
}
// logCampaignSendFailure records failures and automatic reconnect retries in campaign activity.
func (s *JobsService) logCampaignSendFailure(ctx context.Context, campaignID uuid.UUID, ct *repository.CampaignTask, recipient, reason, code string, attempts int, exhausted, rolledBack, reopened bool) {
if s.CampaignLogRepo == nil {
return
}
who := recipient
if who == "" {
who = "the recipient"
}
var msg string
switch {
case code == string(errx.MailErrorCodeRecipientRejected) && !rolledBack:
msg = fmt.Sprintf("The mail server refused %s (hard bounce): %s", who, reason)
case code == string(errx.MailErrorCodeDomainAuthRejected):
msg = fmt.Sprintf("The receiving server refused the message because your sending domain failed its authentication checks, not because of %s. Fix the domain's SPF, DKIM and DMARC records: %s", who, reason)
case exhausted:
msg = fmt.Sprintf("Gave up on %s after %d failed attempts: %s", who, attempts, reason)
case rolledBack:
msg = fmt.Sprintf("Could not send to %s (attempt %d of %d), will retry: %s", who, attempts, config.CampaignSendMaxAttempts, reason)
default:
msg = fmt.Sprintf("Could not send to %s: %s", who, reason)
}
if reopened {
msg += ". Campaign reopened to retry."
}
meta := map[string]interface{}{
"level": "error",
"code": code,
"error": reason,
"attempts": attempts,
"max_attempts": config.CampaignSendMaxAttempts,
"will_retry": rolledBack && !exhausted,
"task_id": ct.TaskID.String(),
}
if ct.ContactID != nil {
meta["contact_id"] = ct.ContactID.String()
}
if ct.SequenceID != nil {
meta["sequence_id"] = ct.SequenceID.String()
}
if reopened {
meta["reopened"] = true
}
eventType := "email_failed"
if code == models.MailboxLoadingCode && rolledBack && !exhausted {
eventType = "email_deferred"
meta["level"] = "info"
meta["mailbox_loading_retry"] = true
msg = fmt.Sprintf("Sending to %s was delayed while the mailbox reconnected. An automatic retry was scheduled.", who)
}
if code == models.ServerPacingCode && rolledBack && !exhausted {
eventType = "email_deferred"
meta["level"] = "info"
msg = fmt.Sprintf("Sending to %s was delayed because the mailbox's mail server is limiting connections from Warmbly's sending address. Nothing was sent yet; an automatic retry was scheduled.", who)
}
if code == models.SenderPausedCode && rolledBack && !exhausted {
eventType = "email_deferred"
meta["level"] = "info"
meta["sender_paused"] = true
msg = fmt.Sprintf("Sending to %s was delayed because the provider paused this mailbox's sending (a sending limit or a temporary restriction), not because of %s. Nothing was sent and no attempt was counted; the mailbox rests until the provider's limit resets and the step is retried: %s", who, who, reason)
}
_ = s.CampaignLogRepo.CreateLog(ctx, &repository.CampaignLogEntry{
CampaignID: campaignID,
EventType: eventType,
Message: msg,
Metadata: meta,
})
}
// notifyUserSendFailed tells the mailbox owner that a one-off send (compose,
// reply, scheduled email) did not leave, since nothing else would.
func (s *JobsService) notifyUserSendFailed(ctx context.Context, task *repository.Task, reason string) {
if s.StreamingPublisher == nil || s.EmailRepository == nil {
return
}
accountID, taskID := task.EmailAccountID, task.ID
repository.AfterSendResultCommit(ctx, func(ctx context.Context) {
account, xerr := s.EmailRepository.GetByID(ctx, accountID)
if xerr != nil || account == nil {
return
}
s.StreamingPublisher.PublishEmailError(ctx, account.UserID, account.ID, taskID,
"Email could not be sent", fmt.Sprintf("%s could not send your email: %s", account.Email, reason))
})
}
// notifyManualSendUnsent tells the owner of a manual send that recovery released before any worker started it.
func (s *JobsService) notifyManualSendUnsent(ctx context.Context, taskID uuid.UUID) {
if s.TaskRepo == nil {
return
}
task, err := s.TaskRepo.GetTask(ctx, taskID)
if err != nil || task == nil {
return
}
s.notifyUserSendFailed(ctx, task, "it never reached its sending worker, so nothing was sent. Send it again.")
}
// sendFailureReason picks the most useful human-readable reason and the
// machine code out of a worker result.
func sendFailureReason(result models.SendEmailResult) (reason, code string) {
if result.Error != nil {
code = result.Error.Code
reason = strings.TrimSpace(result.Error.Message)
if reason == "" {
reason = strings.TrimSpace(result.Error.UserMessage)
}
// The enhanced status is what decides whether a refusal blames the address.
if f := result.Error.Failure; f != nil && len(f.EnhancedStatus) <= 11 && !strings.Contains(reason, f.EnhancedStatus) {
if _, ok := dsn.StatusIn(f.EnhancedStatus); ok {
reason = strings.TrimSpace(reason + "; enhanced status " + f.EnhancedStatus)
}
}
}
if reason == "" {
reason = strings.TrimSpace(result.LegacyErrorMsg)
}
if reason == "" {
reason = "the sending worker reported an unknown error"
}
if strings.HasPrefix(reason, models.MailboxNotLoadedPrefix) && (code == "" || code == string(errx.MailErrorCodeServerUnreachable)) {
var failure *errx.SendFailure
if result.Error != nil {
failure = result.Error.Failure
}
if failure != nil && failure.Protocol == "internal" && failure.Stage == "prepare" && failure.Disposition == errx.SendRetry {
code = models.MailboxLoadingCode
}
}
if f := failureOf(result); f != nil && f.Protocol == "smtp" && f.Cause == errx.SendCauseServerPacing && f.Disposition == errx.SendRetry &&
code == string(errx.MailErrorCodeServerUnreachable) {
code = models.ServerPacingCode
}
if code != models.ServerPacingCode && pauseOf(result).SparesLead(failureOf(result)) {
code = models.SenderPausedCode
}
if code == "" {
code = "SEND_FAILED"
}
return reason, code
}
func failureOf(result models.SendEmailResult) *errx.SendFailure {
if result.Error == nil {
return nil
}
return result.Error.Failure
}
// pauseOf is what the failure does to the sending mailbox, the same reading the send-result transaction stores.
func pauseOf(result models.SendEmailResult) errx.SendPause {
if result.Error == nil {
return errx.SendPauseNone
}
return errx.ClassifySendPause(result.Error.Code, result.Error.Failure)
}
// campaignOrgID returns the campaign's organization id for org-scoped
// realtime events, or "" for legacy orgless rows.
func campaignOrgID(campaign *models.Campaign) string {
if campaign == nil || campaign.OrganizationID == nil {
return ""
}
return campaign.OrganizationID.String()
}
// recheckSendingDomainAuth brings forward the authentication sweep for the
// mailbox's sending domain. Best-effort: missing it only delays the check.
func (s *JobsService) recheckSendingDomainAuth(ctx context.Context, accountID uuid.UUID) {
if s.EmailRepository == nil {
return
}
account, xerr := s.EmailRepository.GetByID(ctx, accountID)
if xerr != nil || account == nil {
return
}
at := strings.LastIndex(account.Email, "@")
if at < 0 {
return
}
domain := strings.ToLower(account.Email[at+1:])
if err := s.EmailRepository.MarkDomainAuthRecheck(ctx, domain); err != nil {
log.Warn().Err(err).Str("domain", domain).Msg("could not bring the domain auth re-check forward")
} else {
log.Info().Str("domain", domain).Msg("sending domain refused on authentication; re-check queued")
}
}