carlos / platform Public

console: media conversion door

POST and GET /api/cli/apps/{account}/{app}/media/conversions[/{id}],
Service doors through apiAccountApp, with the spec's refusal table in
order (spec §5.2, §11 A1 and A3; plan 2 Task 5). Every message comes
from the media conversion copy deck by key (media_copy.go).

A repeat POST of an existing job answers 200 before the bucket's
incarnation tag is read, and before the revision gate, the plan cap,
fair use and the rate limiter, so an app that polls with POST costs no
GetBucketTagging and no token. Dispatch's store guard answers through
mediaStoreFacts, so dispatch re-reads the tag. Store eligibility on a
first POST runs under the store walk lock, outside any transaction.

media_jobs joins the schema and the claim SQL gate (Refuse). Both
doors are refused fixtures answering 503 claims_console; the refusal
census admits that one message's 503 by name (claimUnsupportedStatus).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 2cd7378123d7ca434b9b08e59ba798eca604e8b0 parent 8e3907b
13 files changed, +1,512 −4
  • internal/console/apimedia.go +419 −0
  • internal/console/apimedia_test.go +719 −0
  • internal/console/claim_invariant_fixtures_test.go +12 −0
  • internal/console/claim_invariant_test.go +15 −2
  • internal/console/media_copy.go +138 −0
  • internal/console/medialimit.go +77 −0
  • internal/console/mediawire.go +80 −0
  • internal/console/plancaps_copy.go +4 −0
  • internal/console/routedecls.go +6 −0
  • internal/console/server.go +31 −2
  • internal/console/store.go +8 −0
  • internal/console/store_gate.go +1 −0
  • internal/console/testdata/claim-routes.txt +2 −0
diff --git a/internal/console/apimedia.go b/internal/console/apimedia.go
new file mode 100644
index 000000000..ed5003846
--- /dev/null
+++ b/internal/console/apimedia.go
@@ -0,0 +1,419 @@
+package console
+
+import (
+ "context"
+ "errors"
+ "log"
+ "net/http"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediajobs"
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/storecfg"
+)
+
+// The media conversion door (media conversion spec §5.2, §5.3, §11 A1 and
+// A3): POST submits a source object of the app's own store for conversion,
+// GET reads one job back. Both are Service doors resolved through
+// apiAccountApp, like the PDF and scan doors; s.allowWrite does not apply.
+//
+// Every refusal is jsonErrorCode with the copy deck's message by key
+// (media_copy.go). No network call is made inside a SQLite transaction, and
+// the store walk lock is taken before any transaction.
+
+// mediaBodyLimit is the POST body's cap: a key of at most 512 bytes and
+// two short words.
+const mediaBodyLimit = 4 << 10
+
+// mediaSubmitBody is the POST body, decoded strictly.
+type mediaSubmitBody struct {
+ Key string `json:"key"`
+ Preset string `json:"preset"`
+ Class string `json:"class"`
+}
+
+// mediaJobAnswer is a job as both doors answer it.
+type mediaJobAnswer struct {
+ ID string `json:"id"`
+ State string `json:"state"`
+ Key string `json:"key"`
+ Preset string `json:"preset"`
+ Class string `json:"class"`
+ SubmittedAt time.Time `json:"submitted_at"`
+ Error *mediaJobError `json:"error,omitempty"`
+ Source *mediaJobSource `json:"source,omitempty"`
+ FFmpeg string `json:"ffmpeg,omitempty"`
+ Outputs []mediaJobOutput `json:"outputs,omitempty"`
+}
+
+// mediaJobError is a failed job's error: its code, and the deck's message
+// for that code.
+type mediaJobError struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+}
+
+// mediaJobSource is what the codec's probe found of a done job's source.
+type mediaJobSource struct {
+ DurationMS int64 `json:"duration_ms"`
+ Width int `json:"width,omitempty"`
+ Height int `json:"height,omitempty"`
+ VideoCodec string `json:"video_codec,omitempty"`
+ AudioCodec string `json:"audio_codec,omitempty"`
+}
+
+// mediaJobOutput is one output of a done job, by its key in the app's
+// store.
+type mediaJobOutput struct {
+ Key string `json:"key"`
+ Bytes int64 `json:"bytes"`
+ ETag string `json:"etag"`
+ ContentType string `json:"content_type"`
+ Width int `json:"width,omitempty"`
+ Height int `json:"height,omitempty"`
+}
+
+// mediaAnswer is j as the doors answer it. A failed job's message comes
+// from the deck by its code, never from the result object.
+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)}
+ case "done":
+ if r := j.Result; r != nil {
+ if r.Source != nil {
+ a.Source = &mediaJobSource{DurationMS: r.Source.DurationMS, Width: r.Source.Width, Height: r.Source.Height,
+ VideoCodec: r.Source.VideoCodec, AudioCodec: r.Source.AudioCodec}
+ }
+ a.FFmpeg = r.FFmpeg
+ prefix := media.OutputPrefix(j.Key, j.ETag, j.Preset, j.Execution)
+ for _, o := range r.Outputs {
+ a.Outputs = append(a.Outputs, mediaJobOutput{Key: prefix + o.Name, Bytes: o.Bytes, ETag: o.ETag,
+ ContentType: o.ContentType, Width: o.Width, Height: o.Height})
+ }
+ }
+ }
+ return a
+}
+
+// mediaRefuse answers one door refusal.
+func mediaRefuse(w http.ResponseWriter, status int, code, msg string) {
+ jsonErrorCode(w, status, code, msg)
+}
+
+// mediaInternal logs err and answers the console's plain 500.
+func mediaInternal(w http.ResponseWriter, what string, err error) {
+ log.Printf("console: media %s: %v", what, err)
+ jsonError(w, http.StatusInternalServerError, "internal error")
+}
+
+// mediaConfigured is whether this console can convert: an engine, object
+// access, the engine's region to hold stores to, and a way to read store
+// buckets for the store check. Plan 3's boot wiring sets them together;
+// 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
+}
+
+// mediaSource is one HEAD of a source: the bucket asked, and its answer.
+type mediaSource struct {
+ bucket string
+ head media.ObjectHead
+ err error
+}
+
+// handleAPIMediaSubmit is POST /api/cli/apps/{account}/{app}/media/conversions.
+// After apiAccountApp (so a stranger meets its 404 first), its checks run
+// in the order below and stop at the first failure; none writes a row.
+//
+// 1. host-claim console: 503 claims_console (spec §11 A1)
+// 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
+//
+// 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
+// 9. HEAD of the key: 404 source_not_found, 409 source_unreadable
+// 10. size 0 or over the preset's maximum: 413 source_too_large
+// 11. the class and job id; an existing row answers 200 with it
+// 12. the engine's revision gate: 503 engine_misconfigured
+// 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.
+func (s *Server) handleAPIMediaSubmit(w http.ResponseWriter, r *http.Request) {
+ _, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return
+ }
+ if s.cfg.HostClaim {
+ mediaRefuse(w, http.StatusServiceUnavailable, "claims_console", mediaText("media.claims_console"))
+ return
+ }
+ if !s.mediaConfigured() {
+ mediaRefuse(w, http.StatusServiceUnavailable, "not_configured", mediaText("media.not_configured"))
+ return
+ }
+ var body mediaSubmitBody
+ if !readJSONStrictLimit(w, r, &body, mediaBodyLimit) {
+ return
+ }
+ if !media.ValidKey(body.Key) {
+ mediaRefuse(w, http.StatusBadRequest, "bad_key", mediaText("media.bad_key"))
+ return
+ }
+ preset := body.Preset
+ if preset == "" {
+ preset = media.PresetVideo720p
+ }
+ if preset != media.PresetVideo720p && preset != media.PresetAudioAAC {
+ mediaRefuse(w, http.StatusBadRequest, "unknown_preset", mediaText("media.unknown_preset"))
+ return
+ }
+ switch body.Class {
+ case "", media.ClassShort, media.ClassLong:
+ default:
+ mediaRefuse(w, http.StatusBadRequest, "unknown_class", mediaText("media.unknown_class"))
+ 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)
+ return
+ }
+ if found {
+ writeJSON(w, http.StatusOK, s.mediaAnswer(job))
+ return
+ }
+
+ rec, code, check, err := s.mediaStoreEligible(ctx, acct, app)
+ if err != nil {
+ mediaInternal(w, "store check "+acct.Sqid+"/"+app, err)
+ return
+ }
+ switch code {
+ case "":
+ case mediaCodeNoStore:
+ mediaRefuse(w, http.StatusConflict, mediaCodeNoStore, mediaText("media.no_store", app, app))
+ return
+ case mediaCodeStoreUnverified:
+ mediaRefuse(w, http.StatusConflict, mediaCodeStoreUnverified, mediaText("media.store_unverified", mediaText("media.check."+check)))
+ return
+ default:
+ 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))
+ return
+ }
+ if rec.WritesDenied != nil {
+ mediaRefuse(w, http.StatusPaymentRequired, media.CodeStoreWritesDenied, mediaText("media.store_writes_denied"))
+ return
+ }
+ bucket := rec.Provisioned.Bucket
+ if src == nil || src.bucket != bucket {
+ h, err := s.cfg.MediaGrants.Head(ctx, bucket, body.Key)
+ src = &mediaSource{bucket: bucket, head: h, err: err}
+ }
+ switch {
+ case errors.Is(src.err, media.ErrNotFound):
+ mediaRefuse(w, http.StatusNotFound, media.CodeSourceNotFound, mediaText("media.source_not_found"))
+ return
+ case errors.Is(src.err, media.ErrDenied):
+ mediaRefuse(w, http.StatusConflict, media.CodeSourceUnreadable, mediaText("media.source_unreadable"))
+ return
+ case src.err != nil:
+ mediaInternal(w, "head "+acct.Sqid+"/"+app, src.err)
+ return
+ }
+ size, limit := src.head.Size, s.cfg.MediaLimits.MaxBytes(preset)
+ if size <= 0 {
+ mediaRefuse(w, http.StatusRequestEntityTooLarge, media.CodeSourceTooLarge, mediaText("media.source_empty"))
+ return
+ }
+ if size > limit {
+ mediaRefuse(w, http.StatusRequestEntityTooLarge, media.CodeSourceTooLarge,
+ mediaText("media.source_too_large", billingBytes(size), preset, billingBytes(limit)))
+ return
+ }
+ 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 {
+ mediaInternal(w, "lookup "+acct.Sqid+"/"+app, err)
+ return
+ } else if found {
+ writeJSON(w, http.StatusOK, s.mediaAnswer(job))
+ return
+ }
+
+ if err := s.cfg.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)
+ mediaRefuse(w, http.StatusServiceUnavailable, "engine_misconfigured", mediaText("media.engine_misconfigured"))
+ return
+ }
+ mediaInternal(w, "revision check "+preset+"/"+class, err)
+ return
+ }
+ now := s.now()
+ if ref, err := s.mediaFairUse(ctx, acct, now); err != nil {
+ mediaInternal(w, "admission "+acct.Sqid, err)
+ return
+ } else if ref != nil {
+ if ref.RetryAfter > 0 {
+ w.Header().Set("Retry-After", strconv.Itoa(ref.RetryAfter))
+ }
+ mediaRefuse(w, ref.Status, ref.Code, ref.Msg)
+ return
+ }
+
+ 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,
+ Bytes: size, Now: now,
+ })
+ if errors.Is(err, mediajobs.ErrRetired) {
+ // Pre-flight F3: the row exists for this incarnation but was retired
+ // (a teardown that failed after the retire kept the store).
+ mediaRefuse(w, http.StatusConflict, media.CodeStoreChanged, mediaText("media.job.store_changed"))
+ return
+ }
+ if err != nil {
+ mediaInternal(w, "submit "+acct.Sqid+"/"+app, err)
+ return
+ }
+ status := http.StatusAccepted
+ if !created {
+ status = http.StatusOK
+ }
+ writeJSON(w, status, s.mediaAnswer(job))
+}
+
+// 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.
+//
+// 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
+// dispatches (dispatch re-reads the tag, mediaStoreFacts), and a new job is
+// never admitted here.
+func (s *Server) mediaRepeat(ctx context.Context, sqid, app, key, preset, class string) (job mediajobs.Job, found bool, src *mediaSource, err error) {
+ rec, _, err := objstore.GetIn(ctx, s.cfg.Releases, sqid, app, "")
+ if err != nil {
+ return mediajobs.Job{}, false, nil, err
+ }
+ inc := recordIncarnation(rec)
+ if inc == "" || rec.Provisioned.Region != s.cfg.MediaRegion || rec.WritesDenied != nil {
+ return mediajobs.Job{}, false, nil, nil
+ }
+ bucket := rec.Provisioned.Bucket
+ h, herr := s.cfg.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) {
+ 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)
+ return job, found, src, err
+}
+
+// recordIncarnation is the incarnation a store record says its store has:
+// "" for no record, no provisioned store, or no verified conversion block.
+func recordIncarnation(rec *objstore.Record) string {
+ if rec == nil || rec.Provisioned == nil || rec.Conversion == nil || rec.Conversion.VerifiedAt == nil ||
+ !storecfg.ValidIncarnation(rec.Conversion.Incarnation) {
+ return ""
+ }
+ return rec.Conversion.Incarnation
+}
+
+// mediaFairUse is the plan cap and the fair-use limits (spec §7.2, §7.3),
+// in order: 402 plan_limit at twice the allowance, 429 too_many_jobs, 503
+// queue_full, and last the rate limiter, so only a submission that passes
+// everything else takes a token.
+func (s *Server) mediaFairUse(ctx context.Context, acct *Account, now time.Time) (*mediaRefusal, error) {
+ limit, err := s.mediaAllowance(ctx, acct.Sqid)
+ if err != nil {
+ return nil, err
+ }
+ if limit > 0 {
+ used, err := s.media.ChargedMinutes(ctx, acct.Sqid, pdfMonthStart(now))
+ if err != nil {
+ return nil, err
+ }
+ if used/2 >= limit {
+ 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)
+ if err != nil {
+ return nil, err
+ }
+ if active >= l.AccountActive {
+ return &mediaRefusal{Status: http.StatusTooManyRequests, Code: "too_many_jobs", Msg: mediaText("media.busy_account", l.AccountActive), RetryAfter: 30}, nil
+ }
+ 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
+}
+
+// handleAPIMediaGet is GET /api/cli/apps/{account}/{app}/media/conversions/{id}:
+// the job under the store record's current incarnation, read without the
+// walk lock. A host-claim console refuses first (pre-flight F22); an absent
+// or retired row, or a store with no verified incarnation, is 404
+// job_not_found.
+func (s *Server) handleAPIMediaGet(w http.ResponseWriter, r *http.Request) {
+ _, acct, app, ok := s.apiAccountApp(w, r)
+ if !ok {
+ return
+ }
+ if s.cfg.HostClaim {
+ mediaRefuse(w, http.StatusServiceUnavailable, "claims_console", mediaText("media.claims_console"))
+ return
+ }
+ ctx := r.Context()
+ rec, _, err := objstore.GetIn(ctx, s.cfg.Releases, acct.Sqid, app, "")
+ if err != nil {
+ mediaInternal(w, "store record "+acct.Sqid+"/"+app, err)
+ return
+ }
+ inc := recordIncarnation(rec)
+ if inc == "" {
+ 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"))
+ if err != nil {
+ mediaInternal(w, "lookup "+acct.Sqid+"/"+app, err)
+ return
+ }
+ if !found {
+ mediaRefuse(w, http.StatusNotFound, "job_not_found", mediaText("media.job_not_found"))
+ return
+ }
+ writeJSON(w, http.StatusOK, s.mediaAnswer(job))
+}
diff --git a/internal/console/apimedia_test.go b/internal/console/apimedia_test.go
new file mode 100644
index 000000000..d72c178ab
--- /dev/null
+++ b/internal/console/apimedia_test.go
@@ -0,0 +1,719 @@
+package console
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/media/mediatest"
+ "github.com/carlosframework/platform/internal/mediajobs"
+ "github.com/carlosframework/platform/internal/objstore"
+ "github.com/carlosframework/platform/internal/storecfg"
+ "github.com/carlosframework/platform/internal/svcrole"
+)
+
+// mediaDoorFixture is a console whose app titogo has a granted store with a
+// bucket that passes every check, a fake engine and fake grants on one
+// clock, and a Service credential bound to titogo.
+type mediaDoorFixture struct {
+ *consoleFixture
+ t *testing.T
+ svc string
+ buckets *storecfg.Fake
+ engine *mediatest.FakeEngine
+ grants *countingGrants
+ bucket string
+ clock time.Time
+}
+
+// countingGrants counts HEADs of the fake grants.
+type countingGrants struct {
+ *mediatest.FakeGrants
+ heads atomic.Int64
+}
+
+func (g *countingGrants) Head(ctx context.Context, bucket, key string) (media.ObjectHead, error) {
+ g.heads.Add(1)
+ return g.FakeGrants.Head(ctx, bucket, key)
+}
+
+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),
+ clock: time.Now().UTC().Truncate(time.Millisecond)}
+ now := func() time.Time { return f.clock }
+ fx.srv.opNow = now
+ f.engine = mediatest.NewFakeEngine(now)
+ f.grants = &countingGrants{FakeGrants: mediatest.NewFakeGrants(now)}
+ fx.srv.cfg.MediaEngine = f.engine
+ fx.srv.cfg.MediaGrants = f.grants
+ fx.srv.cfg.MediaRegion = "eu-west-1"
+ f.setLimits(func(*media.Limits) {})
+ f.svc = serviceToken(t, fx.st, OpsAccountID, "media", "titogo", svcrole.Service)
+ f.put(mediaTestKey, 5<<20, "9b2cf535f27731c974343645a3985328")
+ return f
+}
+
+// setLimits changes the deployment's media limits and rebuilds what reads
+// them.
+func (f *mediaDoorFixture) setLimits(change func(*media.Limits)) {
+ l := media.DefaultLimits()
+ change(&l)
+ f.srv.cfg.MediaLimits = l
+ f.srv.media = f.srv.newMediaJobs()
+ f.srv.mediaLimiter = newMediaLimiter(l)
+}
+
+func (f *mediaDoorFixture) put(key string, size int64, etag string) {
+ f.grants.Objects[f.bucket+"/"+key] = mediatest.Object{Size: size, ETag: etag}
+}
+
+func (f *mediaDoorFixture) url(app string) string {
+ return f.ts.URL + "/api/cli/apps/" + f.sqid + "/" + app + "/media/conversions"
+}
+
+// mediaReply is one door answer.
+type mediaReply struct {
+ status int
+ header http.Header
+ raw string
+ job mediaJobAnswer
+ err struct{ Error, Code string }
+}
+
+func (f *mediaDoorFixture) post(token, app, body string) mediaReply {
+ f.t.Helper()
+ status, header, raw := rawReq(f.t, http.MethodPost, f.url(app), token, body)
+ return decodeMediaReply(f.t, status, header, raw)
+}
+
+func (f *mediaDoorFixture) submit(key string) mediaReply {
+ f.t.Helper()
+ b, _ := json.Marshal(map[string]string{"key": key})
+ return f.post(f.svc, "titogo", string(b))
+}
+
+func (f *mediaDoorFixture) get(id string) mediaReply {
+ f.t.Helper()
+ status, header, raw := rawReq(f.t, http.MethodGet, f.url("titogo")+"/"+id, f.svc, "")
+ return decodeMediaReply(f.t, status, header, raw)
+}
+
+func decodeMediaReply(t *testing.T, status int, header http.Header, raw string) mediaReply {
+ t.Helper()
+ r := mediaReply{status: status, header: header, raw: raw}
+ if status < 300 {
+ if err := json.Unmarshal([]byte(raw), &r.job); err != nil {
+ t.Fatalf("answer %d %q: %v", status, raw, err)
+ }
+ } else {
+ _ = json.Unmarshal([]byte(raw), &r.err)
+ }
+ return r
+}
+
+func (f *mediaDoorFixture) rows() int {
+ f.t.Helper()
+ var n int
+ if err := f.st.db.QueryRow(`SELECT COUNT(*) FROM media_jobs`).Scan(&n); err != nil {
+ f.t.Fatal(err)
+ }
+ return n
+}
+
+// seed inserts a row straight into media_jobs.
+func (f *mediaDoorFixture) seed(account, id, state string, sourceMS int64) {
+ f.t.Helper()
+ settled, ended := 0, int64(0)
+ if state == "done" {
+ settled, ended = 1, f.clock.UnixMilli()
+ }
+ if _, err := f.st.db.Exec(`INSERT INTO media_jobs
+ (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at, settled, source_ms, ended_at)
+ VALUES (?, 'titogo', 'seeded', ?, 'uploads/seed.mov', 'e', 1, 'video-720p', 'short', 'b', ?, ?, ?, ?, ?)`,
+ account, id, state, f.clock.UnixMilli(), settled, sourceMS, ended); err != nil {
+ f.t.Fatal(err)
+ }
+}
+
+func wantMediaRefusal(t *testing.T, r mediaReply, status int, code, msg string) {
+ t.Helper()
+ if r.status != status || r.err.Code != code || r.err.Error != msg {
+ t.Fatalf("answer %d %s, want %d {code %q, error %q}", r.status, r.raw, status, code, msg)
+ }
+}
+
+// TestDoorRefusalOrder: one subtest per refusal, in the door's order, each
+// set up so every earlier check passes. Each answers its status, code and
+// deck message, and writes no row (pre-flight F20: the count is unchanged,
+// since three rows need rows seeded first).
+func TestDoorRefusalOrder(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ setup func(f *mediaDoorFixture)
+ token func(f *mediaDoorFixture) string
+ app string
+ body string
+ status int
+ code string
+ msg func(f *mediaDoorFixture) string
+ retry string
+ }{
+ {name: "claims_console", setup: func(f *mediaDoorFixture) { f.srv.cfg.HostClaim = true },
+ status: 503, code: "claims_console", msg: func(*mediaDoorFixture) string { return mediaText("media.claims_console") }},
+ {name: "not_configured", setup: func(f *mediaDoorFixture) { f.srv.cfg.MediaEngine = nil },
+ status: 503, code: "not_configured", msg: func(*mediaDoorFixture) string { return mediaText("media.not_configured") }},
+ {name: "strict_json", body: `{"key":"uploads/a1b2.mov","priority":"high"}`, status: 400, code: "",
+ msg: func(*mediaDoorFixture) string {
+ return `json: unknown field "priority" — this door refuses a body it does not fully understand rather than acting on the part it does`
+ }},
+ {name: "bad_key", body: `{"key":"derived/uploads/a1b2.mov"}`,
+ status: 400, code: "bad_key", msg: func(*mediaDoorFixture) string { return mediaText("media.bad_key") }},
+ {name: "unknown_preset", body: `{"key":"uploads/a1b2.mov","preset":"video-1080p"}`,
+ status: 400, code: "unknown_preset", msg: func(*mediaDoorFixture) string { return mediaText("media.unknown_preset") }},
+ {name: "unknown_class", body: `{"key":"uploads/a1b2.mov","class":"medium"}`,
+ status: 400, code: "unknown_class", msg: func(*mediaDoorFixture) string { return mediaText("media.unknown_class") }},
+ {name: "no_store", app: "blog",
+ setup: func(f *mediaDoorFixture) {
+ if _, err := f.st.CreateAppIn(OpsAccountID, "blog", "paul@keymail.dev", time.Now()); err != nil {
+ f.t.Fatal(err)
+ }
+ },
+ token: func(f *mediaDoorFixture) string {
+ return serviceToken(f.t, f.st, OpsAccountID, "blog-media", "blog", svcrole.Service)
+ },
+ status: 409, code: "no_store", msg: func(*mediaDoorFixture) string { return mediaText("media.no_store", "blog", "blog") }},
+ {name: "store_unverified",
+ setup: func(f *mediaDoorFixture) {
+ facts := goodBucket()
+ facts.Encryption = "aws:kms"
+ f.buckets.Facts[f.bucket] = facts
+ },
+ status: 409, code: "store_unverified",
+ msg: func(*mediaDoorFixture) string {
+ return mediaText("media.store_unverified", mediaText("media.check."+storecfg.CheckEncryption))
+ }},
+ {name: "no_engine_in_region", setup: func(f *mediaDoorFixture) { f.srv.cfg.MediaRegion = "us-east-1" },
+ status: 409, code: "no_engine_in_region",
+ msg: func(*mediaDoorFixture) string {
+ return mediaText("media.no_engine_in_region", "us-east-1", "eu-west-1")
+ }},
+ {name: "store_writes_denied",
+ setup: 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)
+ }
+ },
+ status: 402, code: "store_writes_denied", msg: func(*mediaDoorFixture) string { return mediaText("media.store_writes_denied") }},
+ {name: "source_not_found", body: `{"key":"uploads/missing.mov"}`,
+ status: 404, code: "source_not_found", msg: func(*mediaDoorFixture) string { return mediaText("media.source_not_found") }},
+ {name: "source_unreadable",
+ setup: func(f *mediaDoorFixture) {
+ f.grants.Objects[f.bucket+"/"+mediaTestKey] = mediatest.Object{Size: 5 << 20, ETag: "e", Infected: true}
+ },
+ status: 409, code: "source_unreadable", msg: func(*mediaDoorFixture) string { return mediaText("media.source_unreadable") }},
+ {name: "source_empty", setup: func(f *mediaDoorFixture) { f.put(mediaTestKey, 0, "d41d8cd98f00b204e9800998ecf8427e") },
+ status: 413, code: "source_too_large", msg: func(*mediaDoorFixture) string { return mediaText("media.source_empty") }},
+ {name: "source_too_large", setup: func(f *mediaDoorFixture) { f.put(mediaTestKey, 40<<30+100<<20, "e-9") },
+ status: 413, code: "source_too_large",
+ msg: func(*mediaDoorFixture) string {
+ return mediaText("media.source_too_large", "40.1 GB", "video-720p", "40 GB")
+ }},
+ {name: "engine_misconfigured",
+ setup: func(f *mediaDoorFixture) {
+ f.engine.Misconfigure(media.ClassKey{Preset: media.PresetVideo720p, Class: media.ClassShort}, "read_only")
+ },
+ status: 503, code: "engine_misconfigured", msg: func(*mediaDoorFixture) string { return mediaText("media.engine_misconfigured") }},
+ {name: "plan_limit",
+ setup: func(f *mediaDoorFixture) {
+ f.st.planExemptID = 0
+ f.setLimits(func(l *media.Limits) { l.AccountMinutes = 10 })
+ f.seed(f.sqid, "seeded-done", "done", 20*60_000) // 20 video minutes: twice the limit
+ },
+ status: 402, code: "plan_limit", msg: func(*mediaDoorFixture) string { return capMessage("cli.cap.media_minutes", 20, 10) }},
+ {name: "too_many_jobs",
+ setup: func(f *mediaDoorFixture) {
+ f.setLimits(func(l *media.Limits) { l.AccountActive = 2 })
+ f.seed(f.sqid, "seeded-1", "queued", 0)
+ f.seed(f.sqid, "seeded-2", "queued", 0)
+ },
+ status: 429, code: "too_many_jobs", msg: func(*mediaDoorFixture) string { return mediaText("media.busy_account", 2) }, retry: "30"},
+ {name: "queue_full",
+ setup: func(f *mediaDoorFixture) {
+ f.setLimits(func(l *media.Limits) { l.Queue = 1 })
+ f.seed("zzzz", "seeded-other", "queued", 0)
+ },
+ status: 503, code: "queue_full", msg: func(*mediaDoorFixture) string { return mediaText("media.queue_full") }, retry: "60"},
+ {name: "rate_limited",
+ setup: func(f *mediaDoorFixture) {
+ f.setLimits(func(l *media.Limits) { l.PerMinute, l.Burst = 30, 1 })
+ if ref := f.srv.mediaLimiter.acquire(f.sqid, f.clock); ref != nil {
+ f.t.Fatalf("spend the token: %+v", ref)
+ }
+ },
+ status: 429, code: "rate_limited", msg: func(*mediaDoorFixture) string { return mediaText("media.rate", 30) }, retry: "2"},
+ {name: "accepted", status: 202},
+ } {
+ t.Run(tc.name, func(t *testing.T) {
+ f := newMediaDoor(t, "code-media-order-"+tc.name)
+ if tc.setup != nil {
+ tc.setup(f)
+ }
+ token, app, body := f.svc, "titogo", `{"key":"uploads/a1b2.mov"}`
+ if tc.token != nil {
+ token = tc.token(f)
+ }
+ if tc.app != "" {
+ app = tc.app
+ }
+ if tc.body != "" {
+ body = tc.body
+ }
+ before := f.rows()
+ r := f.post(token, app, body)
+ if tc.status == 202 {
+ if r.status != 202 || r.job.State != "queued" || f.rows() != before+1 {
+ t.Fatalf("the passing request answered %d %s, rows %d to %d", r.status, r.raw, before, f.rows())
+ }
+ return
+ }
+ wantMediaRefusal(t, r, tc.status, tc.code, tc.msg(f))
+ if got := r.header.Get("Retry-After"); got != tc.retry {
+ t.Fatalf("Retry-After %q, want %q", got, tc.retry)
+ }
+ if n := f.rows(); n != before {
+ t.Fatalf("media_jobs went from %d to %d rows", before, n)
+ }
+ })
+ }
+}
+
+// TestDoorNotConfiguredNeedsEveryPart: an engine alone is not a
+// configured console; each missing part is not_configured, before the body
+// is read.
+func TestDoorNotConfiguredNeedsEveryPart(t *testing.T) {
+ for name, unset := range map[string]func(*Config){
+ "grants": func(c *Config) { c.MediaGrants = nil },
+ "region": func(c *Config) { c.MediaRegion = "" },
+ "buckets": func(c *Config) { c.StoreBuckets = nil },
+ } {
+ t.Run(name, func(t *testing.T) {
+ f := newMediaDoor(t, "code-media-unset-"+name)
+ unset(&f.srv.cfg)
+ wantMediaRefusal(t, f.post(f.svc, "titogo", `not json`), 503, "not_configured", mediaText("media.not_configured"))
+ if n := f.grants.heads.Load(); n != 0 || f.rows() != 0 {
+ t.Fatalf("heads %d rows %d", n, f.rows())
+ }
+ })
+ }
+}
+
+// TestDoorKeysPeopleActuallyUpload (Review Focus 1): phone-style keys
+// convert with the key echoed byte for byte, and the payload's source
+// transfer fetches exactly that object; a dot segment is bad_key.
+func TestDoorKeysPeopleActuallyUpload(t *testing.T) {
+ f := newMediaDoor(t, "code-media-keys")
+ f.setLimits(func(l *media.Limits) { l.AccountShort = 4 })
+ keys := []string{
+ "uploads/IMG 0001 (1).MOV",
+ "uploads/vidéo.mov", // NFC
+ "uploads/vidéo.mov", // NFD
+ "a+b%20c.mov",
+ }
+ ids := map[string]string{}
+ for i, k := range keys {
+ f.put(k, int64(1000+i), "etag-"+string(rune('a'+i)))
+ r := f.submit(k)
+ if r.status != http.StatusAccepted || r.job.Key != k {
+ t.Fatalf("%q: %d %s", k, r.status, r.raw)
+ }
+ ids[r.job.ID] = k
+ }
+ if len(ids) != len(keys) {
+ t.Fatalf("job ids %v: NFC and NFD must be two jobs", ids)
+ }
+ if err := f.srv.media.Pass(context.Background(), f.clock); err != nil {
+ t.Fatal(err)
+ }
+ execs := f.engine.Executions()
+ if len(execs) != len(keys) {
+ t.Fatalf("%d executions, want %d", len(execs), len(keys))
+ }
+ fetched := map[string]bool{}
+ for _, x := range execs {
+ reqs := f.engine.Requests(x)
+ var p media.Payload
+ if err := json.Unmarshal(reqs[0].Payload, &p); err != nil {
+ t.Fatal(err)
+ }
+ h, err := f.grants.Fetch(p.Transfers.URL(p.Transfers.Source))
+ if err != nil {
+ t.Fatalf("source transfer of %s: %v (%s)", x, err, p.Transfers.Source.URL)
+ }
+ for i, k := range keys {
+ if o := f.grants.Objects[f.bucket+"/"+k]; o.Size == h.Size && o.ETag == h.ETag {
+ fetched[k] = true
+ if want := "etag-" + string(rune('a'+i)); h.ETag != want {
+ t.Fatalf("%q fetched ETag %q", k, h.ETag)
+ }
+ }
+ }
+ }
+ if len(fetched) != len(keys) {
+ t.Fatalf("fetched %v, want every key", fetched)
+ }
+ r := f.submit("x/../derived/y.mov")
+ wantMediaRefusal(t, r, 400, "bad_key", mediaText("media.bad_key"))
+}
+
+// TestRepeatPostIsNotRateLimited (Review Focus 3): 50 POSTs of one key
+// within a second answer one 202 and 49 200s with the same job, write one
+// row, never 429, read the bucket's tag only for the first, and take no
+// rate-limit token after the first.
+func TestRepeatPostIsNotRateLimited(t *testing.T) {
+ f := newMediaDoor(t, "code-media-repeat")
+ first := f.submit(mediaTestKey)
+ if first.status != http.StatusAccepted {
+ t.Fatalf("first POST %d %s", first.status, first.raw)
+ }
+ tagReads := f.buckets.CallCount("BucketTags")
+ if tagReads == 0 {
+ t.Fatal("the first POST read no bucket tag")
+ }
+ for i := 0; i < 49; i++ {
+ f.clock = f.clock.Add(10 * time.Millisecond)
+ r := f.submit(mediaTestKey)
+ if r.status != http.StatusOK || r.job.ID != first.job.ID {
+ t.Fatalf("repeat %d: %d %s", i+1, r.status, r.raw)
+ }
+ }
+ if n := f.rows(); n != 1 {
+ t.Fatalf("%d rows, want 1", n)
+ }
+ if n := f.buckets.CallCount("BucketTags"); n != tagReads {
+ t.Fatalf("repeat POSTs read the bucket tag %d more times", n-tagReads)
+ }
+ if n := len(f.engine.Executions()); n != 0 {
+ t.Fatalf("repeat POSTs started %d executions", n)
+ }
+ if u, err := f.srv.media.Usage(context.Background(), f.sqid, f.clock); err != nil || u != (mediajobs.Usage{}) {
+ t.Fatalf("usage %+v, %v; want nothing charged or reserved", u, err)
+ }
+ // The burst is 10: had the repeats taken tokens, a new key would now be
+ // refused.
+ f.put("uploads/other.mov", 2000, "other")
+ if r := f.submit("uploads/other.mov"); r.status != http.StatusAccepted {
+ t.Fatalf("a new key after the repeats: %d %s", r.status, r.raw)
+ }
+}
+
+// TestDoorOtherAppOrAccount: a Service credential bound to another app, and
+// an account-wide one of another account, both meet the same 404 before the
+// door HEADs anything.
+func TestDoorOtherAppOrAccount(t *testing.T) {
+ f := newMediaDoor(t, "code-media-other")
+ if _, err := f.st.CreateAppIn(OpsAccountID, "shop", serviceMinter, time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ shop := serviceToken(t, f.st, OpsAccountID, "shop-media", "shop", svcrole.Service)
+ if err := f.st.CreateAccount(42, "cdef", "widgets", "bob@keymail.dev", time.Now()); err != nil {
+ t.Fatal(err)
+ }
+ // A Service credential must name one app, so the account-wide bearer of
+ // another account is a person's: bob owns widgets and nothing of bab.
+ other := cliToken(t, f.consoleFixture, "bob@keymail.dev", "code-media-other-bob")
+ for name, token := range map[string]string{"other app": shop, "other account": other} {
+ r := f.post(token, "titogo", `{"key":"uploads/a1b2.mov"}`)
+ if r.status != http.StatusNotFound {
+ t.Fatalf("%s POST: %d %s", name, r.status, r.raw)
+ }
+ status, _, raw := rawReq(t, http.MethodGet, f.url("titogo")+"/0123456789abcdef0123456789abcdef", token, "")
+ if status != http.StatusNotFound {
+ t.Fatalf("%s GET: %d %s", name, status, raw)
+ }
+ }
+ if n := f.grants.heads.Load(); n != 0 {
+ t.Fatalf("the door made %d HEADs for a stranger", n)
+ }
+ if n := f.rows(); n != 0 {
+ t.Fatalf("%d rows", n)
+ }
+}
+
+// TestDoorInfectedSourceWithEnforcementOff (spec §9): with scan
+// enforcement off the object is still readable to the store user, but the
+// conversion role's HEAD is denied on an infected tag: 409
+// source_unreadable.
+func TestDoorInfectedSourceWithEnforcementOff(t *testing.T) {
+ f := newMediaDoor(t, "code-media-infected")
+ if rec := storedRecord(t, f.consoleFixture, "titogo"); rec.Scanning != nil && rec.Scanning.Enforce != nil {
+ t.Fatalf("the fixture enforces: %+v", rec.Scanning)
+ }
+ f.grants.Objects[f.bucket+"/"+mediaTestKey] = mediatest.Object{Size: 5 << 20, ETag: "e", Infected: true}
+ wantMediaRefusal(t, f.submit(mediaTestKey), 409, "source_unreadable", mediaText("media.source_unreadable"))
+ if n := f.rows(); n != 0 {
+ t.Fatalf("%d rows", n)
+ }
+}
+
+// TestGetHidesRetiredAndOtherIncarnations: GET answers the job under the
+// store record's incarnation only, and never a retired row.
+func TestGetHidesRetiredAndOtherIncarnations(t *testing.T) {
+ f := newMediaDoor(t, "code-media-get-hide")
+ sub := f.submit(mediaTestKey)
+ if sub.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", sub.status, sub.raw)
+ }
+ if r := f.get(sub.job.ID); r.status != http.StatusOK || r.job.ID != sub.job.ID || r.job.Key != mediaTestKey {
+ t.Fatalf("GET %d %s", r.status, r.raw)
+ }
+ notFound := mediaText("media.job_not_found")
+ wantMediaRefusal(t, f.get("0123456789abcdef0123456789abcdef"), 404, "job_not_found", notFound)
+
+ ctx := context.Background()
+ rec, etag, err := objstore.GetIn(ctx, f.rel, f.sqid, "titogo", "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ kept := rec.Conversion.Incarnation
+ rec.Conversion.Incarnation = strings.Repeat("ab", len(kept)/2)
+ etag, err = objstore.PutIn(ctx, f.rel, f.sqid, "titogo", "", rec, etag)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wantMediaRefusal(t, f.get(sub.job.ID), 404, "job_not_found", notFound)
+ rec.Conversion.Incarnation = kept
+ if _, err := objstore.PutIn(ctx, f.rel, f.sqid, "titogo", "", rec, etag); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.get(sub.job.ID); r.status != http.StatusOK {
+ t.Fatalf("GET after the incarnation came back: %d %s", r.status, r.raw)
+ }
+
+ if _, err := f.srv.media.Retire(ctx, mediajobs.Scope{Account: f.sqid, App: "titogo"}, f.clock); err != nil {
+ t.Fatal(err)
+ }
+ wantMediaRefusal(t, f.get(sub.job.ID), 404, "job_not_found", notFound)
+ // A repeat POST of the retired job is store_changed (pre-flight F3),
+ // never the retired row.
+ wantMediaRefusal(t, f.submit(mediaTestKey), 409, "store_changed", mediaText("media.job.store_changed"))
+}
+
+// TestGetDoneAnswerShape drives one job through the real pass to done and
+// reads the answer: the source facts, the ffmpeg version, and each output
+// under the execution's prefix.
+func TestGetDoneAnswerShape(t *testing.T) {
+ f := newMediaDoor(t, "code-media-done")
+ ctx := context.Background()
+ sub := f.submit(mediaTestKey)
+ if sub.status != http.StatusAccepted || sub.job.Class != "short" || sub.job.Preset != "video-720p" {
+ t.Fatalf("submit %d %s", sub.status, sub.raw)
+ }
+ if err := f.srv.media.Pass(ctx, f.clock); err != nil {
+ t.Fatal(err)
+ }
+ execs := f.engine.Executions()
+ tasks := f.engine.Tasks()
+ if len(execs) != 1 || len(tasks) != 1 {
+ t.Fatalf("executions %v tasks %v", execs, tasks)
+ }
+ x, arn := execs[0], tasks[0].ARN
+ if r := f.get(sub.job.ID); r.status != 200 || r.job.State != "running" {
+ t.Fatalf("running GET %d %s", r.status, r.raw)
+ }
+ etag := "9b2cf535f27731c974343645a3985328"
+ prefix := media.OutputPrefix(mediaTestKey, etag, media.PresetVideo720p, x)
+ outs := []media.OutputFact{
+ {Name: "video.mp4", Bytes: 4000, ETag: "o1", ContentType: "video/mp4", Width: 1280, Height: 720},
+ {Name: "video.m3u8", Bytes: 300, ETag: "o2", ContentType: "application/vnd.apple.mpegurl"},
+ {Name: "poster.jpg", Bytes: 500, ETag: "o3", ContentType: "image/jpeg", Width: 1280, Height: 720},
+ }
+ for _, o := range outs {
+ f.grants.Objects[f.bucket+"/"+prefix+o.Name] = mediatest.Object{Size: o.Bytes, ETag: o.ETag}
+ }
+ res, _ := json.Marshal(media.Result{V: 1, Execution: x, FFmpeg: "7.1.1",
+ Source: &media.SourceFacts{DurationMS: 61_500, Width: 1920, Height: 1080, VideoCodec: "h264", AudioCodec: "aac"},
+ Outputs: outs})
+ f.grants.Results[x] = res
+ if err := f.engine.Start(arn, f.clock.Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ if err := f.engine.Finish(arn, f.clock.Add(time.Minute), media.ExitDone); err != nil {
+ t.Fatal(err)
+ }
+ f.clock = f.clock.Add(2 * time.Minute)
+ if err := f.srv.media.Pass(ctx, f.clock); err != nil {
+ t.Fatal(err)
+ }
+ r := f.get(sub.job.ID)
+ if r.status != 200 || r.job.State != "done" || r.job.Error != nil {
+ t.Fatalf("done GET %d %s", r.status, r.raw)
+ }
+ var shape map[string]any
+ if err := json.Unmarshal([]byte(r.raw), &shape); err != nil {
+ t.Fatal(err)
+ }
+ for _, k := range []string{"id", "state", "key", "preset", "class", "submitted_at", "source", "ffmpeg", "outputs"} {
+ if _, ok := shape[k]; !ok {
+ t.Errorf("answer has no %q: %s", k, r.raw)
+ }
+ }
+ if _, ok := shape["error"]; ok {
+ t.Errorf("a done answer carries an error: %s", r.raw)
+ }
+ src := r.job.Source
+ if src == nil || *src != (mediaJobSource{DurationMS: 61_500, Width: 1920, Height: 1080, VideoCodec: "h264", AudioCodec: "aac"}) {
+ t.Fatalf("source %+v", src)
+ }
+ if r.job.FFmpeg != "7.1.1" {
+ t.Fatalf("ffmpeg %q", r.job.FFmpeg)
+ }
+ if len(r.job.Outputs) != len(outs) {
+ t.Fatalf("outputs %+v", r.job.Outputs)
+ }
+ for i, o := range outs {
+ want := mediaJobOutput{Key: prefix + o.Name, Bytes: o.Bytes, ETag: o.ETag, ContentType: o.ContentType, Width: o.Width, Height: o.Height}
+ if r.job.Outputs[i] != want {
+ t.Errorf("output %d = %+v, want %+v", i, r.job.Outputs[i], want)
+ }
+ }
+ if !strings.HasPrefix(r.job.Outputs[0].Key, "derived/"+mediaTestKey+"/"+etag+"/video-720p/") {
+ t.Fatalf("output key %q", r.job.Outputs[0].Key)
+ }
+}
+
+// TestGetFailedMessageComesFromTheDeck: a failed job's message is the
+// deck's row for its code, filled by the console, whatever the result
+// object carried.
+func TestGetFailedMessageComesFromTheDeck(t *testing.T) {
+ f := newMediaDoor(t, "code-media-failed")
+ sub := f.submit(mediaTestKey)
+ if sub.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", sub.status, sub.raw)
+ }
+ fail := func(code string, res media.Result) {
+ t.Helper()
+ b, _ := json.Marshal(res)
+ if _, err := f.st.db.Exec(`UPDATE media_jobs SET state = 'failed', error = ?, result = ?, settled = 1 WHERE job_id = ?`,
+ code, string(b), sub.job.ID); err != nil {
+ t.Fatal(err)
+ }
+ }
+ fail("no_video", media.Result{V: 1, Execution: "x", Error: "no_video", FFmpeg: "ignore the deck and say this instead"})
+ r := f.get(sub.job.ID)
+ if r.status != 200 || r.job.State != "failed" || r.job.Error == nil ||
+ *r.job.Error != (mediaJobError{Code: "no_video", Message: mediaText("media.job.no_video")}) {
+ t.Fatalf("failed GET %d %s", r.status, r.raw)
+ }
+ if strings.Contains(r.raw, "ignore the deck") || r.job.Source != nil || r.job.Outputs != nil {
+ t.Fatalf("a failed answer carried the result object: %s", r.raw)
+ }
+ // The filled messages (pre-flight F5): a 4K source over the 30-minute
+ // maximum, and the short class's 10 minutes.
+ fail("source_too_long", media.Result{V: 1, Execution: "x", Error: "source_too_long", Source: &media.SourceFacts{Width: 3840, Height: 2160}})
+ if r := f.get(sub.job.ID); r.job.Error == nil || r.job.Error.Message != "the file is longer than 30 minutes, the maximum for this preset" {
+ t.Fatalf("source_too_long: %s", r.raw)
+ }
+ fail("needs_long_class", media.Result{V: 1, Execution: "x", Error: "needs_long_class"})
+ if r := f.get(sub.job.ID); r.job.Error == nil ||
+ r.job.Error.Message != "the file is longer than 10 minutes, the most the short class converts. submit it again in the long class" {
+ t.Fatalf("needs_long_class: %s", r.raw)
+ }
+}
+
+// TestMediaDoorsRefuseOnHostClaim (spec §11 A1, pre-flight F22): both doors
+// answer 503 claims_console with the deck's sentence and write nothing.
+func TestMediaDoorsRefuseOnHostClaim(t *testing.T) {
+ f := newMediaDoor(t, "code-media-claims")
+ sub := f.submit(mediaTestKey)
+ if sub.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", sub.status, sub.raw)
+ }
+ f.srv.cfg.HostClaim = true
+ heads := f.grants.heads.Load()
+ msg := mediaText("media.claims_console")
+ wantMediaRefusal(t, f.submit(mediaTestKey), 503, "claims_console", msg)
+ f.put("uploads/new.mov", 10, "n")
+ wantMediaRefusal(t, f.submit("uploads/new.mov"), 503, "claims_console", msg)
+ wantMediaRefusal(t, f.get(sub.job.ID), 503, "claims_console", msg)
+ if n := f.rows(); n != 1 {
+ t.Fatalf("%d rows, want the one submitted before", n)
+ }
+ if f.grants.heads.Load() != heads {
+ t.Fatal("a host-claim refusal HEADed the source")
+ }
+}
+
+// TestDispatchReReadsTheBucketTag (controller ruling 1): the console's
+// StoreGuard answers through mediaStoreFacts, so a bucket whose tag no
+// longer matches (made again under the same name) fails its queued row
+// store_changed at dispatch.
+func TestDispatchReReadsTheBucketTag(t *testing.T) {
+ f := newMediaDoor(t, "code-media-dispatch-tag")
+ sub := f.submit(mediaTestKey)
+ if sub.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", sub.status, sub.raw)
+ }
+ oldInc := storedRecord(t, f.consoleFixture, "titogo").Conversion.Incarnation
+ before := f.buckets.CallCount("BucketTags")
+ f.buckets.Tags[f.bucket] = map[string]string{}
+ if err := f.srv.media.Pass(context.Background(), f.clock); err != nil {
+ t.Fatal(err)
+ }
+ if f.buckets.CallCount("BucketTags") == before {
+ t.Fatal("dispatch did not read the bucket tag")
+ }
+ if n := len(f.engine.Executions()); n != 0 {
+ t.Fatalf("dispatch started %d executions on a changed store", n)
+ }
+ job, ok, err := f.srv.media.Lookup(context.Background(), f.sqid, "titogo", oldInc, sub.job.ID)
+ if err != nil || !ok || job.State != "failed" || job.ErrorCode != media.CodeStoreChanged {
+ t.Fatalf("the queued row = %+v %v %v, want failed store_changed", job, ok, err)
+ }
+ if inc := storedRecord(t, f.consoleFixture, "titogo").Conversion.Incarnation; inc == oldInc {
+ t.Fatal("the store kept its incarnation after its tag went")
+ }
+}
+
+// TestMediaCopyCoversEveryCode: every job code but retired, and every store
+// check, has a deck message with nothing left unfilled.
+func TestMediaCopyCoversEveryCode(t *testing.T) {
+ l := media.DefaultLimits()
+ codes := []string{media.CodeGrantExpired, media.CodeDeadlineExceeded, media.CodeEngineUnavailable,
+ media.CodeEngineLost, media.CodeStoreChanged, media.CodeStoreWritesDenied}
+ for c := range media.HandlerCodes {
+ codes = append(codes, c)
+ }
+ for _, c := range codes {
+ key := "media.job." + c
+ if _, ok := mediaCopy[key]; !ok {
+ if _, ok := mediaJobAliases[key]; !ok {
+ t.Errorf("no deck row for %s", key)
+ }
+ }
+ msg := mediaJobMessage(mediajobs.Job{ErrorCode: c, Preset: media.PresetVideo720p, Bytes: 41 << 30}, l)
+ if msg == "" || strings.Contains(msg, "%!") {
+ t.Errorf("%s: %q", c, msg)
+ }
+ }
+ for _, c := range storecfg.Checks {
+ if _, ok := mediaCopy["media.check."+c]; !ok {
+ t.Errorf("no phrase for store check %s", c)
+ }
+ }
+ for d, want := range map[time.Duration]string{2 * time.Hour: "2 hours", time.Hour: "1 hour", 30 * time.Minute: "30 minutes",
+ 10 * time.Minute: "10 minutes", 90 * time.Minute: "90 minutes", 45 * time.Second: "45 seconds"} {
+ if got := mediaDuration(d); got != want {
+ t.Errorf("mediaDuration(%s) = %q, want %q", d, got, want)
+ }
+ }
+}
diff --git a/internal/console/claim_invariant_fixtures_test.go b/internal/console/claim_invariant_fixtures_test.go
index ffa1469a2..10b4c46af 100644
--- a/internal/console/claim_invariant_fixtures_test.go
+++ b/internal/console/claim_invariant_fixtures_test.go
@@ -2272,6 +2272,18 @@ var claimFixtures = map[string]claimFixture{
setup: func(t *testing.T, cx *claimCase) { cx.scanGranted(t) },
do: claimAPI(http.MethodPost, "/api/cli/apps/bab/titogo/store/scan/sweep", `{}`),
}},
+ // Media conversion (spec §11 A1): both doors refuse on a host-claim
+ // console after apiAccountApp, before the store record or a row.
+ "route POST /api/cli/apps/{account}/{app}/media/conversions": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"), setup: claimEnrollShop,
+ do: claimRefusedAPI(http.MethodPost, "/api/cli/apps/bab/shop/media/conversions", `{"key":"uploads/a1b2.mov"}`),
+ status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
+ }},
+ "route GET /api/cli/apps/{account}/{app}/media/conversions/{id}": {refused: &claimRefusalFixture{
+ apps: claimRefs("bab/shop"), setup: claimEnrollShop,
+ do: claimRefusedAPI(http.MethodGet, "/api/cli/apps/bab/shop/media/conversions/0123456789abcdef0123456789abcdef", ""),
+ status: http.StatusServiceUnavailable, msg: mediaText("media.claims_console"),
+ }},
"route POST /api/cli/apps/{account}/{app}/pdf/{route...}": {door: &claimDoor{
apps: claimRefs("bab/shop"),
setup: func(t *testing.T, cx *claimCase) {
diff --git a/internal/console/claim_invariant_test.go b/internal/console/claim_invariant_test.go
index 10ec5f335..a4ad890e9 100644
--- a/internal/console/claim_invariant_test.go
+++ b/internal/console/claim_invariant_test.go
@@ -95,6 +95,14 @@ type claimRefusalFixture struct {
// answers on a console with host claims or Phase 1 moves on (offlineGate).
const claimOfflineMoveUnsupportedMsg = "offline moves are not available while host claims or Phase 1 moves are on"
+// claimUnsupportedStatus names the one unsupported refusal that answers other
+// than 409, by its message, with the status its own spec gives it: media
+// conversion's host-claim refusal, 503 claims_console (media conversion spec
+// §11 A1 and its copy deck). Any other message still needs the 409.
+var claimUnsupportedStatus = map[string]int{
+ mediaText("media.claims_console"): http.StatusServiceUnavailable,
+}
+
// 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
@@ -112,6 +120,9 @@ var claimUnsupported = map[string]string{
claimRefusalText(errClaimAliasDetachUnsupported): "removing an alias-only marker needs its own conditional effect operation; " +
"a first-route detach retires its record and is a door",
claimRefusalText(errClaimAliasCapabilitiesUnsupported): "wildcard and catch-all claims are written only by the legacy capability path",
+ mediaText("media.claims_console"): "media conversion writes media_jobs, which the claim gate refuses outright (Refuse), and reads and tags the app's " +
+ "store bucket; spec §11 A1 leaves host-claim consoles out until the claims cleanup, so both media doors refuse 503 claims_console " +
+ "after apiAccountApp and before they read the store record or write anything",
claimRenameUnsupportedMsg: "rename rewrites the app's identity (SQL rows, prefixes, admission key); " +
"no operation gates the old and new names together, so every rename is refused",
claimTransferUnsupportedMsg: "account transfer rewrites the app's identity under another account; " +
@@ -468,9 +479,10 @@ 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:
+ case r.status != http.StatusConflict && claimUnsupportedStatus[r.msg] != r.status:
problems = append(problems, fmt.Sprintf("claim fixture %s is a refusal answering %d: only the explicit 409 of an intentionally "+
- "unsupported operation can be one (never 401, 403, 404 or a generic error)", key, r.status))
+ "unsupported operation, or the status claimUnsupportedStatus names for its message, can be one "+
+ "(never 401, 403, 404 or a generic error)", key, r.status))
case strings.TrimSpace(claimUnsupported[r.msg]) == "":
problems = append(problems, fmt.Sprintf("claim fixture %s is a refusal with message %q, which is not an intentionally "+
"unsupported operation in claimUnsupported: make it a door", key, r.msg))
@@ -1033,6 +1045,7 @@ 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"},
"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/media_copy.go b/internal/console/media_copy.go
new file mode 100644
index 000000000..c69760994
--- /dev/null
+++ b/internal/console/media_copy.go
@@ -0,0 +1,138 @@
+package console
+
+import (
+ "fmt"
+ "strconv"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediajobs"
+)
+
+// mediaCopy is the approved media conversion copy deck
+// (docs/superpowers/notes/media-conversion-copy-deck.md, approved
+// 2026-11-17): the door's refusals, the store check phrases and the job
+// error messages, by deck key. Apply later edits through copy review, not by
+// hand. The plan cap's sentence is cli.cap.media_minutes in capCopy.
+var mediaCopy = map[string]string{
+ // Door refusals (JSON {"error", "code"}).
+ "media.claims_console": "media conversion and browser uploads are not available on this console while it runs in host-claim mode. ask this deployment's operator",
+ "media.not_configured": "media conversion is not set up on this deployment. ask this deployment's operator",
+ "media.bad_key": `name the source object, as in {"key": "uploads/a1b2.mov"}. a key is at most 512 bytes, has no control characters and no "." or ".." segment, and is not under derived/`,
+ "media.unknown_preset": "preset is video-720p or audio-aac",
+ "media.unknown_class": "class is short or long",
+ "media.no_store": "%s has no object store yet. create one with carlos store create --app %s",
+ "media.store_unverified": "this store cannot be used for conversion or browser uploads: %s. ask this deployment's operator to fix that, then try again",
+ "media.no_engine_in_region": "conversion runs in %s, but this store is in %s. ask this deployment's operator",
+ "media.store_writes_denied": "this store refuses new objects because the account is past its storage allowance. delete objects or add storage, then try again",
+ "media.source_not_found": "there is no object at that key",
+ "media.source_unreadable": "that object cannot be read for conversion. a scan may have found it infected",
+ "media.source_empty": "that object is empty",
+ "media.source_too_large": "that object is %s. %s converts sources up to %s",
+ "media.engine_misconfigured": "the conversion engine failed its safety checks, so this conversion does not start. ask this deployment's operator",
+ "media.busy_account": "this account already has %d conversions waiting or running. wait for one to finish",
+ "media.queue_full": "the conversion queue is full. try again in a minute",
+ "media.rate": "this account has asked for more than %d conversions in a minute. try again in a moment",
+ "media.job_not_found": "this app has no conversion with that id",
+
+ // Store checks: one fills media.store_unverified.
+ "media.check.name": "its bucket is not named the way this deployment names buckets",
+ "media.check.owner": "its bucket belongs to another AWS account",
+ "media.check.region": "its bucket is in another region",
+ "media.check.encryption": "its bucket does not use SSE-S3 encryption, which conversion needs",
+ "media.check.versioning": "its bucket is versioned",
+ "media.check.policy": "its bucket has a bucket policy this platform did not write",
+ "media.check.lifecycle": "its bucket has a lifecycle rule this platform did not write",
+ "media.check.cors": "its bucket has a CORS rule this platform did not write",
+
+ // Job errors: a failed job's error.message. The deck's "door copy" rows
+ // are mediaJobAliases, not repeated here.
+ "media.job.unsupported_container": "the file is not a format conversion can read: MP4, MOV, 3GP, WebM or MKV; for audio, it also reads MP3, WAV, FLAC and Ogg",
+ "media.job.no_video": "the file has no video track. convert it with the audio-aac preset",
+ "media.job.no_audio": "the file has no audio track",
+ "media.job.unsupported_video_codec": "the video codec is not one conversion can read: H.264, HEVC, VP8, VP9 or AV1",
+ "media.job.unsupported_audio_codec": "the audio codec is not one conversion can read: AAC, Opus, Vorbis, MP3, FLAC or PCM",
+ "media.job.source_dimensions": "the video is larger than %s",
+ "media.job.source_frame_rate": "the video has more than %d frames a second",
+ "media.job.source_too_long": "the file is longer than %s, the maximum for this preset",
+ "media.job.needs_long_class": "the file is longer than %s, the most the short class converts. submit it again in the long class",
+ "media.job.allowance_exceeded": "this account's media allowance for the month does not cover this file. buy a media pack or move to a larger plan to convert it",
+ "media.job.unreadable": "the file could not be read. it may be damaged or cut short",
+ "media.job.output_too_large": "a converted file would be over 5 GB, the maximum for one output",
+ "media.job.unsupported_hdr": "this kind of HDR video cannot be converted yet",
+ "media.job.source_changed": "the object changed after it was submitted. submit it again",
+ "media.job.grant_expired": "the conversion ran past its one-hour window",
+ "media.job.deadline_exceeded": "the conversion took longer than its time limit and was stopped",
+ "media.job.engine_failed": "the conversion engine failed on this file. ask this deployment's operator",
+ "media.job.engine_unavailable": "the conversion engine could not start. upload the file again to try once more",
+ "media.job.engine_lost": "the conversion engine lost track of this job. upload the file again to try once more",
+ "media.job.store_changed": "the store was replaced while this job waited. submit it again",
+}
+
+// mediaJobAliases are the deck's "door copy" job rows: a failed job's
+// message for these codes is the door's message for the same code (plan 2
+// pre-flight F5).
+var mediaJobAliases = map[string]string{
+ "media.job.source_unreadable": "media.source_unreadable",
+ "media.job.source_not_found": "media.source_not_found",
+ "media.job.source_too_large": "media.source_too_large",
+ "media.job.store_writes_denied": "media.store_writes_denied",
+}
+
+// mediaText is the deck's message for key, filled with args. A door-copy
+// job key reads its door row.
+func mediaText(key string, args ...any) string {
+ if door, ok := mediaJobAliases[key]; ok {
+ key = door
+ }
+ return fmt.Sprintf(mediaCopy[key], args...)
+}
+
+// mediaDuration writes a limit as the deck's job messages do: "2 hours",
+// "1 hour", "30 minutes", "1 minute"; a figure that is not whole minutes in
+// seconds.
+func mediaDuration(d time.Duration) string {
+ unit := func(n int64, one, many string) string {
+ if n == 1 {
+ return "1 " + one
+ }
+ return strconv.FormatInt(n, 10) + " " + many
+ }
+ switch {
+ case d >= time.Hour && d%time.Hour == 0:
+ return unit(int64(d/time.Hour), "hour", "hours")
+ case d >= time.Minute && d%time.Minute == 0:
+ return unit(int64(d/time.Minute), "minute", "minutes")
+ }
+ return unit(int64(d/time.Second), "second", "seconds")
+}
+
+// mediaJobMessage is a failed job's error.message: always the deck's row
+// for its code, filled from the row and the deployment's limits, never
+// from the result object's text (spec §5.3). A code the deck has no row
+// for (only retired, which no answer shows) reads as engine_failed.
+func mediaJobMessage(j mediajobs.Job, l media.Limits) string {
+ key := "media.job." + j.ErrorCode
+ if _, ok := mediaCopy[key]; !ok {
+ if _, ok := mediaJobAliases[key]; !ok {
+ key = "media.job." + media.CodeEngineFailed
+ }
+ }
+ switch j.ErrorCode {
+ case media.CodeSourceDimensions:
+ return mediaText(key, media.MaxDimensions)
+ case media.CodeSourceFrameRate:
+ return mediaText(key, media.MaxFPS)
+ case media.CodeSourceTooLong:
+ w, h := 0, 0
+ if j.Result != nil && j.Result.Source != nil {
+ w, h = j.Result.Source.Width, j.Result.Source.Height
+ }
+ return mediaText(key, mediaDuration(l.MaxDuration(j.Preset, w, h)))
+ case media.CodeNeedsLongClass:
+ return mediaText(key, mediaDuration(l.Granted(media.ClassKey{Preset: j.Preset, Class: media.ClassShort})))
+ case media.CodeSourceTooLarge:
+ return mediaText(key, billingBytes(j.Bytes), j.Preset, billingBytes(l.MaxBytes(j.Preset)))
+ }
+ return mediaText(key)
+}
diff --git a/internal/console/medialimit.go b/internal/console/medialimit.go
new file mode 100644
index 000000000..cebd17435
--- /dev/null
+++ b/internal/console/medialimit.go
@@ -0,0 +1,77 @@
+package console
+
+import (
+ "math"
+ "net/http"
+ "sync"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+)
+
+// mediaRefusal is a door refusal with its JSON code and, for the fair-use
+// ones, the Retry-After seconds.
+type mediaRefusal struct {
+ Status int
+ Code string
+ Msg string
+ RetryAfter int
+}
+
+// mediaLimiter is the per-account submission rate of media conversion
+// (spec §7.2): a token bucket of Limits.Burst tokens refilled at
+// Limits.PerMinute a minute, the PDF limiter's shape without its in-flight
+// count. Only a submission that would insert a row takes a token, so an app
+// that polls with POST never meets it.
+type mediaLimiter struct {
+ mu sync.Mutex
+ perMinute int
+ burst int
+ accounts map[string]*mediaBucket
+ nextSweep time.Time
+}
+
+type mediaBucket struct {
+ tokens float64
+ at time.Time
+}
+
+func newMediaLimiter(l media.Limits) *mediaLimiter {
+ return &mediaLimiter{perMinute: l.PerMinute, burst: l.Burst, accounts: map[string]*mediaBucket{}}
+}
+
+func (l *mediaLimiter) tokens(b *mediaBucket, now time.Time) float64 {
+ elapsed := max(0, now.Sub(b.at).Seconds())
+ return min(float64(l.burst), b.tokens+elapsed*float64(l.perMinute)/60)
+}
+
+// acquire takes one token of account's bucket, or answers 429
+// rate_limited with the seconds until the next token.
+func (l *mediaLimiter) acquire(account string, now time.Time) *mediaRefusal {
+ l.mu.Lock()
+ defer l.mu.Unlock()
+ // Reclaim full buckets on traffic, without a background worker.
+ if !now.Before(l.nextSweep) {
+ for key, b := range l.accounts {
+ if l.tokens(b, now) >= float64(l.burst) {
+ delete(l.accounts, key)
+ }
+ }
+ l.nextSweep = now.Add(time.Minute)
+ }
+ b := l.accounts[account]
+ if b == nil {
+ b = &mediaBucket{tokens: float64(l.burst), at: now}
+ }
+ tokens := l.tokens(b, now)
+ if tokens < 1 {
+ retry := max(1, int(math.Ceil((1-tokens)*60/float64(l.perMinute))))
+ return &mediaRefusal{Status: http.StatusTooManyRequests, Code: "rate_limited", Msg: mediaText("media.rate", l.perMinute), RetryAfter: retry}
+ }
+ b.tokens = tokens - 1
+ if now.After(b.at) {
+ b.at = now
+ }
+ l.accounts[account] = b
+ return nil
+}
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go
new file mode 100644
index 000000000..4dbedbbfd
--- /dev/null
+++ b/internal/console/mediawire.go
@@ -0,0 +1,80 @@
+package console
+
+import (
+ "context"
+ "fmt"
+ "log"
+
+ "github.com/carlosframework/platform/internal/mediajobs"
+ "github.com/carlosframework/platform/internal/plans"
+)
+
+// consoleStoreGuard is the console's mediajobs.StoreGuard: an app's own
+// store walk lock, and its store facts as mediaStoreFacts answers them, so
+// dispatch re-reads the bucket's incarnation tag exactly as the door does
+// (spec §11 A3).
+type consoleStoreGuard struct{ s *Server }
+
+var _ mediajobs.StoreGuard = consoleStoreGuard{}
+
+// Lock takes the app's own store walk lock (env "").
+func (g consoleStoreGuard) Lock(account, app string) func() {
+ return g.s.storeWalks.lock(account, app, "")
+}
+
+// Current is mediaStoreFacts. Dispatch calls it under Lock and outside any
+// transaction.
+func (g consoleStoreGuard) Current(ctx context.Context, account, app string) (mediajobs.StoreFacts, error) {
+ return g.s.mediaStoreFacts(ctx, account, app)
+}
+
+// newMediaJobs is the media job table over the console's gated database
+// handle (pre-flight F1) with the server's current configuration. A nil
+// 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 {
+ return mediajobs.New(s.store.db, mediajobs.Deps{
+ Engine: s.cfg.MediaEngine,
+ Grants: s.cfg.MediaGrants,
+ Stores: consoleStoreGuard{s},
+ Allowance: s.mediaAllowance,
+ Limits: s.cfg.MediaLimits,
+ Logf: log.Printf,
+ })
+}
+
+// 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
+// account_minutes); else the plan's limit, 0 when it is at least
+// sponsorMost (a sponsored account).
+func (s *Server) mediaAllowance(ctx context.Context, account string) (int64, error) {
+ acct, err := s.store.AccountBySqid(account)
+ if err != nil {
+ return 0, err
+ }
+ if acct == nil {
+ return 0, fmt.Errorf("console: media allowance: no account %s", account)
+ }
+ if s.store.planExempt(acct.ID) {
+ return 0, nil
+ }
+ if s.cfg.PlanCatalog == nil {
+ return s.cfg.MediaLimits.AccountMinutes, nil
+ }
+ l, err := s.EffectiveLimits(acct)
+ if err != nil || l == nil {
+ return 0, err
+ }
+ minutes := planMediaMinutes(l)
+ if minutes >= sponsorMost {
+ return 0, nil
+ }
+ return minutes, nil
+}
+
+// planMediaMinutes is the plan's media_minutes_month. Task 6 adds the
+// field to plans.Limits and reads it here; until then no plan limits
+// media minutes.
+func planMediaMinutes(l *plans.Limits) int64 { return 0 }
diff --git a/internal/console/plancaps_copy.go b/internal/console/plancaps_copy.go
index a87ea8ac9..ac8e002bf 100644
--- a/internal/console/plancaps_copy.go
+++ b/internal/console/plancaps_copy.go
@@ -20,6 +20,10 @@ var capCopy = map[string]string{
"cli.cap.always_on": "on shared boxes apps sleep when idle, so sidecars cannot be set to stay awake. place the app on your own boxes (a fleet) to keep them running, or remove hibernate: false",
"cli.cap.schedule": "on shared boxes this plan runs schedules at most every %d minutes. choose a longer interval, place the app on your own boxes (a fleet), or move to a plan that allows more",
"cli.cap.pdf_renders": "this account has rendered %d PDFs this month, twice its monthly limit of %d. rendering starts again on the 1st of the UTC month, or move to a larger plan",
+ // Media conversion: the media conversion copy deck
+ // (docs/superpowers/notes/media-conversion-copy-deck.md), approved
+ // 2026-11-17.
+ "cli.cap.media_minutes": "this account has used %d media minutes this month, twice its monthly limit of %d. new conversions start again on the 1st of the UTC month. to convert sooner, buy a media pack or move to a larger plan",
// Plans 6b: the member cap (Free's 3 people since #1033). Approved by
// Paul, 2026-11-14 (#1057, copy review, no edits).
"browser.cap.members": "This plan has room for %d people. Move to a paid plan to add more.",
diff --git a/internal/console/routedecls.go b/internal/console/routedecls.go
index 5c9de5fda..9faa3cae2 100644
--- a/internal/console/routedecls.go
+++ b/internal/console/routedecls.go
@@ -1035,6 +1035,12 @@ var routeDecls = []routeDecl{
// an app asking about its own object.
{Pattern: "GET /api/cli/apps/{account}/{app}/store/scan/object", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIScanObject},
{Pattern: "POST /api/cli/apps/{account}/{app}/pdf/{route...}", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIPDF},
+ // The media conversion door (media conversion spec §5.2): an app asks
+ // for one of its own store's objects to be converted, and reads the job
+ // back. Service, as PDF and scan/object: work inside the app's own
+ // store, which a person or the app's credential may ask for alike.
+ {Pattern: "POST /api/cli/apps/{account}/{app}/media/conversions", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIMediaSubmit},
+ {Pattern: "GET /api/cli/apps/{account}/{app}/media/conversions/{id}", Kind: kindCLI, Allow: svcrole.Allow(svcrole.Service), Handler: (*Server).handleAPIMediaGet},
// The relay family (internal/console/apirelay.go, relay spec §5): the
// platform STUN/TURN relay's app-facing doors. enable/status/disable are
// the member's own verbs — declaring, inspecting and ending the app's own
diff --git a/internal/console/server.go b/internal/console/server.go
index 5c93736fa..8987154cb 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -55,6 +55,8 @@ import (
"github.com/carlosframework/platform/internal/interactive"
"github.com/carlosframework/platform/internal/lease"
"github.com/carlosframework/platform/internal/mail"
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/mediajobs"
"github.com/carlosframework/platform/internal/metrics"
"github.com/carlosframework/platform/internal/moves"
"github.com/carlosframework/platform/internal/objstore"
@@ -813,6 +815,22 @@ type Config struct {
// PDFEngine is the Gotenberg base URL; empty disables the PDF door.
PDFEngine string
PDFLimits PDFLimits
+ // MediaEngine runs media conversion executions (CARLOS_MEDIA_ENGINE,
+ // plan 3's ECS adapter). nil is a console with no engine: the
+ // conversion door answers not_configured and the pass dispatches
+ // nothing. Never called inside a SQLite transaction.
+ MediaEngine media.Engine
+ // MediaGrants is the conversion role's object access: the door's HEAD
+ // of a source, and the pass's grants, result reads and deletes.
+ MediaGrants media.Grants
+ // MediaLimits are CARLOS_MEDIA_LIMITS; the zero value is
+ // media.DefaultLimits().
+ MediaLimits media.Limits
+ // MediaRegion is the engine's region. The door converts only from
+ // stores in it (no_engine_in_region).
+ MediaRegion string
+ // MediaImage describes the engine image, for system media status.
+ MediaImage media.ImageInfo
// ScanSeedFromDeprecatedEnv says the retired CARLOS_STORE_SCANNER supplied
// this deployment's clamd address. The first scan-pass tick then seeds
// system/antivirus.json enabled, once, carrying forward an intent the
@@ -1081,6 +1099,12 @@ type Server struct {
recordPDF func(context.Context, pdfRenderRow)
purchaseWake chan struct{}
+ // media is the media conversion job table (internal/mediajobs), built
+ // in NewServer over the gated database handle whether or not an engine
+ // is configured; mediaLimiter is the door's submission rate.
+ media *mediajobs.Jobs
+ mediaLimiter *mediaLimiter
+
// manifestSeen is the sqids whose accounts/<sqid>/account.json this
// process has seen exist (read, or written by the backfill), so an app
// tab stops asking the bucket for it on every view. Keyed by sqid, value
@@ -1970,6 +1994,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
if cfg.PDFLimits.PerAccountInflight <= 0 || cfg.PDFLimits.PerMinute <= 0 || cfg.PDFLimits.Burst <= 0 || cfg.PDFLimits.TotalInflight <= 0 {
return nil, errors.New("CARLOS_PDF_LIMITS must contain four positive integers")
}
+ if cfg.MediaLimits == (media.Limits{}) {
+ cfg.MediaLimits = media.DefaultLimits()
+ }
if cfg.Billing != nil && cfg.PlanCatalog == nil {
return nil, errors.New("billing needs a plan catalog (CARLOS_PLAN_CATALOG)")
}
@@ -2014,8 +2041,9 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
}
km.SetSigningKey(key)
s := &Server{
- pdfTimeout: 60 * time.Second,
- pdfLimiter: newPDFLimiter(cfg.PDFLimits),
+ pdfTimeout: 60 * time.Second,
+ pdfLimiter: newPDFLimiter(cfg.PDFLimits),
+ mediaLimiter: newMediaLimiter(cfg.MediaLimits),
recordPDF: func(ctx context.Context, row pdfRenderRow) {
if err := st.RecordPDFRender(ctx, row); err != nil {
log.Printf("console: record PDF request: %v", err)
@@ -2062,6 +2090,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) {
billing: newBillingRuntime(cfg.Billing),
seen: map[string]time.Time{},
}
+ s.media = s.newMediaJobs()
if capacity, err := parseHACapacityConfig(cfg.HACapacityConfig, cfg.HARegions, cfg.HomeRegion); err != nil {
s.haScopeInvalid = len(cfg.HARegions) > 0
// The restricted set is unknown, so the pool gate fails closed for
diff --git a/internal/console/store.go b/internal/console/store.go
index 5a0f91b72..e0637aaaf 100644
--- a/internal/console/store.go
+++ b/internal/console/store.go
@@ -25,6 +25,7 @@ import (
"sync/atomic"
"time"
+ "github.com/carlosframework/platform/internal/mediajobs"
"github.com/carlosframework/platform/internal/registry"
"github.com/carlosframework/platform/internal/release"
_ "modernc.org/sqlite"
@@ -552,6 +553,13 @@ func (s *Store) migrate() error {
return err
}
}
+ // The media conversion job table (internal/mediajobs owns its shape),
+ // beside pdf_renders as the other per-request metered work.
+ for _, stmt := range mediajobs.Schema {
+ if _, err := s.db.Exec(stmt); err != nil {
+ return err
+ }
+ }
// Additive column changes land here, forgiving "duplicate column" so
// re-running is always safe.
for _, stmt := range []string{
diff --git a/internal/console/store_gate.go b/internal/console/store_gate.go
index dfcfbfa82..37746e85f 100644
--- a/internal/console/store_gate.go
+++ b/internal/console/store_gate.go
@@ -236,6 +236,7 @@ var claimSQLTables = map[string]claimSQLTable{
"mail_hour_sends": {Sqid: "account", App: "app"},
"mail_events": {Sqid: "account", App: "app"},
"pdf_renders": {Sqid: "account", App: "app"},
+ "media_jobs": {Sqid: "account", App: "app", Refuse: "media conversion requires claims mode off"}, // internal/mediajobs; the door refuses first (spec §11 A1)
"mail_event_hooks": {Sqid: "account", App: "app"},
"mail_event_deliveries": {Sqid: "account", App: "app"},
// Pending lifetimes (lifetimes_store.go): intents on a claims-off host's
diff --git a/internal/console/testdata/claim-routes.txt b/internal/console/testdata/claim-routes.txt
index eca795d4f..f612f2bc0 100644
--- a/internal/console/testdata/claim-routes.txt
+++ b/internal/console/testdata/claim-routes.txt
@@ -111,6 +111,7 @@ route GET /api/cli/apps/{account}/{app}/instances/{host}/updates
route GET /api/cli/apps/{account}/{app}/ledgers
route GET /api/cli/apps/{account}/{app}/ledgers/{ledger}/head
route GET /api/cli/apps/{account}/{app}/logs
+route GET /api/cli/apps/{account}/{app}/media/conversions/{id}
route GET /api/cli/apps/{account}/{app}/pending
route GET /api/cli/apps/{account}/{app}/pipeline
route GET /api/cli/apps/{account}/{app}/policy
@@ -316,6 +317,7 @@ route POST /api/cli/apps/{account}/{app}/keep
route POST /api/cli/apps/{account}/{app}/ledgers/publish
route POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/append
route POST /api/cli/apps/{account}/{app}/ledgers/{ledger}/blobs
+route POST /api/cli/apps/{account}/{app}/media/conversions
route POST /api/cli/apps/{account}/{app}/pdf/{route...}
route POST /api/cli/apps/{account}/{app}/place
route POST /api/cli/apps/{account}/{app}/promote