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") } }