oficina / calendar Public

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

Astra's second round on oficina/slides #20, applied to the same queue.

- Send does no I/O: a drop is counted in an atomic and logged by the
  worker. Every address's link is queued, permitted or not, so the fill
  level does not depend on admission. The refusal count is logged by
  the worker too (allowlistAdmits), never on the request path.
- The worker recovers per message from a panic and keeps draining.
- Sends run under the queue's context; past the drain deadline close
  cancels the one in flight, abandons the rest with a log line, and the
  worker exits. Every New error path after the queue exists closes it.

Tests (each of the first four fails with its defect put back):
TestMailQueueSendNeverBlocksWhenFull, TestMailQueueSurvivesAPanic,
TestMailQueueCloseIsBoundedAndStopsTheWorker (goroutine count),
TestAppCloseStopsTheMailWorker, TestMailQueueQueuesEveryAddress.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev e60b239f73f2035152a7de91ac329e1db1b9dc4c parent 2aa0633
3 files changed, +307 −54
  • internal/calendar/app.go +4 −1
  • internal/calendar/signin_mail.go +126 −53
  • internal/calendar/signin_mail_test.go +177 −0

CI passed — run details

CI log
=== vet ===
go vet ./...
go vet -tags browser ./internal/calendartest/
=== fmt ===
=== test ===
go test ./...
?   	amadan.net/oficina/calendar/cmd/calendar	[no test files]
ok  	amadan.net/oficina/calendar/internal/calendar	4.978s
?   	amadan.net/oficina/calendar/internal/calendar/icons	[no test files]
?   	amadan.net/oficina/calendar/internal/calendar/keymailtest	[no test files]
?   	amadan.net/oficina/calendar/internal/calendar/seal	[no test files]
ok  	amadan.net/oficina/calendar/internal/calendartest	2.597s
ok  	amadan.net/oficina/calendar/internal/guardstest	0.056s
?   	amadan.net/oficina/calendar/scripts/writeestilo	[no test files]
=== migration-check ===
go tool rastrillo migration check
rastrillo migration check: models and migrations agree
diff --git a/internal/calendar/app.go b/internal/calendar/app.go
index c37010c..b20ba8e 100644
--- a/internal/calendar/app.go
+++ b/internal/calendar/app.go
@@ -144,7 +144,7 @@ func New(cfg Config) (*App, error) {
mailer = newBoundedSender(mailer)
// Sign-in links alone go through a queue: sent after the response,
// to permitted addresses only (signin_mail.go). Closed by Close.
- signinMail := newMailQueue(mailer, list.allows, logger)
+ signinMail := newMailQueue(mailer, allowlistAdmits(list, logger), nil, logger)
authPlugin, err := newAuthPlugin(origin, writer, instanceKey, signinMail, list, logger, homeSettings != nil)
if err != nil {
signinMail.close()
@@ -167,6 +167,7 @@ func New(cfg Config) (*App, error) {
if homeSettings != nil {
a.home, err = a.newHome(homeSettings, list)
if err != nil {
+ signinMail.close()
d.Close()
return nil, err
}
@@ -192,6 +193,7 @@ func New(cfg Config) (*App, error) {
// Native wiring comes before the scheduler starts, so a native
// failure leaves no timer goroutine behind to leak.
if err := a.wireNative(); err != nil {
+ signinMail.close()
d.Close()
return nil, err
}
@@ -199,6 +201,7 @@ func New(cfg Config) (*App, error) {
logger.Error("calendar: scheduled work registration failed", "stage", "schedule.register", "err", scrubErr(err))
})
if err := a.scheduled.start(); err != nil {
+ signinMail.close()
d.Close()
return nil, err
}
diff --git a/internal/calendar/signin_mail.go b/internal/calendar/signin_mail.go
index 31a12d3..6882643 100644
--- a/internal/calendar/signin_mail.go
+++ b/internal/calendar/signin_mail.go
@@ -2,6 +2,7 @@ package calendar
import (
"context"
+ "fmt"
"log/slog"
"sync"
"sync/atomic"
@@ -10,115 +11,162 @@ import (
"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 (beginSignin), 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 oficina/slides #20; Calendar had the same split). 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.
//
-// It sits in front of the bounded sender, so an ErrMailBusy is a log
-// line here rather than a ?err=1 only a permitted address could see.
+// 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.)
//
-// 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 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.
//
-// 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.
+// 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
- refusals atomic.Int64
+ drainTimeout time.Duration
+ sendTimeout time.Duration
- mu sync.Mutex
+ 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("calendar: 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("calendar: 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("calendar: 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("calendar: 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
- // delivered, so it is never redeemed. The refusal is COUNTED
- // in the log, without the address: the response has to stay
- // silent, the log does not (AGENTS.md §Logs). Without this line
- // an instance whose allowlist is missing the only address
- // anybody types is indistinguishable from a working one.
- q.logger.Warn("calendar: signin refused by allowlist",
- "stage", "signin.gate", "refusals_since_boot", q.refusals.Add(1))
+ defer func() {
+ if p := recover(); p != nil {
+ q.logger.Error("calendar: 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("calendar: send sign-in link", "err", err)
}
}
-// wait blocks until every link queued so far has been delivered or
-// dropped. SignInForTest uses it to read the recorder 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 {
@@ -128,9 +176,34 @@ func (q *mailQueue) close() {
q.closed = true
close(q.jobs)
q.mu.Unlock()
+ defer q.cancel()
select {
case <-q.done:
- case <-time.After(mailDrainTimeout):
- q.logger.Error("calendar: sign-in mail still sending at shutdown; abandoned")
+ return
+ case <-time.After(q.drainTimeout):
+ }
+ q.cancel()
+ select {
+ case <-q.done:
+ case <-time.After(mailAbandonGrace):
+ q.logger.Error("calendar: sign-in mail worker ignored cancellation; left running")
+ }
+}
+
+// allowlistAdmits is the queue's admission check: list.allows, with
+// each refusal COUNTED in the log, without the address. The response
+// has to stay silent; the log does not (AGENTS.md §Logs). Without this
+// line an instance whose allowlist is missing the only address anybody
+// types is indistinguishable from a working one. It runs on the worker,
+// never on the request path.
+func allowlistAdmits(list allowlist, logger *slog.Logger) func(string) bool {
+ var refusals atomic.Int64
+ return func(to string) bool {
+ if list.allows(to) {
+ return true
+ }
+ logger.Warn("calendar: signin refused by allowlist",
+ "stage", "signin.gate", "refusals_since_boot", refusals.Add(1))
+ return false
}
}
diff --git a/internal/calendar/signin_mail_test.go b/internal/calendar/signin_mail_test.go
new file mode 100644
index 0000000..ef87d73
--- /dev/null
+++ b/internal/calendar/signin_mail_test.go
@@ -0,0 +1,177 @@
+package calendar
+
+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, so no test that builds and closes an app leaves
+// one running.
+func TestAppCloseStopsTheMailWorker(t *testing.T) {
+ a := NewForTest(t, t.TempDir())
+ q := a.signinMail
+ 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")
+ }
+}