oficina / slides Public

Mail queue: nothing on the request path, a worker that survives, a close that ends

Astra on #20, round 2.

P1: Send logged "queue full" on the request path, so a stalled log sink
held the request, and saturation was something to time. Send now does no
I/O at all: a drop is counted in an atomic and the worker logs the count.
Every address's link is queued, permitted or not, so the fill level does
not depend on admission, and a full queue answers exactly like an empty
one.

P2: a panic in the mailer killed the process. The worker recovers per
message, logs, and keeps draining.

P2: close waited 30 s and returned with the worker still blocked. Sends
now run under the queue's context; past the drain deadline close cancels
the send in flight, abandons what is left with a log line, and the
worker exits.

Tests: TestMailQueueSendNeverBlocksWhenFull (stalled log sink, twice the
depth), TestMailQueueSurvivesAPanic, TestMailQueueCloseIsBoundedAndStops
TheWorker (goroutine count back to baseline), TestAppCloseStopsTheMail
Worker, TestMailQueueQueuesEveryAddress, and over HTTP
TestAFullMailQueueAnswersLikeAnEmptyOne. Each of the first four fails
with its defect put back.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 158489df1c6f7892fab3cc1d3700eaad6ce64a0f parent 8339365
4 files changed, +333 −44
  • internal/slides/app.go +1 −1
  • internal/slides/mailqueue.go +110 −43
  • internal/slides/mailqueue_test.go +180 −0
  • internal/slidestest/signin_timing_test.go +42 −0

CI passed — run details

diff --git a/internal/slides/app.go b/internal/slides/app.go
index 55f269c..af0cc97 100644
--- a/internal/slides/app.go
+++ b/internal/slides/app.go
@@ -304,7 +304,7 @@ func newApp(d *db.DB, cfg Config) (*app, *rauth.Auth, error) {
// The sign-in mailer: links are queued and sent after the response,
// to permitted addresses only (mailqueue.go). Closed by app.Close.
- mailer := newMailQueue(cfg.Mailer, list.allows, logger)
+ mailer := newMailQueue(cfg.Mailer, list.allows, nil, logger)
authPlugin, err := newAuthPlugin(cfg, d.Writer(), list, mailer)
if err != nil {
mailer.close()
diff --git a/internal/slides/mailqueue.go b/internal/slides/mailqueue.go
index a0f9d55..27d227c 100644
--- a/internal/slides/mailqueue.go
+++ b/internal/slides/mailqueue.go
@@ -2,111 +2,171 @@ package slides
import (
"context"
+ "fmt"
"log/slog"
"sync"
+ "sync/atomic"
"time"
"amadan.net/rastrillo/rastrillo/mail"
)
-// mailQueue is the sign-in mailer rauth is given: Send queues the link
-// and returns at once, and one background worker asks the allowlist and
-// only then talks to SMTP.
+// mailQueue is the sign-in mailer the auth plugin is given: Send queues
+// the link and returns at once, and one background worker decides
+// whether the address may have it and only then talks to SMTP.
//
-// Both halves are the no-oracle guarantee (gateBegin), measured rather
-// than reasoned about. When the send ran inside the request, a permitted
+// Both halves are the no-oracle guarantee, measured rather than
+// reasoned about. When the send ran inside the request, a permitted
// address waited for the SMTP round trip before its `303 ?sent=1` and a
-// denied one did not: 252 ms against 0.35 ms (Astra on #20). A response
-// time is an answer like any other. So POST /signin does the same
-// synchronous work for every address — rauth's budgets, its link row,
-// this enqueue — and the one admission-dependent step, the send, happens
-// after the response, where nobody can time it. The admission check
-// moved into the worker for the same reason: a check before responding
-// would be a branch an attacker could time, however cheap it is today.
+// denied one did not: 252 ms against 0.35 ms (Astra on oficina/slides
+// #20). A response time is an answer like any other. So POST /signin
+// does the same synchronous work for every address — the auth plugin's
+// budgets, its link row, this enqueue — and the one admission-dependent
+// step, the send, happens after the response, where nobody can time it.
//
-// Delivery failures are logged, never surfaced. A failure only a
-// permitted address can reach is the oracle again, and the person is
-// told what every address is told: check your email, or ask again.
+// The request path is Send, and Send does no I/O and never blocks: not
+// a send, not an admission check, not even a log line. Every address's
+// link is queued, permitted or not, so how full the queue is never
+// depends on admission either; the worker decides afterwards. A full
+// queue drops the link and counts it in an atomic; the worker logs the
+// count when it next runs. The person is answered exactly as when the
+// queue is empty, because a different answer for a full queue would be
+// one more thing to read. (Astra on #20, round 2.)
//
-// Bounded: a queue of mailQueueDepth links. A full queue drops the link
-// with a log line instead of blocking a request — the per-IP and
-// per-address budgets inside Begin keep that from being an ordinary
-// event. Close drains what is queued, within mailDrainTimeout.
+// The worker survives a panic in the mailer: it recovers per message,
+// logs, and keeps draining. Delivery failures are logged, never
+// surfaced: a failure only a permitted address can reach is the oracle
+// again.
+//
+// close drains what is queued within drainTimeout. Past it, the send
+// in flight is cancelled through its context, everything still queued
+// is abandoned with a log line, and close waits a short grace for the
+// worker to stop. A mailer that ignores its context is the only way a
+// worker outlives close, and that is logged too.
type mailQueue struct {
next mail.Sender
- admits func(string) bool
+ admits func(to string) bool
+ // gate, when set, is read off the request's context at enqueue time
+ // and travels with the link; the worker sends only if it said yes.
+ gate func(context.Context) bool
logger *slog.Logger
- mu sync.Mutex
+ drainTimeout time.Duration
+ sendTimeout time.Duration
+
+ mu sync.RWMutex // held for reading by Send, for writing by close
closed bool
jobs chan mailJob
+ dropped atomic.Int64
pending sync.WaitGroup
- done chan struct{}
+
+ ctx context.Context // cancelled when close gives up waiting
+ cancel context.CancelFunc
+ done chan struct{}
}
-type mailJob struct{ to, subject, body string }
+type mailJob struct {
+ to, subject, body string
+ gated bool
+}
const (
mailQueueDepth = 64
mailSendTimeout = time.Minute
mailDrainTimeout = 30 * time.Second
+ mailAbandonGrace = 5 * time.Second
)
-func newMailQueue(next mail.Sender, admits func(string) bool, logger *slog.Logger) *mailQueue {
+func newMailQueue(next mail.Sender, admits func(string) bool, gate func(context.Context) bool, logger *slog.Logger) *mailQueue {
if logger == nil {
logger = slog.Default()
}
- q := &mailQueue{next: next, admits: admits, logger: logger,
- jobs: make(chan mailJob, mailQueueDepth), done: make(chan struct{})}
+ ctx, cancel := context.WithCancel(context.Background())
+ q := &mailQueue{next: next, admits: admits, gate: gate, logger: logger,
+ drainTimeout: mailDrainTimeout, sendTimeout: mailSendTimeout,
+ jobs: make(chan mailJob, mailQueueDepth), ctx: ctx, cancel: cancel,
+ done: make(chan struct{})}
go q.run()
return q
}
-// Send queues one link. It never blocks and never fails: the request
-// that called it answers the same way whatever happens next.
-func (q *mailQueue) Send(_ context.Context, to, subject, body string) error {
- q.mu.Lock()
- defer q.mu.Unlock()
+// Send queues one link. It never blocks, never does I/O and never
+// fails: the request that called it answers the same way whatever
+// happens next.
+func (q *mailQueue) Send(ctx context.Context, to, subject, body string) error {
+ job := mailJob{to: to, subject: subject, body: body, gated: true}
+ if q.gate != nil {
+ job.gated = q.gate(ctx)
+ }
+ q.mu.RLock()
+ defer q.mu.RUnlock()
if q.closed {
- q.logger.Error("slides: sign-in mail after shutdown; dropped")
+ q.dropped.Add(1)
return nil
}
q.pending.Add(1)
select {
- case q.jobs <- mailJob{to: to, subject: subject, body: body}:
+ case q.jobs <- job:
default:
q.pending.Done()
- q.logger.Error("slides: sign-in mail queue full; link dropped")
+ q.dropped.Add(1)
}
return nil
}
func (q *mailQueue) run() {
defer close(q.done)
+ abandoned := 0
for job := range q.jobs {
- q.deliver(job)
+ q.reportDrops()
+ if q.ctx.Err() != nil {
+ abandoned++
+ } else {
+ q.deliver(job)
+ }
q.pending.Done()
}
+ q.reportDrops()
+ if abandoned > 0 {
+ q.logger.Error("slides: sign-in links abandoned at shutdown", "count", abandoned)
+ }
}
+// reportDrops logs the links Send had to drop since the last report.
+// Here, on the worker, so the request path never writes a log line.
+func (q *mailQueue) reportDrops() {
+ if n := q.dropped.Swap(0); n > 0 {
+ q.logger.Error("slides: sign-in mail queue full; links dropped", "count", n)
+ }
+}
+
+// deliver sends one link if it may go. A panic in the admission check
+// or the mailer is this message's failure, not the process's.
func (q *mailQueue) deliver(job mailJob) {
- if !q.admits(job.to) {
- // Not on the allowlist: the link rauth stored is never
+ defer func() {
+ if p := recover(); p != nil {
+ q.logger.Error("slides: sign-in mail worker recovered from a panic", "panic", fmt.Sprint(p))
+ }
+ }()
+ if !job.gated || !q.admits(job.to) {
+ // Not admitted: the link the auth plugin stored is never
// delivered, so it is never redeemed. No address in the log.
return
}
- ctx, cancel := context.WithTimeout(context.Background(), mailSendTimeout)
+ ctx, cancel := context.WithTimeout(q.ctx, q.sendTimeout)
defer cancel()
if err := q.next.Send(ctx, job.to, job.subject, job.body); err != nil {
q.logger.Error("slides: send sign-in link", "err", err)
}
}
-// wait blocks until every link queued so far has been delivered or
-// dropped. Tests use it (App.FlushMail) to read the mailer afterwards.
+// wait blocks until every link queued so far has been sent or refused.
+// Tests use it to read the mailer afterwards.
func (q *mailQueue) wait() { q.pending.Wait() }
-// close stops taking links and drains what is queued.
+// close stops taking links and drains what is queued, within
+// drainTimeout; then it cancels, abandons the rest, and stops the
+// worker (see the type's comment).
func (q *mailQueue) close() {
q.mu.Lock()
if q.closed {
@@ -116,9 +176,16 @@ func (q *mailQueue) close() {
q.closed = true
close(q.jobs)
q.mu.Unlock()
+ defer q.cancel()
+ select {
+ case <-q.done:
+ return
+ case <-time.After(q.drainTimeout):
+ }
+ q.cancel()
select {
case <-q.done:
- case <-time.After(mailDrainTimeout):
- q.logger.Error("slides: sign-in mail still sending at shutdown; abandoned")
+ case <-time.After(mailAbandonGrace):
+ q.logger.Error("slides: sign-in mail worker ignored cancellation; left running")
}
}
diff --git a/internal/slides/mailqueue_test.go b/internal/slides/mailqueue_test.go
new file mode 100644
index 0000000..8408ce9
--- /dev/null
+++ b/internal/slides/mailqueue_test.go
@@ -0,0 +1,180 @@
+package slides
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+ "runtime"
+ "sync"
+ "testing"
+ "time"
+)
+
+// stuckHandler is a slog handler whose every write blocks until release
+// is closed: a log sink that has stalled, as a full pipe does.
+type stuckHandler struct{ release chan struct{} }
+
+func (h stuckHandler) Enabled(context.Context, slog.Level) bool { return true }
+func (h stuckHandler) Handle(context.Context, slog.Record) error {
+ <-h.release
+ return nil
+}
+func (h stuckHandler) WithAttrs([]slog.Attr) slog.Handler { return h }
+func (h stuckHandler) WithGroup(string) slog.Handler { return h }
+
+// funcSender adapts a function to mail.Sender.
+type funcSender func(ctx context.Context, to string) error
+
+func (f funcSender) Send(ctx context.Context, to, _, _ string) error { return f(ctx, to) }
+
+func everyone(string) bool { return true }
+
+// TestMailQueueSendNeverBlocksWhenFull: Send is the request path, so it
+// may not block or do I/O even when the queue is full — not even to log
+// the drop (Astra on oficina/slides #20, round 2, P1: a "queue full" log
+// line on a stalled sink held the request, and saturation is
+// admission-dependent). The worker is stuck on its first link and the
+// log sink is stuck too; twice the queue's depth of Sends must still
+// return at once, and the drops are logged by the worker afterwards.
+func TestMailQueueSendNeverBlocksWhenFull(t *testing.T) {
+ release := make(chan struct{})
+ var once sync.Once
+ free := func() { once.Do(func() { close(release) }) }
+ stuck := funcSender(func(ctx context.Context, _ string) error {
+ select {
+ case <-release:
+ case <-ctx.Done():
+ }
+ return nil
+ })
+ q := newMailQueue(stuck, everyone, nil, slog.New(stuckHandler{release}))
+ t.Cleanup(func() { free(); q.close() })
+
+ done := make(chan struct{})
+ go func() {
+ for i := 0; i < 2*mailQueueDepth; i++ {
+ _ = q.Send(context.Background(), fmt.Sprintf("p%d@example.test", i), "s", "b")
+ }
+ close(done)
+ }()
+ select {
+ case <-done:
+ case <-time.After(2 * time.Second):
+ free()
+ <-done
+ t.Fatal("Send blocked with the queue full: the request path waited on the queue or the log")
+ }
+ if n := q.dropped.Load(); n == 0 {
+ t.Fatal("no drop was counted with twice the queue's depth sent")
+ }
+}
+
+// TestMailQueueQueuesEveryAddress: the queue's fill level must not
+// depend on admission, so Send queues a refused address's link exactly
+// as it queues a permitted one; only the worker asks.
+func TestMailQueueQueuesEveryAddress(t *testing.T) {
+ release := make(chan struct{})
+ stuck := funcSender(func(ctx context.Context, _ string) error {
+ select {
+ case <-release:
+ case <-ctx.Done():
+ }
+ return nil
+ })
+ var asked sync.Map
+ admits := func(to string) bool { asked.Store(to, true); return to == "first@example.test" }
+ q := newMailQueue(stuck, admits, nil, slog.New(slog.DiscardHandler))
+ t.Cleanup(func() { close(release); q.close() })
+ _ = q.Send(context.Background(), "first@example.test", "s", "b")
+ deadline := time.Now().Add(2 * time.Second)
+ for _, ok := asked.Load("first@example.test"); !ok && time.Now().Before(deadline); _, ok = asked.Load("first@example.test") {
+ time.Sleep(5 * time.Millisecond)
+ }
+ for i := 0; i < 5; i++ {
+ _ = q.Send(context.Background(), fmt.Sprintf("refused%d@example.test", i), "s", "b")
+ }
+ if got := len(q.jobs); got != 5 {
+ t.Fatalf("queued %d refused links, want all 5: fill level must not depend on admission", got)
+ }
+}
+
+// TestMailQueueSurvivesAPanic: a panic in the mailer is that message's
+// failure; the worker recovers, logs, and sends the next one (Astra,
+// round 2, P2).
+func TestMailQueueSurvivesAPanic(t *testing.T) {
+ var mu sync.Mutex
+ var sent []string
+ calls := 0
+ s := funcSender(func(_ context.Context, to string) error {
+ mu.Lock()
+ defer mu.Unlock()
+ calls++
+ if calls == 1 {
+ panic("mailer exploded")
+ }
+ sent = append(sent, to)
+ return nil
+ })
+ q := newMailQueue(s, everyone, nil, slog.New(slog.DiscardHandler))
+ t.Cleanup(q.close)
+ _ = q.Send(context.Background(), "first@example.test", "s", "b")
+ _ = q.Send(context.Background(), "second@example.test", "s", "b")
+ q.wait()
+ mu.Lock()
+ defer mu.Unlock()
+ if len(sent) != 1 || sent[0] != "second@example.test" {
+ t.Fatalf("sent = %v, want the second link after the first panicked", sent)
+ }
+}
+
+// TestMailQueueCloseIsBoundedAndStopsTheWorker: close drains within its
+// deadline, then cancels the send in flight, abandons the rest, and the
+// worker is gone — no goroutine outlives close (Astra, round 2, P2).
+func TestMailQueueCloseIsBoundedAndStopsTheWorker(t *testing.T) {
+ baseline := runtime.NumGoroutine()
+ honours := funcSender(func(ctx context.Context, _ string) error {
+ <-ctx.Done() // a relay that never answers, but obeys cancellation
+ return ctx.Err()
+ })
+ q := newMailQueue(honours, everyone, nil, slog.New(slog.DiscardHandler))
+ q.drainTimeout = 50 * time.Millisecond
+ for i := 0; i < 3; i++ {
+ _ = q.Send(context.Background(), fmt.Sprintf("p%d@example.test", i), "s", "b")
+ }
+ start := time.Now()
+ q.close()
+ if took := time.Since(start); took > 2*time.Second {
+ t.Fatalf("close took %v, want about its 50ms deadline", took)
+ }
+ select {
+ case <-q.done:
+ default:
+ t.Fatal("the worker was still running after close")
+ }
+ deadline := time.Now().Add(time.Second)
+ for runtime.NumGoroutine() > baseline && time.Now().Before(deadline) {
+ time.Sleep(5 * time.Millisecond)
+ }
+ if n := runtime.NumGoroutine(); n > baseline {
+ t.Fatalf("%d goroutines after close, %d before: the queue leaked", n, baseline)
+ }
+}
+
+// TestAppCloseStopsTheMailWorker: the app owns its queue, and Close
+// stops its worker — no test that builds an app and closes it leaves
+// one running behind it.
+func TestAppCloseStopsTheMailWorker(t *testing.T) {
+ _, a, err := New(testDB(t), Config{Env: EnvDevelopment, Origin: "http://localhost:8091", Logger: quietLogger()})
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := a.mail
+ if err := a.Close(); err != nil {
+ t.Fatal(err)
+ }
+ select {
+ case <-q.done:
+ case <-time.After(2 * time.Second):
+ t.Fatal("the sign-in mail worker was still running after app.Close")
+ }
+}
diff --git a/internal/slidestest/signin_timing_test.go b/internal/slidestest/signin_timing_test.go
index 9fd99b0..461f884 100644
--- a/internal/slidestest/signin_timing_test.go
+++ b/internal/slidestest/signin_timing_test.go
@@ -2,8 +2,11 @@ package slidestest
import (
"context"
+ "fmt"
+ "net/http"
"net/http/httptest"
"net/url"
+ "strings"
"sync"
"testing"
"time"
@@ -81,3 +84,42 @@ func TestSigninNeverWaitsForTheMailer(t *testing.T) {
t.Fatalf("mail sent = %v, want two links, both to %s", got, allowedAddress)
}
}
+
+// TestAFullMailQueueAnswersLikeAnEmptyOne: the queue holds 64 links.
+// With the mailer stuck on the first (permitted) link, enough POSTs to
+// overflow it — each from its own address and IP, so no budget stands
+// in — must every one be answered exactly as the first was, and at
+// once. Every address's link is queued, permitted or not, so a refused
+// address fills the queue as surely as a permitted one (Astra on #20,
+// round 2).
+func TestAFullMailQueueAnswersLikeAnEmptyOne(t *testing.T) {
+ bm := &blockingMailer{release: make(chan struct{})}
+ cfg, _ := newConfig(t)
+ cfg.Mailer = bm
+ app := newAppWith(t, cfg, nil)
+ var once sync.Once
+ free := func() { once.Do(func() { close(bm.release) }) }
+ t.Cleanup(free)
+
+ postFrom := func(i int, address string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodPost, "/signin", strings.NewReader(url.Values{"address": {address}}.Encode()))
+ req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ req.Header.Set("Origin", testOrigin)
+ req.Header.Set("Sec-Fetch-Site", "same-origin")
+ req.RemoteAddr = fmt.Sprintf("198.51.100.%d:1234", i%250+1)
+ rec := httptest.NewRecorder()
+ app.ServeHTTP(rec, req)
+ return rec
+ }
+ first := postFrom(0, allowedAddress)
+ for i := 1; i <= 80; i++ {
+ start := time.Now()
+ rec := postFrom(i, fmt.Sprintf("stranger%d@else.test", i))
+ if took := time.Since(start); took > time.Second {
+ t.Fatalf("POST %d took %v with the queue full", i, took)
+ }
+ if rec.Code != first.Code || rec.Header().Get("Location") != first.Header().Get("Location") || rec.Body.String() != first.Body.String() {
+ t.Fatalf("POST %d answered %d %q, want exactly the first answer %d %q", i, rec.Code, rec.Header().Get("Location"), first.Code, first.Header().Get("Location"))
+ }
+ }
+}