Something went wrong. Try again.
forked from scottlanoue.com/atmosphere-mail
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235// SPDX-License-Identifier: AGPL-3.0-or-later
package notify
import ( "context" "errors" "sync" "testing" "time"
"comail/internal/relaystore")
func newTestStore(t *testing.T) *relaystore.Store { t.Helper() s, err := relaystore.New(":memory:") if err != nil { t.Fatalf("relaystore.New: %v", err) } t.Cleanup(func() { s.Close() }) return s}
// TestQueueWorkerDeliversEnqueuedRows is the happy path: a row lands// in the queue, the worker drains it on a single RunOnce, delivery// succeeds, row is gone.func TestQueueWorkerDeliversEnqueuedRows(t *testing.T) { s := newTestStore(t) ctx := context.Background()
id, err := s.EnqueueNotification(ctx, relaystore.NotificationKindWelcome, "r@example.com", map[string]any{"domain": "ex.com"}) if err != nil { t.Fatalf("EnqueueNotification: %v", err) }
var mu sync.Mutex var seen []relaystore.Notification deliver := func(ctx context.Context, n relaystore.Notification) error { mu.Lock() defer mu.Unlock() seen = append(seen, n) return nil }
w := NewQueueWorker(s, deliver, time.Second) w.RunOnce(ctx)
mu.Lock() defer mu.Unlock() if len(seen) != 1 { t.Fatalf("expected 1 delivery, got %d", len(seen)) } if seen[0].ID != id { t.Errorf("delivered ID: want %d got %d", id, seen[0].ID) } if seen[0].Recipient != "r@example.com" { t.Errorf("Recipient: want r@example.com got %q", seen[0].Recipient) } // Row should be deleted on success. n, _ := s.GetNotification(ctx, id) if n != nil { t.Errorf("expected nil row after success, got %+v", n) }}
// TestQueueWorkerHonorsBackoffOnFailure confirms that a failed delivery// does not re-appear in the next RunOnce call — backoff is enforced by// the store's next_attempt_at, which the worker passes through `now`.func TestQueueWorkerHonorsBackoffOnFailure(t *testing.T) { s := newTestStore(t) ctx := context.Background()
if _, err := s.EnqueueNotification(ctx, relaystore.NotificationKindWelcome, "r@example.com", nil); err != nil { t.Fatalf("EnqueueNotification: %v", err) }
calls := 0 deliver := func(ctx context.Context, n relaystore.Notification) error { calls++ return errors.New("transient") } w := NewQueueWorker(s, deliver, time.Second) // Freeze "now" so the first-failure backoff lands 60s (±jitter) in // the future regardless of test wall-clock drift. fixedNow := time.Now().UTC() w.nowFn = func() time.Time { return fixedNow }
w.RunOnce(ctx) if calls != 1 { t.Fatalf("expected 1 call on first pass, got %d", calls) }
// Second pass at the same fixed-now: no new delivery, the row is // sitting inside its backoff window. w.RunOnce(ctx) if calls != 1 { t.Errorf("expected no second call inside backoff, got %d total calls", calls) }}
// TestQueueWorkerDeadLettersAfterMaxAttempts drives the full failure// cascade: a delivery that keeps failing flips to dead_letter after// MaxNotificationAttempts tries and stops being claimed.func TestQueueWorkerDeadLettersAfterMaxAttempts(t *testing.T) { s := newTestStore(t) ctx := context.Background()
id, err := s.EnqueueNotification(ctx, relaystore.NotificationKindKeyRegenerated, "dead@example.com", nil) if err != nil { t.Fatalf("EnqueueNotification: %v", err) }
deliver := func(ctx context.Context, n relaystore.Notification) error { return errors.New("always fails") } w := NewQueueWorker(s, deliver, time.Second)
// Advance simulated time past each backoff so every RunOnce picks // the row back up. Increment by a large constant so we don't have // to track the exact jitter. baseTime := time.Now().UTC() for i := 0; i < relaystore.MaxNotificationAttempts; i++ { w.nowFn = func() time.Time { return baseTime.Add(time.Duration(i) * 10 * time.Hour) } w.RunOnce(ctx) }
dl, err := s.IsDeadLetter(ctx, id) if err != nil { t.Fatalf("IsDeadLetter: %v", err) } if !dl { t.Fatalf("expected dead_letter=1 after %d failed attempts", relaystore.MaxNotificationAttempts) }
// Dead-letter rows must not be claimed again no matter how far // into the future we advance. claimed, err := s.ClaimPendingNotifications(ctx, time.Now().Add(100*time.Hour).Unix(), 50) if err != nil { t.Fatalf("claim after dead letter: %v", err) } if len(claimed) != 0 { t.Errorf("expected 0 claimed after dead letter, got %d", len(claimed)) }
deadList, _ := s.ListDeadLetterNotifications(ctx) if len(deadList) != 1 { t.Errorf("expected 1 dead-letter row, got %d", len(deadList)) }}
// TestQueueWorkerRespectsContextCancellation ensures Run returns// promptly when the parent context is canceled — no leaked goroutines,// no infinite ticker loop.func TestQueueWorkerRespectsContextCancellation(t *testing.T) { s := newTestStore(t)
deliver := func(ctx context.Context, n relaystore.Notification) error { return nil } w := NewQueueWorker(s, deliver, 10*time.Millisecond)
ctx, cancel := context.WithCancel(context.Background()) done := make(chan error, 1) go func() { done <- w.Run(ctx) }()
// Let the worker run at least one tick. time.Sleep(30 * time.Millisecond) cancel()
select { case err := <-done: if !errors.Is(err, context.Canceled) { t.Errorf("expected context.Canceled, got %v", err) } case <-time.After(500 * time.Millisecond): t.Fatalf("worker did not exit within 500ms of cancel") }}
// TestComputeBackoffSeconds exercises the backoff curve at the edge// cases: first retry near base, later retries clamped at cap, never// returns a sub-1-second delay.func TestComputeBackoffSeconds(t *testing.T) { s := newTestStore(t) w := NewQueueWorker(s, func(ctx context.Context, n relaystore.Notification) error { return nil }, time.Second) // Turn off jitter for deterministic assertions. w.jitterFraction = 0
cases := []struct { attempts int min int max int }{ {attempts: 0, min: 60, max: 60}, // base {attempts: 1, min: 120, max: 120}, // 2x {attempts: 2, min: 240, max: 240}, // 4x {attempts: 10, min: 3600, max: 3600}, // capped at 1h {attempts: 100, min: 3600, max: 3600}, // still capped } for _, tc := range cases { got := w.computeBackoffSeconds(tc.attempts) if got < tc.min || got > tc.max { t.Errorf("attempts=%d: want [%d..%d], got %d", tc.attempts, tc.min, tc.max, got) } }}
// TestQueueWorkerBatchDrainsMultiple confirms the batch-limit knob// works end-to-end — a backlog of N rows drains in ceil(N/limit) ticks.func TestQueueWorkerBatchDrainsMultiple(t *testing.T) { s := newTestStore(t) ctx := context.Background()
for i := 0; i < 7; i++ { _, err := s.EnqueueNotification(ctx, relaystore.NotificationKindWelcome, "r@example.com", map[string]any{"i": i}) if err != nil { t.Fatalf("enqueue %d: %v", i, err) } }
var delivered int deliver := func(ctx context.Context, n relaystore.Notification) error { delivered++ return nil } w := NewQueueWorker(s, deliver, time.Second) w.batchLimit = 3
w.RunOnce(ctx) // 3 delivered w.RunOnce(ctx) // 3 more w.RunOnce(ctx) // last 1 if delivered != 7 { t.Errorf("expected 7 total deliveries across 3 runs, got %d", delivered) }}