media: bound each pass call; unknown image age is null
Task 8 fix round 1 (Astra P1, P2). P1: mediajobs.New wraps the engine, grants and store guard so every external call runs under its own child deadline (EngineCallTimeout 30 s, EngineListTimeout 60 s, GrantsCallTimeout 30 s, StoreCheckTimeout 30 s). The caller's context carries on to the next row, phase and pass, so one stalled call no longer stops conversion deployment-wide. A timeout takes each call's existing failure path. Deps.CallTimeout overrides the bounds for tests. TestMediaPassOutlivesAStalledCall and TestEveryCallIsBounded cover it. P2: system media status reports age_days null when the image build date is missing or malformed, and with an engine configured fails the "image" check as "error: no build date" (the deck's check_error line).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+450
−17
internal/console/apisystem.go+14 −5internal/console/mediapass.go+19 −6internal/console/mediapass_test.go+98 −4internal/console/mediawire.go+2 −0internal/console/server.go+4 −0internal/mediajobs/bounds.go+161 −0internal/mediajobs/bounds_test.go+143 −0internal/mediajobs/jobs.go+9 −2
CI failed — run details
diff --git a/internal/console/apisystem.go b/internal/console/apisystem.go| index e5cfaef75..c39185e7d 100644 |
| --- a/internal/console/apisystem.go |
| +++ b/internal/console/apisystem.go |
| @@ -291,9 +291,11 @@ func (s *Server) handleAPISystemPDFGet(w http.ResponseWriter, r *http.Request) { |
| // handleAPISystemMediaGet answers `carlos system media status` (spec §5.5, |
| // §9): whether the conversion engine is set up and in which region, the |
| -// image it runs and that image's age, each class's revision check, the |
| -// queue, the running tasks and the last 24 hours' results. A person on |
| -// either operator list reads it; it writes nothing. |
| +// image it runs and that image's age in days (null when its build date is |
| +// missing or unreadable, which with an engine configured fails the |
| +// "image" check), each class's revision check, the queue, the running |
| +// tasks and the last 24 hours' results. A person on either operator list |
| +// reads it; it writes nothing. |
| func (s *Server) handleAPISystemMediaGet(w http.ResponseWriter, r *http.Request) { |
| if !s.apiSystemStatusReader(w, r, mediaText("system_media.forbidden")) { |
| return |
| @@ -306,6 +308,13 @@ func (s *Server) handleAPISystemMediaGet(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| img := s.cfg.MediaImage |
| + checks := s.mediaChecks(r.Context()) |
| + var ageDays any // null when the build date is unknown, never 0 |
| + if days, ok := mediaImageAgeDays(img.BuiltAt, now); ok { |
| + ageDays = days |
| + } else if s.cfg.MediaEngine != nil { |
| + checks[mediaImageCheck] = mediaNoBuildDate |
| + } |
| writeJSON(w, http.StatusOK, map[string]any{ |
| "configured": s.mediaConfigured(), |
| "region": s.cfg.MediaRegion, |
| @@ -313,9 +322,9 @@ func (s *Server) handleAPISystemMediaGet(w http.ResponseWriter, r *http.Request) |
| "digest": img.Digest, |
| "built_at": img.BuiltAt, |
| "ffmpeg": img.FFmpeg, |
| - "age_days": mediaImageAgeDays(img.BuiltAt, now), |
| + "age_days": ageDays, |
| }, |
| - "checks": s.mediaChecks(r.Context()), |
| + "checks": checks, |
| "queued": sum.Queued, |
| "running": sum.Running, |
| "done_24h": sum.Done24h, |
diff --git a/internal/console/mediapass.go b/internal/console/mediapass.go| index ef9301feb..f707bf8b4 100644 |
| --- a/internal/console/mediapass.go |
| +++ b/internal/console/mediapass.go |
| @@ -106,12 +106,25 @@ func (s *Server) mediaChecks(ctx context.Context) map[string]string { |
| } |
| // mediaImageAgeDays is how many whole days ago the engine image was built |
| -// (ImageInfo.BuiltAt, RFC 3339): 0 for a build date in the future, and 0 |
| -// when the date is missing or unreadable. |
| -func mediaImageAgeDays(builtAt string, now time.Time) int { |
| +// (ImageInfo.BuiltAt, RFC 3339), 0 for a build date in the future. ok is |
| +// false when the date is missing or unreadable: the age is unknown, never |
| +// 0 (Task 8 fix round 1, P2). |
| +func mediaImageAgeDays(builtAt string, now time.Time) (days int, ok bool) { |
| t, err := time.Parse(time.RFC3339, builtAt) |
| - if err != nil || !now.After(t) { |
| - return 0 |
| + if err != nil { |
| + return 0, false |
| } |
| - return int(now.Sub(t) / (24 * time.Hour)) |
| + if !now.After(t) { |
| + return 0, true |
| + } |
| + return int(now.Sub(t) / (24 * time.Hour)), true |
| } |
| + |
| +// mediaImageCheck is the "image" check of system media status, made when |
| +// an engine is configured: a missing or unreadable build date fails it as |
| +// a check that could not be read, "error: no build date" (the deck's |
| +// cli.system_media.check_error line), since its staleness cannot be told. |
| +const ( |
| + mediaImageCheck = "image" |
| + mediaNoBuildDate = "error: no build date" |
| +) |
diff --git a/internal/console/mediapass_test.go b/internal/console/mediapass_test.go| index 4072a04ff..ba6efc243 100644 |
| --- a/internal/console/mediapass_test.go |
| +++ b/internal/console/mediapass_test.go |
| @@ -10,6 +10,7 @@ import ( |
| "reflect" |
| "slices" |
| "strings" |
| + "sync/atomic" |
| "testing" |
| "time" |
| @@ -362,7 +363,7 @@ func TestSystemMediaStatus(t *testing.T) { |
| status, out := getJSON(t, fx.ts.URL+path, token) |
| want := map[string]any{ |
| "configured": false, "region": "", |
| - "image": map[string]any{"digest": "", "built_at": "", "ffmpeg": "", "age_days": float64(0)}, |
| + "image": map[string]any{"digest": "", "built_at": "", "ffmpeg": "", "age_days": nil}, |
| "checks": map[string]any{}, |
| "queued": map[string]any{"short": float64(0), "long": float64(0)}, |
| "running": map[string]any{"short": float64(0), "long": float64(0)}, |
| @@ -372,6 +373,28 @@ func TestSystemMediaStatus(t *testing.T) { |
| t.Fatalf("status = %d, body = %#v\nwant 200, %#v", status, out, want) |
| } |
| }) |
| + // P2 (Task 8 fix round 1): with an engine configured, a missing or |
| + // malformed build date leaves the age unknown (null, never 0) and |
| + // fails the image check with the check_error line's reason. |
| + for name, built := range map[string]string{"missing build date": "", "malformed build date": "last tuesday"} { |
| + t.Run(name, func(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-status-"+strings.ReplaceAll(name, " ", "-")) |
| + f.srv.cfg.MediaImage = media.ImageInfo{Digest: "sha256:9f2c", BuiltAt: built, FFmpeg: "7.1.2"} |
| + status, out := getJSON(t, f.ts.URL+path, f.member) |
| + if status != http.StatusOK { |
| + t.Fatalf("status = %d %v", status, out) |
| + } |
| + image, _ := out["image"].(map[string]any) |
| + if age, ok := image["age_days"]; !ok || age != nil { |
| + t.Errorf("age_days = %#v (present %v), want null", age, ok) |
| + } |
| + want := map[string]any{"image": "error: no build date", |
| + "video-720p/short": "ok", "video-720p/long": "ok", "audio-aac/short": "ok", "audio-aac/long": "ok"} |
| + if !reflect.DeepEqual(out["checks"], want) { |
| + t.Errorf("checks = %#v, want %#v", out["checks"], want) |
| + } |
| + }) |
| + } |
| t.Run("database error is generic", func(t *testing.T) { |
| fx, token := systemArmed(t, "code-media-status-db") |
| if _, err := fx.st.db.Exec(`DROP TABLE media_jobs`); err != nil { |
| @@ -385,6 +408,7 @@ func TestSystemMediaStatus(t *testing.T) { |
| t.Run("each check times out at 5 s, together", func(t *testing.T) { |
| f := newMediaDoor(t, "code-media-status-slow") |
| f.srv.cfg.MediaEngine = &mediaCheckEngine{Engine: f.engine, block: true} |
| + f.srv.cfg.MediaImage = media.ImageInfo{Digest: "sha256:9f2c", BuiltAt: f.clock.Format(time.RFC3339), FFmpeg: "7.1.2"} |
| start := time.Now() |
| status, out := getJSON(t, f.ts.URL+path, f.member) |
| if elapsed := time.Since(start); elapsed < 4*time.Second || elapsed > 8*time.Second { |
| @@ -406,10 +430,14 @@ func TestMediaImageAgeDays(t *testing.T) { |
| now := time.Date(2026, 11, 17, 12, 0, 0, 0, time.UTC) |
| for built, want := range map[string]int{ |
| "2026-11-17T11:00:00Z": 0, "2026-11-16T12:00:00Z": 1, "2026-10-01T00:00:00Z": 47, |
| - "2026-11-18T00:00:00Z": 0, "": 0, "yesterday": 0, |
| + "2026-11-18T00:00:00Z": 0, "": -1, "yesterday": -1, |
| } { |
| - if got := mediaImageAgeDays(built, now); got != want { |
| - t.Errorf("mediaImageAgeDays(%q) = %d, want %d", built, got, want) |
| + got, ok := mediaImageAgeDays(built, now) |
| + if !ok { |
| + got = -1 // unknown |
| + } |
| + if got != want { |
| + t.Errorf("mediaImageAgeDays(%q) = %d, %v; want %d (-1 is unknown)", built, got, ok, want) |
| } |
| } |
| } |
| @@ -455,3 +483,69 @@ func TestMediaJobsClaimSQLRefused(t *testing.T) { |
| t.Fatal(err) |
| } |
| } |
| + |
| +// stallingEngine is the fake engine with one execution's ListByStartedBy |
| +// waiting until its context ends, as a call to a stalled endpoint would. |
| +type stallingEngine struct { |
| + media.Engine |
| + stall string |
| + stalled atomic.Int64 |
| +} |
| + |
| +func (e *stallingEngine) ListByStartedBy(ctx context.Context, execution string) (media.Task, bool, error) { |
| + if execution == e.stall { |
| + e.stalled.Add(1) |
| + <-ctx.Done() |
| + return media.Task{}, false, ctx.Err() |
| + } |
| + return e.Engine.ListByStartedBy(ctx, execution) |
| +} |
| + |
| +// TestMediaPassOutlivesAStalledCall (Task 8 fix round 1, P1): one |
| +// account's engine call waits until its context is cancelled; the other |
| +// account's row still progresses in the same pass, the pass ends, and the |
| +// next tick runs. |
| +func TestMediaPassOutlivesAStalledCall(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-pass-stall") |
| + eng := &stallingEngine{Engine: f.engine, stall: "exec-a"} |
| + f.srv.cfg.MediaEngine = eng |
| + f.srv.mediaCallTimeout = 100 * time.Millisecond |
| + f.srv.media = f.srv.newMediaJobs() |
| + // Account b's task exists; neither row has its ARN yet (a crash |
| + // between RunTask and saving it), so the pass recovers both by |
| + // execution id, account a's first. |
| + arn, err := f.engine.Run(context.Background(), media.RunRequest{Execution: "exec-b", DeadlineS: 600, GrantExpiry: f.clock.Add(time.Hour)}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, r := range []struct{ account, exec string }{{"acct-a", "exec-a"}, {"acct-b", "exec-b"}} { |
| + if _, err := f.st.db.Exec(`INSERT INTO media_jobs |
| + (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at, |
| + execution_id, dispatched_at, granted_s, deadline_s, task_stopped) |
| + VALUES (?, 'titogo', 'i', 'j', 'uploads/a.mov', 'e', 1, 'video-720p', 'short', 'b', 'running', ?, ?, ?, 600, 600, 0)`, |
| + r.account, f.clock.UnixMilli(), r.exec, f.clock.UnixMilli()); err != nil { |
| + t.Fatal(err) |
| + } |
| + } |
| + taskARN := func(account string) (string, string) { |
| + var a, state string |
| + if err := f.st.db.QueryRow(`SELECT task_arn, state FROM media_jobs WHERE account = ?`, account).Scan(&a, &state); err != nil { |
| + t.Fatal(err) |
| + } |
| + return a, state |
| + } |
| + w := startMediaPass(f) |
| + if got, state := taskARN("acct-b"); got != arn || state != "running" { |
| + t.Fatalf("account b's row after pass 1: task %q, %s; want %q, running", got, state, arn) |
| + } |
| + if got, state := taskARN("acct-a"); got != "" || state != "running" { |
| + t.Fatalf("account a's row after its stalled call: task %q, %s; want it left as it was", got, state) |
| + } |
| + if n := eng.stalled.Load(); n != 1 { |
| + t.Fatalf("account a's call stalled %d times in pass 1, want 1", n) |
| + } |
| + w.tick(2, time.Second) |
| + if n := eng.stalled.Load(); n != 2 { |
| + t.Fatalf("account a's call stalled %d times after pass 2, want 2: the next tick ran", n) |
| + } |
| +} |
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go| index 9fdfb7067..e83692f78 100644 |
| --- a/internal/console/mediawire.go |
| +++ b/internal/console/mediawire.go |
| @@ -46,6 +46,8 @@ func (s *Server) newMediaJobs() *mediajobs.Jobs { |
| // A deleted or reaped account's remaining rows are retired by the |
| // pass once its tasks are confirmed stopped (Task 7 fix round 2). |
| AccountGone: s.mediaAccountGone, |
| + // 0 in production: the mediajobs bounds (bounds.go). |
| + CallTimeout: s.mediaCallTimeout, |
| }) |
| } |
diff --git a/internal/console/server.go b/internal/console/server.go| index ac05582ec..9b2bb2a16 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1714,6 +1714,10 @@ type Server struct { |
| // (mediapass.go): nil is a tick every media.PassEvery. Tests set it; |
| // nothing in production does. |
| mediaPassTicks <-chan time.Time |
| + // mediaCallTimeout, when positive, replaces the mediajobs bound on each |
| + // engine, grants and store call (newMediaJobs). Tests set it; nothing |
| + // in production does. |
| + mediaCallTimeout time.Duration |
| // recordView is the record view the run and seed sweeps read through |
| // (recordview.go), set by SetRecordView when CARLOS_CHANGE_INDEX=read |
diff --git a/internal/mediajobs/bounds.go b/internal/mediajobs/bounds.go| new file mode 100644 |
| index 000000000..c26c15c63 |
| --- /dev/null |
| +++ b/internal/mediajobs/bounds.go |
| @@ -0,0 +1,161 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// Each external call the job table makes runs under its own deadline, a |
| +// child of the caller's context cancelled when the call returns, so one |
| +// stalled call costs one row its turn and never the pass: the next row, |
| +// the next phase and the next pass go on under the caller's context |
| +// (Task 8 fix round 1). A whole-pass deadline would not do, as a row whose |
| +// call stalls every time would spend every pass's budget. |
| +// |
| +// A call that times out answers the context's error, which every caller |
| +// already treats as a failed call: a Describe leaves its rows as they are, |
| +// a Run is ambiguous and the row goes to recovery, a Grant is a retryable |
| +// launch rejection, a CheckRevision keeps the class's rows queued, a store |
| +// check keeps the row queued, a result read or output HEAD leaves the row |
| +// for the next pass, a Stop is logged and retried on the next pass, and a |
| +// cleanup delete keeps cleanup_due. |
| +// |
| +// Allowance and AccountGone are not bounded here: in the console they read |
| +// its own SQLite database, which takes no context, and no network. |
| +const ( |
| + // EngineCallTimeout bounds one engine request: RunTask, DescribeTasks |
| + // (up to describeBatch ARNs), StopTask or the revision check. ECS |
| + // answers in well under a second; 30 s leaves room for the SDK's own |
| + // retries with backoff and still frees the pass within a few ticks. |
| + EngineCallTimeout = 30 * time.Second |
| + // EngineListTimeout bounds ListByStartedBy, which is several ECS |
| + // requests in one call: two paginated ListTasks (RUNNING and STOPPED) |
| + // and their DescribeTasks. Twice the single-request bound. |
| + EngineListTimeout = 60 * time.Second |
| + // GrantsCallTimeout bounds one object call: a HEAD, a presign of five |
| + // transfers (which may first refresh the conversion role's credentials |
| + // through STS), a result read of at most media.MaxResultBytes, or a |
| + // delete of at most three keys. Each is one or two small S3 or STS |
| + // requests; 30 s is the same allowance for retries as the engine's. |
| + GrantsCallTimeout = 30 * time.Second |
| + // StoreCheckTimeout bounds dispatch's re-check of an app's store: the |
| + // store record's GET and the bucket's tag and configuration reads, a |
| + // handful of S3 requests made under the app's store walk lock, which a |
| + // stalled read would otherwise hold against every teardown of that |
| + // app. |
| + StoreCheckTimeout = 30 * time.Second |
| +) |
| + |
| +// callTimeouts are the bounds one Jobs applies. |
| +type callTimeouts struct{ engine, list, grants, store time.Duration } |
| + |
| +func timeoutsFor(d Deps) callTimeouts { |
| + if d.CallTimeout > 0 { |
| + return callTimeouts{d.CallTimeout, d.CallTimeout, d.CallTimeout, d.CallTimeout} |
| + } |
| + return callTimeouts{EngineCallTimeout, EngineListTimeout, GrantsCallTimeout, StoreCheckTimeout} |
| +} |
| + |
| +// bound wraps d's engine, grants and store guard so every call carries its |
| +// deadline. A nil collaborator stays nil: the job table reads nil as "not |
| +// configured". |
| +func bound(d Deps) Deps { |
| + t := timeoutsFor(d) |
| + if d.Engine != nil { |
| + d.Engine = boundedEngine{d.Engine, t} |
| + } |
| + if d.Grants != nil { |
| + d.Grants = boundedGrants{d.Grants, t.grants} |
| + } |
| + if d.Stores != nil { |
| + d.Stores = boundedStores{d.Stores, t.store} |
| + } |
| + return d |
| +} |
| + |
| +type boundedEngine struct { |
| + e media.Engine |
| + t callTimeouts |
| +} |
| + |
| +func (b boundedEngine) Run(ctx context.Context, req media.RunRequest) (string, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.t.engine) |
| + defer cancel() |
| + return b.e.Run(ctx, req) |
| +} |
| + |
| +func (b boundedEngine) Describe(ctx context.Context, arns []string) ([]media.Task, []string, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.t.engine) |
| + defer cancel() |
| + return b.e.Describe(ctx, arns) |
| +} |
| + |
| +func (b boundedEngine) ListByStartedBy(ctx context.Context, execution string) (media.Task, bool, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.t.list) |
| + defer cancel() |
| + return b.e.ListByStartedBy(ctx, execution) |
| +} |
| + |
| +func (b boundedEngine) Stop(ctx context.Context, arn, reason string) error { |
| + ctx, cancel := context.WithTimeout(ctx, b.t.engine) |
| + defer cancel() |
| + return b.e.Stop(ctx, arn, reason) |
| +} |
| + |
| +func (b boundedEngine) CheckRevision(ctx context.Context, class media.ClassKey) error { |
| + ctx, cancel := context.WithTimeout(ctx, b.t.engine) |
| + defer cancel() |
| + return b.e.CheckRevision(ctx, class) |
| +} |
| + |
| +type boundedGrants struct { |
| + g media.Grants |
| + d time.Duration |
| +} |
| + |
| +func (b boundedGrants) Head(ctx context.Context, bucket, key string) (media.ObjectHead, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.d) |
| + defer cancel() |
| + return b.g.Head(ctx, bucket, key) |
| +} |
| + |
| +func (b boundedGrants) Grant(ctx context.Context, r media.GrantRequest) (media.Transfers, time.Time, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.d) |
| + defer cancel() |
| + return b.g.Grant(ctx, r) |
| +} |
| + |
| +func (b boundedGrants) ReadResult(ctx context.Context, execution string) ([]byte, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.d) |
| + defer cancel() |
| + return b.g.ReadResult(ctx, execution) |
| +} |
| + |
| +func (b boundedGrants) DeleteResult(ctx context.Context, execution string) error { |
| + ctx, cancel := context.WithTimeout(ctx, b.d) |
| + defer cancel() |
| + return b.g.DeleteResult(ctx, execution) |
| +} |
| + |
| +func (b boundedGrants) DeleteOutputs(ctx context.Context, bucket string, keys []string) error { |
| + ctx, cancel := context.WithTimeout(ctx, b.d) |
| + defer cancel() |
| + return b.g.DeleteOutputs(ctx, bucket, keys) |
| +} |
| + |
| +// boundedStores bounds Current only: Lock is the console's in-process walk |
| +// lock, not a call out. |
| +type boundedStores struct { |
| + s StoreGuard |
| + d time.Duration |
| +} |
| + |
| +func (b boundedStores) Lock(account, app string) func() { return b.s.Lock(account, app) } |
| + |
| +func (b boundedStores) Current(ctx context.Context, account, app string) (StoreFacts, error) { |
| + ctx, cancel := context.WithTimeout(ctx, b.d) |
| + defer cancel() |
| + return b.s.Current(ctx, account, app) |
| +} |
diff --git a/internal/mediajobs/bounds_test.go b/internal/mediajobs/bounds_test.go| new file mode 100644 |
| index 000000000..c69ea7c1d |
| --- /dev/null |
| +++ b/internal/mediajobs/bounds_test.go |
| @@ -0,0 +1,143 @@ |
| +package mediajobs |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// stall is every collaborator at once: each call waits until its context |
| +// ends and answers the context's error. It records the deadline it saw. |
| +type stall struct{ deadlines map[string]time.Duration } |
| + |
| +func (s *stall) wait(ctx context.Context, name string) error { |
| + dl, ok := ctx.Deadline() |
| + if !ok { |
| + s.deadlines[name] = -1 |
| + } else { |
| + s.deadlines[name] = time.Until(dl) |
| + } |
| + <-ctx.Done() |
| + return ctx.Err() |
| +} |
| + |
| +func (s *stall) Run(ctx context.Context, _ media.RunRequest) (string, error) { |
| + return "", s.wait(ctx, "Run") |
| +} |
| +func (s *stall) Describe(ctx context.Context, _ []string) ([]media.Task, []string, error) { |
| + return nil, nil, s.wait(ctx, "Describe") |
| +} |
| +func (s *stall) ListByStartedBy(ctx context.Context, _ string) (media.Task, bool, error) { |
| + return media.Task{}, false, s.wait(ctx, "ListByStartedBy") |
| +} |
| +func (s *stall) Stop(ctx context.Context, _, _ string) error { return s.wait(ctx, "Stop") } |
| +func (s *stall) CheckRevision(ctx context.Context, _ media.ClassKey) error { |
| + return s.wait(ctx, "CheckRevision") |
| +} |
| +func (s *stall) Head(ctx context.Context, _, _ string) (media.ObjectHead, error) { |
| + return media.ObjectHead{}, s.wait(ctx, "Head") |
| +} |
| +func (s *stall) Grant(ctx context.Context, _ media.GrantRequest) (media.Transfers, time.Time, error) { |
| + return media.Transfers{}, time.Time{}, s.wait(ctx, "Grant") |
| +} |
| +func (s *stall) ReadResult(ctx context.Context, _ string) ([]byte, error) { |
| + return nil, s.wait(ctx, "ReadResult") |
| +} |
| +func (s *stall) DeleteResult(ctx context.Context, _ string) error { return s.wait(ctx, "DeleteResult") } |
| +func (s *stall) DeleteOutputs(ctx context.Context, _ string, _ []string) error { |
| + return s.wait(ctx, "DeleteOutputs") |
| +} |
| +func (s *stall) Lock(string, string) func() { return func() {} } |
| +func (s *stall) Current(ctx context.Context, _, _ string) (StoreFacts, error) { |
| + return StoreFacts{}, s.wait(ctx, "Current") |
| +} |
| + |
| +// TestEveryCallIsBounded: each engine, grants and store call the job table |
| +// makes gets its own deadline, and a stalled call returns the context's |
| +// error once it passes, with the caller's context still live. The default |
| +// bounds are the named constants. |
| +func TestEveryCallIsBounded(t *testing.T) { |
| + want := map[string]time.Duration{ |
| + "Run": EngineCallTimeout, "Describe": EngineCallTimeout, "Stop": EngineCallTimeout, "CheckRevision": EngineCallTimeout, |
| + "ListByStartedBy": EngineListTimeout, |
| + "Head": GrantsCallTimeout, "Grant": GrantsCallTimeout, "ReadResult": GrantsCallTimeout, |
| + "DeleteResult": GrantsCallTimeout, "DeleteOutputs": GrantsCallTimeout, |
| + "Current": StoreCheckTimeout, |
| + } |
| + for _, tc := range []struct { |
| + name string |
| + timeout time.Duration |
| + check func(t *testing.T, call string, saw time.Duration) |
| + }{ |
| + {"defaults", 0, func(t *testing.T, call string, saw time.Duration) { |
| + if saw <= want[call]-time.Second || saw > want[call] { |
| + t.Errorf("%s saw a deadline %s away, want %s", call, saw, want[call]) |
| + } |
| + }}, |
| + {"override", 20 * time.Millisecond, func(t *testing.T, call string, saw time.Duration) { |
| + if saw < 0 || saw > 20*time.Millisecond { |
| + t.Errorf("%s saw a deadline %s away, want 20ms", call, saw) |
| + } |
| + }}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + s := &stall{deadlines: map[string]time.Duration{}} |
| + d := bound(Deps{Engine: s, Grants: s, Stores: s, CallTimeout: tc.timeout}) |
| + // The closures read ctx when called, so the defaults case can |
| + // give each call its own caller context. |
| + ctx := context.Background() |
| + calls := map[string]func() error{ |
| + "Run": func() error { _, err := d.Engine.Run(ctx, media.RunRequest{}); return err }, |
| + "Describe": func() error { _, _, err := d.Engine.Describe(ctx, nil); return err }, |
| + "ListByStartedBy": func() error { _, _, err := d.Engine.ListByStartedBy(ctx, "x"); return err }, |
| + "Stop": func() error { return d.Engine.Stop(ctx, "a", "r") }, |
| + "CheckRevision": func() error { return d.Engine.CheckRevision(ctx, media.ClassKey{}) }, |
| + "Head": func() error { _, err := d.Grants.Head(ctx, "b", "k"); return err }, |
| + "Grant": func() error { _, _, err := d.Grants.Grant(ctx, media.GrantRequest{}); return err }, |
| + "ReadResult": func() error { _, err := d.Grants.ReadResult(ctx, "x"); return err }, |
| + "DeleteResult": func() error { return d.Grants.DeleteResult(ctx, "x") }, |
| + "DeleteOutputs": func() error { return d.Grants.DeleteOutputs(ctx, "b", nil) }, |
| + "Current": func() error { _, err := d.Stores.Current(ctx, "a", "p"); return err }, |
| + } |
| + if len(calls) != len(want) { |
| + t.Fatalf("%d calls for %d bounds", len(calls), len(want)) |
| + } |
| + if tc.timeout == 0 { |
| + // The defaults are too long to wait out: each call runs under |
| + // a caller context cancelled once it has recorded its |
| + // deadline. |
| + for name, call := range calls { |
| + c, cancel := context.WithCancel(context.Background()) |
| + ctx = c |
| + go func() { time.Sleep(10 * time.Millisecond); cancel() }() |
| + if err := call(); !errors.Is(err, context.Canceled) { |
| + t.Errorf("%s answered %v, want the caller's cancellation", name, err) |
| + } |
| + tc.check(t, name, s.deadlines[name]) |
| + } |
| + return |
| + } |
| + for name, call := range calls { |
| + if err := call(); !errors.Is(err, context.DeadlineExceeded) { |
| + t.Errorf("%s answered %v, want its own deadline exceeded", name, err) |
| + } |
| + tc.check(t, name, s.deadlines[name]) |
| + if ctx.Err() != nil { |
| + t.Fatal("a call's deadline ended the caller's context") |
| + } |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestBoundLeavesNilCollaboratorsNil: an unconfigured engine, grants or |
| +// store guard stays nil, which the job table reads as not configured. |
| +func TestBoundLeavesNilCollaboratorsNil(t *testing.T) { |
| + d := bound(Deps{}) |
| + if d.Engine != nil || d.Grants != nil || d.Stores != nil { |
| + t.Fatalf("bound(Deps{}) = %+v, want nil collaborators", d) |
| + } |
| +} |
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go| index 8dcdb03ab..0a80db59a 100644 |
| --- a/internal/mediajobs/jobs.go |
| +++ b/internal/mediajobs/jobs.go |
| @@ -84,6 +84,11 @@ type Deps struct { |
| // reaped). The pass asks it only of accounts retireGone's query picks; |
| // nil asks nothing. |
| AccountGone func(ctx context.Context, account string) (bool, error) |
| + // CallTimeout, when positive, bounds every engine, grants and store |
| + // call in place of EngineCallTimeout, EngineListTimeout, |
| + // GrantsCallTimeout and StoreCheckTimeout (bounds.go). Tests shorten |
| + // it; production leaves it 0. |
| + CallTimeout time.Duration |
| } |
| // Jobs is the job table and its pass. |
| @@ -92,9 +97,11 @@ type Jobs struct { |
| d Deps |
| } |
| -// New is the job table over db, whose schema includes Schema. |
| +// New is the job table over db, whose schema includes Schema. Every call |
| +// it makes to d's engine, grants and store guard carries its own deadline |
| +// (bounds.go). |
| func New(db DB, d Deps) *Jobs { |
| - return &Jobs{db: db, d: d} |
| + return &Jobs{db: db, d: bound(d)} |
| } |
| // SubmitRequest is one admitted job, as the door resolved it under the |