console: media pass worker and system status
StartMediaPass runs mediajobs' Pass through s.jobs.Run every media.PassEvery, on the console clock. It returns at once with no engine, and logs and returns on a host-claim console. It is registered as a claim worker, labelled "Media conversion" and started in cmd/console beside StartScanPass (pre-flight F11). GET /api/cli/system/media (closed to service credentials) answers operators the engine's region, image and age in days, each class's revision check, the queue, running tasks and 24 hours of results. The key is checks (F12): "ok", "refused: <check>" for a Misconfigured revision, or "error: <reason>" for a transport error or the 5 s timeout (F13). The four checks run concurrently. claimWriterReasons gains sql/media_jobs, which no host-claim door reaches by design, with TestMediaJobsClaimSQLRefused as its witness.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
16 files changed,
+645
−2
cmd/console/main.go+5 −0internal/console/apisystem.go+35 −0internal/console/apisystem_test.go+1 −0internal/console/claim_invariant_fixtures_test.go+2 −0internal/console/claim_invariant_probes_read_test.go+1 −0internal/console/claim_invariant_probes_worker_test.go+5 −0internal/console/claim_invariant_test.go+4 −0internal/console/claim_workers.go+1 −0internal/console/jobs.go+1 −0internal/console/media_copy.go+6 −0internal/console/mediapass.go+117 −0internal/console/mediapass_test.go+457 −0internal/console/routedecls.go+1 −0internal/console/server.go+4 −0internal/console/svcroutes_test.go+3 −2internal/console/testdata/claim-routes.txt+2 −0
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 1237af9b7..470c9974a 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -858,6 +858,11 @@ func serve() { |
| // from the sweep above and not a phase inside it: a queue phase behind a |
| // sequential per-app budget would starve for as long as the sweep takes. |
| startClaimWorker("StartScanDrain") |
| + // The media conversion pass (internal/console/mediapass.go): recover, |
| + // track, dispatch, clean up and prune media_jobs every 5 seconds. Same |
| + // placement rule again. It returns immediately with no media engine |
| + // configured, and on a host-claim console. |
| + startClaimWorker("StartMediaPass") |
| // The temporary-app expiry pass (internal/console/expirypass.go). Same |
| // placement rule as every pass above: started here, never in NewServer. |
| startClaimWorker("StartExpiryPass") |
diff --git a/internal/console/apisystem.go b/internal/console/apisystem.go| index 6ebdaf574..e5cfaef75 100644 |
| --- a/internal/console/apisystem.go |
| +++ b/internal/console/apisystem.go |
| @@ -289,6 +289,41 @@ func (s *Server) handleAPISystemPDFGet(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusOK, out) |
| } |
| +// 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. |
| +func (s *Server) handleAPISystemMediaGet(w http.ResponseWriter, r *http.Request) { |
| + if !s.apiSystemStatusReader(w, r, mediaText("system_media.forbidden")) { |
| + return |
| + } |
| + now := s.now() |
| + sum, err := s.media.Summary(r.Context(), now) |
| + if err != nil { |
| + log.Printf("console: system media summary: %v", err) |
| + jsonError(w, http.StatusInternalServerError, "internal error") |
| + return |
| + } |
| + img := s.cfg.MediaImage |
| + writeJSON(w, http.StatusOK, map[string]any{ |
| + "configured": s.mediaConfigured(), |
| + "region": s.cfg.MediaRegion, |
| + "image": map[string]any{ |
| + "digest": img.Digest, |
| + "built_at": img.BuiltAt, |
| + "ffmpeg": img.FFmpeg, |
| + "age_days": mediaImageAgeDays(img.BuiltAt, now), |
| + }, |
| + "checks": s.mediaChecks(r.Context()), |
| + "queued": sum.Queued, |
| + "running": sum.Running, |
| + "done_24h": sum.Done24h, |
| + "failed_24h": sum.Failed24h, |
| + "failed_by_code_24h": sum.FailedByCode, |
| + }) |
| +} |
| + |
| func systemPDFEngineStatus(ctx context.Context, addr string) (string, error) { |
| engine, err := url.Parse(addr) |
| if err != nil || engine.Scheme != "http" || engine.Hostname() == "" { |
diff --git a/internal/console/apisystem_test.go b/internal/console/apisystem_test.go| index 731b6f15e..3030353be 100644 |
| --- a/internal/console/apisystem_test.go |
| +++ b/internal/console/apisystem_test.go |
| @@ -330,6 +330,7 @@ func TestSystemStatusDoorsAdmitEitherOperator(t *testing.T) { |
| handler func(*Server, http.ResponseWriter, *http.Request) |
| }{ |
| {"pdf", "/api/cli/system/pdf", "pdf status", (*Server).handleAPISystemPDFGet}, |
| + {"media", "/api/cli/system/media", "media status", (*Server).handleAPISystemMediaGet}, |
| {"antivirus", systemAntivirusURL, "antivirus status", (*Server).handleAPISystemAntivirusGet}, |
| } |
| for _, door := range doors { |
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go| index 10b4c46af..78aa94587 100644 |
| --- a/internal/console/claim_invariant_fixtures_test.go |
| +++ b/internal/console/claim_invariant_fixtures_test.go |
| @@ -927,6 +927,7 @@ var claimFixtures = map[string]claimFixture{ |
| "route GET /api/cli/system/jobs/{id}": claimRead("reads a system update job"), |
| "route GET /api/cli/system/layout": claimRead("reads the deployment layout intent"), |
| "route GET /api/cli/system/pdf": claimRead("reads PDF engine health, version and render counts; writes nothing"), |
| + "route GET /api/cli/system/media": claimRead("reads the media engine's revision checks and the media_jobs counts; writes nothing"), |
| "route GET /api/cli/system/pointer-digests": claimRead("operator report of each account's pointer digest marker and the channels whose head has no digest; writes nothing"), |
| "route GET /api/cli/system/status": claimRead("reads platform release status"), |
| "route GET /api/cli/system/backups": claimRead("the operator restore tests page as JSON: instance records, status objects and the restore-test reader's records; writes nothing"), |
| @@ -2500,6 +2501,7 @@ var claimFixtures = map[string]claimFixture{ |
| "worker LinkSync": claimNonApp("writes linked deployments' channels in the hub registry from the console's links rows, and records the sync on those rows; names no app"), |
| "worker PublishMovesConsole": claimNonApp("the moves console record (control/moves-console.json): the platform's moves protocol and key fingerprint; no app, and nothing with the moves switch off and no secrets key"), |
| "worker ReportApexSquats": claimRead("logs apex squats found in the registry; writes nothing"), |
| + "worker StartMediaPass": claimRead("off on a host-claim console: media conversion refuses claims mode and the worker returns at once"), |
| "worker StartRunSweep": claimRead("off on a host-claim console, where every run route refuses: it logs that and writes nothing"), |
| "worker StartSeedsPass": claimRead("off on a host-claim console, where every seed door and finishSeed refuse: it logs that and writes nothing"), |
| "worker StartLifetimesCutoverWatch": claimRead("off on a host-claim console, where lifetimes are not for it: it logs that and reads nothing"), |
diff --git a/internal/console/claim_invariant_probes_read_test.go b/internal/console/claim_invariant_probes_read_test.go| index 4cc42ab6a..8d51467f3 100644 |
| --- a/internal/console/claim_invariant_probes_read_test.go |
| +++ b/internal/console/claim_invariant_probes_read_test.go |
| @@ -372,6 +372,7 @@ var claimReadProbes = map[string]claimProbe{ |
| "route GET /api/cli/system/managed-fleets": claimAPIRead(nil, "/api/cli/system/managed-fleets", `"enabled":false`), |
| "route GET /api/cli/system/antivirus": claimAPIRead(nil, "/api/cli/system/antivirus", `"wired":true`), |
| "route GET /api/cli/system/pdf": claimAPIRead(nil, "/api/cli/system/pdf", `"configured":false`, `"rendered_24h":0`, `"refused_24h":0`, `"failed_24h":0`), |
| + "route GET /api/cli/system/media": claimAPIRead(nil, "/api/cli/system/media", `"configured":false`, `"checks":{}`, `"done_24h":0`, `"failed_24h":0`), |
| "route GET /api/cli/system/backups": claimAPIRead(nil, "/api/cli/system/backups", `"loaded":false`, `"regions":[`), |
| "route GET /api/cli/system/geoip": func() claimProbe { |
| p := claimAPIRead(claimWorldGeoip, "/api/cli/system/geoip", `"pointer"`, "GeoIP2-City") |
diff --git a/internal/console/claim_invariant_probes_worker_test.go b/internal/console/claim_invariant_probes_worker_test.go| index 007d82750..dd6718499 100644 |
| --- a/internal/console/claim_invariant_probes_worker_test.go |
| +++ b/internal/console/claim_invariant_probes_worker_test.go |
| @@ -21,6 +21,7 @@ import ( |
| "github.com/carlosframework/platform/internal/hostfloor" |
| "github.com/carlosframework/platform/internal/hostops" |
| "github.com/carlosframework/platform/internal/infraview" |
| + "github.com/carlosframework/platform/internal/media/mediatest" |
| "github.com/carlosframework/platform/internal/metrics" |
| "github.com/carlosframework/platform/internal/moves" |
| "github.com/carlosframework/platform/internal/plans" |
| @@ -87,6 +88,10 @@ var claimWorkerProbes = map[string]claimProbe{ |
| "worker StartLifetimesCutoverWatch": claimLogWorkerProbe("StartLifetimesCutoverWatch", nil, "lifetimes cutover watch", "host-claim console"), |
| "worker StartLifetimeRecoveryPass": claimLogWorkerProbe("StartLifetimeRecoveryPass", nil, "lifetime recovery pass", "host-claim console"), |
| "worker StartIncarnationMigrationPass": claimLogWorkerProbe("StartIncarnationMigrationPass", nil, "incarnation migration pass", "host-claim console"), |
| + "worker StartMediaPass": claimLogWorkerProbe("StartMediaPass", func(t *testing.T, cx *claimCase) { |
| + // With an engine, so the worker reaches its host-claim refusal. |
| + cx.srv.cfg.MediaEngine = mediatest.NewFakeEngine(time.Now) |
| + }, "media pass", "host-claim console"), |
| "worker LogPlacementDiscrepancies": claimLogWorkerProbe("LogPlacementDiscrepancies", claimRegionalApp, |
| msgPlacementDiscrepancy("drift.go.tito.io", "blog", "uk")), |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index 284331ac6..29486973d 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -230,6 +230,10 @@ var claimWriterReasons = map[string]string{ |
| "sql/demo_job_outbox": "anonymous demo dispatch refuses claims mode; TestDemoSQLClaimsRefuseBuildState proves every write is denied even with an app permit", |
| "bucket/PutFrom": "the only console streaming caller is geoippublish.go, which writes deployment GeoIP blobs, not app state; app-prefixed fallback writes are checked by Put and the streaming new-door witness", |
| + "sql/media_jobs": "media conversion refuses claims mode (spec §11 A1): both media doors answer 503 claims_console before any row, " + |
| + "StartMediaPass returns at once on a host-claim console, and the claim gate refuses every media_jobs write (Refuse); " + |
| + "TestMediaJobsClaimSQLRefused proves writes are denied even with an app permit", |
| + |
| "bucket/Delete": "the data boundary never sends an unconditional delete: Delete reads the exact revision, " + |
| "authorizes it and issues DeleteIfMatch, which bucket/DeleteIfMatch counts", |
| "versioned/PutIfAbsent": "no console door calls it: the console imports neither internal/park nor internal/hostbox, " + |
diff --git a/internal/console/claim_workers.go b/internal/console/claim_workers.go| index 139668ec7..8c1385ebf 100644 |
| --- a/internal/console/claim_workers.go |
| +++ b/internal/console/claim_workers.go |
| @@ -13,6 +13,7 @@ func (s *Server) registerClaimWorkers() { |
| "StartInfraPass": s.StartInfraPass, |
| "StartScanPass": s.StartScanPass, |
| "StartScanDrain": s.StartScanDrain, |
| + "StartMediaPass": s.StartMediaPass, |
| "StartExpiryPass": s.StartExpiryPass, |
| "StartPlanLimitsPass": s.StartPlanLimitsPass, |
| "StartPlanGracePass": s.StartPlanGracePass, |
diff --git a/internal/console/jobs.go b/internal/console/jobs.go| index fc26aea09..46889c6b6 100644 |
| --- a/internal/console/jobs.go |
| +++ b/internal/console/jobs.go |
| @@ -306,6 +306,7 @@ var jobLabels = map[string]string{ |
| "StartInfraPass": "Architecture", |
| "StartScanPass": "Virus scan", |
| "StartScanDrain": "Scan queue", |
| + "StartMediaPass": mediaCopy["jobs.label.media_pass"], |
| "StartExpiryPass": "Temporary app expiry", |
| "StartPlanLimitsPass": "Plan limits", |
| "StartPlanGracePass": "Plan grace", |
diff --git a/internal/console/media_copy.go b/internal/console/media_copy.go| index 5f901f650..740be02f9 100644 |
| --- a/internal/console/media_copy.go |
| +++ b/internal/console/media_copy.go |
| @@ -73,6 +73,12 @@ var mediaCopy = map[string]string{ |
| // account deletion (pre-flight F23). |
| "media.retire_pending": "Conversions for “%s” are still stopping. Try again in a minute.", |
| "media.retire_pending_account": "This account’s conversions are still stopping. Try again in a minute.", |
| + |
| + // Operator surfaces: the pass worker's name on the operator pages' |
| + // job list, and system media status's refusal for a person on |
| + // neither operator list (403). |
| + "jobs.label.media_pass": "Media conversion", |
| + "system_media.forbidden": "media status needs a deployment operator (CARLOS_SYSTEM_OPERATORS or CARLOS_STORE_OPERATORS)", |
| } |
| // mediaJobAliases are the deck's "door copy" job rows: a failed job's |
diff --git a/internal/console/mediapass.go b/internal/console/mediapass.go| new file mode 100644 |
| index 000000000..ef9301feb |
| --- /dev/null |
| +++ b/internal/console/mediapass.go |
| @@ -0,0 +1,117 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "errors" |
| + "log" |
| + "sync" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| +) |
| + |
| +// StartMediaPass runs the media job table's pass (internal/mediajobs Pass) |
| +// once at start and then every media.PassEvery: recover rows with no task |
| +// ARN, track running tasks, dispatch and launch, retire gone accounts, |
| +// clean up and prune (spec §5.3). It holds no state of its own: every pass |
| +// reads its work from media_jobs, so a restart loses nothing. |
| +// |
| +// A console with no media engine returns at once: no row is ever |
| +// admitted there, and none is tracked or launched. A host-claim console |
| +// returns at once too, and says so: both media doors refuse claims mode |
| +// (spec §11 A1), so it has no rows of its own to run. |
| +func (s *Server) StartMediaPass(ctx context.Context) { |
| + if s.cfg.MediaEngine == nil { |
| + return |
| + } |
| + if s.cfg.HostClaim { |
| + log.Print("console: media pass: off on a host-claim console, where media conversion is refused") |
| + return |
| + } |
| + ticks, stop := s.mediaPassTicks, func() {} |
| + if ticks == nil { |
| + t := time.NewTicker(media.PassEvery) |
| + ticks, stop = t.C, t.Stop |
| + } |
| + defer stop() |
| + for { |
| + if err := s.jobs.Run(ctx, "StartMediaPass", s.mediaPass); err != nil { |
| + log.Printf("console: media pass: %v", err) |
| + } |
| + select { |
| + case <-ctx.Done(): |
| + return |
| + case <-ticks: |
| + } |
| + } |
| +} |
| + |
| +// mediaPass is one pass on the console's clock, the one the door stamps |
| +// submissions with. |
| +func (s *Server) mediaPass(ctx context.Context) error { |
| + return s.media.Pass(ctx, s.now()) |
| +} |
| + |
| +// mediaCheckTimeout bounds each class's CheckRevision in system media |
| +// status. |
| +const mediaCheckTimeout = 5 * time.Second |
| + |
| +// mediaStatusClasses are the class rows system media status checks, in the |
| +// order the deck prints them. |
| +var mediaStatusClasses = []media.ClassKey{ |
| + {Preset: media.PresetVideo720p, Class: media.ClassShort}, |
| + {Preset: media.PresetVideo720p, Class: media.ClassLong}, |
| + {Preset: media.PresetAudioAAC, Class: media.ClassShort}, |
| + {Preset: media.PresetAudioAAC, Class: media.ClassLong}, |
| +} |
| + |
| +// mediaChecks asks the engine's refusal gate about each class's current |
| +// task definition revision, all at once, each bounded by |
| +// mediaCheckTimeout. A class answers "ok"; "refused: <check>" when the |
| +// gate refuses it (*media.Misconfigured), the jobs that dispatch skips; |
| +// or "error: <reason>" when the revision could not be read at all (a |
| +// transport error or the timeout, pre-flight F13), the jobs that wait. A |
| +// console with no engine answers no classes. |
| +func (s *Server) mediaChecks(ctx context.Context) map[string]string { |
| + out := map[string]string{} |
| + eng := s.cfg.MediaEngine |
| + if eng == nil { |
| + return out |
| + } |
| + var mu sync.Mutex |
| + var wg sync.WaitGroup |
| + for _, k := range mediaStatusClasses { |
| + wg.Add(1) |
| + go func() { |
| + defer wg.Done() |
| + cctx, cancel := context.WithTimeout(ctx, mediaCheckTimeout) |
| + defer cancel() |
| + v := "ok" |
| + if err := eng.CheckRevision(cctx, k); err != nil { |
| + var mis *media.Misconfigured |
| + if errors.As(err, &mis) { |
| + v = "refused: " + mis.Check |
| + } else { |
| + log.Printf("console: system media status: revision check %s: %v", k, err) |
| + v = "error: " + err.Error() |
| + } |
| + } |
| + mu.Lock() |
| + out[k.String()] = v |
| + mu.Unlock() |
| + }() |
| + } |
| + wg.Wait() |
| + return out |
| +} |
| + |
| +// 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 { |
| + t, err := time.Parse(time.RFC3339, builtAt) |
| + if err != nil || !now.After(t) { |
| + return 0 |
| + } |
| + return int(now.Sub(t) / (24 * time.Hour)) |
| +} |
diff --git a/internal/console/mediapass_test.go b/internal/console/mediapass_test.go| new file mode 100644 |
| index 000000000..4072a04ff |
| --- /dev/null |
| +++ b/internal/console/mediapass_test.go |
| @@ -0,0 +1,457 @@ |
| +package console |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "errors" |
| + "fmt" |
| + "net/http" |
| + "path/filepath" |
| + "reflect" |
| + "slices" |
| + "strings" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/media" |
| + "github.com/carlosframework/platform/internal/media/mediatest" |
| +) |
| + |
| +// mediaPassWorker is StartMediaPass running on f's console through |
| +// RunClaimWorker, its passes driven by tick. |
| +type mediaPassWorker struct { |
| + f *mediaDoorFixture |
| + ticks chan time.Time |
| +} |
| + |
| +// startMediaPass starts the worker; it runs its first pass at once. The |
| +// test's cleanup stops it and waits for it to return. |
| +func startMediaPass(f *mediaDoorFixture) *mediaPassWorker { |
| + f.t.Helper() |
| + w := &mediaPassWorker{f: f, ticks: make(chan time.Time)} |
| + f.srv.mediaPassTicks = w.ticks |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + done := make(chan struct{}) |
| + go func() { |
| + defer close(done) |
| + f.srv.RunClaimWorker(ctx, "StartMediaPass") |
| + }() |
| + f.t.Cleanup(func() { cancel(); <-done }) |
| + w.wait(1) |
| + return w |
| +} |
| + |
| +// tick advances the clock by d and runs pass n (the first is 1). |
| +func (w *mediaPassWorker) tick(n int64, d time.Duration) { |
| + w.f.t.Helper() |
| + w.f.clock = w.f.clock.Add(d) |
| + w.ticks <- w.f.clock |
| + w.wait(n) |
| +} |
| + |
| +// wait blocks until the worker has finished n passes, and fails if the |
| +// last one failed. |
| +func (w *mediaPassWorker) wait(n int64) { |
| + w.f.t.Helper() |
| + deadline := time.Now().Add(10 * time.Second) |
| + for { |
| + for _, st := range w.f.srv.jobs.Snapshot() { |
| + if st.Name != "StartMediaPass" || st.Runs < n { |
| + continue |
| + } |
| + if st.State != JobOK { |
| + w.f.t.Fatalf("pass %d: %s", n, st.Err) |
| + } |
| + return |
| + } |
| + if time.Now().After(deadline) { |
| + w.f.t.Fatalf("the worker did not finish pass %d", n) |
| + } |
| + time.Sleep(5 * time.Millisecond) |
| + } |
| +} |
| + |
| +// mediaPassRow is the one job row's facts the codec needs. |
| +type mediaPassRow struct { |
| + id, key, etag, preset, bucket, execution, arn string |
| +} |
| + |
| +func (f *mediaDoorFixture) onlyRow() mediaPassRow { |
| + f.t.Helper() |
| + var r mediaPassRow |
| + if err := f.st.db.QueryRow(`SELECT job_id, key, etag, preset, bucket, execution_id, task_arn FROM media_jobs`). |
| + Scan(&r.id, &r.key, &r.etag, &r.preset, &r.bucket, &r.execution, &r.arn); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + return r |
| +} |
| + |
| +// outputKeys are the row's three output keys in the app's bucket. |
| +func (r mediaPassRow) outputKeys() []string { |
| + prefix := media.OutputPrefix(r.key, r.etag, r.preset, r.execution) |
| + var keys []string |
| + for _, n := range media.OutputNames(r.preset) { |
| + keys = append(keys, prefix+n) |
| + } |
| + return keys |
| +} |
| + |
| +// codecWrites puts the three outputs in the bucket, as the codec uploads |
| +// them, and the result object: a success naming them, or the handler code |
| +// failed. |
| +func (f *mediaDoorFixture) codecWrites(r mediaPassRow, failed string) { |
| + f.t.Helper() |
| + res := media.Result{V: media.ResultVersion, Execution: r.execution, Error: failed} |
| + if failed == "" { |
| + res.Source, res.FFmpeg = &media.SourceFacts{DurationMS: 42_000, Width: 1280, Height: 720}, "7.1.2" |
| + } |
| + for i, key := range r.outputKeys() { |
| + size, etag := int64(1000+i), fmt.Sprintf("%032x", i+1) |
| + f.grants.Objects[r.bucket+"/"+key] = mediatest.Object{Size: size, ETag: etag} |
| + if failed == "" { |
| + name := media.OutputNames(r.preset)[i] |
| + res.Outputs = append(res.Outputs, media.OutputFact{Name: name, Bytes: size, ETag: etag, ContentType: media.ContentType(name)}) |
| + } |
| + } |
| + b, err := json.Marshal(res) |
| + if err != nil { |
| + f.t.Fatal(err) |
| + } |
| + f.grants.Results[r.execution] = b |
| +} |
| + |
| +// runToStopped submits the test key, and runs the worker through dispatch |
| +// (pass 1), the task's start (pass 2) and the codec writing what it does |
| +// and exiting with exit (pass 3). |
| +func runToStopped(t *testing.T, f *mediaDoorFixture, failed string, exit int) mediaPassRow { |
| + t.Helper() |
| + sub := f.submit(mediaTestKey) |
| + if sub.status != http.StatusAccepted || sub.job.State != "queued" { |
| + t.Fatalf("submit = %d %s, want 202 queued", sub.status, sub.raw) |
| + } |
| + w := startMediaPass(f) |
| + r := f.onlyRow() |
| + if r.arn == "" || r.execution == "" { |
| + t.Fatalf("after pass 1 the row has task %q, execution %q: want it dispatched and launched", r.arn, r.execution) |
| + } |
| + if err := f.engine.Start(r.arn, f.clock.Add(time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.tick(2, 2*time.Second) |
| + if got := f.get(sub.job.ID); got.job.State != "running" { |
| + t.Fatalf("after the task started, GET = %d %s, want running", got.status, got.raw) |
| + } |
| + f.codecWrites(r, failed) |
| + if err := f.engine.Finish(r.arn, f.clock.Add(40*time.Second), exit); err != nil { |
| + t.Fatal(err) |
| + } |
| + w.tick(3, time.Minute) |
| + return r |
| +} |
| + |
| +// TestMediaPassRunsTheLifecycle: the worker takes a job the door admitted |
| +// from queued to done over three passes, keeps the three outputs and |
| +// deletes the result object. |
| +func TestMediaPassRunsTheLifecycle(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-pass-done") |
| + r := runToStopped(t, f, "", media.ExitDone) |
| + |
| + got := f.get(r.id) |
| + if got.status != http.StatusOK || got.job.State != "done" || len(got.job.Outputs) != 3 { |
| + t.Fatalf("GET = %d %s, want done with three outputs", got.status, got.raw) |
| + } |
| + for i, key := range r.outputKeys() { |
| + if got.job.Outputs[i].Key != key { |
| + t.Errorf("output %d = %q, want %q", i, got.job.Outputs[i].Key, key) |
| + } |
| + if _, ok := f.grants.Objects[r.bucket+"/"+key]; !ok { |
| + t.Errorf("output %s was deleted from a done job", key) |
| + } |
| + } |
| + if _, ok := f.grants.Results[r.execution]; ok { |
| + t.Error("the result object outlived the cleanup") |
| + } |
| + resultKey := "carlos-deployment/" + media.ResultKey(r.execution) |
| + if !slices.Equal(f.grants.Deleted, []string{resultKey}) { |
| + t.Errorf("deleted %q, want only the result object %q", f.grants.Deleted, resultKey) |
| + } |
| + var settled, stopped int |
| + var cleanup, charged int64 |
| + if err := f.st.db.QueryRow(`SELECT settled, task_stopped, cleanup_due, charged_ms FROM media_jobs`). |
| + Scan(&settled, &stopped, &cleanup, &charged); err != nil { |
| + t.Fatal(err) |
| + } |
| + // The task started a second after pass 1 and stopped 40 s after pass 2, |
| + // itself 2 s after pass 1: ECS's 41 s. |
| + if settled != 1 || stopped != 1 || cleanup != 0 || charged != 41_000 { |
| + t.Errorf("row settled %d, stopped %d, cleanup_due %d, charged %d ms: want settled, stopped, cleaned, 41000", settled, stopped, cleanup, charged) |
| + } |
| +} |
| + |
| +// TestMediaPassFailedCleansOutputs: a job whose codec fails ends failed |
| +// with its code, and the cleanup deletes whatever outputs it uploaded as |
| +// well as the result object. |
| +func TestMediaPassFailedCleansOutputs(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-pass-failed") |
| + r := runToStopped(t, f, media.CodeNoVideo, media.ExitFailed) |
| + |
| + got := f.get(r.id) |
| + if got.status != http.StatusOK || got.job.State != "failed" || got.job.Error == nil || |
| + got.job.Error.Code != media.CodeNoVideo || got.job.Error.Message != mediaText("media.job.no_video") { |
| + t.Fatalf("GET = %d %s, want failed no_video with the deck's message", got.status, got.raw) |
| + } |
| + want := []string{"carlos-deployment/" + media.ResultKey(r.execution)} |
| + for _, key := range r.outputKeys() { |
| + want = append(want, r.bucket+"/"+key) |
| + if _, ok := f.grants.Objects[r.bucket+"/"+key]; ok { |
| + t.Errorf("output %s of a failed job is still in the bucket", key) |
| + } |
| + } |
| + if !slices.Equal(f.grants.Deleted, want) { |
| + t.Errorf("deleted %q, want %q", f.grants.Deleted, want) |
| + } |
| + if _, ok := f.grants.Objects[r.bucket+"/"+mediaTestKey]; !ok { |
| + t.Error("the cleanup deleted the source") |
| + } |
| +} |
| + |
| +// TestMediaPassReturnsAtOnce: with no engine the worker returns without a |
| +// pass; on a host-claim console it says why and returns. |
| +func TestMediaPassReturnsAtOnce(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + setup func(*Server) |
| + log string |
| + }{ |
| + {"no engine", func(s *Server) {}, ""}, |
| + {"host claim", func(s *Server) { |
| + s.cfg.MediaEngine = mediatest.NewFakeEngine(time.Now) |
| + s.cfg.HostClaim = true |
| + }, "console: media pass: off on a host-claim console"}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + tc.setup(fx.srv) |
| + var logs strings.Builder |
| + restore := captureLogTo(&logs) |
| + done := make(chan struct{}) |
| + go func() { fx.srv.StartMediaPass(context.Background()); close(done) }() |
| + select { |
| + case <-done: |
| + case <-time.After(5 * time.Second): |
| + t.Fatal("StartMediaPass did not return") |
| + } |
| + restore() |
| + for _, st := range fx.srv.jobs.Snapshot() { |
| + if st.Name == "StartMediaPass" && st.Runs > 0 { |
| + t.Errorf("the worker ran a pass: %+v", st) |
| + } |
| + } |
| + if !strings.Contains(logs.String(), tc.log) || tc.log == "" && strings.Contains(logs.String(), "media pass") { |
| + t.Errorf("log = %q, want %q", logs.String(), tc.log) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// mediaCheckEngine is an engine whose CheckRevision answers errs[class] |
| +// first, or blocks until its context ends when block is set. |
| +type mediaCheckEngine struct { |
| + media.Engine |
| + errs map[media.ClassKey]error |
| + block bool |
| +} |
| + |
| +func (e *mediaCheckEngine) CheckRevision(ctx context.Context, class media.ClassKey) error { |
| + if e.block { |
| + <-ctx.Done() |
| + return ctx.Err() |
| + } |
| + if err := e.errs[class]; err != nil { |
| + return err |
| + } |
| + return e.Engine.CheckRevision(ctx, class) |
| +} |
| + |
| +// insertMediaRow writes one row for the summary. |
| +func (f *mediaDoorFixture) insertMediaRow(id, state, class, code string, stopped bool, ended time.Time) { |
| + f.t.Helper() |
| + settled, endedMS, taskStopped := 0, int64(0), 1 |
| + if state == "done" || state == "failed" { |
| + settled, endedMS = 1, ended.UnixMilli() |
| + } |
| + if !stopped { |
| + taskStopped = 0 |
| + } |
| + if _, err := f.st.db.Exec(`INSERT INTO media_jobs |
| + (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at, task_stopped, settled, error, ended_at) |
| + VALUES ('bab', 'titogo', 'seeded', ?, 'uploads/seed.mov', 'e', 1, 'video-720p', ?, 'b', ?, ?, ?, ?, ?, ?)`, |
| + id, class, state, f.clock.UnixMilli(), taskStopped, settled, code, endedMS); err != nil { |
| + f.t.Fatal(err) |
| + } |
| +} |
| + |
| +// TestSystemMediaStatus: GET /api/cli/system/media for an operator, a |
| +// person on neither list, a Service credential, and a console with no |
| +// engine. |
| +func TestSystemMediaStatus(t *testing.T) { |
| + const path = "/api/cli/system/media" |
| + t.Run("operator: shape and counts", func(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-status") |
| + f.srv.cfg.MediaImage = media.ImageInfo{Digest: "sha256:9f2c4e1a7b3d" + strings.Repeat("0", 52), |
| + BuiltAt: f.clock.Add(-47*24*time.Hour - time.Hour).Format(time.RFC3339), FFmpeg: "7.1.2"} |
| + f.engine.Misconfigure(media.ClassKey{Preset: media.PresetAudioAAC, Class: media.ClassLong}, "read_only") |
| + f.srv.cfg.MediaEngine = &mediaCheckEngine{Engine: f.engine, errs: map[media.ClassKey]error{ |
| + {Preset: media.PresetVideo720p, Class: media.ClassLong}: errors.New("dial tcp: i/o timeout"), |
| + }} |
| + day := 24 * time.Hour |
| + f.insertMediaRow("q1", "queued", "short", "", true, time.Time{}) |
| + f.insertMediaRow("q2", "queued", "short", "", true, time.Time{}) |
| + f.insertMediaRow("q3", "queued", "long", "", true, time.Time{}) |
| + f.insertMediaRow("r1", "running", "long", "", false, time.Time{}) |
| + f.insertMediaRow("d1", "done", "short", "", true, f.clock.Add(-time.Hour)) |
| + f.insertMediaRow("d2", "done", "short", "", true, f.clock.Add(-day+time.Minute)) |
| + f.insertMediaRow("d3", "done", "short", "", true, f.clock.Add(-day-time.Minute)) |
| + f.insertMediaRow("f1", "failed", "short", "no_video", true, f.clock.Add(-time.Hour)) |
| + f.insertMediaRow("f2", "failed", "short", "no_video", true, f.clock.Add(-2*time.Hour)) |
| + f.insertMediaRow("f3", "failed", "long", "engine_failed", true, f.clock.Add(-3*time.Hour)) |
| + f.insertMediaRow("f4", "failed", "long", "engine_failed", true, f.clock.Add(-2*day)) |
| + |
| + status, out := getJSON(t, f.ts.URL+path, f.member) |
| + want := map[string]any{ |
| + "configured": true, |
| + "region": "eu-west-1", |
| + "image": map[string]any{"digest": f.srv.cfg.MediaImage.Digest, "built_at": f.srv.cfg.MediaImage.BuiltAt, |
| + "ffmpeg": "7.1.2", "age_days": float64(47)}, |
| + "checks": map[string]any{ |
| + "video-720p/short": "ok", |
| + "video-720p/long": "error: dial tcp: i/o timeout", |
| + "audio-aac/short": "ok", |
| + "audio-aac/long": "refused: read_only", |
| + }, |
| + "queued": map[string]any{"short": float64(2), "long": float64(1)}, |
| + "running": map[string]any{"short": float64(0), "long": float64(1)}, |
| + "done_24h": float64(2), |
| + "failed_24h": float64(3), |
| + "failed_by_code_24h": map[string]any{"no_video": float64(2), "engine_failed": float64(1)}, |
| + } |
| + if status != http.StatusOK || !reflect.DeepEqual(out, want) { |
| + t.Fatalf("status = %d, body = %#v\nwant 200, %#v", status, out, want) |
| + } |
| + }) |
| + t.Run("a person on neither list", func(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-status-member") |
| + f.srv.cfg.StoreOperators = []string{"someone-else@keymail.dev"} |
| + status, out := getJSON(t, f.ts.URL+path, f.member) |
| + if status != http.StatusForbidden || !reflect.DeepEqual(out, map[string]any{"error": mediaText("system_media.forbidden")}) { |
| + t.Fatalf("member = %d %v, want 403 with the deck's refusal", status, out) |
| + } |
| + }) |
| + t.Run("a Service credential", func(t *testing.T) { |
| + // The route layer shuts the door on every service credential |
| + // (svcrole.Set{}, closedDoors) before the handler, whose own |
| + // non-person answer is 404 (TestSystemStatusDoorsAdmitEitherOperator). |
| + f := newMediaDoor(t, "code-media-status-svc") |
| + status, out := getJSON(t, f.ts.URL+path, f.svc) |
| + if status != http.StatusForbidden || !strings.Contains(fmt.Sprint(out["error"]), "closed to service credentials") { |
| + t.Fatalf("service = %d %v, want the closed-door 403", status, out) |
| + } |
| + }) |
| + t.Run("unconfigured", func(t *testing.T) { |
| + fx, token := systemArmed(t, "code-media-status-off") |
| + 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)}, |
| + "checks": map[string]any{}, |
| + "queued": map[string]any{"short": float64(0), "long": float64(0)}, |
| + "running": map[string]any{"short": float64(0), "long": float64(0)}, |
| + "done_24h": float64(0), "failed_24h": float64(0), "failed_by_code_24h": map[string]any{}, |
| + } |
| + if status != http.StatusOK || !reflect.DeepEqual(out, want) { |
| + t.Fatalf("status = %d, body = %#v\nwant 200, %#v", status, out, 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 { |
| + t.Fatal(err) |
| + } |
| + status, out := getJSON(t, fx.ts.URL+path, token) |
| + if status != http.StatusInternalServerError || !reflect.DeepEqual(out, map[string]any{"error": "internal error"}) { |
| + t.Fatalf("database error = %d %v, want 500 with the generic error", status, out) |
| + } |
| + }) |
| + 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} |
| + 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 { |
| + t.Errorf("four blocked checks took %s, want 5 s", elapsed) |
| + } |
| + checks, _ := out["checks"].(map[string]any) |
| + if status != http.StatusOK || len(checks) != 4 { |
| + t.Fatalf("status = %d, body = %v", status, out) |
| + } |
| + for k, v := range checks { |
| + if v != "error: "+context.DeadlineExceeded.Error() { |
| + t.Errorf("check %s = %v, want the timeout as an error", k, v) |
| + } |
| + } |
| + }) |
| +} |
| + |
| +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, |
| + } { |
| + if got := mediaImageAgeDays(built, now); got != want { |
| + t.Errorf("mediaImageAgeDays(%q) = %d, want %d", built, got, want) |
| + } |
| + } |
| +} |
| + |
| +// TestMediaJobsClaimSQLRefused: on a gated (host-claim) database every |
| +// media_jobs write is denied, even under an app permit, so no claim |
| +// operation can carry a conversion (spec §11 A1; claimWriterReasons). |
| +func TestMediaJobsClaimSQLRefused(t *testing.T) { |
| + // One row written before the gate, so the UPDATE and DELETE have a row |
| + // to be refused on. |
| + path := filepath.Join(t.TempDir(), "console.db") |
| + plain, err := Open(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := plain.db.Exec(`INSERT INTO media_jobs (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at) |
| + VALUES ('acct7', 'blog', 'i', 'j0', 'k', 'e', 1, 'video-720p', 'short', 'b', 'queued', 1)`); err != nil { |
| + t.Fatal(err) |
| + } |
| + plain.Close() |
| + s, err := OpenGated(path) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { s.Close() }) |
| + seedGateApp(t, s) |
| + if claimSQLTables["media_jobs"].Refuse == "" || claimWriterReasons["sql/media_jobs"] == "" { |
| + t.Fatal("media_jobs is not a refused table with a written reason") |
| + } |
| + err = s.withClaimSQL(gateCtx(t), []claimSQLScope{gateScope}, allowAllClaimSQL, func(v *Store) error { |
| + for _, q := range []string{ |
| + `INSERT INTO media_jobs (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at) |
| + VALUES ('acct7', 'blog', 'i', 'j', 'k', 'e', 1, 'video-720p', 'short', 'b', 'queued', 1)`, |
| + `UPDATE media_jobs SET state = 'failed'`, |
| + `DELETE FROM media_jobs`, |
| + } { |
| + _, err := v.db.Exec(q) |
| + requireDenied(t, q, err) |
| + } |
| + return nil |
| + }) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go| index 9faa3cae2..af6f6e09f 100644 |
| --- a/internal/console/routedecls.go |
| +++ b/internal/console/routedecls.go |
| @@ -1097,6 +1097,7 @@ var routeDecls = []routeDecl{ |
| {Pattern: "POST /api/cli/system/layout", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemLayoutSet}, |
| {Pattern: "GET /api/cli/system/antivirus", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemAntivirusGet}, |
| {Pattern: "GET /api/cli/system/pdf", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemPDFGet}, |
| + {Pattern: "GET /api/cli/system/media", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemMediaGet}, |
| {Pattern: "POST /api/cli/system/antivirus", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemAntivirusSet}, |
| {Pattern: "POST /api/cli/system/antivirus/rotate-webhook-key", Kind: kindCLI, Allow: svcrole.Set{}, Handler: (*Server).handleAPISystemWebhookRotate}, |
| // Platform GeoIP (geoip spec §4.2): apiSystemRoller, like the update |
diff --git a/internal/console/server.go b/internal/console/server.go| index 6b456b3f1..ac05582ec 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1710,6 +1710,10 @@ type Server struct { |
| // opNow is the operator pages' clock seam (Server.now, opboxes.go): |
| // nil means time.Now. Tests set it; nothing in production does. |
| opNow func() time.Time |
| + // mediaPassTicks drives StartMediaPass in place of its ticker |
| + // (mediapass.go): nil is a tick every media.PassEvery. Tests set it; |
| + // nothing in production does. |
| + mediaPassTicks <-chan time.Time |
| // 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/console/svcroutes_test.go b/internal/console/svcroutes_test.go| index 51836b3d9..4348be54d 100644 |
| --- a/internal/console/svcroutes_test.go |
| +++ b/internal/console/svcroutes_test.go |
| @@ -113,6 +113,7 @@ var closedDoors = []string{ |
| // credential's. |
| "GET /api/cli/system/antivirus", |
| "GET /api/cli/system/pdf", |
| + "GET /api/cli/system/media", |
| "POST /api/cli/system/antivirus", |
| "POST /api/cli/system/antivirus/rotate-webhook-key", |
| // Platform GeoIP (geoip spec §4.2): deployment-wide, operator-only, a |
| @@ -1754,8 +1755,8 @@ func TestEveryClosedDoorRefusesAServiceCredential(t *testing.T) { |
| } |
| seen++ |
| } |
| - if seen != len(closedDoors) || seen != 103 { |
| - t.Errorf("walked %d closed doors, want all %d (and 103 today: three domain purchase doors, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the instance label door, the fleet secrets key door, the two person link doors (list and unlink), the six home link doors, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, eleven system doors, three deployment-wide antivirus, the PDF status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, the billing revenue and payments doors, the billing house door, three account subdomain doors, the subdomain inventory, and the claimed source door)", |
| + if seen != len(closedDoors) || seen != 104 { |
| + t.Errorf("walked %d closed doors, want all %d (and 104 today: three domain purchase doors, two managed admission doors, the fleet show door, two managed configuration doors, three environment ownership doors, instance-token, three door-key doors, the routes door, the regional placements write, instances-manifest, the app update policy, sidecars-manifest, the route-channel move, three instance update settings doors, two db replica doors, the forwarded db read, seven fleets, the instance label door, the fleet secrets key door, the two person link doors (list and unlink), the six home link doors, four services, two email credentials, email pause, the build probe, the swap policy, the copy count, the interactive setting, the interactive session door, two app policy doors, two app region doors, the live tenancy read, the layout read, the activation-cancel door, eleven system doors, three deployment-wide antivirus, the PDF status door, the media status door, three platform geoip doors, two pointer digest doors, the hostname history status, the channel resign, two release authorize doors, four store-entitlement doors, two account plan doors, two billing problem doors, the billing revenue and payments doors, the billing house door, three account subdomain doors, the subdomain inventory, and the claimed source door)", |
| seen, len(closedDoors)) |
| } |
| } |
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt| index f612f2bc0..037040197 100644 |
| --- a/internal/console/testdata/claim-routes.txt |
| +++ b/internal/console/testdata/claim-routes.txt |
| @@ -151,6 +151,7 @@ route GET /api/cli/system/hosts-used/status |
| route GET /api/cli/system/jobs/{id} |
| route GET /api/cli/system/layout |
| route GET /api/cli/system/managed-fleets |
| +route GET /api/cli/system/media |
| route GET /api/cli/system/pdf |
| route GET /api/cli/system/pointer-digests |
| route GET /api/cli/system/status |
| @@ -447,6 +448,7 @@ worker StartPlanGracePass |
| worker StartPlanLimitsPass |
| worker StartRelay |
| worker StartRunSweep |
| +worker StartMediaPass |
| worker StartScanDrain |
| worker StartScanPass |
| worker StartSeedsPass |