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
+34
View File
@@ -1968,6 +1968,40 @@ than planned: rather than helpers in every query, the SQL stays as it is
The first users: exports (part 7), then uploads and images.
**Part 6 built 2026-11-25** on `phase9`.
- `internal/jobs` holds locks as leases in the database (schema 31: tables
`locks` and `instances`). Taking a lock is one conditional `UPDATE`
(free, or its lease lapsed), the same on SQLite and Postgres. That's
simpler than a queue with `SKIP LOCKED`: each loop already keeps what's
due in the database, so a lock per job is enough.
- A lease lasts 2 minutes and is renewed every 30 seconds while the work
runs. If a copy stops, its work is taken over once the lease lapses.
- If a lease is lost, the work's context is cancelled.
- Locks aren't re-entrant: two goroutines in one copy exclude each other
too.
- What runs under a lock:
- each background loop's turn (`job:scheduler`, `job:imports`,
`job:discovery`, `job:outreach`, `job:tracking`, `job:seo`,
`job:metrics`)
- sending an email, from the queue or *Send now* (`outreach:send`,
replacing the in-memory mutex)
- an audit per site, a discovery per signal and source, and an import per
tool (replacing three in-memory guards)
- when replies were last read
- OAuth sign-ins under way are kept in the database (`oauth:flow:<state>`
settings), so the callback can reach any copy; a state works once. Left
in memory, as caches per copy: Google's access token, Reddit's app
token, and the git working copies' locks (each copy has its own clones).
- Each copy checks in every 30 seconds. At start, work marked "running"
(publishing, audits, briefs, changes, site pages, discovery) is marked
interrupted only when no other copy is alive. A copy that crashes while
others run leaves its "running" rows until every copy has restarted;
tying each row to its copy would fix that, in Phase 13.
- Settings → About lists the copies running and the work under way.
- Leases compare the copies' clocks: keep them in sync (NTP), as any
server would.
- The backup loop stays as it is: it's the local edition's, with one copy.
Nothing changes for the local user; this makes the rest possible. A
commit after each part; the whole test suite runs against both SQLite and
Postgres from part 2 on.
+4
View File
@@ -805,3 +805,7 @@ Throughout, also notice:
Postgres password, it says which and why.
- [ ] After the update to schema 30, Settings → Backups shows the "before
schema 30" backup, and `~/.local/share/supermarket/files` exists, empty.
- [ ] Settings → About → Running lists one copy, "(this one)", seen just
now. While an audit runs, `audit:<site>` shows under *Under way*.
- [ ] Connecting a social account or Search Console still works (sign-ins
under way are now kept in the database).
+16 -1
View File
@@ -42,6 +42,7 @@ import (
"supermarket/internal/crm"
"supermarket/internal/db"
"supermarket/internal/fileutil"
"supermarket/internal/jobs"
"supermarket/internal/legacy"
"supermarket/internal/mcpserver"
"supermarket/internal/secrets"
@@ -207,7 +208,19 @@ func run(log *slog.Logger) error {
log.Info("database: migrated", "database", database.Dialect, "from", database.MigratedFrom, "to", db.Schema())
}
if n, err := content.RecoverInterrupted(database); err != nil {
// This copy of the app, for the locks it shares with any others.
runner, err := jobs.New(database, version, log)
if err != nil {
return err
}
defer runner.Stop() // before the database closes
alone, err := runner.Alone()
if err != nil {
return err
}
if !alone {
log.Info("jobs: other copies of Supermarket are running; work they have under way is left to them")
} else if n, err := content.RecoverInterrupted(database); err != nil {
return err
} else if n > 0 {
log.Warn("drafts were being published when Supermarket stopped; marked failed for review", "count", n)
@@ -279,6 +292,7 @@ func run(log *slog.Logger) error {
Core: c,
DataDir: dataDir,
Files: files,
Jobs: runner,
PublicURL: publicURL,
Version: version,
MCPToken: token,
@@ -310,6 +324,7 @@ func run(log *slog.Logger) error {
errCh <- fmt.Errorf("MCP socket %s: %w", mcpSocket, err)
}
}()
go runner.CheckIns(ctx)
go srv.RunScheduler(ctx)
go srv.RunImports(ctx)
go srv.RunDiscovery(ctx)
+19
View File
@@ -33,6 +33,25 @@ CREATE TABLE secrets (
key_id TEXT NOT NULL, -- which key sealed it: a fingerprint, never the key
updated_at TEXT NOT NULL
);
`,
},
// 31
{
Note: "copies of the app, and the locks that let only one of them do a job",
SQLite: `
CREATE TABLE instances (
id TEXT PRIMARY KEY, -- a copy of the app, while it runs
host TEXT NOT NULL DEFAULT '',
version TEXT NOT NULL DEFAULT '',
started_at TEXT NOT NULL,
seen_at TEXT NOT NULL -- its last check-in (every 30 seconds)
);
CREATE TABLE locks (
name TEXT PRIMARY KEY, -- the work, e.g. job:seo, outreach:send, audit:<site>
holder TEXT NOT NULL DEFAULT '', -- <instance>:<random>, or '' when free
taken_at TEXT NOT NULL DEFAULT '',
expires_at TEXT NOT NULL DEFAULT '' -- renewed while the work runs; free after it
);
`,
},
}
+255
View File
@@ -0,0 +1,255 @@
// Package jobs lets several copies of the app share one database without
// doing the same work twice: a named lock, held as a lease in the
// database, renewed while the work runs and lapsing if its copy stops.
// It works the same on SQLite (one copy) and Postgres (several).
//
// Each copy also checks in, so one starting up can tell whether others
// are running (and so whether work marked "running" is really
// interrupted).
package jobs
import (
"context"
"crypto/rand"
"encoding/hex"
"errors"
"log/slog"
"os"
"sync"
"time"
"supermarket/internal/db"
)
// Timing. A lease lasts Lease and is renewed every Renew; a copy that
// hasn't checked in for Gone is taken to have stopped.
const (
Lease = 2 * time.Minute
Renew = 30 * time.Second
CheckIn = 30 * time.Second
Gone = 2 * time.Minute
forgetDay = 24 * time.Hour
)
// ErrBusy means another copy, or another part of this one, holds the lock.
var ErrBusy = errors.New("already under way")
// timeFormat sorts as text: fixed width, UTC.
const timeFormat = "2006-01-02T15:04:05.000Z"
func ts(t time.Time) string { return t.UTC().Format(timeFormat) }
// Runner is this copy of the app.
type Runner struct {
d *db.DB
id string
log *slog.Logger
now func() time.Time // tests
}
// New registers this copy of the app.
func New(d *db.DB, version string, log *slog.Logger) (*Runner, error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return nil, err
}
host, _ := os.Hostname()
r := &Runner{d: d, id: hex.EncodeToString(b), log: log, now: time.Now}
now := ts(r.now())
if _, err := d.Exec(`INSERT INTO instances (id, host, version, started_at, seen_at) VALUES (?, ?, ?, ?, ?)`,
r.id, host, version, now, now); err != nil {
return nil, err
}
return r, nil
}
// ID is this copy's.
func (r *Runner) ID() string { return r.id }
// Stop removes this copy's check-in and frees its locks, when it stops.
func (r *Runner) Stop() {
r.d.Exec(`DELETE FROM instances WHERE id = ?`, r.id)
r.d.Exec(`UPDATE locks SET holder = '', expires_at = '' WHERE holder LIKE ?`, r.id+":%")
}
// CheckIns keeps this copy's check-in current until ctx ends. Copies gone
// a day are forgotten.
func (r *Runner) CheckIns(ctx context.Context) {
tick := time.NewTicker(CheckIn)
defer tick.Stop()
for {
select {
case <-ctx.Done():
return
case <-tick.C:
now := r.now()
if _, err := r.d.Exec(`UPDATE instances SET seen_at = ? WHERE id = ?`, ts(now), r.id); err != nil {
r.log.Warn("jobs: checking in", "err", err)
}
r.d.Exec(`DELETE FROM instances WHERE seen_at < ?`, ts(now.Add(-forgetDay)))
}
}
}
// Alone says whether no other copy of the app has checked in lately.
func (r *Runner) Alone() (bool, error) {
var n int
err := r.d.QueryRow(`SELECT count(*) FROM instances WHERE id != ? AND seen_at >= ?`, r.id, ts(r.now().Add(-Gone))).Scan(&n)
return n == 0, err
}
// Instance is a copy of the app that's running.
type Instance struct {
ID, Host, Version string
Started, Seen time.Time
This bool
}
// Instances are the copies that have checked in lately, this one first.
func (r *Runner) Instances() ([]Instance, error) {
rows, err := r.d.Query(`SELECT id, host, version, started_at, seen_at FROM instances WHERE seen_at >= ? OR id = ? ORDER BY started_at`,
ts(r.now().Add(-Gone)), r.id)
if err != nil {
return nil, err
}
defer rows.Close()
var out []Instance
for rows.Next() {
var in Instance
var started, seen string
if err := rows.Scan(&in.ID, &in.Host, &in.Version, &started, &seen); err != nil {
return nil, err
}
in.Started, _ = time.Parse(timeFormat, started)
in.Seen, _ = time.Parse(timeFormat, seen)
in.This = in.ID == r.id
if in.This {
out = append([]Instance{in}, out...)
} else {
out = append(out, in)
}
}
return out, rows.Err()
}
// Held is a lock someone holds.
type Held struct {
Name, Instance string
Since time.Time
}
// Locks are the locks held now.
func (r *Runner) Locks() ([]Held, error) {
rows, err := r.d.Query(`SELECT name, holder, taken_at FROM locks WHERE holder != '' AND expires_at >= ? ORDER BY name`, ts(r.now()))
if err != nil {
return nil, err
}
defer rows.Close()
var out []Held
for rows.Next() {
var h Held
var holder, since string
if err := rows.Scan(&h.Name, &holder, &since); err != nil {
return nil, err
}
if i := len(holder) - 13; i > 0 { // <instance>:<12 hex>
h.Instance = holder[:i]
}
h.Since, _ = time.Parse(timeFormat, since)
out = append(out, h)
}
return out, rows.Err()
}
// TryLock takes the lock name if it's free (or its holder's lease
// lapsed), or returns ErrBusy. The returned context ends when release is
// called, when ctx ends, or if the lease is lost (the database couldn't
// renew it in time, or another copy took it after it lapsed): the work
// should stop then.
func (r *Runner) TryLock(ctx context.Context, name string) (context.Context, func(), error) {
b := make([]byte, 6)
if _, err := rand.Read(b); err != nil {
return nil, nil, err
}
holder := r.id + ":" + hex.EncodeToString(b)
now := r.now()
if _, err := r.d.Exec(`INSERT INTO locks (name) VALUES (?) ON CONFLICT DO NOTHING`, name); err != nil {
return nil, nil, err
}
res, err := r.d.Exec(`UPDATE locks SET holder = ?, taken_at = ?, expires_at = ? WHERE name = ? AND (holder = '' OR expires_at < ?)`,
holder, ts(now), ts(now.Add(Lease)), name, ts(now))
if err != nil {
return nil, nil, err
}
if n, err := res.RowsAffected(); err != nil {
return nil, nil, err
} else if n == 0 {
return nil, nil, ErrBusy
}
wctx, cancel := context.WithCancel(ctx)
done := make(chan struct{})
go func() { // renew while held
tick := time.NewTicker(Renew)
defer tick.Stop()
for {
select {
case <-done:
return
case <-wctx.Done():
return
case <-tick.C:
res, err := r.d.Exec(`UPDATE locks SET expires_at = ? WHERE name = ? AND holder = ?`, ts(r.now().Add(Lease)), name, holder)
n := int64(0)
if err == nil {
n, _ = res.RowsAffected()
}
if n == 0 {
r.log.Warn("jobs: lost the lock; stopping the work", "lock", name, "err", err)
cancel()
return
}
}
}
}()
var once sync.Once
release := func() {
once.Do(func() {
close(done)
cancel()
if _, err := r.d.Exec(`UPDATE locks SET holder = '', expires_at = '' WHERE name = ? AND holder = ?`, name, holder); err != nil {
r.log.Warn("jobs: releasing a lock", "lock", name, "err", err)
}
})
}
return wctx, release, nil
}
// Lock waits for the lock name until ctx ends.
func (r *Runner) Lock(ctx context.Context, name string) (context.Context, func(), error) {
for {
wctx, release, err := r.TryLock(ctx, name)
if !errors.Is(err, ErrBusy) {
return wctx, release, err
}
select {
case <-ctx.Done():
return nil, nil, ErrBusy
case <-time.After(250 * time.Millisecond):
}
}
}
// Do runs fn under the lock name if it's free, and says whether it ran.
// A busy lock isn't an error: another copy is doing the work.
func (r *Runner) Do(ctx context.Context, name string, fn func(ctx context.Context)) (bool, error) {
wctx, release, err := r.TryLock(ctx, name)
if errors.Is(err, ErrBusy) {
return false, nil
}
if err != nil {
return false, err
}
defer release()
fn(wctx)
return true, nil
}
+169
View File
@@ -0,0 +1,169 @@
package jobs
import (
"context"
"errors"
"io"
"log/slog"
"path/filepath"
"sync"
"sync/atomic"
"testing"
"time"
"supermarket/internal/db"
)
func setup(t *testing.T) *db.DB {
t.Helper()
d, err := db.Open(filepath.Join(t.TempDir(), "app.db"))
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { d.Close() })
return d
}
var quiet = slog.New(slog.NewTextHandler(io.Discard, nil))
func runner(t *testing.T, d *db.DB) *Runner {
t.Helper()
r, err := New(d, "test", quiet)
if err != nil {
t.Fatal(err)
}
return r
}
// Two copies of the app: only one does a job at a time.
func TestOneAtATime(t *testing.T) {
d := setup(t)
a, b := runner(t, d), runner(t, d)
ctx := context.Background()
wctx, release, err := a.TryLock(ctx, "job:seo")
if err != nil {
t.Fatal(err)
}
if _, _, err := b.TryLock(ctx, "job:seo"); !errors.Is(err, ErrBusy) {
t.Fatalf("the other copy took it: %v", err)
}
if _, _, err := a.TryLock(ctx, "job:seo"); !errors.Is(err, ErrBusy) { // not re-entrant, even in one copy
t.Fatalf("taken twice in one copy: %v", err)
}
if ran, _ := b.Do(ctx, "job:seo", func(context.Context) {}); ran {
t.Fatal("Do ran while busy")
}
held, _ := b.Locks()
if len(held) != 1 || held[0].Name != "job:seo" || held[0].Instance != a.ID() {
t.Fatalf("held: %+v", held)
}
release()
if wctx.Err() == nil {
t.Error("the work's context goes on after release")
}
if ran, err := b.Do(ctx, "job:seo", func(context.Context) {}); !ran || err != nil {
t.Fatalf("free again: %v %v", ran, err)
}
// Many goroutines, two copies: never two at once.
var inside, most, runs int32
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
r := a
if i%2 == 1 {
r = b
}
go func() {
defer wg.Done()
_, release, err := r.Lock(ctx, "outreach:send")
if err != nil {
t.Error(err)
return
}
n := atomic.AddInt32(&inside, 1)
for {
m := atomic.LoadInt32(&most)
if n <= m || atomic.CompareAndSwapInt32(&most, m, n) {
break
}
}
time.Sleep(2 * time.Millisecond)
atomic.AddInt32(&inside, -1)
atomic.AddInt32(&runs, 1)
release()
}()
}
wg.Wait()
if most != 1 || runs != 20 {
t.Errorf("at most %d at once, %d runs", most, runs)
}
}
// A copy that stops holding a lock: once its lease lapses, another takes it.
func TestLapsedLease(t *testing.T) {
d := setup(t)
a, b := runner(t, d), runner(t, d)
clock := time.Now()
a.now = func() time.Time { return clock }
b.now = func() time.Time { return clock }
if _, _, err := a.TryLock(context.Background(), "job:metrics"); err != nil { // never released: a crashed
t.Fatal(err)
}
if _, _, err := b.TryLock(context.Background(), "job:metrics"); !errors.Is(err, ErrBusy) {
t.Fatal("taken before the lease lapsed")
}
clock = clock.Add(Lease + time.Second)
if _, release, err := b.TryLock(context.Background(), "job:metrics"); err != nil {
t.Fatalf("not taken after it lapsed: %v", err)
} else {
release()
}
}
// Lock gives up when its context ends.
func TestLockWaits(t *testing.T) {
d := setup(t)
a := runner(t, d)
_, release, _ := a.TryLock(context.Background(), "x")
defer release()
ctx, cancel := context.WithTimeout(context.Background(), 300*time.Millisecond)
defer cancel()
if _, _, err := a.Lock(ctx, "x"); !errors.Is(err, ErrBusy) {
t.Fatalf("lock: %v", err)
}
}
// Copies see each other; one that stops checking in is gone.
func TestInstances(t *testing.T) {
d := setup(t)
a := runner(t, d)
if alone, err := a.Alone(); !alone || err != nil {
t.Fatalf("alone: %v %v", alone, err)
}
b := runner(t, d)
if alone, _ := a.Alone(); alone {
t.Fatal("doesn't see the other copy")
}
list, _ := a.Instances()
if len(list) != 2 || !list[0].This || list[1].ID != b.ID() || list[1].Version != "test" {
t.Fatalf("instances: %+v", list)
}
a.now = func() time.Time { return time.Now().Add(Gone + time.Minute) } // b hasn't checked in since
if alone, _ := a.Alone(); !alone {
t.Error("a stopped copy still counts")
}
// Stopping: the check-in and the copy's locks go.
if _, _, err := b.TryLock(context.Background(), "job:seo"); err != nil {
t.Fatal(err)
}
b.Stop()
a.now = time.Now
if held, _ := a.Locks(); len(held) != 0 {
t.Errorf("still held: %+v", held)
}
if list, _ := a.Instances(); len(list) != 1 {
t.Errorf("instances: %+v", list)
}
}
+8 -3
View File
@@ -6,6 +6,7 @@ import (
"supermarket/internal/config"
"supermarket/internal/db"
"supermarket/internal/jobs"
)
// config is how this Supermarket is run: the local edition's defaults when
@@ -33,12 +34,16 @@ type aboutData struct {
Version string
Schema int
Items []config.Item
Copies []jobs.Instance // copies of the app running now
Locks []jobs.Held // work they have under way
}
// aboutPage shows the edition and how it's run (Settings → About).
func (s *Server) aboutPage(w http.ResponseWriter, r *http.Request) {
c := s.config()
s.render(w, r, "about", page{Title: "About", Nav: "settings/about", Data: aboutData{
Edition: c.Edition, Version: s.Version, Schema: db.Schema(), Items: c.Summary(),
}})
d := aboutData{Edition: c.Edition, Version: s.Version, Schema: db.Schema(), Items: c.Summary()}
d.Copies, _ = s.jobs().Instances()
d.Locks, _ = s.jobs().Locks()
s.render(w, r, "about", page{Title: "About", Nav: "settings/about", Data: d})
}
+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")
}
}
+2
View File
@@ -371,7 +371,9 @@ func (s *Server) RunScheduler(ctx context.Context) {
tick := time.NewTicker(schedulerInterval)
defer tick.Stop()
for {
s.jobDo(ctx, "scheduler", func(ctx context.Context) {
s.publishDue(ctx, time.Now())
})
select {
case <-ctx.Done():
return
+2
View File
@@ -184,6 +184,7 @@ func (s *Server) RunMetrics(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
for {
s.jobDo(ctx, "metrics", func(ctx context.Context) {
if c := s.stripe(); c != nil {
if _, err := metrics.SyncOutsideSpend(s.DB, time.Now()); err != nil {
s.Log.Warn("metrics: outside spend", "err", err)
@@ -197,6 +198,7 @@ func (s *Server) RunMetrics(ctx context.Context) {
cancel()
}
}
})
select {
case <-ctx.Done():
return
+30 -12
View File
@@ -3,9 +3,11 @@ package web
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"supermarket/internal/jobs"
"time"
"supermarket/internal/ai"
@@ -357,9 +359,14 @@ func (s *Server) outreachAction(w http.ResponseWriter, r *http.Request) {
var mb outreach.Mailbox
if set, mb, err = s.mailbox(); err == nil {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute)
s.sending.Lock()
err = outreach.SendNow(ctx, s.DB, set, mb, s.tagger(), id, now)
s.sending.Unlock()
var sctx context.Context
var release func()
if sctx, release, err = s.jobs().Lock(ctx, sendLock); err == nil {
err = outreach.SendNow(sctx, s.DB, set, mb, s.tagger(), id, now)
release()
} else if errors.Is(err, jobs.ErrBusy) {
err = errors.New("another email is still being sent; try again in a minute")
}
cancel()
}
msg = "sent"
@@ -399,24 +406,35 @@ func (s *Server) outreachCheck(w http.ResponseWriter, r *http.Request) {
// RunOutreach sends queued emails as their turn comes, and reads replies
// every 10 minutes.
// repliesCheckedKey is when the mailbox was last read for replies.
const repliesCheckedKey = "outreach:replies-checked"
func (s *Server) RunOutreach(ctx context.Context) {
tick := time.NewTicker(time.Minute)
defer tick.Stop()
var lastCheck time.Time
for {
if set, mb, err := s.mailbox(); err == nil {
s.sending.Lock()
s.jobDo(ctx, "outreach", func(ctx context.Context) {
set, mb, err := s.mailbox()
if err != nil {
return
}
sctx, cancel := context.WithTimeout(ctx, 3*time.Minute)
m, err := outreach.SendDue(sctx, s.DB, set, mb, s.tagger(), time.Now())
cancel()
s.sending.Unlock()
if lctx, release, err := s.jobs().Lock(sctx, sendLock); err == nil {
m, err := outreach.SendDue(lctx, s.DB, set, mb, s.tagger(), time.Now())
release()
if err != nil {
s.Log.Warn("outreach: sending", "message", idOf(m), "err", err)
} else if m != nil {
s.Log.Info("outreach: sent", "message", m.ID, "to", m.To)
}
if set.ReadReplies && time.Since(lastCheck) >= 10*time.Minute {
lastCheck = time.Now()
}
cancel()
// Replies, every 10 minutes (kept in the database: another copy
// may have read them last).
var last time.Time
_, _ = s.DB.GetJSON(repliesCheckedKey, &last)
if set.ReadReplies && time.Since(last) >= 10*time.Minute {
_ = s.DB.PutJSON(repliesCheckedKey, time.Now())
cctx, cancel := context.WithTimeout(ctx, 5*time.Minute)
if res, err := outreach.CheckReplies(cctx, s.DB, set, mb.Password, time.Now()); err != nil {
s.Log.Warn("outreach: reading replies", "err", err)
@@ -425,7 +443,7 @@ func (s *Server) RunOutreach(ctx context.Context) {
}
cancel()
}
}
})
select {
case <-ctx.Done():
return
+14 -7
View File
@@ -13,6 +13,7 @@ import (
"time"
"supermarket/internal/api/gsc"
"supermarket/internal/jobs"
"supermarket/internal/oauth"
"supermarket/internal/outreach"
"supermarket/internal/profile"
@@ -263,6 +264,7 @@ func (s *Server) syncSearchConsole(ctx context.Context) error {
// RunSEO syncs Search Console twice a day.
func (s *Server) RunSEO(ctx context.Context) {
if s.alone() { // otherwise "running" may be another copy's work
if err := seo.RecoverAudits(s.DB); err != nil {
s.Log.Error("seo: recovering audits", "err", err)
}
@@ -275,9 +277,11 @@ func (s *Server) RunSEO(ctx context.Context) {
if err := sites.RecoverPages(s.DB); err != nil {
s.Log.Error("sites: recovering pages", "err", err)
}
}
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
for {
s.jobDo(ctx, "seo", func(ctx context.Context) {
s.weeklyAudits(time.Now())
if s.gsc() != nil {
due := false
@@ -303,6 +307,7 @@ func (s *Server) RunSEO(ctx context.Context) {
s.refreshBriefs(ctx)
s.refreshSitePages(ctx)
s.pingNewlyLive(ctx)
})
select {
case <-ctx.Done():
return
@@ -543,9 +548,6 @@ func (s *Server) dailyChecks(ctx context.Context) {
var pageSpeedKey = secretField{"pagespeed", secrets.PageSpeedAPIKey, "PageSpeed Insights API key (optional)",
"Free. In Google Cloud, enable the PageSpeed Insights API and create an API key under Credentials. Without one, Google allows only a few speed checks.", googleCreds}
// auditing marks the sites being audited now.
var auditing sync.Map
// auditSites are every website in the profile (an audit doesn't need
// Search Console; with it, issues are ranked by traffic).
func (s *Server) auditSites(r *http.Request) ([]seoSite, *seoSite) {
@@ -611,18 +613,23 @@ func (s *Server) seoAuditRun(w http.ResponseWriter, r *http.Request) {
// startAudit runs one in the background, unless one is running for the
// site.
func (s *Server) startAudit(site seoSite, speed bool) {
if _, busy := auditing.LoadOrStore(site.URL, true); busy {
// One audit per site at a time, across copies of the app.
lctx, release, err := s.jobs().TryLock(context.Background(), "audit:"+site.URL)
if err != nil {
if !errors.Is(err, jobs.ErrBusy) {
s.Log.Error("seo: starting the audit", "err", err)
}
return
}
id, err := seo.StartAudit(s.DB, site.URL, time.Now())
if err != nil {
auditing.Delete(site.URL)
release()
s.Log.Error("seo: starting the audit", "err", err)
return
}
go func() {
defer auditing.Delete(site.URL)
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Minute)
defer release()
ctx, cancel := context.WithTimeout(lctx, 45*time.Minute)
defer cancel()
a, err := seo.RunAudit(ctx, s.DB, seo.NewFetcher("Supermarket/"+s.Version+" (SEO audit)"), site.URL, site.Property)
if err == nil && speed {
+41 -6
View File
@@ -2,6 +2,7 @@
package web
import (
"context"
"embed"
"fmt"
"html/template"
@@ -15,6 +16,7 @@ import (
"strconv"
"strings"
"supermarket/internal/config"
"supermarket/internal/jobs"
"supermarket/internal/storage"
"sync"
"time"
@@ -27,7 +29,6 @@ import (
"supermarket/internal/db"
"supermarket/internal/legacy"
"supermarket/internal/metrics"
"supermarket/internal/oauth"
"supermarket/internal/prospects"
"supermarket/internal/secrets"
"supermarket/internal/seo"
@@ -50,6 +51,7 @@ type Server struct {
Core *core.Core // nil without a Core
DataDir string
Files storage.Store // exports and uploads: a folder or S3; nil in tests
Jobs *jobs.Runner // this copy of the app, for locks shared with others; made on first use in tests
PublicURL string // e.g. http://localhost:8470, for OAuth redirect URIs
Version string
MCPToken string
@@ -65,7 +67,7 @@ type Server struct {
pages map[string]*template.Template
mu sync.Mutex
pending map[string]*oauth.Pending // OAuth flows by state
jobsOnce sync.Once
// Reddit: an app-only token for reading rules before sign-in, and the
// account's recent posts for the warnings.
@@ -73,17 +75,50 @@ type Server struct {
redditAppTokenExp time.Time
redditHist []reddit.Submission
redditHistAt time.Time
// sending lets one email go out at a time, from the queue or Send now.
sending sync.Mutex
}
// jobs is this copy of the app, for the locks it shares with the others.
func (s *Server) jobs() *jobs.Runner {
s.jobsOnce.Do(func() {
if s.Jobs == nil {
r, err := jobs.New(s.DB, s.Version, s.Log)
if err != nil {
panic(fmt.Sprintf("jobs: %v", err)) // only without a Runner from main: tests
}
s.Jobs = r
}
})
return s.Jobs
}
// alone says whether no other copy of the app is running: only then is
// work marked "running" really interrupted, and safe to mark so.
func (s *Server) alone() bool {
ok, err := s.jobs().Alone()
if err != nil {
s.Log.Warn("jobs: looking for other copies", "err", err)
return false
}
return ok
}
// jobDo runs one turn of a background job under its lock, job:<name>:
// with several copies of the app, one of them does it.
func (s *Server) jobDo(ctx context.Context, name string, fn func(context.Context)) {
if _, err := s.jobs().Do(ctx, "job:"+name, fn); err != nil {
s.Log.Warn("jobs: taking the lock", "job", name, "err", err)
}
}
// sendLock is held while an email goes out, from the queue or Send now:
// one at a time, across every copy of the app.
const sendLock = "outreach:send"
// Handler builds the routes.
func (s *Server) Handler() (http.Handler, error) {
if err := s.loadTemplates(); err != nil {
return nil, err
}
s.pending = map[string]*oauth.Pending{}
mux := http.NewServeMux()
static, _ := fs.Sub(staticFS, "static")
+16
View File
@@ -758,3 +758,19 @@ func TestAboutPage(t *testing.T) {
}
}
}
// Settings → About lists this copy of the app, and work under way.
func TestAboutRunning(t *testing.T) {
s, h := newTestServer(t, nil)
_, release, err := s.jobs().TryLock(context.Background(), "job:seo")
if err != nil {
t.Fatal(err)
}
defer release()
body := do(h, "GET", "/settings/about", nil, nil).Body.String()
for _, want := range []string{"<code>" + s.jobs().ID() + "</code> <span class=\"muted\">(this one)</span>", "<code>job:seo</code>"} {
if !strings.Contains(body, want) {
t.Errorf("no %q", want)
}
}
}
+50 -11
View File
@@ -2,6 +2,7 @@ package web
import (
"context"
"encoding/json"
"html"
"net/http"
"net/url"
@@ -391,26 +392,64 @@ func (s *Server) oauthStart(w http.ResponseWriter, r *http.Request) {
s.serverError(w, err)
return
}
s.mu.Lock()
for state, old := range s.pending {
if time.Since(old.Started) > oauthTTL {
delete(s.pending, state)
// Kept in the database: the callback may reach another copy of the app.
if err := s.DB.PutJSON(oauthFlowKey+p.State, p); err != nil {
s.serverError(w, err)
return
}
}
s.pending[p.State] = p
s.mu.Unlock()
s.forgetOldOAuthFlows()
s.Log.Info("oauth: sign-in started", "provider", provider, "redirect_uri", p.RedirectURI)
http.Redirect(w, r, authURL, http.StatusSeeOther)
}
// OAuth sign-ins under way are kept as settings, by state.
const oauthFlowKey = "oauth:flow:"
// takeOAuthFlow reads and removes the sign-in a callback's state names: a
// state is good for one callback, even if two copies of the app get it.
func (s *Server) takeOAuthFlow(state string) *oauth.Pending {
if state == "" {
return nil
}
var p oauth.Pending
if ok, err := s.DB.GetJSON(oauthFlowKey+state, &p); !ok || err != nil {
return nil
}
res, err := s.DB.Exec(`DELETE FROM settings WHERE key = ?`, oauthFlowKey+state)
if err != nil {
return nil
}
if n, _ := res.RowsAffected(); n != 1 {
return nil // the other copy took it
}
return &p
}
// forgetOldOAuthFlows removes sign-ins never finished.
func (s *Server) forgetOldOAuthFlows() {
rows, err := s.DB.Query(`SELECT key, value FROM settings WHERE key LIKE 'oauth:flow:%'`)
if err != nil {
return
}
var old []string
for rows.Next() {
var key, raw string
var p oauth.Pending
if rows.Scan(&key, &raw) == nil && (json.Unmarshal([]byte(raw), &p) != nil || time.Since(p.Started) > oauthTTL) {
old = append(old, key)
}
}
rows.Close()
for _, k := range old {
s.DB.Exec(`DELETE FROM settings WHERE key = ?`, k)
}
}
func (s *Server) oauthCallback(w http.ResponseWriter, r *http.Request) {
provider := r.PathValue("provider")
q := r.URL.Query()
s.mu.Lock()
p := s.pending[q.Get("state")]
delete(s.pending, q.Get("state")) // a state is good for one callback
s.mu.Unlock()
p := s.takeOAuthFlow(q.Get("state"))
back, nav := "/settings/accounts", "settings/accounts"
if provider == "google" {
back, nav = "/settings/search", "settings/search"
+25 -2
View File
@@ -9,6 +9,7 @@ import (
"net/url"
"strconv"
"strings"
"supermarket/internal/jobs"
"supermarket/internal/sites"
"supermarket/internal/tracking"
"time"
@@ -476,6 +477,14 @@ func (s *Server) importSource(w http.ResponseWriter, r *http.Request) {
// runImport imports from one tool, if its key is saved. It returns nil, nil
// without one.
func (s *Server) runImport(ctx context.Context, source string) (*leadsource.Result, error) {
// One import per tool at a time, across copies of the app.
ctx, release, err := s.jobs().TryLock(ctx, "import:"+source)
if errors.Is(err, jobs.ErrBusy) {
return nil, leadsource.ErrRunning
} else if err != nil {
return nil, err
}
defer release()
now := time.Now()
switch source {
case signals.SourceExplee:
@@ -496,6 +505,7 @@ func (s *Server) RunImports(ctx context.Context) {
tick := time.NewTicker(10 * time.Minute)
defer tick.Stop()
for {
s.jobDo(ctx, "imports", func(ctx context.Context) {
for _, src := range []string{signals.SourceOrigami, signals.SourceExplee} {
last, _ := leadsource.Last(s.DB, src)
if last != nil && time.Since(last.At) < leadsource.Every {
@@ -513,6 +523,7 @@ func (s *Server) RunImports(ctx context.Context) {
"prospects", res.Prospects, "suppressed", res.Suppressed)
}
}
})
select {
case <-ctx.Done():
return
@@ -574,9 +585,17 @@ func (s *Server) discover(sig *signals.Signal, source string) error {
default:
return errors.New("unknown source")
}
// One search per signal and source at a time, across copies of the app.
lctx, release, err := s.jobs().TryLock(context.Background(), fmt.Sprintf("discover:%d:%s", sig.ID, source))
if errors.Is(err, jobs.ErrBusy) {
return discovery.ErrRunning
} else if err != nil {
return err
}
started := make(chan error, 1)
go func() {
ctx, cancel := context.WithTimeout(context.Background(), discoverTimeout)
defer release()
ctx, cancel := context.WithTimeout(lctx, discoverTimeout)
defer cancel()
res, err := run(ctx)
if res == nil {
@@ -639,9 +658,11 @@ func (s *Server) signalRuns(w http.ResponseWriter, r *http.Request) {
// RunDiscovery searches for signals that ask to be searched on a schedule.
func (s *Server) RunDiscovery(ctx context.Context) {
if s.alone() {
if err := discovery.RecoverInterrupted(s.DB); err != nil {
s.Log.Error("discovery: recovering interrupted runs", "err", err)
}
}
tick := time.NewTicker(30 * time.Minute)
defer tick.Stop()
for {
@@ -650,10 +671,11 @@ func (s *Server) RunDiscovery(ctx context.Context) {
return
case <-tick.C:
}
s.jobDo(ctx, "discovery", func(ctx context.Context) {
list, err := signals.List(s.DB)
if err != nil {
s.Log.Error("discovery: listing signals", "err", err)
continue
return
}
for i := range list {
sig := &list[i]
@@ -675,6 +697,7 @@ func (s *Server) RunDiscovery(ctx context.Context) {
}
}
}
})
}
}
+16
View File
@@ -13,4 +13,20 @@
<p class="help">Supermarket also comes as a <strong>server</strong> edition, for a team signing in on a server, and a <strong>multi-tenant</strong> one, for many teams at one address. The edition is chosen with <code>SUPERMARKET_MODE</code> when it starts; <code>supermarket config</code> checks the settings.</p>
{{end}}
</section>
<section class="card">
<h2>Running</h2>
<p class="help">Copies of Supermarket using this database, and the work each has under way. Only one copy does a background job at a time; if one stops, another takes its work over within two minutes.</p>
<table class="list">
<thead><tr><th>Copy</th><th>Host</th><th>Version</th><th>Started</th><th>Last seen</th></tr></thead>
<tbody>
{{range .Copies}}<tr><td><code>{{.ID}}</code>{{if .This}} <span class="muted">(this one)</span>{{end}}</td><td>{{.Host}}</td><td>{{.Version}}</td><td>{{ago .Started}}</td><td>{{ago .Seen}}</td></tr>
{{end}}
</tbody>
</table>
{{if .Locks}}
<h3>Under way</h3>
<ul>{{range .Locks}}<li><code>{{.Name}}</code> on <code>{{.Instance}}</code>, since {{ago .Since}}</li>{{end}}</ul>
{{else}}<p class="muted">No background work under way just now.</p>{{end}}
</section>
{{end}}{{template "settings-end"}}{{end}}
+2
View File
@@ -254,6 +254,7 @@ func (s *Server) RunTracking(ctx context.Context) {
defer tick.Stop()
tried := map[string]time.Time{}
for {
s.jobDo(ctx, "tracking", func(ctx context.Context) {
s.hourlyOptOuts(ctx)
yesterday := time.Now().AddDate(0, 0, -1).Format("2006-01-02")
for _, src := range []string{tracking.SourcePlausible, tracking.SourceStripe} {
@@ -276,6 +277,7 @@ func (s *Server) RunTracking(ctx context.Context) {
}
cancel()
}
})
select {
case <-ctx.Done():
return