// 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 { // :<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 }