jobs.go249 lines, 7.3 KB
| 1 | // Package jobs is a job queue in Postgres: work that is saved now, and done later by a worker. |
| 2 | package jobs |
| 3 | |
| 4 | import ( |
| 5 | "context" |
| 6 | "errors" |
| 7 | "fmt" |
| 8 | "log/slog" |
| 9 | "math/rand/v2" |
| 10 | "sync" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/jackc/pgx/v5" |
| 14 | "github.com/jackc/pgx/v5/pgconn" |
| 15 | "github.com/jackc/pgx/v5/pgxpool" |
| 16 | ) |
| 17 | |
| 18 | // DB is what Enqueue writes through: a pool, or a transaction. |
| 19 | type DB interface { |
| 20 | Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) |
| 21 | } |
| 22 | |
| 23 | // Enqueue saves a job. In a transaction, it's saved only if that commits. |
| 24 | func Enqueue(ctx context.Context, db DB, kind string, payload any) error { |
| 25 | _, err := db.Exec(ctx, `insert into jobs (kind, payload, created_at, run_at) values ($1, $2, $3, $3)`, |
| 26 | kind, payload, time.Now()) |
| 27 | return err |
| 28 | } |
| 29 | |
| 30 | // MaxAttempts is how often a job is tried before it's dead. |
| 31 | const MaxAttempts = 5 |
| 32 | |
| 33 | // The wait before the next try starts at baseWait, doubles every time, and stops at maxWait. |
| 34 | const ( |
| 35 | baseWait = time.Second |
| 36 | maxWait = time.Minute |
| 37 | ) |
| 38 | |
| 39 | // backoff is how long a job waits after a failed attempt. r is a random number, |
| 40 | // from 0 up to 1, and it picks a wait between half of the full one and all of it. |
| 41 | func backoff(attempt int, r float64) time.Duration { |
| 42 | wait := baseWait |
| 43 | for i := 1; i < attempt && wait < maxWait; i++ { |
| 44 | wait *= 2 |
| 45 | } |
| 46 | wait = min(wait, maxWait) |
| 47 | return wait/2 + time.Duration(r*float64(wait/2)) |
| 48 | } |
| 49 | |
| 50 | // A Handler does one kind of job. An error means the job is tried again. |
| 51 | type Handler func(ctx context.Context, payload []byte) error |
| 52 | |
| 53 | // A Worker claims jobs, one at a time, and runs them. |
| 54 | type Worker struct { |
| 55 | db *pgxpool.Pool |
| 56 | handlers map[string]Handler |
| 57 | done tally |
| 58 | now func() time.Time // the worker's clock. A test can set its own |
| 59 | |
| 60 | // Ended hears about every job that ends: how long it waited, how long it ran, |
| 61 | // and the error if it failed. Nobody has to listen. |
| 62 | Ended func(kind string, waited, ran time.Duration, err error) |
| 63 | } |
| 64 | |
| 65 | func NewWorker(db *pgxpool.Pool) *Worker { |
| 66 | return &Worker{ |
| 67 | db: db, handlers: map[string]Handler{}, now: time.Now, |
| 68 | Ended: func(string, time.Duration, time.Duration, error) {}, |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | // Handle says which func runs jobs of this kind. |
| 73 | func (w *Worker) Handle(kind string, h Handler) { |
| 74 | w.handlers[kind] = h |
| 75 | } |
| 76 | |
| 77 | type job struct { |
| 78 | id int64 |
| 79 | kind string |
| 80 | payload []byte |
| 81 | queued time.Time |
| 82 | attempt int // which try this is, counted by the claim |
| 83 | } |
| 84 | |
| 85 | // claim takes the waiting job that is due first and marks it running, in one statement. |
| 86 | func (w *Worker) claim(ctx context.Context) (job, error) { |
| 87 | var j job |
| 88 | err := w.db.QueryRow(ctx, ` |
| 89 | update jobs set status = 'running', attempts = attempts + 1, claimed_at = $1 |
| 90 | where id = ( |
| 91 | select id |
| 92 | from jobs |
| 93 | where status = 'waiting' and run_at <= $1 |
| 94 | order by run_at, id |
| 95 | limit 1 |
| 96 | for update skip locked |
| 97 | ) |
| 98 | returning id, kind, payload, attempts, created_at`, w.now()). |
| 99 | Scan(&j.id, &j.kind, &j.payload, &j.attempt, &j.queued) |
| 100 | return j, err |
| 101 | } |
| 102 | |
| 103 | // fail writes down a failed attempt. The job waits for its next try, or it's dead. |
| 104 | func (w *Worker) fail(ctx context.Context, j job, cause error) error { |
| 105 | if j.attempt >= MaxAttempts { |
| 106 | _, err := w.db.Exec(ctx, `update jobs set status = 'dead', last_error = $2 where id = $1`, |
| 107 | j.id, cause.Error()) |
| 108 | return err |
| 109 | } |
| 110 | at := w.now().Add(backoff(j.attempt, rand.Float64())) |
| 111 | _, err := w.db.Exec(ctx, ` |
| 112 | update jobs set status = 'waiting', run_at = $2, last_error = $3 |
| 113 | where id = $1`, j.id, at, cause.Error()) |
| 114 | return err |
| 115 | } |
| 116 | |
| 117 | // Sweep takes back every job that has been running for longer than timeout, |
| 118 | // because its worker is gone. It returns how many jobs that were. |
| 119 | func (w *Worker) Sweep(ctx context.Context, timeout time.Duration) (int64, error) { |
| 120 | tag, err := w.db.Exec(ctx, ` |
| 121 | update jobs |
| 122 | set status = case when attempts >= $2 then 'dead' else 'waiting' end, |
| 123 | last_error = 'its worker went away' |
| 124 | where status = 'running' and claimed_at < $1`, w.now().Add(-timeout), MaxAttempts) |
| 125 | return tag.RowsAffected(), err |
| 126 | } |
| 127 | |
| 128 | // RunOne claims one job and runs it. It returns false when no job is due. |
| 129 | func (w *Worker) RunOne(ctx context.Context) (bool, error) { |
| 130 | j, err := w.claim(ctx) |
| 131 | if errors.Is(err, pgx.ErrNoRows) { |
| 132 | return false, nil |
| 133 | } |
| 134 | if err != nil { |
| 135 | return false, fmt.Errorf("claim a job: %w", err) |
| 136 | } |
| 137 | start := w.now() |
| 138 | h, ok := w.handlers[j.kind] |
| 139 | if !ok { |
| 140 | err = errors.New("no handler") |
| 141 | } else { |
| 142 | err = h(ctx, j.payload) |
| 143 | } |
| 144 | w.Ended(j.kind, start.Sub(j.queued), w.now().Sub(start), err) |
| 145 | if err != nil { |
| 146 | back := w.fail(ctx, j, err) |
| 147 | err = fmt.Errorf("job %d (%s), attempt %d of %d: %w", j.id, j.kind, j.attempt, MaxAttempts, err) |
| 148 | return true, errors.Join(err, back) |
| 149 | } |
| 150 | _, err = w.db.Exec(ctx, `delete from jobs where id = $1`, j.id) |
| 151 | if err == nil { |
| 152 | w.done.add(w.now().Sub(j.queued)) |
| 153 | } |
| 154 | return true, err |
| 155 | } |
| 156 | |
| 157 | // Run works through the queue with n loops side by side, until ctx is cancelled. |
| 158 | // A job that has been running for longer than timeout goes back to the queue. |
| 159 | // After the cancel, no loop takes a new job, and Run returns when the jobs in hand are done. |
| 160 | // A job that needs longer than grace for that is cut off. A sweep will find it. |
| 161 | func (w *Worker) Run(ctx context.Context, n int, poll, timeout, grace time.Duration) { |
| 162 | // Jobs get a context of their own, so a cancel doesn't stop them halfway. |
| 163 | work, cut := context.WithCancel(context.WithoutCancel(ctx)) |
| 164 | defer cut() |
| 165 | go func() { |
| 166 | <-ctx.Done() |
| 167 | select { |
| 168 | case <-time.After(grace): |
| 169 | slog.Warn("out of time, jobs in hand are cut off") |
| 170 | cut() |
| 171 | case <-work.Done(): |
| 172 | } |
| 173 | }() |
| 174 | var loops sync.WaitGroup |
| 175 | for range n { |
| 176 | loops.Go(func() { w.loop(ctx, work, poll) }) |
| 177 | } |
| 178 | idle := make(chan struct{}) |
| 179 | go func() { |
| 180 | loops.Wait() |
| 181 | close(idle) |
| 182 | }() |
| 183 | w.tend(work, idle, timeout) |
| 184 | } |
| 185 | |
| 186 | // tend does what the loops share: it sweeps, and it reports. |
| 187 | func (w *Worker) tend(ctx context.Context, idle <-chan struct{}, timeout time.Duration) { |
| 188 | sweep, report := time.NewTicker(timeout/2), time.NewTicker(every) |
| 189 | defer sweep.Stop() |
| 190 | defer report.Stop() |
| 191 | w.sweep(ctx, timeout) |
| 192 | last := time.Now() |
| 193 | for { |
| 194 | select { |
| 195 | case <-sweep.C: |
| 196 | w.sweep(ctx, timeout) |
| 197 | case <-report.C: |
| 198 | w.report(time.Since(last)) |
| 199 | last = time.Now() |
| 200 | case <-idle: |
| 201 | w.report(time.Since(last)) |
| 202 | return |
| 203 | } |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | // loop claims a job and runs it, again and again. With nothing due, it sleeps for poll. |
| 208 | func (w *Worker) loop(ctx, work context.Context, poll time.Duration) { |
| 209 | for ctx.Err() == nil { |
| 210 | // A job that has started is finished, even after a cancel. |
| 211 | ok, err := w.RunOne(work) |
| 212 | if err != nil { |
| 213 | slog.Error("job failed", "error", err) |
| 214 | } |
| 215 | if ok { |
| 216 | continue |
| 217 | } |
| 218 | select { |
| 219 | case <-ctx.Done(): |
| 220 | case <-time.After(poll): |
| 221 | } |
| 222 | } |
| 223 | } |
| 224 | |
| 225 | // sweep is one Sweep, and a line in the log when it found something. |
| 226 | func (w *Worker) sweep(ctx context.Context, timeout time.Duration) { |
| 227 | n, err := w.Sweep(ctx, timeout) |
| 228 | if err != nil { |
| 229 | slog.Error("sweep failed", "error", err) |
| 230 | } else if n > 0 { |
| 231 | slog.Info("jobs swept", "count", n) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | // every is how often a worker reports what it got done. |
| 236 | const every = 5 * time.Second |
| 237 | |
| 238 | // report logs what got done since the last report. |
| 239 | func (w *Worker) report(over time.Duration) { |
| 240 | waits := w.done.take() |
| 241 | n := len(waits) |
| 242 | if n == 0 { |
| 243 | return |
| 244 | } |
| 245 | slog.Info("jobs done", "count", n, "over", over.Round(100*time.Millisecond).String(), |
| 246 | "per_second", int(float64(n)/over.Seconds()), |
| 247 | "median_wait", waits[n/2].Round(time.Millisecond).String(), |
| 248 | "longest_wait", waits[n-1].Round(time.Millisecond).String()) |
| 249 | } |