jobs.go102 lines, 3.2 KB
| 1 | package jobs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "log/slog" |
| 7 | "sync" |
| 8 | "time" |
| 9 | |
| 10 | "github.com/jackc/pgx/v5" |
| 11 | "github.com/jackc/pgx/v5/pgxpool" |
| 12 | "github.com/prometheus/client_golang/prometheus" |
| 13 | "github.com/prometheus/client_golang/prometheus/promauto" |
| 14 | ) |
| 15 | |
| 16 | var runs = promauto.NewCounterVec(prometheus.CounterOpts{ |
| 17 | Name: "job_runs_total", |
| 18 | Help: "Runs of scheduled jobs, by job, and whether they succeeded.", |
| 19 | }, []string{"job", "status"}) |
| 20 | |
| 21 | // A Job is work that runs on a schedule. |
| 22 | type Job struct { |
| 23 | Name string |
| 24 | Every time.Duration // how often: 24 * time.Hour is once a day |
| 25 | At time.Duration // how far into each period: with a day, 2 * time.Hour is 02:00 UTC |
| 26 | // Run does the work, and returns what it found, for the job's history. |
| 27 | Run func(ctx context.Context) (summary any, err error) |
| 28 | } |
| 29 | |
| 30 | // Next returns when j is next due after t: At past a multiple of Every, counted |
| 31 | // from midnight UTC. Every replica works out the same times, without talking. |
| 32 | func (j Job) Next(t time.Time) time.Time { |
| 33 | return t.Add(-j.At).Truncate(j.Every).Add(j.Every + j.At) |
| 34 | } |
| 35 | |
| 36 | // A Runner runs jobs when they're due, and keeps their history in the |
| 37 | // job_runs table, which every service with jobs has. |
| 38 | type Runner struct { |
| 39 | pool *pgxpool.Pool |
| 40 | logger *slog.Logger |
| 41 | jobs []Job |
| 42 | } |
| 43 | |
| 44 | // NewRunner returns a Runner for jobs, with their history in pool's database. |
| 45 | func NewRunner(pool *pgxpool.Pool, logger *slog.Logger, jobs ...Job) *Runner { |
| 46 | return &Runner{pool: pool, logger: logger, jobs: jobs} |
| 47 | } |
| 48 | |
| 49 | // Run runs each job whenever it's due, until ctx is done. Only the leader |
| 50 | // calls it. |
| 51 | func (r *Runner) Run(ctx context.Context) { |
| 52 | var wg sync.WaitGroup |
| 53 | for _, j := range r.jobs { |
| 54 | wg.Go(func() { |
| 55 | for { |
| 56 | slot := j.Next(time.Now()) |
| 57 | select { |
| 58 | case <-ctx.Done(): |
| 59 | return |
| 60 | case <-time.After(time.Until(slot)): |
| 61 | r.run(ctx, j, slot) |
| 62 | } |
| 63 | } |
| 64 | }) |
| 65 | } |
| 66 | wg.Wait() |
| 67 | } |
| 68 | |
| 69 | // run runs j for slot, once. The slot is claimed first: if it's already in |
| 70 | // job_runs, someone else ran it, or is running it. |
| 71 | func (r *Runner) run(ctx context.Context, j Job, slot time.Time) { |
| 72 | var id int64 |
| 73 | err := r.pool.QueryRow(ctx, `INSERT INTO job_runs (job, slot) VALUES ($1, $2) |
| 74 | ON CONFLICT (job, slot) DO NOTHING RETURNING id`, j.Name, slot).Scan(&id) |
| 75 | if errors.Is(err, pgx.ErrNoRows) { |
| 76 | return |
| 77 | } |
| 78 | if err != nil { |
| 79 | r.logger.ErrorContext(ctx, "claim a job run", "job", j.Name, "err", err) |
| 80 | return |
| 81 | } |
| 82 | // A run must finish before the next one is due, so runs never overlap. |
| 83 | runCtx, cancel := context.WithDeadline(ctx, j.Next(slot)) |
| 84 | start := time.Now() |
| 85 | summary, err := j.Run(runCtx) |
| 86 | cancel() |
| 87 | |
| 88 | status, took := "succeeded", time.Since(start).Round(time.Millisecond) |
| 89 | if err != nil { |
| 90 | status, summary = "failed", map[string]string{"error": err.Error()} |
| 91 | r.logger.ErrorContext(ctx, "job failed", "job", j.Name, "took", took, "err", err) |
| 92 | } else { |
| 93 | r.logger.InfoContext(ctx, "job succeeded", "job", j.Name, "took", took) |
| 94 | } |
| 95 | runs.WithLabelValues(j.Name, status).Inc() |
| 96 | // Even when ctx is done: the history must say how the run ended. |
| 97 | _, err = r.pool.Exec(context.WithoutCancel(ctx), `UPDATE job_runs |
| 98 | SET status = $2, summary = $3, finished_at = now() WHERE id = $1`, id, status, summary) |
| 99 | if err != nil { |
| 100 | r.logger.ErrorContext(ctx, "record a job run", "job", j.Name, "err", err) |
| 101 | } |
| 102 | } |