package mailsender import ( "context" "errors" "log/slog" "sync" "testing" "time" "github.com/google/uuid" "lincodex/backend/internal/domain" "lincodex/backend/internal/port/inbound" "lincodex/backend/internal/worker/retry" ) const testWait = 5 * time.Second type scriptedPass struct { mu sync.Mutex steps []step calls []time.Time called chan struct{} workCtx context.Context paused []bool } type step struct { result inbound.MailPassResult err error } func newScriptedPass(steps ...step) *scriptedPass { return &scriptedPass{steps: steps, called: make(chan struct{}, 64)} } func (pass *scriptedPass) ProcessNext(_, workCtx context.Context) (inbound.MailPassResult, error) { pass.mu.Lock() pass.calls = append(pass.calls, time.Now()) pass.workCtx = workCtx next := step{result: inbound.MailPassResult{Outcome: inbound.MailPassIdle}} if len(pass.steps) > 0 { next, pass.steps = pass.steps[0], pass.steps[1:] } pass.mu.Unlock() pass.called <- struct{}{} return next.result, next.err } func (pass *scriptedPass) PauseFailureCounting(paused bool) { pass.mu.Lock() defer pass.mu.Unlock() pass.paused = append(pass.paused, paused) } func (pass *scriptedPass) count() int { pass.mu.Lock() defer pass.mu.Unlock() return len(pass.calls) } type gauge struct { mu sync.Mutex history []bool cancelled []string } func (g *gauge) ObserveMailCancelled(reason string) { g.mu.Lock() defer g.mu.Unlock() g.cancelled = append(g.cancelled, reason) } func (g *gauge) SetMailSenderRunning(running bool) { g.mu.Lock() defer g.mu.Unlock() g.history = append(g.history, running) } func (g *gauge) values() []bool { g.mu.Lock() defer g.mu.Unlock() return append([]bool(nil), g.history...) } func testSettings() Settings { return Settings{ PollInterval: 20 * time.Millisecond, Backoff: retry.Backoff{Initial: 40 * time.Millisecond, Max: 80 * time.Millisecond}, ShutdownGrace: 50 * time.Millisecond, } } func newTestWorker(t *testing.T, pass inbound.MailPass, metrics Metrics, settings Settings) *Worker { t.Helper() worker, err := New(pass, metrics, slog.New(slog.DiscardHandler), settings) if err != nil { t.Fatalf("New() error = %v", err) } return worker } func runWorker(t *testing.T, worker *Worker) (stop func()) { t.Helper() ctx, cancel := context.WithCancel(t.Context()) stopped := make(chan struct{}) go func() { defer close(stopped) worker.Run(ctx) }() return func() { cancel() select { case <-stopped: case <-time.After(testWait): t.Fatal("Run() did not return after its context ended") } } } func waitForCalls(t *testing.T, pass *scriptedPass, want int) { t.Helper() deadline := time.After(testWait) for pass.count() < want { select { case <-pass.called: case <-deadline: t.Fatalf("pass called %d times, want at least %d", pass.count(), want) } } } func TestNewRejectsUnusableSettings(t *testing.T) { for name, change := range map[string]func(*Settings){ "no poll interval": func(settings *Settings) { settings.PollInterval = 0 }, "no shutdown grace": func(settings *Settings) { settings.ShutdownGrace = 0 }, "no initial backoff": func(settings *Settings) { settings.Backoff.Initial = 0 }, "maximum below start": func(settings *Settings) { settings.Backoff = retry.Backoff{Initial: time.Second, Max: time.Millisecond} }, } { t.Run(name, func(t *testing.T) { settings := testSettings() change(&settings) if _, err := New(newScriptedPass(), &gauge{}, slog.New(slog.DiscardHandler), settings); err == nil { t.Fatal("New() accepted unusable settings") } }) } } func TestRunReportsThatItRunsOnlyWhileTheLoopDoes(t *testing.T) { metrics := &gauge{} worker := newTestWorker(t, newScriptedPass(), metrics, testSettings()) if got := metrics.values(); len(got) != 0 { t.Fatalf("gauge was set before Run: %v", got) } stop := runWorker(t, worker) deadline := time.After(testWait) for len(metrics.values()) == 0 { select { case <-deadline: t.Fatal("the loop never reported that it runs") case <-time.After(time.Millisecond): } } if got := metrics.values(); got[0] != true { t.Fatalf("first gauge value = %v, want true", got[0]) } stop() if got := metrics.values(); got[len(got)-1] != false { t.Fatalf("last gauge value = %v, want false after the loop stopped", got[len(got)-1]) } } func TestRunWaitsAfterAnIdlePassAndContinuesAtOnceAfterAHandledDelivery(t *testing.T) { handled := step{result: inbound.MailPassResult{Outcome: inbound.MailPassAccepted}} pass := newScriptedPass(handled, handled, handled) settings := testSettings() settings.PollInterval = time.Hour // an idle pass would stall the test stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings)) defer stop() // Three handled passes run back to back; the fourth is idle and the // worker then waits for the poll interval. waitForCalls(t, pass, 4) time.Sleep(100 * time.Millisecond) if got := pass.count(); got != 4 { t.Fatalf("pass called %d times, want 4: an idle pass must wait for the poll interval", got) } } func TestRunBacksOffInsteadOfSpinningWhenNothingCanBeSent(t *testing.T) { for name, failing := range map[string]step{ "no transport": {result: inbound.MailPassResult{Outcome: inbound.MailPassChannelUnavailable}}, "interrupted call": {result: inbound.MailPassResult{Outcome: inbound.MailPassInterrupted}}, "database failure": {err: errors.New("database unavailable")}, } { t.Run(name, func(t *testing.T) { steps := make([]step, 50) for index := range steps { steps[index] = failing } pass := newScriptedPass(steps...) stop := runWorker(t, newTestWorker(t, pass, &gauge{}, testSettings())) time.Sleep(300 * time.Millisecond) stop() // The delay starts at 20..40 ms and doubles to 40..80 ms: a loop // that did not back off would have made hundreds of passes. if got := pass.count(); got < 3 || got > 15 { t.Fatalf("pass called %d times in 300 ms, want a few spaced by the backoff", got) } pass.mu.Lock() defer pass.mu.Unlock() for index := 1; index < len(pass.calls); index++ { if gap := pass.calls[index].Sub(pass.calls[index-1]); gap < 15*time.Millisecond { t.Fatalf("passes %d and %d were %s apart, want the backoff between them", index, index+1, gap) } } }) } } func TestRunReleasesItsWorkContextWhenItStops(t *testing.T) { pass := newScriptedPass() worker := newTestWorker(t, pass, &gauge{}, testSettings()) stop := runWorker(t, worker) waitForCalls(t, pass, 1) pass.mu.Lock() workCtx := pass.workCtx pass.mu.Unlock() if workCtx.Err() != nil { t.Fatal("the work context ended while the loop runs") } stop() // Run returned after its own context ended; the work context is released // by then, so no goroutine waits for a grace that nobody needs. A send in // progress at shutdown keeps running for the grace first, which the // integration tests cover with a real transport. select { case <-workCtx.Done(): case <-time.After(testWait): t.Fatal("the work context was not released when Run returned") } } func TestRunCountsCancelledDeliveriesByReasonAndDoesNotBackOffForARowFailure(t *testing.T) { metrics := &gauge{} pass := newScriptedPass( step{result: inbound.MailPassResult{Outcome: inbound.MailPassCancelled, CancelReason: domain.DeliveryCancelContentInvalid}}, step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed}}, step{result: inbound.MailPassResult{Outcome: inbound.MailPassCancelled, CancelReason: domain.DeliveryCancelProcessingFailed}}, ) settings := testSettings() settings.PollInterval = time.Hour stop := runWorker(t, newTestWorker(t, pass, metrics, settings)) defer stop() // The first three passes follow each other at once, because a failing row // has left the head of the queue; the fourth is idle and waits. waitForCalls(t, pass, 4) metrics.mu.Lock() defer metrics.mu.Unlock() if len(metrics.cancelled) != 2 || metrics.cancelled[0] != "content_invalid" || metrics.cancelled[1] != "processing_failed" { t.Fatalf("cancelled reasons = %v, want content_invalid and processing_failed", metrics.cancelled) } } func TestRunPausesFailureCountingWhenFailuresHitRowAfterRowAndResumesAfterASuccess(t *testing.T) { failed := func() step { return step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: uuid.New()}} } pass := newScriptedPass(failed(), failed(), failed(), failed(), step{result: inbound.MailPassResult{Outcome: inbound.MailPassAccepted}}) settings := testSettings() settings.PollInterval = time.Hour stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings)) waitForCalls(t, pass, 6) stop() pass.mu.Lock() defer pass.mu.Unlock() // Paused from the third different row on, resumed by the success. var sawPause bool for _, paused := range pass.paused { sawPause = sawPause || paused } if !sawPause || pass.paused[len(pass.paused)-1] { t.Fatalf("pause calls = %v, want a pause after three different rows and no pause at the end", pass.paused) } } func TestRunDoesNotPauseWhenTheSameRowFailsAgain(t *testing.T) { id := uuid.New() same := step{result: inbound.MailPassResult{Outcome: inbound.MailPassRowFailed, DeliveryID: id}} pass := newScriptedPass(same, same, same, same) settings := testSettings() settings.PollInterval = time.Hour stop := runWorker(t, newTestWorker(t, pass, &gauge{}, settings)) waitForCalls(t, pass, 5) stop() pass.mu.Lock() defer pass.mu.Unlock() for _, paused := range pass.paused { if paused { t.Fatalf("pause calls = %v; one row failing repeatedly is not a global fault", pass.paused) } } }