Files
lincodex/backend/integration_test/scheduled_jobs_test.go
T

759 lines
31 KiB
Go

//go:build integration
package integration_test
import (
"context"
"errors"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
postgresadapter "lincodex/backend/internal/adapter/secondary/postgres"
"lincodex/backend/internal/adapter/secondary/prometheus"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/inbound"
"lincodex/backend/internal/port/outbound"
"lincodex/backend/internal/worker/jobrunner"
"lincodex/backend/internal/worker/retry"
"lincodex/backend/pkg/testutil"
)
const (
jobTestTimeout = 3 * time.Minute
// jobTestKind is registered only by the test handler.
jobTestKind = "test.effect"
// jobTestLease is long in real time: the fake clock alone decides when
// a lease expired, and a handler never runs out of it by accident.
jobTestLease = time.Minute
jobTestBackoff = time.Second
jobTestGrace = 2 * time.Second
jobTestShortGrace = 200 * time.Millisecond
jobTestMaxAttempts = 3
// jobTestConcurrentJobs is enough jobs for two workers to overlap.
jobTestConcurrentJobs = 40
jobEffectsSchema = "job_test"
jobEffectsTable = "effects"
jobCancelApplication = "job_cancel"
)
var (
jobTestStart = time.Date(2026, 10, 6, 9, 0, 0, 0, time.UTC)
jobEffects = pgx.Identifier{jobEffectsSchema, jobEffectsTable}
createJobEffectsTable = fmt.Sprintf(`
CREATE SCHEMA %[1]s;
-- No unique key: a second effect of a job must stay visible. seq
-- records the commit order of the effects.
CREATE TABLE %[2]s (
seq bigint GENERATED ALWAYS AS IDENTITY,
job_id bigint NOT NULL,
job_key text NOT NULL,
worker text NOT NULL
)`, pgx.Identifier{jobEffectsSchema}.Sanitize(), jobEffects.Sanitize())
errJobEffectFailed = errors.New("job effect failed")
)
// jobEffectHandler is the test-only handler: it writes one effect row in
// the transaction that completes the job, then runs hook in it.
type jobEffectHandler struct {
worker string
hook func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error
}
func (*jobEffectHandler) JobKind() string { return jobTestKind }
func (handler *jobEffectHandler) Handle(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
if !ok {
return errors.New("unit of work is not a PostgreSQL transaction")
}
if _, err := tx.Exec(ctx, "INSERT INTO "+jobEffects.Sanitize()+" (job_id, job_key, worker) VALUES ($1, $2, $3)", job.ID, job.Key, handler.worker); err != nil {
return err
}
if handler.hook == nil {
return nil
}
return handler.hook(ctx, unit, job)
}
// jobHarness schedules jobs through the scheduler port and builds workers
// the way the application does, each with its own pool, against one
// database and one fake clock.
type jobHarness struct {
env *testEnvironment
pool *pgxpool.Pool
clock *testutil.FakeClock
}
// jobInstance is one simulated backend process: its own pool, store, and
// worker. Dropping it and building another one is a restart.
type jobInstance struct {
pool *pgxpool.Pool
store *postgresadapter.ScheduledJobStore
worker *jobrunner.Worker
metrics *prometheus.Metrics
}
func jobTestSettings(grace time.Duration) jobrunner.Settings {
return jobrunner.Settings{
BatchSize: 5,
PollInterval: 10 * time.Millisecond,
Lease: jobTestLease,
MaxAttempts: jobTestMaxAttempts,
Backoff: retry.Backoff{Initial: jobTestBackoff, Max: jobTestBackoff},
ShutdownGrace: grace,
StoreTimeout: 5 * time.Second,
BacklogInterval: time.Second,
}
}
func (harness *jobHarness) start(ctx context.Context, t *testing.T, handler *jobEffectHandler, settings jobrunner.Settings) *jobInstance {
t.Helper()
pool := harness.env.newPool(ctx, t)
store := postgresadapter.NewScheduledJobStore(pool, settings.Lease)
metrics := prometheus.New()
worker, err := jobrunner.New([]inbound.JobHandler{handler}, store, metrics, slog.New(slog.DiscardHandler), settings, harness.clock.Now)
if err != nil {
t.Fatalf("jobrunner.New() error = %v", err)
}
return &jobInstance{pool: pool, store: store, worker: worker, metrics: metrics}
}
// schedule schedules a job of the test kind in its own transaction and
// reports whether it was new.
func (harness *jobHarness) schedule(ctx context.Context, t *testing.T, key string, dueAt time.Time, maxAttempts int) bool {
t.Helper()
job, err := domain.NewScheduledJob(domain.ScheduledJobInput{
Kind: jobTestKind, Key: key, DueAt: dueAt, MaxAttempts: maxAttempts,
Payload: []byte(`{"subject_id":"` + key + `"}`),
})
if err != nil {
t.Fatalf("NewScheduledJob() error = %v", err)
}
var scheduled bool
err = postgresadapter.NewTransactor(harness.pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
scheduled, err = unit.ScheduledJobs().Schedule(ctx, job)
return err
})
if err != nil {
t.Fatalf("Schedule() error = %v", err)
}
return scheduled
}
func (harness *jobHarness) cancel(ctx context.Context, t *testing.T, key string) bool {
t.Helper()
cancelled, err := cancelJob(ctx, harness.pool, key)
if err != nil {
t.Fatalf("Cancel() error = %v", err)
}
return cancelled
}
// cancelJob cancels a job of the test kind in its own transaction on pool.
func cancelJob(ctx context.Context, pool *pgxpool.Pool, key string) (bool, error) {
var cancelled bool
err := postgresadapter.NewTransactor(pool).WithinTransaction(ctx, func(ctx context.Context, unit outbound.UnitOfWork) error {
var err error
cancelled, err = unit.ScheduledJobs().Cancel(ctx, jobTestKind, key)
return err
})
return cancelled, err
}
// stall claims the one due job with a lease owner of its own, as a worker
// that then stops would, and with started also records that its handler
// began. It returns the stale claim.
func (harness *jobHarness) stall(ctx context.Context, t *testing.T, instance *jobInstance, started bool) outbound.ClaimedJob {
t.Helper()
claimed, err := instance.store.Claim(ctx, outbound.JobClaim{
Owner: uuid.New(), Kinds: []string{jobTestKind}, Now: harness.clock.Now(),
Lease: jobTestLease, Limit: 1, DefaultMaxAttempts: jobTestMaxAttempts,
})
if err != nil || len(claimed) != 1 {
t.Fatalf("Claim() = %v, %v; want one job", claimed, err)
}
if !started {
return claimed[0]
}
job, ok, err := instance.store.Start(ctx, claimed[0], harness.clock.Now(), jobTestLease)
if err != nil || !ok {
t.Fatalf("Start() = %t, %v; want started", ok, err)
}
return job
}
type jobRow struct {
id int64
status string
attempts int
dueAt time.Time
availableAt time.Time
errorClass *string
leaseOwner *uuid.UUID
}
func (harness *jobHarness) job(ctx context.Context, t *testing.T, key string) jobRow {
t.Helper()
var row jobRow
err := harness.pool.QueryRow(ctx, `
SELECT id, status, attempts, due_at, available_at, last_error_class, lease_owner
FROM scheduled_jobs WHERE kind = $1 AND dedup_key = $2`, jobTestKind, key).
Scan(&row.id, &row.status, &row.attempts, &row.dueAt, &row.availableAt, &row.errorClass, &row.leaseOwner)
if err != nil {
t.Fatalf("read job %s: %v", key, err)
}
return row
}
// effectKeys returns the job keys of the committed effects in commit order.
func (harness *jobHarness) effectKeys(ctx context.Context, t *testing.T) []string {
t.Helper()
rows, err := harness.pool.Query(ctx, "SELECT job_key FROM "+jobEffects.Sanitize()+" ORDER BY seq")
if err != nil {
t.Fatalf("read effects: %v", err)
}
keys, err := pgx.CollectRows(rows, pgx.RowTo[string])
if err != nil {
t.Fatalf("scan effects: %v", err)
}
return keys
}
func runDueJobs(ctx context.Context, t *testing.T, instance *jobInstance) jobrunner.PassResult {
t.Helper()
result, err := instance.worker.RunDue(ctx)
if err != nil {
t.Fatalf("RunDue() error = %v", err)
}
return result
}
// runWorker runs the worker loop until the returned stop is called, which
// waits for Run to return.
func runWorker(ctx context.Context, t *testing.T, instance *jobInstance) (stop func()) {
t.Helper()
ctx, cancel := context.WithCancel(ctx)
stopped := make(chan struct{})
go func() {
defer close(stopped)
instance.worker.Run(ctx)
}()
var once sync.Once
stop = func() {
once.Do(func() {
cancel()
select {
case <-stopped:
case <-time.After(consumerStopTimeout):
t.Fatal("the job worker did not stop")
}
})
}
t.Cleanup(stop)
return stop
}
func TestScheduledJobs(t *testing.T) {
env := bootstrap(t, postgresService)
ctx, cancel := context.WithTimeout(t.Context(), jobTestTimeout)
defer cancel()
pool := env.newPool(ctx, t)
if _, err := pool.Exec(ctx, createJobEffectsTable); err != nil {
t.Fatalf("create test-only tables: %v", err)
}
// Subtests share the tables and run sequentially; each starts empty
// with a fresh clock.
reset := func(t *testing.T) *jobHarness {
t.Helper()
truncateTables(ctx, t, pool, jobEffects, pgx.Identifier{"scheduled_jobs"})
return &jobHarness{env: env, pool: pool, clock: testutil.NewFakeClock(jobTestStart)}
}
t.Run("jobs on different dates survive restarts and each runs once in due order", func(t *testing.T) {
harness := reset(t)
inThreeDays, tomorrow := jobTestStart.AddDate(0, 0, 3), jobTestStart.AddDate(0, 0, 1)
if !harness.schedule(ctx, t, "later", inThreeDays, 0) || !harness.schedule(ctx, t, "sooner", tomorrow, 0) {
t.Fatal("Schedule() did not create the jobs")
}
// A repeated schedule keeps the first due time.
if harness.schedule(ctx, t, "sooner", jobTestStart, 0) {
t.Fatal("a repeated Schedule() created a second job")
}
first := harness.start(ctx, t, &jobEffectHandler{worker: "first"}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, first); result.Claimed != 0 {
t.Fatalf("a job ran before it was due: %+v", result)
}
// Restart: the first process is gone with its pool; a new one
// finds the jobs in the database.
first.pool.Close()
second := harness.start(ctx, t, &jobEffectHandler{worker: "second"}, jobTestSettings(jobTestGrace))
harness.clock.Advance(24 * time.Hour)
if result := runDueJobs(ctx, t, second); result.Done != 1 {
t.Fatalf("pass after one day = %+v, want one done job", result)
}
if result := runDueJobs(ctx, t, second); result.Claimed != 0 {
t.Fatalf("a done job ran again: %+v", result)
}
second.pool.Close()
third := harness.start(ctx, t, &jobEffectHandler{worker: "third"}, jobTestSettings(jobTestGrace))
harness.clock.Advance(48*time.Hour - time.Microsecond)
if result := runDueJobs(ctx, t, third); result.Claimed != 0 {
t.Fatalf("the later job ran a microsecond early: %+v", result)
}
harness.clock.Advance(time.Microsecond)
if result := runDueJobs(ctx, t, third); result.Done != 1 {
t.Fatalf("pass after three days = %+v, want one done job", result)
}
harness.clock.Advance(30 * 24 * time.Hour)
if result := runDueJobs(ctx, t, third); result.Claimed != 0 {
t.Fatalf("a done job ran again a month later: %+v", result)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "sooner" || keys[1] != "later" {
t.Fatalf("effects = %v, want sooner then later, once each", keys)
}
for _, key := range []string{"sooner", "later"} {
if row := harness.job(ctx, t, key); row.status != "done" || row.attempts != 1 || row.leaseOwner != nil {
t.Fatalf("job %s = %+v, want done after one attempt", key, row)
}
}
if !harness.job(ctx, t, "sooner").dueAt.Equal(tomorrow) {
t.Fatal("the repeated Schedule() moved the due time")
}
})
t.Run("two concurrent workers produce exactly one effect per job", func(t *testing.T) {
harness := reset(t)
for index := range jobTestConcurrentJobs {
harness.schedule(ctx, t, "job-"+strconv.Itoa(index), jobTestStart.Add(-time.Duration(index)*time.Second), 0)
}
slow := func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
// Keeps the two workers' transactions overlapping.
select {
case <-time.After(5 * time.Millisecond):
return nil
case <-ctx.Done():
return ctx.Err()
}
}
left := harness.start(ctx, t, &jobEffectHandler{worker: "left", hook: slow}, jobTestSettings(jobTestGrace))
right := harness.start(ctx, t, &jobEffectHandler{worker: "right", hook: slow}, jobTestSettings(jobTestGrace))
stopLeft, stopRight := runWorker(ctx, t, left), runWorker(ctx, t, right)
waitFor(ctx, t, "every job to be done", func() bool {
var done int
err := pool.QueryRow(ctx, "SELECT count(*) FROM scheduled_jobs WHERE status = 'done'").Scan(&done)
return err == nil && done == jobTestConcurrentJobs
})
stopLeft()
stopRight()
var total, distinct int
var workers []string
err := pool.QueryRow(ctx, "SELECT count(*), count(DISTINCT job_id), array_agg(DISTINCT worker) FROM "+jobEffects.Sanitize()).
Scan(&total, &distinct, &workers)
if err != nil {
t.Fatalf("count effects: %v", err)
}
if total != jobTestConcurrentJobs || distinct != jobTestConcurrentJobs {
t.Fatalf("%d effects for %d distinct jobs, want exactly one for each of %d jobs", total, distinct, jobTestConcurrentJobs)
}
t.Logf("effects were written by workers %v", workers)
})
t.Run("a handler that outlives its lease keeps the job locked and another worker skips it", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "slow", jobTestStart, 0)
inEffect, release := make(chan struct{}), make(chan struct{})
holder := harness.start(ctx, t, &jobEffectHandler{worker: "holder", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
close(inEffect)
return awaitOrCancel(ctx, release, nil)
}}, jobTestSettings(jobTestGrace))
other := harness.start(ctx, t, &jobEffectHandler{worker: "other"}, jobTestSettings(jobTestGrace))
finished := make(chan jobrunner.PassResult, 1)
go func() {
result, _ := holder.worker.RunDue(ctx)
finished <- result
}()
awaitSignal(ctx, t, inEffect, "the first handler to start")
// By the clock the lease expired, but the row is locked by the
// running handler, so the claim skips it instead of running the
// job a second time.
harness.clock.Advance(2 * jobTestLease)
if result := runDueJobs(ctx, t, other); result.Claimed != 0 {
t.Fatalf("another worker claimed a job whose handler is running: %+v", result)
}
close(release)
if result := <-finished; result.Done != 1 {
t.Fatalf("holder pass = %+v, want one done job", result)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 1 {
t.Fatalf("effects = %v, want one", keys)
}
})
t.Run("an expired lease is reclaimed by another worker and the late completion is refused", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "abandoned", jobTestStart, 0)
stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace))
// Worker A starts the job and stops inside it, like a process that
// froze or crashed while its handler ran.
claimed := harness.stall(ctx, t, stalled, true)
reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer"}, jobTestSettings(jobTestGrace))
harness.clock.Advance(jobTestLease - time.Microsecond)
if result := runDueJobs(ctx, t, reclaimer); result.Claimed != 0 {
t.Fatalf("a job was reclaimed before its lease expired: %+v", result)
}
harness.clock.Advance(time.Microsecond)
if result := runDueJobs(ctx, t, reclaimer); result.Done != 1 {
t.Fatalf("pass after the lease expired = %+v, want one done job", result)
}
row := harness.job(ctx, t, "abandoned")
if row.status != "done" || row.attempts != 2 || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorLeaseExpired) {
t.Fatalf("job = %+v, want done on the second attempt after lease_expired", row)
}
// Worker A wakes up: its start, completion, failure record, and
// release are all refused, and its handler never runs.
if _, ok, err := stalled.store.Start(ctx, claimed, harness.clock.Now(), jobTestLease); err != nil || ok {
t.Fatalf("late Start() = %t, %v; want refused", ok, err)
}
ran := false
err := stalled.store.Run(ctx, claimed, func(context.Context, outbound.UnitOfWork) error {
ran = true
return nil
})
if !errors.Is(err, outbound.ErrJobLeaseLost) || ran {
t.Fatalf("late Run() = %v, ran %t; want ErrJobLeaseLost without running", err, ran)
}
if recorded, err := stalled.store.Fail(ctx, claimed, outbound.JobFailure{Class: outbound.JobErrorHandlerFailed, RetryAt: harness.clock.Now()}); err != nil || recorded {
t.Fatalf("late Fail() = %t, %v; want refused", recorded, err)
}
if released, err := stalled.store.Release(ctx, []outbound.ClaimedJob{claimed}); err != nil || len(released) != 0 {
t.Fatalf("late Release() = %v, %v; want refused", released, err)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 1 || harness.job(ctx, t, "abandoned").status != "done" {
t.Fatalf("effects = %v, want one and the job still done", keys)
}
})
t.Run("a started last attempt whose lease expired makes the job dead without running it", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "crashing", jobTestStart, 1)
stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace))
harness.stall(ctx, t, stalled, true)
calls := 0
reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer", hook: func(context.Context, outbound.UnitOfWork, outbound.ClaimedJob) error {
calls++
return nil
}}, jobTestSettings(jobTestGrace))
harness.clock.Advance(jobTestLease)
if result := runDueJobs(ctx, t, reclaimer); result.Dead != 1 || calls != 0 {
t.Fatalf("pass = %+v, handler calls %d; want a dead job without a call", result, calls)
}
row := harness.job(ctx, t, "crashing")
if row.status != "dead" || row.attempts != 1 || row.leaseOwner != nil || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorLeaseExpired) {
t.Fatalf("job = %+v, want dead after one attempt with lease_expired", row)
}
assertJobMetric(t, reclaimer.metrics, "dead", 1)
})
t.Run("a claim that never started is reused, so a single allowed attempt is not lost", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "unstarted", jobTestStart, 1)
stalled := harness.start(ctx, t, &jobEffectHandler{worker: "stalled"}, jobTestSettings(jobTestGrace))
// Worker A claims the job and stops before it started the handler.
harness.stall(ctx, t, stalled, false)
reclaimer := harness.start(ctx, t, &jobEffectHandler{worker: "reclaimer"}, jobTestSettings(jobTestGrace))
harness.clock.Advance(jobTestLease)
if result := runDueJobs(ctx, t, reclaimer); result.Done != 1 {
t.Fatalf("pass = %+v, want the job done", result)
}
if row := harness.job(ctx, t, "unstarted"); row.status != "done" || row.attempts != 1 || row.errorClass != nil {
t.Fatalf("job = %+v, want done on its first counted attempt without an error class", row)
}
})
t.Run("a slow job neither starves nor kills the next job of its batch", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "slow", jobTestStart.Add(-time.Minute), 0)
harness.schedule(ctx, t, "next", jobTestStart, 1)
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(_ context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
if job.Key == "slow" {
// The first job runs past the lease the batch was claimed with.
harness.clock.Advance(2 * jobTestLease)
}
return nil
}}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, worker); result.Claimed != 2 || result.Done != 1 || result.Released != 1 {
t.Fatalf("first pass = %+v, want the slow job done and the next one released", result)
}
if row := harness.job(ctx, t, "next"); row.status != "pending" || row.attempts != 0 || row.leaseOwner != nil {
t.Fatalf("next job = %+v, want pending with its attempt intact", row)
}
if result := runDueJobs(ctx, t, worker); result.Done != 1 {
t.Fatalf("second pass = %+v, want the next job done", result)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "slow" || keys[1] != "next" {
t.Fatalf("effects = %v, want slow then next", keys)
}
})
t.Run("another worker runs a job that a busy worker claimed but did not start", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "slow", jobTestStart.Add(-time.Minute), 0)
harness.schedule(ctx, t, "waiting", jobTestStart, 1)
inSlow, finishSlow := make(chan struct{}), make(chan struct{})
busy := harness.start(ctx, t, &jobEffectHandler{worker: "busy", hook: func(ctx context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
if job.Key != "slow" {
return nil
}
close(inSlow)
return awaitOrCancel(ctx, finishSlow, nil)
}}, jobTestSettings(jobTestGrace))
other := harness.start(ctx, t, &jobEffectHandler{worker: "other"}, jobTestSettings(jobTestGrace))
finished := make(chan jobrunner.PassResult, 1)
go func() {
result, _ := busy.worker.RunDue(ctx)
finished <- result
}()
awaitSignal(ctx, t, inSlow, "the slow job to start")
harness.clock.Advance(2 * jobTestLease)
// The slow job is locked by its handler; the waiting job's attempt
// never started, so the other worker runs it on that same attempt.
if result := runDueJobs(ctx, t, other); result.Claimed != 1 || result.Done != 1 {
t.Fatalf("other worker pass = %+v, want only the waiting job, done", result)
}
close(finishSlow)
if result := <-finished; result.Done != 1 || result.LeaseLost != 1 {
t.Fatalf("busy worker pass = %+v, want its slow job done and the waiting one lost", result)
}
if row := harness.job(ctx, t, "waiting"); row.status != "done" || row.attempts != 1 {
t.Fatalf("waiting job = %+v, want done on its single attempt", row)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 2 {
t.Fatalf("effects = %v, want one per job", keys)
}
})
t.Run("a job that cancels itself is finished and the queue moves on", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "self", jobTestStart.Add(-time.Minute), 0)
harness.schedule(ctx, t, "after", jobTestStart, 0)
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
if job.Key != "self" {
return nil
}
// An expiry that also cancels the deadline job it stands for.
cancelled, err := unit.ScheduledJobs().Cancel(ctx, jobTestKind, job.Key)
if err == nil && !cancelled {
err = errors.New("the running job was not canceled")
}
return err
}}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, worker); result.Done != 2 {
t.Fatalf("pass = %+v, want both jobs done", result)
}
if row := harness.job(ctx, t, "self"); row.status != "cancelled" || row.leaseOwner != nil || row.attempts != 1 {
t.Fatalf("self-canceled job = %+v, want cancelled after one attempt", row)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 2 || keys[0] != "self" {
t.Fatalf("effects = %v, want the self-canceled job's effect committed and the next job run", keys)
}
if result := runDueJobs(ctx, t, worker); result.Claimed != 0 {
t.Fatalf("a self-canceled job was claimed again: %+v", result)
}
})
t.Run("a handler that changes its own job otherwise makes it dead", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "meddling", jobTestStart, 0)
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, unit outbound.UnitOfWork, job outbound.ClaimedJob) error {
tx, ok := postgresadapter.TransactionForIntegrationTest(unit)
if !ok {
return errors.New("unit of work is not a PostgreSQL transaction")
}
_, err := tx.Exec(ctx, `UPDATE scheduled_jobs
SET status = 'done', lease_owner = NULL, lease_expires_at = NULL, started_at = NULL
WHERE id = $1`, job.ID)
return err
}}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, worker); result.Dead != 1 {
t.Fatalf("pass = %+v, want a dead job", result)
}
row := harness.job(ctx, t, "meddling")
if row.status != "dead" || row.errorClass == nil || *row.errorClass != string(outbound.JobErrorCompletionConflict) {
t.Fatalf("job = %+v, want dead with completion_conflict", row)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 0 {
t.Fatalf("effects = %v, want the rolled back attempt to leave none", keys)
}
})
t.Run("graceful shutdown leaves the job not done and reclaimable", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "interrupted", jobTestStart, 0)
inEffect := make(chan struct{})
stopping := harness.start(ctx, t, &jobEffectHandler{worker: "stopping", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
close(inEffect)
// Outlasts the shutdown grace.
<-ctx.Done()
return ctx.Err()
}}, jobTestSettings(jobTestShortGrace))
stop := runWorker(ctx, t, stopping)
awaitSignal(ctx, t, inEffect, "the handler to start")
stop()
// The effect rolled back, the job is not done, and the release
// returned it without counting the attempt.
row := harness.job(ctx, t, "interrupted")
if row.status != "pending" || row.attempts != 0 || row.leaseOwner != nil || row.errorClass != nil {
t.Fatalf("job after shutdown = %+v, want pending without an attempt", row)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 0 {
t.Fatalf("effects after shutdown = %v, want none", keys)
}
next := harness.start(ctx, t, &jobEffectHandler{worker: "next"}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, next); result.Done != 1 {
t.Fatalf("pass after the restart = %+v, want the job done without waiting for a lease", result)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 1 {
t.Fatalf("effects = %v, want one", keys)
}
})
t.Run("a failing job is retried after the backoff and then dead", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "failing", jobTestStart, 2)
var seenDueAt []time.Time
failing := harness.start(ctx, t, &jobEffectHandler{worker: "failing", hook: func(_ context.Context, _ outbound.UnitOfWork, job outbound.ClaimedJob) error {
seenDueAt = append(seenDueAt, job.DueAt)
return errJobEffectFailed
}}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, failing); result.Retried != 1 {
t.Fatalf("first attempt = %+v, want a retry", result)
}
row := harness.job(ctx, t, "failing")
// The retry moves only the claim time; the deadline stays.
wait := row.availableAt.Sub(harness.clock.Now())
if row.status != "failed" || row.attempts != 1 || wait < jobTestBackoff/2 || wait > jobTestBackoff ||
*row.errorClass != string(outbound.JobErrorHandlerFailed) || !row.dueAt.Equal(jobTestStart) {
t.Fatalf("job after the first attempt = %+v, retry in %s", row, wait)
}
if result := runDueJobs(ctx, t, failing); result.Claimed != 0 {
t.Fatal("the job was retried before its backoff passed")
}
harness.clock.Advance(jobTestBackoff)
// The per-job limit of two attempts overrides the default of three.
if result := runDueJobs(ctx, t, failing); result.Dead != 1 {
t.Fatalf("second attempt = %+v, want a dead job", result)
}
if row := harness.job(ctx, t, "failing"); row.status != "dead" || row.attempts != 2 {
t.Fatalf("job = %+v, want dead after two attempts", row)
}
// The handler saw the deadline on the retry too, not the retry time.
if len(seenDueAt) != 2 || !seenDueAt[0].Equal(jobTestStart) || !seenDueAt[1].Equal(jobTestStart) {
t.Fatalf("handler saw due times %v, want %s twice", seenDueAt, jobTestStart)
}
if keys := harness.effectKeys(ctx, t); len(keys) != 0 {
t.Fatalf("failed attempts left effects %v", keys)
}
backlog, err := failing.store.Backlog(ctx, harness.clock.Now())
if err != nil || backlog.Dead != 1 || backlog.Due != 0 {
t.Fatalf("Backlog() = %+v, %v; want one dead job", backlog, err)
}
assertJobMetric(t, failing.metrics, "dead", 1)
assertJobMetric(t, failing.metrics, "retry", 1)
})
t.Run("a canceled job never runs and its key stays reserved", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "withdrawn", jobTestStart, 0)
if !harness.cancel(ctx, t, "withdrawn") {
t.Fatal("Cancel() did not cancel a pending job")
}
if harness.cancel(ctx, t, "withdrawn") || harness.schedule(ctx, t, "withdrawn", jobTestStart, 0) {
t.Fatal("a canceled job was canceled or scheduled again")
}
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker"}, jobTestSettings(jobTestGrace))
if result := runDueJobs(ctx, t, worker); result.Claimed != 0 {
t.Fatalf("a canceled job was claimed: %+v", result)
}
backlog, err := worker.store.Backlog(ctx, harness.clock.Now())
if err != nil || backlog.Due != 0 {
t.Fatalf("Backlog() = %+v, %v; want nothing due", backlog, err)
}
})
t.Run("a cancel waits for a running handler and then finds the job done", func(t *testing.T) {
harness := reset(t)
harness.schedule(ctx, t, "racing", jobTestStart, 0)
inEffect, release := make(chan struct{}), make(chan struct{})
worker := harness.start(ctx, t, &jobEffectHandler{worker: "worker", hook: func(ctx context.Context, _ outbound.UnitOfWork, _ outbound.ClaimedJob) error {
close(inEffect)
return awaitOrCancel(ctx, release, nil)
}}, jobTestSettings(jobTestGrace))
finished := make(chan jobrunner.PassResult, 1)
go func() {
result, _ := worker.worker.RunDue(ctx)
finished <- result
}()
awaitSignal(ctx, t, inEffect, "the handler to start")
cancelPool := env.newPoolWithApplicationName(ctx, t, jobCancelApplication)
type cancelResult struct {
cancelled bool
err error
}
cancelled := make(chan cancelResult, 1)
go func() {
result, err := cancelJob(ctx, cancelPool, "racing")
cancelled <- cancelResult{cancelled: result, err: err}
}()
if waitEvent, waiting := waitForLockWait(ctx, pool, jobCancelApplication); !waiting {
t.Fatalf("the cancel did not wait for the running handler; last wait event %q", waitEvent)
}
close(release)
if result := <-finished; result.Done != 1 {
t.Fatalf("pass = %+v, want the job done", result)
}
if result := <-cancelled; result.err != nil || result.cancelled {
t.Fatalf("Cancel() = %t, %v; want false for a job its handler completed", result.cancelled, result.err)
}
if row := harness.job(ctx, t, "racing"); row.status != "done" {
t.Fatalf("job = %+v, want done", row)
}
})
}
// assertJobMetric reads lincodex_scheduled_jobs_total for the test kind and
// one outcome from the scrape output.
func assertJobMetric(t *testing.T, metrics *prometheus.Metrics, outcome string, want int) {
t.Helper()
prefix := fmt.Sprintf(`lincodex_scheduled_jobs_total{kind=%q,outcome=%q} `, jobTestKind, outcome)
response := httptest.NewRecorder()
metrics.Handler().ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/metrics", nil))
for line := range strings.SplitSeq(response.Body.String(), "\n") {
if value, found := strings.CutPrefix(line, prefix); found {
if value != strconv.Itoa(want) {
t.Fatalf("%s%s, want %d", prefix, value, want)
}
return
}
}
t.Fatalf("metrics output has no series %s", prefix)
}