Phase 9, part 6: background work shared safely between copies of the app

internal/jobs keeps named locks as leases in the database (schema 31:
locks, instances), taken with one conditional UPDATE on SQLite or Postgres,
renewed while the work runs and lapsing if its copy stops. Each background
loop's turn, sending an email, audits, discovery runs and imports run
under a lock; OAuth sign-ins under way are kept in the database. Copies
check in, and work marked running is recovered at start only when no
other copy is alive. Settings -> About lists the copies and work under
way.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 07:56:47 -07:00
co-authored by Claude Opus 5.5
parent ba6114f367
commit c6c4c40600
18 changed files with 873 additions and 150 deletions
+62
View File
@@ -0,0 +1,62 @@
package web
import (
"context"
"io"
"log/slog"
"testing"
"time"
"supermarket/internal/oauth"
)
// Two copies of the app on one database, as behind a load balancer.
func TestTwoCopies(t *testing.T) {
a, _ := newTestServer(t, nil)
b := &Server{DB: a.DB, Secrets: a.Secrets, DataDir: t.TempDir(), PublicURL: a.PublicURL, Version: "test",
Log: slog.New(slog.NewTextHandler(io.Discard, nil))}
if _, err := b.Handler(); err != nil {
t.Fatal(err)
}
// A sign-in started on one copy finishes on the other, once.
a.DB.PutJSON(oauthFlowKey+"st4te", oauth.Pending{Provider: "google", State: "st4te", Started: time.Now()})
if p := b.takeOAuthFlow("st4te"); p == nil || p.Provider != "google" {
t.Fatalf("the other copy didn't find the sign-in: %+v", p)
}
if a.takeOAuthFlow("st4te") != nil {
t.Error("the same state worked twice")
}
// Sign-ins never finished are forgotten.
a.DB.PutJSON(oauthFlowKey+"old", oauth.Pending{Provider: "x", State: "old", Started: time.Now().Add(-2 * oauthTTL)})
a.DB.PutJSON(oauthFlowKey+"new", oauth.Pending{Provider: "x", State: "new", Started: time.Now()})
b.forgetOldOAuthFlows()
if a.takeOAuthFlow("old") != nil || a.takeOAuthFlow("new") == nil {
t.Error("forgot the wrong sign-ins")
}
// A job runs on one copy at a time.
_, release, err := a.jobs().TryLock(context.Background(), "job:seo")
if err != nil {
t.Fatal(err)
}
ran := false
b.jobDo(context.Background(), "seo", func(context.Context) { ran = true })
if ran {
t.Error("both copies ran the SEO job")
}
release()
b.jobDo(context.Background(), "seo", func(context.Context) { ran = true })
if !ran {
t.Error("the job didn't run once free")
}
// Each sees the other: neither recovers "running" work at start.
if a.alone() || b.alone() {
t.Error("a copy thinks it's alone")
}
b.jobs().Stop()
if !a.alone() {
t.Error("a stopped copy still counts")
}
}