console: retry media wiring after a cloud failure at boot
Branch review round 1, P2-2 (Fable). Invariant: rows in flight are always tracked. Task 10's ruling turned media off until the next start when the cloud did not answer at boot, which left rows already running untracked; their outputs would be deleted as engine_lost days later. The boot still comes up with media off and says so, and settings errors still stop it. The wiring is now kept as MediaRetry, which the media pass worker calls with backoff (10 s doubling to 10 min) until the cloud answers; it then installs the configuration whole, as a successful boot would, and runs the pass in the same goroutine. A guard keeps one pass loop per console. Media reads go through mediaCfg, mediaJobs and mediaRate, which see the installed wiring. system media status shows not configured until then. The boot line changes, and the success and settings-refused lines are logged once each (deck rows pending Luna). The serve witness boots against a cloud that refuses, lets it answer, and sees media configured, the pass recovering a row seeded before boot, and each line logged once.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+496
−62
cmd/console/media.go+30 −11cmd/console/media_serve_test.go+118 −5cmd/console/media_test.go+4 −3docs/superpowers/notes/media-conversion-copy-deck.md+3 −1internal/console/apimedia.go+20 −20internal/console/apistoreuploads.go+4 −4internal/console/apisystem.go+4 −4internal/console/mediapass.go+95 −4internal/console/mediapass_test.go+140 −0internal/console/mediaretire.go+2 −2internal/console/mediastore.go+2 −2internal/console/mediawire.go+73 −5internal/console/planmeasure.go+1 −1
diff --git a/cmd/console/media.go b/cmd/console/media.go| index aac8c7316..a5cd0c0fd 100644 |
| --- a/cmd/console/media.go |
| +++ b/cmd/console/media.go |
| @@ -27,8 +27,9 @@ import ( |
| const mediaBootTimeout = 30 * time.Second |
| // mediaOffAtBoot is the deck's console.media.off_at_boot, logged once when |
| -// the cloud does not answer at boot. |
| -const mediaOffAtBoot = "console: media conversion is off until the next start: %v" |
| +// the cloud does not answer at boot. The console then retries the wiring |
| +// in the background (console.MediaConfig.MediaRetry). |
| +const mediaOffAtBoot = "console: media conversion is off until the cloud answers; trying again in the background: %v" |
| // errMediaCloud marks a media wiring failure that is the cloud's and not the |
| // operator's: the settings are fine, but the account could not be read or a |
| @@ -206,25 +207,43 @@ func mediaFromEnv(ctx context.Context, getenv func(string) string, store storeEn |
| // mediaConfig is serve's media wiring. A wrong setting stops the boot, as |
| // storeBackend's do. A cloud that does not answer does not: as with |
| // mailBackends, one feature's dependency being briefly unreachable must not |
| -// take down every other door, so the console boots with media off and says |
| +// take down every other door, so the console boots with media off, says |
| // so, and `carlos system media status` shows the engine as not configured. |
| -// The next start tries again. |
| +// Rows already running must still be tracked, so the wiring is retried in |
| +// the background (MediaRetry, run by StartMediaPass) until the cloud |
| +// answers, and then installed as a successful boot would install it |
| +// (branch review round 1, P2-2). |
| func mediaConfig(store objstore.Deployment, rec *perf.Recorder) console.MediaConfig { |
| - // Detached: serve has no context of its own this early in the boot. |
| - ctx, cancel := context.WithTimeout(context.Background(), mediaBootTimeout) |
| - cfg, err := mediaFromEnv(ctx, os.Getenv, storeEnv{ |
| + env := storeEnv{ |
| Backend: store.Backend, |
| Region: store.Region, |
| Prefix: store.BucketPrefix, |
| Endpoint: store.Endpoint, |
| - }, realMediaClients(rec)) |
| - cancel() |
| - if errors.Is(err, errMediaCloud) { |
| + } |
| + wire := mediaWiring(os.Getenv, env, realMediaClients(rec)) |
| + // Detached: serve has no context of its own this early in the boot. |
| + cfg, again, err := wire(context.Background()) |
| + if again { |
| log.Printf(mediaOffAtBoot, err) |
| - return console.MediaConfig{} |
| + return console.MediaConfig{MediaRetry: wire} |
| } |
| if err != nil { |
| log.Fatalf("console: %v", err) |
| } |
| return cfg |
| } |
| + |
| +// mediaWiring is one attempt at mediaFromEnv, bounded by mediaBootTimeout: |
| +// again is true when the cloud did not answer (errMediaCloud), so the |
| +// attempt is worth making later; any other error is a setting. |
| +func mediaWiring(getenv func(string) string, store storeEnv, clients mediaClients) func(context.Context) (console.MediaConfig, bool, error) { |
| + return func(ctx context.Context) (console.MediaConfig, bool, error) { |
| + ctx, cancel := context.WithTimeout(ctx, mediaBootTimeout) |
| + defer cancel() |
| + cfg, err := mediaFromEnv(ctx, getenv, store, clients) |
| + if errors.Is(err, errMediaCloud) { |
| + return console.MediaConfig{}, true, err |
| + } |
| + return cfg, false, err |
| + } |
| +} |
diff --git a/cmd/console/media_serve_test.go b/cmd/console/media_serve_test.go| index 711b40cbc..a3de04c8c 100644 |
| --- a/cmd/console/media_serve_test.go |
| +++ b/cmd/console/media_serve_test.go |
| @@ -5,6 +5,7 @@ package main |
| import ( |
| "bufio" |
| "context" |
| + "database/sql" |
| "encoding/json" |
| "fmt" |
| "io" |
| @@ -44,11 +45,13 @@ type mediaCloudStub struct { |
| denyCode string |
| identities int |
| revisions map[string]int |
| + listTasks int |
| + listed chan struct{} // receives once a ListTasks has arrived |
| } |
| func newMediaCloudStub(t *testing.T) *mediaCloudStub { |
| t.Helper() |
| - s := &mediaCloudStub{account: testMediaAccount, revisions: map[string]int{}} |
| + s := &mediaCloudStub{account: testMediaAccount, revisions: map[string]int{}, listed: make(chan struct{}, 1)} |
| s.srv = httptest.NewServer(http.HandlerFunc(s.serve)) |
| t.Cleanup(s.srv.Close) |
| return s |
| @@ -58,6 +61,18 @@ func (s *mediaCloudStub) serve(w http.ResponseWriter, r *http.Request) { |
| body, _ := io.ReadAll(r.Body) |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| + if strings.HasSuffix(r.Header.Get("X-Amz-Target"), ".ListTasks") { |
| + // Only the media pass lists tasks: recovery of a running row with |
| + // no ARN. ECS has none. |
| + s.listTasks++ |
| + select { |
| + case s.listed <- struct{}{}: |
| + default: |
| + } |
| + w.Header().Set("Content-Type", "application/x-amz-json-1.1") |
| + fmt.Fprint(w, `{"taskArns":[]}`) |
| + return |
| + } |
| if strings.HasSuffix(r.Header.Get("X-Amz-Target"), ".DescribeTaskDefinition") { |
| var in struct { |
| TaskDefinition string `json:"taskDefinition"` |
| @@ -101,6 +116,19 @@ func (s *mediaCloudStub) denyIdentity(code string) { |
| s.denyIdent, s.denyCode = true, code |
| } |
| +// allowIdentity makes GetCallerIdentity answer again. |
| +func (s *mediaCloudStub) allowIdentity() { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + s.denyIdent = false |
| +} |
| + |
| +func (s *mediaCloudStub) listTasksCalls() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.listTasks |
| +} |
| + |
| func (s *mediaCloudStub) identityCalls() int { |
| s.mu.Lock() |
| defer s.mu.Unlock() |
| @@ -117,10 +145,12 @@ func (s *mediaCloudStub) revisionCalls() map[string]int { |
| return out |
| } |
| -// mediaWitness runs the real console binary through serve. |
| +// mediaWitness runs the real console binary through serve. seed, when |
| +// set, writes to the console's database before serve opens it. |
| type mediaWitness struct { |
| bin string |
| stub *mediaCloudStub |
| + seed func(t *testing.T, db string) |
| } |
| // env is what a console with a store backend boots on, every AWS client held |
| @@ -188,8 +218,23 @@ func mintMediaToken(t *testing.T, db string) string { |
| type runningConsole struct { |
| addr, token string |
| - mu sync.Mutex |
| - log strings.Builder |
| + mu sync.Mutex |
| + log strings.Builder |
| + lines chan struct{} // receives after each log line, when nobody has yet |
| +} |
| + |
| +// waitFor blocks until the log holds line, or fails after d. |
| +func (c *runningConsole) waitFor(t *testing.T, line string, d time.Duration) { |
| + t.Helper() |
| + deadline := time.NewTimer(d) |
| + defer deadline.Stop() |
| + for !strings.Contains(c.output(), line) { |
| + select { |
| + case <-c.lines: |
| + case <-deadline.C: |
| + t.Fatalf("the log never said %q:\n%s", line, c.output()) |
| + } |
| + } |
| } |
| func (c *runningConsole) output() string { |
| @@ -204,7 +249,10 @@ func (w mediaWitness) boot(t *testing.T, extra ...string) *runningConsole { |
| t.Helper() |
| dir := t.TempDir() |
| addr := freeLoopbackAddr(t) |
| - c := &runningConsole{addr: addr, token: mintMediaToken(t, filepath.Join(dir, "console.db"))} |
| + c := &runningConsole{addr: addr, token: mintMediaToken(t, filepath.Join(dir, "console.db")), lines: make(chan struct{}, 1)} |
| + if w.seed != nil { |
| + w.seed(t, filepath.Join(dir, "console.db")) |
| + } |
| cmd := exec.Command(w.bin, "serve") |
| cmd.Dir = dir |
| cmd.Env = w.env(dir, addr, extra...) |
| @@ -226,6 +274,10 @@ func (w mediaWitness) boot(t *testing.T, extra ...string) *runningConsole { |
| c.mu.Lock() |
| c.log.WriteString(sc.Text() + "\n") |
| c.mu.Unlock() |
| + select { |
| + case c.lines <- struct{}{}: |
| + default: |
| + } |
| if strings.Contains(sc.Text(), "listening on") { |
| once.Do(func() { close(listening) }) |
| } |
| @@ -416,6 +468,42 @@ func TestServeMediaWiring(t *testing.T) { |
| } |
| }) |
| + t.Run("a cloud that answers later turns media on and starts the pass", func(t *testing.T) { |
| + // Branch review round 1, P2-2: a row running when the console |
| + // started must be tracked once the cloud answers, not after the |
| + // next start. |
| + w := mediaWitness{bin: bin, stub: newMediaCloudStub(t), seed: seedRunningMediaRow} |
| + w.stub.denyIdentity("InvalidClientTokenId") |
| + c := w.boot(t, "CARLOS_STORE_CONVERSION=1", "CARLOS_MEDIA_ENGINE="+testMediaEngine(t, nil)) |
| + if got := c.status(t); got.Configured { |
| + t.Fatalf("status before the cloud answers = %+v", got) |
| + } |
| + if n := w.stub.listTasksCalls(); n != 0 { |
| + t.Fatalf("%d ListTasks before the cloud answered: a pass ran with no engine", n) |
| + } |
| + w.stub.allowIdentity() |
| + const on = "console: media conversion is on: the cloud answered" |
| + c.waitFor(t, on, 2*time.Minute) |
| + got := c.status(t) |
| + if !got.Configured || got.Region != testMediaRegion || got.Image.Digest != testMediaDigest { |
| + t.Fatalf("status after the cloud answered = %+v\n%s", got, c.output()) |
| + } |
| + if out := c.operatorStatus(t, carlos); strings.Contains(out, "not configured") { |
| + t.Fatalf("carlos system media status printed %q", out) |
| + } |
| + // The pass runs: it lists ECS's tasks to recover the seeded row. |
| + select { |
| + case <-w.stub.listed: |
| + case <-time.After(time.Minute): |
| + t.Fatalf("the pass never listed ECS's tasks:\n%s", c.output()) |
| + } |
| + for line, want := range map[string]int{strings.TrimSuffix(mediaOffAtBoot, "%v"): 1, on: 1} { |
| + if n := strings.Count(c.output(), line); n != want { |
| + t.Fatalf("the log says %q %d times, want %d:\n%s", line, n, want, c.output()) |
| + } |
| + } |
| + }) |
| + |
| t.Run("a secret in the error code stays out of the log", func(t *testing.T) { |
| w := mediaWitness{bin: bin, stub: newMediaCloudStub(t)} |
| w.stub.denyIdentity(mediaCloudSecret) |
| @@ -485,3 +573,28 @@ func TestServeMediaWiring(t *testing.T) { |
| } |
| }) |
| } |
| + |
| +// seedRunningMediaRow writes, into the console's database, a row running |
| +// when the console starts, with no task ARN saved: only a running media |
| +// pass reaches ECS for it. |
| +func seedRunningMediaRow(t *testing.T, db string) { |
| + t.Helper() |
| + st, err := console.Open(db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + st.Close() |
| + h, err := sql.Open("sqlite", db) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer h.Close() |
| + now := time.Now().UnixMilli() |
| + if _, err := h.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 ('acct', 'app', 'i', 'j', 'uploads/a.mov', 'e', 1, 'video-720p', 'short', 'b', 'running', ?, |
| + '0123456789abcdef0123456789abcdef', ?, 600, 600, 0)`, now, now); err != nil { |
| + t.Fatal(err) |
| + } |
| +} |
diff --git a/cmd/console/media_test.go b/cmd/console/media_test.go| index ffd21060c..987ddfc40 100644 |
| --- a/cmd/console/media_test.go |
| +++ b/cmd/console/media_test.go |
| @@ -10,6 +10,7 @@ import ( |
| "net/http/httptest" |
| "os" |
| "path/filepath" |
| + "reflect" |
| "strings" |
| "sync" |
| "testing" |
| @@ -137,7 +138,7 @@ func TestMediaFromEnvUnset(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - if got != (console.MediaConfig{}) { |
| + if !reflect.DeepEqual(got, console.MediaConfig{}) { |
| t.Fatalf("configured %+v, want nothing", got) |
| } |
| if f.identities+f.s3s+f.engines != 0 { |
| @@ -305,7 +306,7 @@ func TestMediaFromEnvRefusals(t *testing.T) { |
| if f.engines != 0 { |
| t.Fatal("an engine was built for a refused setting") |
| } |
| - if got != (console.MediaConfig{}) { |
| + if !reflect.DeepEqual(got, console.MediaConfig{}) { |
| t.Fatalf("a refusal also configured %+v", got) |
| } |
| }) |
| @@ -350,7 +351,7 @@ func TestMediaFromEnvCloudFailures(t *testing.T) { |
| if !errors.Is(err, errMediaCloud) { |
| t.Fatalf("err = %v, want errMediaCloud", err) |
| } |
| - if got != (console.MediaConfig{}) { |
| + if !reflect.DeepEqual(got, console.MediaConfig{}) { |
| t.Fatalf("half configured: %+v", got) |
| } |
| }) |
diff --git a/docs/superpowers/notes/media-conversion-copy-deck.md b/docs/superpowers/notes/media-conversion-copy-deck.md| index c2a3b3b21..0778775c6 100644 |
| --- a/docs/superpowers/notes/media-conversion-copy-deck.md |
| +++ b/docs/superpowers/notes/media-conversion-copy-deck.md |
| @@ -694,7 +694,9 @@ for whoever deploys the console and are not listed here. |
| | `engine.aws.grant.request` | `the execution is not 32 hex characters`, `the source key is not valid`, `the source ETag is not valid`, `the output prefix is not a directory under derived/`, `the grant does not name %d outputs`, `an output's name or content type is not one the engine writes` (pending Luna pass; plan 3 Task 9) | |
| | `engine.aws.grant.presign` | `the presigned transfers do not share one credential`, `an output's URL is not under the output prefix`, `a presigned URL does not have the expected shape`, `a presigned URL does not sign the expected headers` (pending Luna pass; plan 3 Task 9) | |
| | `engine.aws.rejected` | The reason in `engine rejected the launch: %s`: an AWS error code, `HTTP 429`, one of the `engine.aws.failure.*` words, `no task definition for this class`, `no task and no failure reported`, or `the API refused the request` (pending Luna pass; plan 3 Task 9, branch review round 1) | |
| -| `console.media.off_at_boot` | `console: media conversion is off until the next start: %v`, logged once at boot when the cloud account cannot be read or a client cannot be built. `%v` is `the cloud account could not be reached: <step>: <cause>`. The step is `sts GetCallerIdentity`, `build the S3 client` or `build the conversion engine`; the cause is one of the `engine.aws.cause.*` texts, never the error's own message (pending Luna pass; plan 3 Task 10 fix 2) | |
| +| `console.media.off_at_boot` | `console: media conversion is off until the cloud answers; trying again in the background: %v`, logged once at boot when the cloud account cannot be read or a client cannot be built (changed in branch review round 1: the console retries the wiring instead of waiting for the next start). `%v` is `the cloud account could not be reached: <step>: <cause>`. The step is `sts GetCallerIdentity`, `build the S3 client` or `build the conversion engine`; the cause is one of the `engine.aws.cause.*` texts, never the error's own message (pending Luna pass; plan 3 Task 10 fix 2) | |
| +| `console.media.on_after_retry` | `console: media conversion is on: the cloud answered`, logged once when the background retry wires media after `console.media.off_at_boot` (pending Luna pass; branch review round 1) | |
| +| `console.media.retry_refused` | `console: media conversion stays off: %v`, logged once when the background retry finds a setting that is wrong (the engine's account is not the console's, or its limits are refused); `%v` names the setting, never its value (pending Luna pass; branch review round 1) | |
| ### The media-engine module (plan 3 Task 11) |
diff --git a/internal/console/apimedia.go b/internal/console/apimedia.go| index 48514d50e..f7b1c726a 100644 |
| --- a/internal/console/apimedia.go |
| +++ b/internal/console/apimedia.go |
| @@ -81,7 +81,7 @@ func (s *Server) mediaAnswer(j mediajobs.Job) mediaJobAnswer { |
| a := mediaJobAnswer{ID: j.ID, State: j.State, Key: j.Key, Preset: j.Preset, Class: j.Class, SubmittedAt: j.SubmittedAt} |
| switch j.State { |
| case "failed": |
| - a.Error = &mediaJobError{Code: j.ErrorCode, Message: mediaJobMessage(j, s.cfg.MediaLimits)} |
| + a.Error = &mediaJobError{Code: j.ErrorCode, Message: mediaJobMessage(j, s.mediaCfg().MediaLimits)} |
| case "done": |
| if r := j.Result; r != nil { |
| if r.Source != nil { |
| @@ -118,7 +118,7 @@ func mediaInternal(w http.ResponseWriter, what string, err error) { |
| // any one missing is not_configured, never a 500 or a refusal naming an |
| // empty region. |
| func (s *Server) mediaConfigured() bool { |
| - return s.cfg.MediaEngine != nil && s.cfg.MediaGrants != nil && s.cfg.MediaRegion != "" && s.cfg.StoreBuckets != nil |
| + return s.mediaCfg().MediaEngine != nil && s.mediaCfg().MediaGrants != nil && s.mediaCfg().MediaRegion != "" && s.mediaCfg().StoreBuckets != nil |
| } |
| // mediaSource is one HEAD of a source: the bucket asked, and its answer. |
| @@ -241,8 +241,8 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| mediaInternal(w, "store check "+acct.Sqid+"/"+app, errors.New("unknown code "+code)) |
| return |
| } |
| - if rec.Provisioned.Region != s.cfg.MediaRegion { |
| - mediaRefuse(w, http.StatusConflict, "no_engine_in_region", mediaText("media.no_engine_in_region", s.cfg.MediaRegion, rec.Provisioned.Region)) |
| + if rec.Provisioned.Region != s.mediaCfg().MediaRegion { |
| + mediaRefuse(w, http.StatusConflict, "no_engine_in_region", mediaText("media.no_engine_in_region", s.mediaCfg().MediaRegion, rec.Provisioned.Region)) |
| return |
| } |
| if rec.WritesDenied != nil { |
| @@ -251,7 +251,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| } |
| bucket := rec.Provisioned.Bucket |
| if src == nil || src.bucket != bucket { |
| - h, err := s.cfg.MediaGrants.Head(ctx, bucket, body.Key) |
| + h, err := s.mediaCfg().MediaGrants.Head(ctx, bucket, body.Key) |
| src = &mediaSource{bucket: bucket, head: h, err: err} |
| } |
| switch { |
| @@ -265,7 +265,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| mediaInternal(w, "head "+acct.Sqid+"/"+app, src.err) |
| return |
| } |
| - size, limit := src.head.Size, s.cfg.MediaLimits.MaxBytes(preset) |
| + size, limit := src.head.Size, s.mediaCfg().MediaLimits.MaxBytes(preset) |
| if size <= 0 { |
| mediaRefuse(w, http.StatusRequestEntityTooLarge, media.CodeSourceTooLarge, mediaText("media.source_empty")) |
| return |
| @@ -278,7 +278,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| class := media.PickClass(preset, body.Class, size) |
| inc := rec.Conversion.Incarnation |
| id := media.JobID(body.Key, src.head.ETag, preset, class) |
| - if job, found, err := s.media.Lookup(ctx, acct.Sqid, app, inc, id); err != nil { |
| + if job, found, err := s.mediaJobs().Lookup(ctx, acct.Sqid, app, inc, id); err != nil { |
| mediaInternal(w, "lookup "+acct.Sqid+"/"+app, err) |
| return |
| } else if found { |
| @@ -286,7 +286,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| - if err := s.cfg.MediaEngine.CheckRevision(ctx, media.ClassKey{Preset: preset, Class: class}); err != nil { |
| + if err := s.mediaCfg().MediaEngine.CheckRevision(ctx, media.ClassKey{Preset: preset, Class: class}); err != nil { |
| var mis *media.Misconfigured |
| if errors.As(err, &mis) { |
| log.Printf("console: media engine %s/%s: %v", preset, class, err) |
| @@ -311,7 +311,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| if s.mediaBeforeSubmit != nil { |
| s.mediaBeforeSubmit() |
| } |
| - job, created, err := s.media.Submit(ctx, mediajobs.SubmitRequest{ |
| + job, created, err := s.mediaJobs().Submit(ctx, mediajobs.SubmitRequest{ |
| Account: acct.Sqid, App: app, Incarnation: inc, Bucket: bucket, |
| Key: body.Key, ETag: src.head.ETag, Preset: preset, Class: class, |
| Bytes: size, Now: now, |
| @@ -327,7 +327,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| // may have taken the last place since mediaFairUse counted (Astra P1). |
| if errors.Is(err, mediajobs.ErrAccountBusy) { |
| w.Header().Set("Retry-After", "30") |
| - mediaRefuse(w, http.StatusTooManyRequests, "too_many_jobs", mediaText("media.busy_account", s.cfg.MediaLimits.AccountActive)) |
| + mediaRefuse(w, http.StatusTooManyRequests, "too_many_jobs", mediaText("media.busy_account", s.mediaCfg().MediaLimits.AccountActive)) |
| return |
| } |
| if errors.Is(err, mediajobs.ErrQueueFull) { |
| @@ -369,20 +369,20 @@ func (s *Server) mediaRepeat(ctx context.Context, sqid, app, key, preset, class |
| return mediajobs.Job{}, false, nil, err |
| } |
| inc := recordIncarnation(rec) |
| - if inc == "" || rec.Provisioned.Region != s.cfg.MediaRegion || rec.WritesDenied != nil { |
| + if inc == "" || rec.Provisioned.Region != s.mediaCfg().MediaRegion || rec.WritesDenied != nil { |
| return mediajobs.Job{}, false, nil, nil |
| } |
| - if ok, err := s.media.Submitted(ctx, sqid, app, inc, key, preset, class); err != nil || !ok { |
| + if ok, err := s.mediaJobs().Submitted(ctx, sqid, app, inc, key, preset, class); err != nil || !ok { |
| return mediajobs.Job{}, false, nil, err |
| } |
| bucket := rec.Provisioned.Bucket |
| - h, herr := s.cfg.MediaGrants.Head(ctx, bucket, key) |
| + h, herr := s.mediaCfg().MediaGrants.Head(ctx, bucket, key) |
| src = &mediaSource{bucket: bucket, head: h, err: herr} |
| - if herr != nil || h.Size <= 0 || h.Size > s.cfg.MediaLimits.MaxBytes(preset) { |
| + if herr != nil || h.Size <= 0 || h.Size > s.mediaCfg().MediaLimits.MaxBytes(preset) { |
| return mediajobs.Job{}, false, src, nil |
| } |
| id := media.JobID(key, h.ETag, preset, media.PickClass(preset, class, h.Size)) |
| - job, found, err = s.media.Lookup(ctx, sqid, app, inc, id) |
| + job, found, err = s.mediaJobs().Lookup(ctx, sqid, app, inc, id) |
| return job, found, src, err |
| } |
| @@ -406,7 +406,7 @@ func (s *Server) mediaFairUse(ctx context.Context, acct *Account, now time.Time) |
| return nil, err |
| } |
| if limit > 0 { |
| - used, err := s.media.ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now)) |
| + used, err := s.mediaJobs().ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now)) |
| if err != nil { |
| return nil, err |
| } |
| @@ -414,8 +414,8 @@ func (s *Server) mediaFairUse(ctx context.Context, acct *Account, now time.Time) |
| return &mediaRefusal{Status: http.StatusPaymentRequired, Code: "plan_limit", Msg: capMessage("cli.cap.media_minutes", used, limit)}, nil |
| } |
| } |
| - l := s.cfg.MediaLimits |
| - active, queued, err := s.media.Counts(ctx, acct.Sqid) |
| + l := s.mediaCfg().MediaLimits |
| + active, queued, err := s.mediaJobs().Counts(ctx, acct.Sqid) |
| if err != nil { |
| return nil, err |
| } |
| @@ -425,7 +425,7 @@ func (s *Server) mediaFairUse(ctx context.Context, acct *Account, now time.Time) |
| if queued >= l.Queue { |
| return &mediaRefusal{Status: http.StatusServiceUnavailable, Code: "queue_full", Msg: mediaText("media.queue_full"), RetryAfter: 60}, nil |
| } |
| - return s.mediaLimiter.acquire(acct.Sqid, now), nil |
| + return s.mediaRate().acquire(acct.Sqid, now), nil |
| } |
| // handleAPIMediaGet is GET /api/cli/apps/{account}/{app}/media/conversions/{id}: |
| @@ -453,7 +453,7 @@ func (s *Server) handleAPIMediaGet(w http.ResponseWriter, r *http.Request) { |
| mediaRefuse(w, http.StatusNotFound, "job_not_found", mediaText("media.job_not_found")) |
| return |
| } |
| - job, found, err := s.media.Lookup(ctx, acct.Sqid, app, inc, r.PathValue("id")) |
| + job, found, err := s.mediaJobs().Lookup(ctx, acct.Sqid, app, inc, r.PathValue("id")) |
| if err != nil { |
| mediaInternal(w, "lookup "+acct.Sqid+"/"+app, err) |
| return |
diff --git a/internal/console/apistoreuploads.go b/internal/console/apistoreuploads.go| index c9962336f..836cdcdd8 100644 |
| --- a/internal/console/apistoreuploads.go |
| +++ b/internal/console/apistoreuploads.go |
| @@ -72,7 +72,7 @@ type uploadsAnswer struct { |
| // uploadsConfigured: this console can read and write its stores' bucket |
| // settings (CARLOS_STORE_CONVERSION and its adapter). |
| func (s *Server) uploadsConfigured() bool { |
| - return s.cfg.StoreConversion && s.cfg.StoreBuckets != nil |
| + return s.mediaCfg().StoreConversion && s.mediaCfg().StoreBuckets != nil |
| } |
| // uploadsOrigin is raw as the one form an origin takes in the rule, and |
| @@ -266,7 +266,7 @@ func (s *Server) handleAPIStoreUploadsGet(w http.ResponseWriter, r *http.Request |
| writeJSON(w, http.StatusOK, uploadsOff()) |
| return |
| } |
| - facts, err := s.cfg.StoreBuckets.Inspect(ctx, rec.Provisioned.Bucket) |
| + facts, err := s.mediaCfg().StoreBuckets.Inspect(ctx, rec.Provisioned.Bucket) |
| if err != nil { |
| uploadsInternal(w, "status inspect "+acct.Sqid+"/"+app, err) |
| return |
| @@ -399,7 +399,7 @@ func (s *Server) handleAPIStoreUploadsSet(w http.ResponseWriter, r *http.Request |
| uploadsInternal(w, "policy "+acct.Sqid+"/"+app, err) |
| return |
| } |
| - if err := s.cfg.StoreBuckets.PutUploads(ctx, bucket, origins); err != nil { |
| + if err := s.mediaCfg().StoreBuckets.PutUploads(ctx, bucket, origins); err != nil { |
| uploadsInternal(w, "put rules "+acct.Sqid+"/"+app, err) |
| return |
| } |
| @@ -449,7 +449,7 @@ func (s *Server) handleUploadsDisable(w http.ResponseWriter, r *http.Request, ad |
| return |
| } |
| bucket, inc := rec.Provisioned.Bucket, rec.Conversion.Incarnation |
| - if err := s.cfg.StoreBuckets.DeleteUploads(ctx, bucket); err != nil { |
| + if err := s.mediaCfg().StoreBuckets.DeleteUploads(ctx, bucket); err != nil { |
| uploadsInternal(w, "delete rules "+acct.Sqid+"/"+app, err) |
| return |
| } |
diff --git a/internal/console/apisystem.go b/internal/console/apisystem.go| index c39185e7d..86ea0e132 100644 |
| --- a/internal/console/apisystem.go |
| +++ b/internal/console/apisystem.go |
| @@ -301,23 +301,23 @@ func (s *Server) handleAPISystemMediaGet(w http.ResponseWriter, r *http.Request) |
| return |
| } |
| now := s.now() |
| - sum, err := s.media.Summary(r.Context(), now) |
| + sum, err := s.mediaJobs().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 |
| + img := s.mediaCfg().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 { |
| + } else if s.mediaCfg().MediaEngine != nil { |
| checks[mediaImageCheck] = mediaNoBuildDate |
| } |
| writeJSON(w, http.StatusOK, map[string]any{ |
| "configured": s.mediaConfigured(), |
| - "region": s.cfg.MediaRegion, |
| + "region": s.mediaCfg().MediaRegion, |
| "image": map[string]any{ |
| "digest": img.Digest, |
| "built_at": img.BuiltAt, |
diff --git a/internal/console/mediapass.go b/internal/console/mediapass.go| index 9433fa9de..fa62f6b50 100644 |
| --- a/internal/console/mediapass.go |
| +++ b/internal/console/mediapass.go |
| @@ -20,14 +20,31 @@ import ( |
| // 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. |
| +// |
| +// A console whose boot could not reach the cloud has MediaRetry: this |
| +// worker retries the wiring first (awaitMedia), and once it is installed |
| +// runs the pass in this same goroutine, so there is never a second pass. |
| func (s *Server) StartMediaPass(ctx context.Context) { |
| - if s.cfg.MediaEngine == nil { |
| - return |
| + if s.mediaCfg().MediaEngine == nil { |
| + // Nothing to run, unless boot could not reach the cloud: then the |
| + // wiring is retried here first. Not on a host-claim console, |
| + // which refuses media; and a retry that wires browser uploads |
| + // alone leaves no pass to run. |
| + if s.cfg.HostClaim || !s.awaitMedia(ctx) || s.mediaCfg().MediaEngine == nil { |
| + return |
| + } |
| } |
| if s.cfg.HostClaim { |
| log.Print("console: media pass: off on a host-claim console, where media conversion is refused") |
| return |
| } |
| + // One pass loop per console, however the worker came to start: a |
| + // second returns at once, so two passes never run side by side (the |
| + // wiring installed late included). |
| + if !s.mediaPassRunning.CompareAndSwap(false, true) { |
| + return |
| + } |
| + defer s.mediaPassRunning.Store(false) |
| ticks, stop := s.mediaPassTicks, func() {} |
| if ticks == nil { |
| t := time.NewTicker(media.PassEvery) |
| @@ -53,10 +70,84 @@ func (s *Server) StartMediaPass(ctx context.Context) { |
| } |
| } |
| +// The wait before each MediaRetry attempt: mediaRetryFirst, doubling to |
| +// mediaRetryMost. The first is short enough that a brief outage at boot |
| +// costs seconds, and the cap keeps a long one to a few cheap calls an |
| +// hour. |
| +const ( |
| + mediaRetryFirst = 10 * time.Second |
| + mediaRetryMost = 10 * time.Minute |
| +) |
| + |
| +// The deck's console.media.on_after_retry and console.media.retry_refused |
| +// (pending Luna pass), each logged at most once. |
| +const ( |
| + mediaOnAfterRetry = "console: media conversion is on: the cloud answered" |
| + mediaRetryRefused = "console: media conversion stays off: %v" |
| +) |
| + |
| +// mediaRetryDelay is the wait before attempt n (0 for the first). |
| +func mediaRetryDelay(n int) time.Duration { |
| + d := mediaRetryFirst |
| + for range n { |
| + if d *= 2; d >= mediaRetryMost { |
| + return mediaRetryMost |
| + } |
| + } |
| + return d |
| +} |
| + |
| +// awaitMedia retries MediaRetry until it answers, ctx ends, or it names a |
| +// wrong setting, and reports whether media was installed. The cloud's |
| +// first failure was logged at boot, so a further one is not; the outcome |
| +// is logged once. |
| +func (s *Server) awaitMedia(ctx context.Context) bool { |
| + retry := s.cfg.MediaRetry |
| + if retry == nil { |
| + return false |
| + } |
| + wait := s.mediaRetryWait |
| + if wait == nil { |
| + wait = waitMediaRetry |
| + } |
| + for n := 0; ; n++ { |
| + if wait(ctx, mediaRetryDelay(n)) != nil { |
| + return false |
| + } |
| + cfg, again, err := retry(ctx) |
| + switch { |
| + case err == nil: |
| + if err := s.installMedia(cfg); err != nil { |
| + log.Printf(mediaRetryRefused, err) |
| + return false |
| + } |
| + log.Print(mediaOnAfterRetry) |
| + return true |
| + case ctx.Err() != nil: |
| + return false |
| + case !again: |
| + log.Printf(mediaRetryRefused, err) |
| + return false |
| + } |
| + } |
| +} |
| + |
| +// waitMediaRetry waits d, or until ctx ends. |
| +func waitMediaRetry(ctx context.Context, d time.Duration) error { |
| + t := time.NewTimer(d) |
| + defer t.Stop() |
| + select { |
| + case <-t.C: |
| + return nil |
| + case <-ctx.Done(): |
| + return ctx.Err() |
| + } |
| +} |
| + |
| // 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()) |
| + return s.mediaJobs().Pass(ctx, s.now()) |
| } |
| // mediaCheckTimeout bounds each class's CheckRevision in system media |
| @@ -81,7 +172,7 @@ var mediaStatusClasses = []media.ClassKey{ |
| // 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 |
| + eng := s.mediaCfg().MediaEngine |
| if eng == nil { |
| return out |
| } |
diff --git a/internal/console/mediapass_test.go b/internal/console/mediapass_test.go| index d7a469c43..65f7b8c7b 100644 |
| --- a/internal/console/mediapass_test.go |
| +++ b/internal/console/mediapass_test.go |
| @@ -6,6 +6,7 @@ import ( |
| "errors" |
| "fmt" |
| "net/http" |
| + "os" |
| "path/filepath" |
| "reflect" |
| "slices" |
| @@ -553,3 +554,142 @@ func TestMediaPassOutlivesAStalledCall(t *testing.T) { |
| t.Fatalf("account a's call stalled %d times after pass 2, want 2: the next tick ran", n) |
| } |
| } |
| + |
| +// TestMediaPassWiresMediaAfterACloudFailure (branch review round 1, |
| +// P2-2): a console whose boot could not reach the cloud retries the |
| +// wiring with capped backoff, installs it once the cloud answers, and only |
| +// then runs the pass, in the same worker: a row already running before the |
| +// restart is tracked, and every pass is that one worker's. |
| +func TestMediaPassWiresMediaAfterACloudFailure(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-pass-retry") |
| + wired := f.srv.cfg.MediaConfig |
| + var attempts atomic.Int64 |
| + f.srv.cfg.MediaConfig = MediaConfig{MediaRetry: func(ctx context.Context) (MediaConfig, bool, error) { |
| + if attempts.Add(1) < 3 { |
| + return MediaConfig{}, true, errors.New("the cloud account could not be reached: sts GetCallerIdentity: timed out") |
| + } |
| + return wired, false, nil |
| + }} |
| + f.srv.media = f.srv.newMediaJobs() |
| + if f.srv.mediaConfigured() { |
| + t.Fatal("configured before the retry") |
| + } |
| + var delays []time.Duration |
| + f.srv.mediaRetryWait = func(_ context.Context, d time.Duration) error { |
| + delays = append(delays, d) |
| + return nil |
| + } |
| + // A row running when the console restarted, its task's ARN not yet |
| + // saved: only a running pass recovers it. |
| + 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) |
| + } |
| + 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 ('acct-b', 'titogo', 'i', 'j', 'uploads/a.mov', 'e', 1, 'video-720p', 'short', 'b', 'running', ?, 'exec-b', ?, 600, 600, 0)`, |
| + f.clock.UnixMilli(), f.clock.UnixMilli()); err != nil { |
| + t.Fatal(err) |
| + } |
| + var logs strings.Builder |
| + restore := captureLogTo(&logs) |
| + defer restore() |
| + w := startMediaPass(f) // waits for pass 1 |
| + if n := attempts.Load(); n != 3 { |
| + t.Fatalf("%d attempts, want 3", n) |
| + } |
| + if want := []time.Duration{10 * time.Second, 20 * time.Second, 40 * time.Second}; !slices.Equal(delays, want) { |
| + t.Fatalf("waits %v, want %v", delays, want) |
| + } |
| + if !f.srv.mediaConfigured() || f.srv.mediaCfg().MediaEngine != f.engine { |
| + t.Fatal("the answered wiring is not in force") |
| + } |
| + var got string |
| + if err := f.st.db.QueryRow(`SELECT task_arn FROM media_jobs WHERE account = 'acct-b'`).Scan(&got); err != nil || got != arn { |
| + t.Fatalf("the running row's task %q (%v), want %q recovered by the first pass", got, err, arn) |
| + } |
| + w.tick(2, time.Second) // runs counted 2: one worker, one pass a tick |
| + if n := strings.Count(logs.String(), mediaOnAfterRetry); n != 1 { |
| + t.Fatalf("logged %q %d times, want once:\n%s", mediaOnAfterRetry, n, logs.String()) |
| + } |
| +} |
| + |
| +// TestMediaPassRunsOnce: while the worker's pass loop runs, a second |
| +// StartMediaPass returns at once without a pass, and the worker's passes |
| +// stay one a tick. |
| +func TestMediaPassRunsOnce(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-pass-once") |
| + w := startMediaPass(f) |
| + second := make(chan struct{}) |
| + go func() { f.srv.StartMediaPass(context.Background()); close(second) }() |
| + select { |
| + case <-second: |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("a second StartMediaPass is running a pass loop of its own") |
| + } |
| + w.tick(2, time.Second) |
| + w.tick(3, time.Second) |
| +} |
| + |
| +// TestMediaRetryStops: the retry gives up, with media left off and no |
| +// pass, on a wrong setting (logged once) and when the console stops. |
| +func TestMediaRetryStops(t *testing.T) { |
| + t.Run("a wrong setting", func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + fx.srv.cfg.MediaRetry = func(context.Context) (MediaConfig, bool, error) { |
| + return MediaConfig{}, false, errors.New("CARLOS_MEDIA_ENGINE: the engine is in account 1 but this console's credentials are in account 2") |
| + } |
| + fx.srv.mediaRetryWait = func(context.Context, time.Duration) error { return nil } |
| + var logs strings.Builder |
| + restore := captureLogTo(&logs) |
| + fx.srv.StartMediaPass(context.Background()) |
| + restore() |
| + if fx.srv.mediaConfigured() || fx.srv.mediaCfg().StoreConversion { |
| + t.Fatal("a refused wiring was installed") |
| + } |
| + if want := "console: media conversion stays off: CARLOS_MEDIA_ENGINE"; strings.Count(logs.String(), want) != 1 { |
| + t.Fatalf("log = %q, want %q once", logs.String(), want) |
| + } |
| + }) |
| + t.Run("the console stops", func(t *testing.T) { |
| + fx := newConsoleFixture(t) |
| + ctx, cancel := context.WithCancel(context.Background()) |
| + fx.srv.cfg.MediaRetry = func(context.Context) (MediaConfig, bool, error) { |
| + cancel() |
| + return MediaConfig{}, true, context.Canceled |
| + } |
| + fx.srv.mediaRetryWait = func(ctx context.Context, _ time.Duration) error { return ctx.Err() } |
| + fx.srv.StartMediaPass(ctx) // returns once ctx has ended |
| + if fx.srv.mediaConfigured() { |
| + t.Fatal("configured") |
| + } |
| + }) |
| +} |
| + |
| +// The retry's waits double from 10 seconds to a 10-minute cap. |
| +func TestMediaRetryDelay(t *testing.T) { |
| + want := []time.Duration{10 * time.Second, 20 * time.Second, 40 * time.Second, 80 * time.Second, 160 * time.Second, |
| + 320 * time.Second, 10 * time.Minute, 10 * time.Minute, 10 * time.Minute} |
| + for n, w := range want { |
| + if got := mediaRetryDelay(n); got != w { |
| + t.Errorf("wait %d = %s, want %s", n, got, w) |
| + } |
| + } |
| + if got := mediaRetryDelay(1000); got != mediaRetryMost { |
| + t.Errorf("wait 1000 = %s", got) |
| + } |
| +} |
| + |
| +// The retry's two log lines are the deck's rows. |
| +func TestMediaRetryLinesAreTheDecksWording(t *testing.T) { |
| + deck, err := os.ReadFile("../../docs/superpowers/notes/media-conversion-copy-deck.md") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + for key, line := range map[string]string{"console.media.on_after_retry": mediaOnAfterRetry, "console.media.retry_refused": mediaRetryRefused} { |
| + if !strings.Contains(string(deck), "| `"+key+"` | `"+line+"`") { |
| + t.Errorf("the deck has no %s row reading %q", key, line) |
| + } |
| + } |
| +} |
diff --git a/internal/console/mediaretire.go b/internal/console/mediaretire.go| index bbd7e7333..4dd044785 100644 |
| --- a/internal/console/mediaretire.go |
| +++ b/internal/console/mediaretire.go |
| @@ -43,7 +43,7 @@ func (s *Server) mediaStoreRetire(ctx context.Context, acct, app, env string) (r |
| if env != "" { |
| return "", nil |
| } |
| - pending, err := s.media.Retire(ctx, mediajobs.Scope{Account: acct, App: app}, s.now()) |
| + pending, err := s.mediaJobs().Retire(ctx, mediajobs.Scope{Account: acct, App: app}, s.now()) |
| if err != nil { |
| return "", err |
| } |
| @@ -60,7 +60,7 @@ func (s *Server) mediaStoreRetire(ctx context.Context, acct, app, env string) (r |
| // dispatch to use, and a dispatch that raced it holds a row whose task is |
| // not confirmed stopped, which pending counts. |
| func (s *Server) mediaAccountRetire(ctx context.Context, acct string) (refusal string, err error) { |
| - pending, err := s.media.Retire(ctx, mediajobs.Scope{Account: acct}, s.now()) |
| + pending, err := s.mediaJobs().Retire(ctx, mediajobs.Scope{Account: acct}, s.now()) |
| if err != nil { |
| return "", err |
| } |
diff --git a/internal/console/mediastore.go b/internal/console/mediastore.go| index 9d6e1632c..6e281db97 100644 |
| --- a/internal/console/mediastore.go |
| +++ b/internal/console/mediastore.go |
| @@ -66,7 +66,7 @@ func (s *Server) mediaStoreCheck(ctx context.Context, sqid, app string) (rec *ob |
| if rec == nil || rec.Provisioned == nil { |
| return rec, mediaCodeNoStore, "", nil |
| } |
| - b := s.cfg.StoreBuckets |
| + b := s.mediaCfg().StoreBuckets |
| if b == nil { |
| return nil, "", "", errStoreBucketsUnset |
| } |
| @@ -85,7 +85,7 @@ func (s *Server) mediaStoreCheck(ctx context.Context, sqid, app string) (rec *ob |
| want := storecfg.Want{ |
| Bucket: bucket, |
| MintedName: objstore.MintedBucketIn(s.cfg.StoreDeployment, sqid, app, ""), |
| - Account: s.cfg.StoreAccountID, |
| + Account: s.mediaCfg().StoreAccountID, |
| Region: rec.Provisioned.Region, |
| } |
| var uploads *objstore.Uploads |
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go| index 2524d3521..5da1324a1 100644 |
| --- a/internal/console/mediawire.go |
| +++ b/internal/console/mediawire.go |
| @@ -5,6 +5,7 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| + "sync/atomic" |
| "time" |
| "github.com/carlosframework/platform/internal/media" |
| @@ -45,6 +46,15 @@ type MediaConfig struct { |
| // StoreAccountID is the deployment's cloud account id, the owner every |
| // store bucket must have to pass verification. "" fails that check. |
| StoreAccountID string |
| + // MediaRetry wires media again: set, with everything above unset, when |
| + // the cloud did not answer at boot (cmd/console's media.go), so rows |
| + // already running are not left untracked until the next start (branch |
| + // review round 1, P2-2). StartMediaPass calls it with capped backoff |
| + // until it answers a configuration, installs that as a successful boot |
| + // would, and runs the pass. again is true when the cloud still did not |
| + // answer; an error with again false is a setting that is wrong, and |
| + // media stays off. |
| + MediaRetry func(ctx context.Context) (cfg MediaConfig, again bool, err error) |
| } |
| // settle is NewServer's check of the media configuration: zero limits |
| @@ -79,6 +89,61 @@ type mediaRuntime struct { |
| // engine, grants and store call (newMediaJobs). Tests set it; nothing |
| // in production does. |
| mediaCallTimeout time.Duration |
| + // mediaLate is media's wiring once installed after boot (installMedia); |
| + // nil until then, and on a console whose boot wired media itself. Read |
| + // through mediaCfg, mediaJobs and mediaRate. |
| + mediaLate atomic.Pointer[mediaWiring] |
| + // mediaRetryWait waits before each MediaRetry attempt; nil is a timer |
| + // that honours ctx. Tests set it; nothing in production does. |
| + mediaRetryWait func(ctx context.Context, d time.Duration) error |
| + // mediaPassRunning is true while a StartMediaPass loop runs. |
| + mediaPassRunning atomic.Bool |
| +} |
| + |
| +// mediaWiring is media's configuration and what is built from it, |
| +// installed whole when MediaRetry answers after boot. |
| +type mediaWiring struct { |
| + cfg MediaConfig |
| + jobs *mediajobs.Jobs |
| + limiter *mediaLimiter |
| +} |
| + |
| +// mediaCfg is the media configuration in force: the one installed after |
| +// boot, else Config's. Install happens once, from nothing configured to a |
| +// whole configuration, so reads within one request never go backwards. |
| +func (s *Server) mediaCfg() MediaConfig { |
| + if w := s.mediaLate.Load(); w != nil { |
| + return w.cfg |
| + } |
| + return s.cfg.MediaConfig |
| +} |
| + |
| +// mediaJobs is the media job table in force (see mediaCfg). |
| +func (s *Server) mediaJobs() *mediajobs.Jobs { |
| + if w := s.mediaLate.Load(); w != nil { |
| + return w.jobs |
| + } |
| + return s.media |
| +} |
| + |
| +// mediaRate is the door's submission limiter in force (see mediaCfg). |
| +func (s *Server) mediaRate() *mediaLimiter { |
| + if w := s.mediaLate.Load(); w != nil { |
| + return w.limiter |
| + } |
| + return s.mediaLimiter |
| +} |
| + |
| +// installMedia puts cfg in force after boot, exactly as NewServer would |
| +// have: its limits settled and checked, a job table and a limiter built |
| +// from it. |
| +func (s *Server) installMedia(cfg MediaConfig) error { |
| + cfg.MediaRetry = nil |
| + if err := cfg.settle(); err != nil { |
| + return err |
| + } |
| + s.mediaLate.Store(&mediaWiring{cfg: cfg, jobs: s.newMediaJobsFor(cfg), limiter: newMediaLimiter(cfg.MediaLimits)}) |
| + return nil |
| } |
| // initMedia builds the door's limiter and the job table from s.cfg, once |
| @@ -112,13 +177,16 @@ func (g consoleStoreGuard) Current(ctx context.Context, account, app string) (me |
| // MediaEngine is a console with no engine: the pass dispatches nothing and |
| // the door answers not_configured. NewServer calls it; a test that changes |
| // the media configuration after construction calls it again. |
| -func (s *Server) newMediaJobs() *mediajobs.Jobs { |
| +func (s *Server) newMediaJobs() *mediajobs.Jobs { return s.newMediaJobsFor(s.cfg.MediaConfig) } |
| + |
| +// newMediaJobsFor is newMediaJobs with cfg's engine, grants and limits. |
| +func (s *Server) newMediaJobsFor(cfg MediaConfig) *mediajobs.Jobs { |
| return mediajobs.New(s.store.db, mediajobs.Deps{ |
| - Engine: s.cfg.MediaEngine, |
| - Grants: s.cfg.MediaGrants, |
| + Engine: cfg.MediaEngine, |
| + Grants: cfg.MediaGrants, |
| Stores: consoleStoreGuard{s}, |
| Allowance: s.mediaAllowance, |
| - Limits: s.cfg.MediaLimits, |
| + Limits: cfg.MediaLimits, |
| Logf: log.Printf, |
| // A deleted or reaped account's remaining rows are retired by the |
| // pass once its tasks are confirmed stopped (Task 7 fix round 2). |
| @@ -172,7 +240,7 @@ func (s *Server) mediaAllowance(ctx context.Context, account string) (int64, err |
| return 0, nil |
| } |
| if s.cfg.PlanCatalog == nil { |
| - return s.cfg.MediaLimits.AccountMinutes, nil |
| + return s.mediaCfg().MediaLimits.AccountMinutes, nil |
| } |
| l, err := s.EffectiveLimits(acct) |
| if err != nil || l == nil { |
diff --git a/internal/console/planmeasure.go b/internal/console/planmeasure.go| index 4e013fd94..183f0667a 100644 |
| --- a/internal/console/planmeasure.go |
| +++ b/internal/console/planmeasure.go |
| @@ -67,7 +67,7 @@ func (s *Server) measureCaps(ctx context.Context, acct *Account, l *plans.Limits |
| // The door's figure (mediaFairUse): settled charges in the UTC |
| // month each job ended, so a job that ends after midnight on the |
| // last day counts in the month it ended. |
| - n, err := s.media.ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now)) |
| + n, err := s.mediaJobs().ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now)) |
| put(capMedia, n, int64(l.MediaMinutesMonth), err) |
| } |
| return got, errs |