Background jobs run for each active team on its own Server and under its own locks, a few teams at a time and from a different team each round, so the work is shared between copies of the app and no team holds up another. Each team's files are under its own prefix, and an OAuth sign-in comes back only to the team that started it. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
63 lines
1.9 KiB
Go
63 lines
1.9 KiB
Go
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, *Server) { ran = true })
|
|
if ran {
|
|
t.Error("both copies ran the SEO job")
|
|
}
|
|
release()
|
|
b.jobDo(context.Background(), "seo", func(context.Context, *Server) { 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")
|
|
}
|
|
}
|