| 59 | } |
| 60 | |
| 61 | func (s *Sender) ProcessMessage(ctx context.Context, job workertypes.IncomingEmailDeliveryJob) error { |
| 62 | // 1. Render (Parsing happens inside RenderDigest implementation) |
| 63 | subject, body, err := s.renderer.RenderDigest(job) |
| 64 | if err != nil { |
| 65 | slog.ErrorContext(ctx, "failed to render email", "subscription_id", job.SubscriptionID, "error", err) |
| 66 | if dbErr := s.stateManager.RecordFailure( |
| 67 | ctx, |
| 68 | job.ChannelID, |
| 69 | err, |
| 70 | s.now(), |
| 71 | false, |
| 72 | job.EmailEventID, |
| 73 | ); dbErr != nil { |
| 74 | slog.ErrorContext(ctx, "failed to record channel failure", "channel_id", job.ChannelID, "error", dbErr) |
| 75 | } |
| 76 | |
| 77 | return err |
| 78 | } |
| 79 | |
| 80 | // 2. Send |
| 81 | if err := s.sender.Send(ctx, job.EmailEventID, job.RecipientEmail, subject, body); err != nil { |
| 82 | isPermanentUserError := errors.Is(err, workertypes.ErrUnrecoverableUserFailureEmailSending) |
| 83 | isPermanent := errors.Is(err, workertypes.ErrUnrecoverableSystemFailureEmailSending) || |
| 84 | isPermanentUserError |
| 85 | slog.ErrorContext(ctx, "failed to send email", "recipient", job.RecipientEmail, "error", err) |
| 86 | // Record failure in DB |
| 87 | if dbErr := s.stateManager.RecordFailure(ctx, job.ChannelID, err, s.now(), |
| 88 | isPermanentUserError, job.EmailEventID); dbErr != nil { |
| 89 | slog.ErrorContext(ctx, "failed to record channel failure", "channel_id", job.ChannelID, "error", dbErr) |
| 90 | } |
| 91 | if isPermanent { |
| 92 | return err |
| 93 | } |
| 94 | |
| 95 | // If not permanent, wrap with ErrTransient to trigger NACK (which will retry) |
| 96 | return errors.Join(event.ErrTransientFailure, err) |
| 97 | } |
| 98 | |
| 99 | // 3. Success |
| 100 | if err := s.stateManager.RecordSuccess(ctx, job.ChannelID, s.now(), job.EmailEventID); err != nil { |
| 101 | // Non-critical error, but good to log |
| 102 | slog.WarnContext(ctx, "failed to record channel success", "channel_id", job.ChannelID, "error", err) |
| 103 | } |
| 104 | |
| 105 | return nil |
| 106 | } |