console: media door fix round 1, limits in Submit, repeat path
Submit counts the account's queued and running rows and the deployment's queued rows in its own transaction, before the insert (ErrAccountBusy, ErrQueueFull), so two apps or two accounts that each saw the last place cannot both take it (Astra P1). The door maps them to 429 too_many_jobs and 503 queue_full. The repeat path runs before the walk lock and HEADs only when the table holds a live row for the key and preset (Jobs.Submitted), so a new key meets the store check before any HEAD and a poll never holds the lock dispatch needs (Astra P2, Fable Important 2). Each fast-path guard now has a test that fails without it (Fable Important 1). The claim refusal census takes 409, or the one status its message is given, never 0. NewServer refuses non-positive media limits.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8 files changed,
+456
−20
internal/console/apimedia.go+41 −14internal/console/apimedia_test.go+220 −2internal/console/claim_invariant_test.go+14 −1internal/console/mediawire.go+17 −0internal/console/server.go+6 −0internal/mediajobs/jobs.go+67 −3internal/mediajobs/jobs_test.go+86 −0internal/sim/mediajobs/actions_test.go+5 −0
diff --git a/internal/console/apimedia.go b/internal/console/apimedia.go| index ed5003846..6e06b9efd 100644 |
| --- a/internal/console/apimedia.go |
| +++ b/internal/console/apimedia.go |
| @@ -134,13 +134,15 @@ type mediaSource struct { |
| // 2. no engine configured: 503 not_configured |
| // 3. body not strict JSON of at most 4 KiB: readJSONStrictLimit's refusal |
| // 4. key: 400 bad_key; preset: 400 unknown_preset; class: 400 unknown_class |
| +// 5. a repeat POST of an existing job answers 200 with it (mediaRepeat), |
| +// before the walk lock and the bucket's incarnation tag (an app polls |
| +// with POST). It HEADs only when the table already holds a candidate |
| +// row for the key, and answers only where checks 7 to 10 pass, so for |
| +// a request with no row the refusals below keep the spec's order |
| +// exactly, and a new key is never HEADed before the store check. |
| // |
| -// then, under the app's store walk lock: |
| +// Then, under the app's store walk lock: |
| // |
| -// 5. a repeat POST of an existing job answers 200 with it (mediaRepeat), |
| -// before the bucket's incarnation tag is read (an app polls with POST). |
| -// It answers only where checks 7 to 10 pass, so for a request with no |
| -// row the refusals below keep the spec's order exactly |
| // 6. mediaStoreEligible: 409 no_store, 409 store_unverified |
| // 7. store region not the engine's: 409 no_engine_in_region |
| // 8. store writes denied: 402 store_writes_denied |
| @@ -151,7 +153,10 @@ type mediaSource struct { |
| // 13. plan cap: 402 plan_limit |
| // 14. fair use: 429 too_many_jobs, 503 queue_full, 429 rate_limited |
| // |
| -// and then Submit, 202 with the new job. |
| +// And then Submit, 202 with the new job. Submit counts the account's and |
| +// the deployment's rows again in its own transaction (the lock holds one |
| +// app only), answering 429 too_many_jobs or 503 queue_full when another |
| +// app or account took the last place meanwhile. |
| func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| _, acct, app, ok := s.apiAccountApp(w, r) |
| if !ok { |
| @@ -188,8 +193,6 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| ctx := r.Context() |
| - defer s.storeWalks.lock(acct.Sqid, app, "")() |
| - |
| job, found, src, err := s.mediaRepeat(ctx, acct.Sqid, app, body.Key, preset, body.Class) |
| if err != nil { |
| mediaInternal(w, "repeat lookup "+acct.Sqid+"/"+app, err) |
| @@ -199,6 +202,7 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| writeJSON(w, http.StatusOK, s.mediaAnswer(job)) |
| return |
| } |
| + defer s.storeWalks.lock(acct.Sqid, app, "")() |
| rec, code, check, err := s.mediaStoreEligible(ctx, acct, app) |
| if err != nil { |
| @@ -284,6 +288,9 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| return |
| } |
| + if s.mediaBeforeSubmit != nil { |
| + s.mediaBeforeSubmit() |
| + } |
| job, created, err := s.media.Submit(ctx, mediajobs.SubmitRequest{ |
| Account: acct.Sqid, App: app, Incarnation: inc, Bucket: bucket, |
| Key: body.Key, ETag: src.head.ETag, Preset: preset, Class: class, |
| @@ -295,6 +302,19 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| mediaRefuse(w, http.StatusConflict, media.CodeStoreChanged, mediaText("media.job.store_changed")) |
| return |
| } |
| + // The fair-use counts again, in Submit's own transaction: the walk lock |
| + // holds one app, so another app of the account, or another account, |
| + // 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)) |
| + return |
| + } |
| + if errors.Is(err, mediajobs.ErrQueueFull) { |
| + w.Header().Set("Retry-After", "60") |
| + mediaRefuse(w, http.StatusServiceUnavailable, "queue_full", mediaText("media.queue_full")) |
| + return |
| + } |
| if err != nil { |
| mediaInternal(w, "submit "+acct.Sqid+"/"+app, err) |
| return |
| @@ -308,12 +328,16 @@ func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) { |
| // mediaRepeat is the repeat POST's answer (Review Focus 3): an app that |
| // polls with POST must not cost a bucket tag read, a rate-limit token or a |
| -// fair-use count each time. It reads the store record (no tag), and only |
| -// when the record is verified, in the engine's region and not write-denied |
| -// (so no refusal of the ordered path could come first) it HEADs the source |
| -// and looks the job up under the record's incarnation. found is a live |
| -// row; otherwise src is the HEAD made, if any, for the ordered path to |
| -// reuse. |
| +// fair-use count each time, nor hold the app's walk lock (which dispatch |
| +// takes, one row at a time) over its network reads. It runs before the |
| +// lock. It reads the store record (no tag); only when the record is |
| +// verified, in the engine's region and not write-denied (so no refusal of |
| +// the ordered path could come first), and the table already holds a live |
| +// row of that incarnation for the key and preset (Jobs.Submitted), does it |
| +// HEAD the source, for the ETag the job id needs, and look the job up. |
| +// found is a live row; otherwise src is the HEAD made, if any, for the |
| +// ordered path to reuse. A key with no row is never HEADed here, so it |
| +// meets the store check before any HEAD. |
| // |
| // It trusts the record's incarnation without the tag, as GET does. That |
| // only ever answers a row that exists: a row of a stale incarnation never |
| @@ -328,6 +352,9 @@ func (s *Server) mediaRepeat(ctx context.Context, sqid, app, key, preset, class |
| if inc == "" || rec.Provisioned.Region != s.cfg.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 { |
| + return mediajobs.Job{}, false, nil, err |
| + } |
| bucket := rec.Provisioned.Bucket |
| h, herr := s.cfg.MediaGrants.Head(ctx, bucket, key) |
| src = &mediaSource{bucket: bucket, head: h, err: herr} |
diff --git a/internal/console/apimedia_test.go b/internal/console/apimedia_test.go| index d72c178ab..a141c15ce 100644 |
| --- a/internal/console/apimedia_test.go |
| +++ b/internal/console/apimedia_test.go |
| @@ -5,6 +5,7 @@ import ( |
| "encoding/json" |
| "net/http" |
| "strings" |
| + "sync" |
| "sync/atomic" |
| "testing" |
| "time" |
| @@ -24,6 +25,7 @@ type mediaDoorFixture struct { |
| *consoleFixture |
| t *testing.T |
| svc string |
| + member string // alice's CLI token: she may declare and grant stores |
| buckets *storecfg.Fake |
| engine *mediatest.FakeEngine |
| grants *countingGrants |
| @@ -46,8 +48,8 @@ const mediaTestKey = "uploads/a1b2.mov" |
| func newMediaDoor(t *testing.T, code string) *mediaDoorFixture { |
| t.Helper() |
| - fx, _, buckets, _ := grantedMediaStore(t, code) |
| - f := &mediaDoorFixture{consoleFixture: fx, t: t, buckets: buckets, bucket: mediaMintedName(fx), |
| + fx, _, buckets, member := grantedMediaStore(t, code) |
| + f := &mediaDoorFixture{consoleFixture: fx, t: t, member: member, buckets: buckets, bucket: mediaMintedName(fx), |
| clock: time.Now().UTC().Truncate(time.Millisecond)} |
| now := func() time.Time { return f.clock } |
| fx.srv.opNow = now |
| @@ -717,3 +719,219 @@ func TestMediaCopyCoversEveryCode(t *testing.T) { |
| } |
| } |
| } |
| + |
| +// staleHeadGrants answers a failed HEAD together with the last head it |
| +// answered for that key, as an adapter that fills metadata on an error |
| +// might. The door must take the error alone. |
| +type staleHeadGrants struct { |
| + *countingGrants |
| + mu sync.Mutex |
| + last map[string]media.ObjectHead |
| +} |
| + |
| +func (g *staleHeadGrants) Head(ctx context.Context, bucket, key string) (media.ObjectHead, error) { |
| + h, err := g.countingGrants.Head(ctx, bucket, key) |
| + g.mu.Lock() |
| + defer g.mu.Unlock() |
| + if err != nil { |
| + return g.last[bucket+"/"+key], err |
| + } |
| + g.last[bucket+"/"+key] = h |
| + return h, nil |
| +} |
| + |
| +// TestRepeatPathKeepsTheOrderedRefusals (Fable Important 1): a job is |
| +// submitted, then each change makes its repeat POST meet the ordered |
| +// path's refusal, not the fast path's 200. Each case fails when the fast |
| +// path's guard for it is removed. |
| +func TestRepeatPathKeepsTheOrderedRefusals(t *testing.T) { |
| + for _, tc := range []struct { |
| + name string |
| + change func(f *mediaDoorFixture) |
| + status int |
| + code string |
| + msg string |
| + }{ |
| + {"writes_denied", func(f *mediaDoorFixture) { |
| + if _, err := objstore.SetWritesDenied(context.Background(), f.rel, f.sqid, "titogo", "", |
| + &objstore.WritesDenied{Reason: "storage grace ended", At: f.clock}); err != nil { |
| + f.t.Fatal(err) |
| + } |
| + }, 402, "store_writes_denied", mediaText("media.store_writes_denied")}, |
| + {"region", func(f *mediaDoorFixture) { f.srv.cfg.MediaRegion = "us-east-1" }, |
| + 409, "no_engine_in_region", mediaText("media.no_engine_in_region", "us-east-1", "eu-west-1")}, |
| + {"infected", func(f *mediaDoorFixture) { |
| + o := f.grants.Objects[f.bucket+"/"+mediaTestKey] |
| + o.Infected = true |
| + f.grants.Objects[f.bucket+"/"+mediaTestKey] = o |
| + }, 409, "source_unreadable", mediaText("media.source_unreadable")}, |
| + {"deleted", func(f *mediaDoorFixture) { delete(f.grants.Objects, f.bucket+"/"+mediaTestKey) }, |
| + 404, "source_not_found", mediaText("media.source_not_found")}, |
| + {"over_the_maximum", func(f *mediaDoorFixture) { f.setLimits(func(l *media.Limits) { l.VideoBytes = 1 << 20 }) }, |
| + 413, "source_too_large", mediaText("media.source_too_large", "5 MB", "video-720p", "1 MB")}, |
| + } { |
| + t.Run(tc.name, func(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-repeat-"+tc.name) |
| + f.srv.cfg.MediaGrants = &staleHeadGrants{countingGrants: f.grants, last: map[string]media.ObjectHead{}} |
| + if r := f.submit(mediaTestKey); r.status != http.StatusAccepted { |
| + t.Fatalf("submit %d %s", r.status, r.raw) |
| + } |
| + if r := f.submit(mediaTestKey); r.status != http.StatusOK { |
| + t.Fatalf("repeat before the change %d %s", r.status, r.raw) |
| + } |
| + tc.change(f) |
| + wantMediaRefusal(t, f.submit(mediaTestKey), tc.status, tc.code, tc.msg) |
| + if n := f.rows(); n != 1 { |
| + t.Fatalf("%d rows", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestRepeatNeverHeadsANewKeyBeforeTheStoreCheck (Astra P2): the store's |
| +// verification has gone stale (its tag is gone and its bucket now uses |
| +// KMS). A key with no job meets store_unverified without a single HEAD. |
| +func TestRepeatNeverHeadsANewKeyBeforeTheStoreCheck(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-stale") |
| + if r := f.submit(mediaTestKey); r.status != http.StatusAccepted { |
| + t.Fatalf("submit %d %s", r.status, r.raw) |
| + } |
| + f.buckets.Tags[f.bucket] = map[string]string{} |
| + facts := goodBucket() |
| + facts.Encryption = "aws:kms" |
| + f.buckets.Facts[f.bucket] = facts |
| + f.put("uploads/new.mov", 10<<20, "new") |
| + heads := f.grants.heads.Load() |
| + wantMediaRefusal(t, f.submit("uploads/new.mov"), 409, "store_unverified", |
| + mediaText("media.store_unverified", mediaText("media.check."+storecfg.CheckEncryption))) |
| + if n := f.grants.heads.Load() - heads; n != 0 { |
| + t.Fatalf("%d HEADs before the store check", n) |
| + } |
| +} |
| + |
| +// TestRepeatPostTakesNoWalkLock (Fable Important 2): a poll answers while |
| +// the app's walk lock is held elsewhere (by dispatch, say). |
| +func TestRepeatPostTakesNoWalkLock(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-nolock") |
| + first := f.submit(mediaTestKey) |
| + if first.status != http.StatusAccepted { |
| + t.Fatalf("submit %d %s", first.status, first.raw) |
| + } |
| + unlock := f.srv.storeWalks.lock(f.sqid, "titogo", "") |
| + defer unlock() |
| + done := make(chan mediaReply, 1) |
| + go func() { |
| + status, header, raw := rawReq(t, http.MethodPost, f.url("titogo"), f.svc, `{"key":"`+mediaTestKey+`"}`) |
| + var r mediaReply |
| + r.status, r.header, r.raw = status, header, raw |
| + _ = json.Unmarshal([]byte(raw), &r.job) |
| + done <- r |
| + }() |
| + select { |
| + case r := <-done: |
| + if r.status != http.StatusOK || r.job.ID != first.job.ID { |
| + t.Fatalf("repeat %d %s", r.status, r.raw) |
| + } |
| + case <-time.After(10 * time.Second): |
| + t.Fatal("the repeat POST waited for the walk lock") |
| + } |
| +} |
| + |
| +// TestDoorLastPlaceRaceAcrossApps (Astra P1): the account has one place |
| +// left. A submission for titogo passes the door's counts, and before it |
| +// reaches Submit one for blog, another app under another walk lock, takes |
| +// the place. Exactly one is admitted; the other is 429 too_many_jobs. |
| +func TestDoorLastPlaceRaceAcrossApps(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-race-apps") |
| + f.setLimits(func(l *media.Limits) { l.AccountActive = 2 }) |
| + f.seed(f.sqid, "seeded-1", "queued", 0) |
| + if _, err := f.st.CreateAppIn(OpsAccountID, "blog", "paul@keymail.dev", time.Now()); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, path := range []string{"", "/grant"} { |
| + if status, out := postJSON(t, storeURL(f.consoleFixture, "blog")+path, map[string]any{}, f.member); status != http.StatusOK { |
| + t.Fatalf("blog store%s = %d %v", path, status, out) |
| + } |
| + } |
| + blogBucket := objstore.MintedBucketIn(f.srv.cfg.StoreDeployment, f.sqid, "blog", "") |
| + f.buckets.Facts[blogBucket] = goodBucket() |
| + f.grants.Objects[blogBucket+"/"+mediaTestKey] = mediatest.Object{Size: 5 << 20, ETag: "blog-etag"} |
| + blog := serviceToken(t, f.st, OpsAccountID, "blog-media", "blog", svcrole.Service) |
| + |
| + var raced atomic.Bool |
| + var other mediaReply |
| + f.srv.mediaBeforeSubmit = func() { |
| + if raced.CompareAndSwap(false, true) { |
| + other = f.post(blog, "blog", `{"key":"uploads/a1b2.mov"}`) |
| + } |
| + } |
| + r := f.submit(mediaTestKey) |
| + if other.status != http.StatusAccepted { |
| + t.Fatalf("blog, first to Submit: %d %s", other.status, other.raw) |
| + } |
| + wantMediaRefusal(t, r, 429, "too_many_jobs", mediaText("media.busy_account", 2)) |
| + if got := r.header.Get("Retry-After"); got != "30" { |
| + t.Fatalf("Retry-After %q", got) |
| + } |
| + if n := f.rows(); n != 2 { |
| + t.Fatalf("%d rows, want the seeded one and blog's", n) |
| + } |
| +} |
| + |
| +// TestDoorLastPlaceRaceAcrossAccounts (Astra P1): the deployment's queue |
| +// has one place left. A submission passes the door's counts, and before it |
| +// reaches Submit another account's submission takes the place. The door |
| +// answers 503 queue_full and writes nothing. |
| +func TestDoorLastPlaceRaceAcrossAccounts(t *testing.T) { |
| + f := newMediaDoor(t, "code-media-race-accounts") |
| + f.setLimits(func(l *media.Limits) { l.Queue = 2 }) |
| + f.seed("yyyy", "seeded-other", "queued", 0) |
| + var raced atomic.Bool |
| + f.srv.mediaBeforeSubmit = func() { |
| + if !raced.CompareAndSwap(false, true) { |
| + return |
| + } |
| + if _, created, err := f.srv.media.Submit(context.Background(), mediajobs.SubmitRequest{ |
| + Account: "zzzz", App: "shop", Incarnation: "inc-zzzz", Bucket: "carlos-zzzz-shop", Key: "uploads/z.mov", |
| + ETag: "z", Preset: media.PresetVideo720p, Class: media.ClassShort, Bytes: 1, Now: f.clock, |
| + }); err != nil || !created { |
| + t.Errorf("the other account's submission: %v %v", created, err) |
| + } |
| + } |
| + r := f.submit(mediaTestKey) |
| + wantMediaRefusal(t, r, 503, "queue_full", mediaText("media.queue_full")) |
| + if got := r.header.Get("Retry-After"); got != "60" { |
| + t.Fatalf("Retry-After %q", got) |
| + } |
| + if n := f.rows(); n != 2 { |
| + t.Fatalf("%d rows, want the two other accounts'", n) |
| + } |
| +} |
| + |
| +// TestNewServerRefusesBadMediaLimits: a non-positive figure (a zero |
| +// PerMinute would divide by zero in the limiter) refuses the boot, as the |
| +// PDF limits do; account_minutes 0 is no limit and boots. |
| +func TestNewServerRefusesBadMediaLimits(t *testing.T) { |
| + boot := func(l media.Limits) error { |
| + _, err := NewServer(Config{Origin: "https://console.example", Keymail: "https://keymail.example", MediaLimits: l}, openTestStore(t)) |
| + return err |
| + } |
| + for name, change := range map[string]func(*media.Limits){ |
| + "per_minute": func(l *media.Limits) { l.PerMinute = 0 }, |
| + "burst": func(l *media.Limits) { l.Burst = -1 }, |
| + "queue": func(l *media.Limits) { l.Queue = 0 }, |
| + "video_max": func(l *media.Limits) { l.VideoMax = 0 }, |
| + "minutes": func(l *media.Limits) { l.AccountMinutes = -1 }, |
| + } { |
| + l := media.DefaultLimits() |
| + change(&l) |
| + if err := boot(l); err == nil || !strings.Contains(err.Error(), "CARLOS_MEDIA_LIMITS") { |
| + t.Errorf("%s: NewServer = %v, want the limits refused", name, err) |
| + } |
| + } |
| + l := media.DefaultLimits() |
| + l.AccountMinutes = 0 |
| + if err := boot(l); err != nil { |
| + t.Fatalf("default limits: %v", err) |
| + } |
| +} |
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go| index a4ad890e9..284331ac6 100644 |
| --- a/internal/console/claim_invariant_test.go |
| +++ b/internal/console/claim_invariant_test.go |
| @@ -103,6 +103,16 @@ var claimUnsupportedStatus = map[string]int{ |
| mediaText("media.claims_console"): http.StatusServiceUnavailable, |
| } |
| +// claimRefusalStatus is the one status a refusal with msg may answer: 409, |
| +// or the status claimUnsupportedStatus names for msg. |
| +func claimRefusalStatus(msg string) int { |
| + want := http.StatusConflict |
| + if s, ok := claimUnsupportedStatus[msg]; ok { |
| + want = s |
| + } |
| + return want |
| +} |
| + |
| // claimUnsupported is the closed list of operations an enabled console |
| // refuses on purpose, keyed by the exact message production answers. Only |
| // these may be a refused fixture; every other app mutator is a door that |
| @@ -479,7 +489,7 @@ func claimFixtureCensus(entries []claimEntry, fixtures map[string]claimFixture) |
| switch { |
| case len(r.apps) == 0 || r.do == nil: |
| problems = append(problems, fmt.Sprintf("claim fixture %s is a refusal with no affected app or no request", key)) |
| - case r.status != http.StatusConflict && claimUnsupportedStatus[r.msg] != r.status: |
| + case r.status != claimRefusalStatus(r.msg): |
| problems = append(problems, fmt.Sprintf("claim fixture %s is a refusal answering %d: only the explicit 409 of an intentionally "+ |
| "unsupported operation, or the status claimUnsupportedStatus names for its message, can be one "+ |
| "(never 401, 403, 404 or a generic error)", key, r.status)) |
| @@ -1046,6 +1056,9 @@ func TestClaimConsoleMutationInvariantWitnesses(t *testing.T) { |
| "401": {claimRefusalFixture{apps: claimWitnessApps, do: do, status: http.StatusUnauthorized, msg: claimMoveUnsupportedMsg}, "answering 401"}, |
| "404": {claimRefusalFixture{apps: claimWitnessApps, do: do, status: http.StatusNotFound, msg: claimMoveUnsupportedMsg}, "answering 404"}, |
| "503": {claimRefusalFixture{apps: claimWitnessApps, do: do, status: http.StatusServiceUnavailable, msg: claimMoveUnsupportedMsg}, "answering 503"}, |
| + "no status": {claimRefusalFixture{apps: claimWitnessApps, do: do, msg: claimMoveUnsupportedMsg}, "answering 0"}, |
| + "media 409": {claimRefusalFixture{apps: claimWitnessApps, do: do, status: http.StatusConflict, msg: mediaText("media.claims_console")}, "answering 409"}, |
| + "media none": {claimRefusalFixture{apps: claimWitnessApps, do: do, msg: mediaText("media.claims_console")}, "answering 0"}, |
| "generic 409": {claimRefusalFixture{apps: claimWitnessApps, do: do, status: http.StatusConflict, msg: claimRetireBusyMsg}, "not an intentionally unsupported operation"}, |
| "no request": {claimRefusalFixture{apps: claimWitnessApps, status: http.StatusConflict, msg: claimMoveUnsupportedMsg}, "no affected app or no request"}, |
| } { |
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go| index 4dbedbbfd..854a944f7 100644 |
| --- a/internal/console/mediawire.go |
| +++ b/internal/console/mediawire.go |
| @@ -2,9 +2,11 @@ package console |
| import ( |
| "context" |
| + "errors" |
| "fmt" |
| "log" |
| + "github.com/carlosframework/platform/internal/media" |
| "github.com/carlosframework/platform/internal/mediajobs" |
| "github.com/carlosframework/platform/internal/plans" |
| ) |
| @@ -44,6 +46,21 @@ func (s *Server) newMediaJobs() *mediajobs.Jobs { |
| }) |
| } |
| +// validMediaLimits refuses media limits NewServer cannot run with, as the |
| +// PDF limits are refused: every figure positive (a zero PerMinute would |
| +// divide by zero in the limiter), account_minutes at least 0 (0 is no |
| +// limit). media.ParseLimits gives only such limits; this holds for a |
| +// Config built any other way. |
| +func validMediaLimits(l media.Limits) error { |
| + ok := l.VideoMax > 0 && l.VideoMaxHi > 0 && l.AudioMax > 0 && l.VideoBytes > 0 && l.AudioBytes > 0 && |
| + l.AccountMinutes >= 0 && l.Short > 0 && l.Long > 0 && l.AccountShort > 0 && l.AccountLong > 0 && |
| + l.AccountActive > 0 && l.PerMinute > 0 && l.Burst > 0 && l.Queue > 0 |
| + if !ok { |
| + return errors.New("CARLOS_MEDIA_LIMITS: every limit must be positive (account_minutes may be 0)") |
| + } |
| + return nil |
| +} |
| + |
| // mediaAllowance is the account's media_minutes_month, 0 meaning no limit |
| // (spec §7.3): 0 for the plan-exempt ops account; with no plan catalog the |
| // deployment's one per-account figure (CARLOS_MEDIA_LIMITS |
diff --git a/internal/console/server.go b/internal/console/server.go| index 8987154cb..7770a5063 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -1104,6 +1104,9 @@ type Server struct { |
| // is configured; mediaLimiter is the door's submission rate. |
| media *mediajobs.Jobs |
| mediaLimiter *mediaLimiter |
| + // mediaBeforeSubmit, when set, runs after the door's checks and before |
| + // Submit: a test seam for two submissions racing for the last place. |
| + mediaBeforeSubmit func() |
| // manifestSeen is the sqids whose accounts/<sqid>/account.json this |
| // process has seen exist (read, or written by the backfill), so an app |
| @@ -1997,6 +2000,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| if cfg.MediaLimits == (media.Limits{}) { |
| cfg.MediaLimits = media.DefaultLimits() |
| } |
| + if err := validMediaLimits(cfg.MediaLimits); err != nil { |
| + return nil, err |
| + } |
| if cfg.Billing != nil && cfg.PlanCatalog == nil { |
| return nil, errors.New("billing needs a plan catalog (CARLOS_PLAN_CATALOG)") |
| } |
diff --git a/internal/mediajobs/jobs.go b/internal/mediajobs/jobs.go| index ea8ac33d4..dc9901c7d 100644 |
| --- a/internal/mediajobs/jobs.go |
| +++ b/internal/mediajobs/jobs.go |
| @@ -27,6 +27,16 @@ import ( |
| // store_changed (plan 2 pre-flight F3). |
| var ErrRetired = errors.New("mediajobs: the job's row is retired") |
| +// ErrAccountBusy and ErrQueueFull are Submit's fair-use refusals (spec |
| +// §7.2): the account already has Limits.AccountActive rows queued or |
| +// running, or the deployment Limits.Queue rows queued. Submit counts them |
| +// in its own transaction, so two doors that each saw one place left cannot |
| +// both take it. The door answers 429 too_many_jobs and 503 queue_full. |
| +var ( |
| + ErrAccountBusy = errors.New("mediajobs: the account has as many jobs queued or running as it may") |
| + ErrQueueFull = errors.New("mediajobs: the deployment's queue is full") |
| +) |
| + |
| // ErrLaunchStale is Launch's answer for a launch more than |
| // media.GrantMintSlack after its row's dispatched_at, or whose grant would |
| // outlive the row's cleanup bound: no task was started, and the row was |
| @@ -268,7 +278,10 @@ func guarded(ctx context.Context, tx *sql.Tx, query string, args ...any) (bool, |
| } |
| // Submit inserts a queued row, or answers the existing one with created |
| -// false; ErrRetired when that row is retired. |
| +// false; ErrRetired when that row is retired. A new row is refused |
| +// ErrAccountBusy or ErrQueueFull when the fair-use counts, read in the |
| +// same transaction as the insert, are at their limits (a limit of 0 is |
| +// none); an existing row is answered whatever the counts. |
| func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error) { |
| if r.Account == "" || r.App == "" || r.Incarnation == "" || r.Bucket == "" || r.Key == "" || r.ETag == "" { |
| return Job{}, false, errors.New("mediajobs: incomplete submit request") |
| @@ -292,6 +305,9 @@ func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error) { |
| job = existing[0] |
| return nil |
| } |
| + if err := j.admit(ctx, tx, r.Account); err != nil { |
| + return err |
| + } |
| if _, err := tx.ExecContext(ctx, `INSERT INTO media_jobs |
| (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at) |
| VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, |
| @@ -315,6 +331,54 @@ func (j *Jobs) Submit(ctx context.Context, r SubmitRequest) (Job, bool, error) { |
| return job, created, nil |
| } |
| +// admit is Submit's fair-use check, inside its transaction: the account's |
| +// queued or running rows, then the deployment's queued rows, as Counts |
| +// reads them. |
| +func (j *Jobs) admit(ctx context.Context, tx *sql.Tx, account string) error { |
| + l := j.d.Limits |
| + if l.AccountActive > 0 { |
| + var active int |
| + if err := tx.QueryRowContext(ctx, countActiveSQL, account).Scan(&active); err != nil { |
| + return err |
| + } |
| + if active >= l.AccountActive { |
| + return ErrAccountBusy |
| + } |
| + } |
| + if l.Queue > 0 { |
| + var queued int |
| + if err := tx.QueryRowContext(ctx, countQueuedSQL).Scan(&queued); err != nil { |
| + return err |
| + } |
| + if queued >= l.Queue { |
| + return ErrQueueFull |
| + } |
| + } |
| + return nil |
| +} |
| + |
| +// The fair-use counts: an account's queued or running rows, and the |
| +// deployment's queued rows. |
| +const ( |
| + countActiveSQL = `SELECT COUNT(*) FROM media_jobs WHERE account = ? AND state IN ('queued', 'running')` |
| + countQueuedSQL = `SELECT COUNT(*) FROM media_jobs WHERE state = 'queued'` |
| +) |
| + |
| +// Submitted reports whether the store incarnation has a live row for key |
| +// in preset: the door's repeat candidate, read before it HEADs anything. |
| +// class "long" asks for a long row only; "" or "short" may have become |
| +// either (media.PickClass), so they ask for any. |
| +func (j *Jobs) Submitted(ctx context.Context, account, app, incarnation, key, preset, class string) (bool, error) { |
| + if class != media.ClassLong { |
| + class = "" |
| + } |
| + var n int |
| + err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs |
| + WHERE account = ? AND app = ? AND incarnation = ? AND key = ? AND preset = ? AND (? = '' OR class = ?) AND retired_at = 0`, |
| + account, app, incarnation, key, preset, class, class).Scan(&n) |
| + return n > 0, err |
| +} |
| + |
| // Lookup answers the row by its key; never a retired row. |
| func (j *Jobs) Lookup(ctx context.Context, account, app, incarnation, id string) (Job, bool, error) { |
| rows, err := queryJobs(ctx, j.db, `SELECT `+jobColumns+` FROM media_jobs |
| @@ -328,10 +392,10 @@ func (j *Jobs) Lookup(ctx context.Context, account, app, incarnation, id string) |
| // Counts answers the account's queued or running rows and the |
| // deployment's queued rows. |
| func (j *Jobs) Counts(ctx context.Context, account string) (accountActive, deploymentQueued int, err error) { |
| - if err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE account = ? AND state IN ('queued', 'running')`, account).Scan(&accountActive); err != nil { |
| + if err := j.db.QueryRowContext(ctx, countActiveSQL, account).Scan(&accountActive); err != nil { |
| return 0, 0, err |
| } |
| - if err := j.db.QueryRowContext(ctx, `SELECT COUNT(*) FROM media_jobs WHERE state = 'queued'`).Scan(&deploymentQueued); err != nil { |
| + if err := j.db.QueryRowContext(ctx, countQueuedSQL).Scan(&deploymentQueued); err != nil { |
| return 0, 0, err |
| } |
| return accountActive, deploymentQueued, nil |
diff --git a/internal/mediajobs/jobs_test.go b/internal/mediajobs/jobs_test.go| index f5cdfeb05..999c3e325 100644 |
| --- a/internal/mediajobs/jobs_test.go |
| +++ b/internal/mediajobs/jobs_test.go |
| @@ -338,6 +338,92 @@ func TestSubmitOnARetiredRow(t *testing.T) { |
| } |
| } |
| +// submitReq is the request h.submit makes, without the harness's checks. |
| +func (h *harness) submitReq(account, app, key string, size int64) SubmitRequest { |
| + s := h.store(account, app) |
| + etag := fmt.Sprintf("%032x", len(key)*7919+int(size%7919)) |
| + h.gr.Objects[s.Bucket+"/"+key] = mediatest.Object{Size: size, ETag: etag} |
| + return SubmitRequest{Account: account, App: app, Incarnation: s.Incarnation, Bucket: s.Bucket, |
| + Key: key, ETag: etag, Preset: video, Class: media.ClassShort, Bytes: size, Now: h.now} |
| +} |
| + |
| +// TestSubmitHoldsTheAccountLimit (Astra P1, fix round 1): with one place |
| +// left for the account, submissions for two of its apps both reach Submit |
| +// (each door's own count saw the place); exactly one is admitted, and an |
| +// existing job is still answered at the limit. |
| +func TestSubmitHoldsTheAccountLimit(t *testing.T) { |
| + h := newHarness(t, "account_active=2", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + shop, blog := h.submitReq("acct1", "shop", "uploads/b.mov", 10<<20), h.submitReq("acct1", "blog", "uploads/c.mov", 10<<20) |
| + if active, _, err := h.jobs.Counts(tctx, "acct1"); err != nil || active != 1 { |
| + t.Fatalf("counts %d %v", active, err) |
| + } |
| + if _, created, err := h.jobs.Submit(tctx, blog); err != nil || !created { |
| + t.Fatalf("blog: created %v, %v", created, err) |
| + } |
| + if _, _, err := h.jobs.Submit(tctx, shop); !errors.Is(err, ErrAccountBusy) { |
| + t.Fatalf("shop past the limit: %v, want ErrAccountBusy", err) |
| + } |
| + if active, _, err := h.jobs.Counts(tctx, "acct1"); err != nil || active != 2 { |
| + t.Fatalf("counts %d %v, want 2", active, err) |
| + } |
| + again, created, err := h.jobs.Submit(tctx, h.submitReq("acct1", "shop", a.Key, a.Bytes)) |
| + if err != nil || created || again.ID != a.ID { |
| + t.Fatalf("an existing job at the limit: %+v %v %v", again, created, err) |
| + } |
| + // Another account is not held by acct1's limit. |
| + if _, created, err := h.jobs.Submit(tctx, h.submitReq("acct2", "shop", "uploads/d.mov", 10<<20)); err != nil || !created { |
| + t.Fatalf("acct2: %v %v", created, err) |
| + } |
| +} |
| + |
| +// TestSubmitHoldsTheQueueLimit: with one place left in the deployment's |
| +// queue, submissions from two accounts: exactly one is admitted. |
| +func TestSubmitHoldsTheQueueLimit(t *testing.T) { |
| + h := newHarness(t, "queue=2", nil) |
| + h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + one, two := h.submitReq("acct1", "blog", "uploads/b.mov", 10<<20), h.submitReq("acct2", "shop", "uploads/c.mov", 10<<20) |
| + if _, created, err := h.jobs.Submit(tctx, two); err != nil || !created { |
| + t.Fatalf("acct2: created %v, %v", created, err) |
| + } |
| + if _, _, err := h.jobs.Submit(tctx, one); !errors.Is(err, ErrQueueFull) { |
| + t.Fatalf("acct1 past the queue: %v, want ErrQueueFull", err) |
| + } |
| + if _, queued, err := h.jobs.Counts(tctx, "acct1"); err != nil || queued != 2 { |
| + t.Fatalf("queued %d %v, want 2", queued, err) |
| + } |
| +} |
| + |
| +// TestSubmittedIsTheRepeatCandidate: the door's pre-HEAD candidate is a |
| +// live row of the incarnation for the key and preset; long asks for long. |
| +func TestSubmittedIsTheRepeatCandidate(t *testing.T) { |
| + h := newHarness(t, "", nil) |
| + a := h.submit("acct1", "shop", "uploads/a.mov", video, "", 10<<20) |
| + inc := h.store("acct1", "shop").Incarnation |
| + for _, c := range []struct { |
| + app, inc, key, preset, class string |
| + want bool |
| + }{ |
| + {"shop", inc, a.Key, video, "", true}, |
| + {"shop", inc, a.Key, video, media.ClassShort, true}, |
| + {"shop", inc, a.Key, video, media.ClassLong, false}, |
| + {"shop", inc, a.Key, media.PresetAudioAAC, "", false}, |
| + {"shop", inc, "uploads/other.mov", video, "", false}, |
| + {"shop", "inc-other", a.Key, video, "", false}, |
| + {"blog", inc, a.Key, video, "", false}, |
| + } { |
| + if got, err := h.jobs.Submitted(tctx, "acct1", c.app, c.inc, c.key, c.preset, c.class); err != nil || got != c.want { |
| + t.Errorf("%+v: %v %v", c, got, err) |
| + } |
| + } |
| + if _, err := h.jobs.Retire(tctx, Scope{"acct1", "shop"}, h.now); err != nil { |
| + t.Fatal(err) |
| + } |
| + if got, err := h.jobs.Submitted(tctx, "acct1", "shop", inc, a.Key, video, ""); err != nil || got { |
| + t.Fatalf("a retired row is a candidate: %v %v", got, err) |
| + } |
| +} |
| + |
| // TestRetireAccountWide (pre-flight F2): App "" is every app of the |
| // account and nothing of another account. |
| func TestRetireAccountWide(t *testing.T) { |
diff --git a/internal/sim/mediajobs/actions_test.go b/internal/sim/mediajobs/actions_test.go| index e9b742c76..0dafc37b7 100644 |
| --- a/internal/sim/mediajobs/actions_test.go |
| +++ b/internal/sim/mediajobs/actions_test.go |
| @@ -145,6 +145,11 @@ func actSubmit(w *world) bool { |
| w.events["door-retired"]++ |
| return true |
| } |
| + if errors.Is(err, mj.ErrAccountBusy) || errors.Is(err, mj.ErrQueueFull) { |
| + w.logf("submit %s %s %s/%s: %v", ref, key, preset, class, err) |
| + w.events["door-fair-use"]++ |
| + return false |
| + } |
| w.errAccepted("submit", err, false) |
| if err != nil { |
| return false |