console: media code back under the code-health ratchet
Task 12b. server.go: the media fields move into MediaConfig (embedded in Config) and mediaRuntime (embedded in Server) in mediawire.go; NewServer settles the PDF and media limits through Config.settleMeteredLimits (meteredlimits.go; the PDF check moved unchanged) and builds the media limiter and job table with initMedia. server.go is back at its record. The launch-sponsorship carry runs under a context: carryLaunchFiguresTx, clearLaunchRuleCarrying and StartLaunchSponsorship take ctx and use BeginTx/ExecContext/QueryContext; SettleLaunchSponsorshipContext is beside the old name, which the console's start calls with Background. migrate creates media_jobs from its first statement loop (the schema is appended to it), so it neither grows nor gains an Exec. serve starts the scan and media passes through startStoreObjectPasses. Tests wait on signals: StartMediaPass sends on the mediaPassDone seam after each pass, and the mediajobs stall fake says when it has recorded its deadline. make code-health-record lowered four lines (three StartLaunchSponsorship db-no-context sites, serve 370 to 369); none raised.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
13 files changed,
+202
−129
.amadan/code-health.tsv+1 −4cmd/console/main.go+22 −14internal/console/accountplans.go+5 −5internal/console/apimedia_test.go+1 −1internal/console/mediapass.go+7 −0internal/console/mediapass_test.go+22 −18internal/console/mediawire.go+77 −0internal/console/meteredlimits.go+17 −0internal/console/planmedia_test.go+1 −1internal/console/plansponsor.go+21 −11internal/console/server.go+10 −61internal/console/store.go+5 −9internal/mediajobs/bounds_test.go+13 −5
diff --git a/.amadan/code-health.tsv b/.amadan/code-health.tsv| index 22c4f90bb..bfeef050d 100644 |
| --- a/.amadan/code-health.tsv |
| +++ b/.amadan/code-health.tsv |
| @@ -1625,9 +1625,6 @@ db-no-context internal/console (*Store).Snooze console.sqlHandle.Exec 1 |
| db-no-context internal/console (*Store).Snoozed console.sqlHandle.QueryRow 1 |
| db-no-context internal/console (*Store).StallRestoreCheck (*sql.Tx).QueryRow 1 |
| db-no-context internal/console (*Store).StallRestoreCheck console.sqlHandle.Begin 1 |
| -db-no-context internal/console (*Store).StartLaunchSponsorship (*sql.Tx).Exec 1 |
| -db-no-context internal/console (*Store).StartLaunchSponsorship (*sql.Tx).Query 1 |
| -db-no-context internal/console (*Store).StartLaunchSponsorship console.sqlHandle.Begin 1 |
| db-no-context internal/console (*Store).StashPendingAction console.sqlHandle.Exec 2 |
| db-no-context internal/console (*Store).TakeConfirmation (*sql.Tx).Exec 1 |
| db-no-context internal/console (*Store).TakeConfirmation (*sql.Tx).QueryRow 1 |
| @@ -2185,7 +2182,7 @@ host-context internal/host withEffectiveMovesFloorLock context.Background 2 |
| func-lines . TestFleetAppServesThroughTheHub - 408 |
| func-lines . runDeploy - 331 |
| func-lines . runRoute - 519 |
| -func-lines cmd/console serve - 370 |
| +func-lines cmd/console serve - 369 |
| func-lines internal/activator (*Service).doWakeOnce - 567 |
| func-lines internal/analytics Prune - 343 |
| func-lines internal/appconfig SyncExecWithCallbacks - 320 |
diff --git a/cmd/console/main.go b/cmd/console/main.go| index 470c9974a..6700d3d90 100644 |
| --- a/cmd/console/main.go |
| +++ b/cmd/console/main.go |
| @@ -327,6 +327,25 @@ func migrateApp(args []string) { |
| fmt.Printf("moved %s to %s (%s)\n", *app, *to, dst.Name) |
| } |
| +// startStoreObjectPasses starts, through serve's startClaimWorker (so on |
| +// the stop's worker context), the claim workers that work on objects in |
| +// apps' stores. |
| +func startStoreObjectPasses(startClaimWorker func(name string)) { |
| + // The object-storage scan pass advances each opted-in store's coverage |
| + // (internal/console/scanpass.go). It returns immediately when no engine |
| + // is configured, which is every deployment that has not opted in. |
| + startClaimWorker("StartScanPass") |
| + // The on-demand drain, on its own clock (spec §7.2). Separate goroutine |
| + // from the sweep above and not a phase inside it: a queue phase behind a |
| + // sequential per-app budget would starve for as long as the sweep takes. |
| + startClaimWorker("StartScanDrain") |
| + // The media conversion pass (internal/console/mediapass.go): recover, |
| + // track, dispatch, clean up and prune media_jobs every 5 seconds. It |
| + // returns immediately with no media engine configured, and on a |
| + // host-claim console. |
| + startClaimWorker("StartMediaPass") |
| +} |
| + |
| func serve() { |
| // The serve lock (servelock_*.go), held for the life of the process: |
| // the offline hosts-used verbs need the console stopped, and refuse |
| @@ -849,20 +868,9 @@ func serve() { |
| // /fleet/architecture (internal/console/infrapass.go). Same placement |
| // rule as the economics pass: started here, never in NewServer. |
| startClaimWorker("StartInfraPass") |
| - // The object-storage scan pass advances each opted-in store's coverage |
| - // (internal/console/scanpass.go). Same placement rule again: started |
| - // here, never in NewServer. It returns immediately when no engine is |
| - // configured, which is every deployment that has not opted in. |
| - startClaimWorker("StartScanPass") |
| - // The on-demand drain, on its own clock (spec §7.2). Separate goroutine |
| - // from the sweep above and not a phase inside it: a queue phase behind a |
| - // sequential per-app budget would starve for as long as the sweep takes. |
| - startClaimWorker("StartScanDrain") |
| - // The media conversion pass (internal/console/mediapass.go): recover, |
| - // track, dispatch, clean up and prune media_jobs every 5 seconds. Same |
| - // placement rule again. It returns immediately with no media engine |
| - // configured, and on a host-claim console. |
| - startClaimWorker("StartMediaPass") |
| + // The store object passes: scanning and media conversion. Same |
| + // placement rule again: started here, never in NewServer. |
| + startStoreObjectPasses(startClaimWorker) |
| // The temporary-app expiry pass (internal/console/expirypass.go). Same |
| // placement rule as every pass above: started here, never in NewServer. |
| startClaimWorker("StartExpiryPass") |
diff --git a/internal/console/accountplans.go b/internal/console/accountplans.go| index 0b44d4e15..ddd0cc7a8 100644 |
| --- a/internal/console/accountplans.go |
| +++ b/internal/console/accountplans.go |
| @@ -285,7 +285,7 @@ func (s *Store) EnsureDefaultPlans(defaultPlan string, now time.Time) (int, erro |
| // account with no row has no lapse to start, no throttle or cap rows to |
| // reset, and nothing published; the first limits pass publishes the rows |
| // (revision 1, published 0) and the first grace pass measures them. |
| -func (s *Store) StartLaunchSponsorship(cat *plans.Catalog, cutoff time.Time, sponsored plans.Limits, reason, by string, now time.Time) (int, int, error) { |
| +func (s *Store) StartLaunchSponsorship(ctx context.Context, cat *plans.Catalog, cutoff time.Time, sponsored plans.Limits, reason, by string, now time.Time) (int, int, error) { |
| if cutoff.IsZero() { |
| return 0, 0, errors.New("console: launch sponsorship with no cutoff") |
| } |
| @@ -294,23 +294,23 @@ func (s *Store) StartLaunchSponsorship(cat *plans.Catalog, cutoff time.Time, spo |
| return 0, 0, err |
| } |
| rule := &launchRule{cutoff: cutoff.Unix(), plan: cat.DefaultPlan, sponsored: string(sj), reason: reason, by: by} |
| - tx, err := s.db.Begin() |
| + tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return 0, 0, err |
| } |
| defer tx.Rollback() |
| - if _, err := tx.Exec(`INSERT INTO plan_launch_sponsorship (id, cutoff, plan, sponsored, reason, updated_by, updated_at) |
| + if _, err := tx.ExecContext(ctx, `INSERT INTO plan_launch_sponsorship (id, cutoff, plan, sponsored, reason, updated_by, updated_at) |
| VALUES (1, ?, ?, ?, ?, ?, ?) ON CONFLICT(id) DO UPDATE SET cutoff = excluded.cutoff, plan = excluded.plan, |
| sponsored = excluded.sponsored, reason = excluded.reason, updated_by = excluded.updated_by, updated_at = excluded.updated_at`, |
| rule.cutoff, rule.plan, rule.sponsored, rule.reason, rule.by, now.Unix()); err != nil { |
| return 0, 0, err |
| } |
| - carried, err := carryLaunchFiguresTx(tx, sponsored, reason, by, now) |
| + carried, err := carryLaunchFiguresTx(ctx, tx, sponsored, reason, by, now) |
| if err != nil { |
| return 0, 0, err |
| } |
| type candidate struct{ id, created int64 } |
| - rows, err := tx.Query(`SELECT id, created_at FROM accounts |
| + rows, err := tx.QueryContext(ctx, `SELECT id, created_at FROM accounts |
| WHERE deleted_at = 0 AND id NOT IN (SELECT account_id FROM account_plans) ORDER BY id`) |
| if err != nil { |
| return 0, 0, err |
diff --git a/internal/console/apimedia_test.go b/internal/console/apimedia_test.go| index 8d90e3b2b..0f19e0fd4 100644 |
| --- a/internal/console/apimedia_test.go |
| +++ b/internal/console/apimedia_test.go |
| @@ -913,7 +913,7 @@ func TestDoorLastPlaceRaceAcrossAccounts(t *testing.T) { |
| // 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)) |
| + _, err := NewServer(Config{Origin: "https://console.example", Keymail: "https://keymail.example", MediaConfig: MediaConfig{MediaLimits: l}}, openTestStore(t)) |
| return err |
| } |
| for name, change := range map[string]func(*media.Limits){ |
diff --git a/internal/console/mediapass.go b/internal/console/mediapass.go| index f707bf8b4..9433fa9de 100644 |
| --- a/internal/console/mediapass.go |
| +++ b/internal/console/mediapass.go |
| @@ -38,6 +38,13 @@ func (s *Server) StartMediaPass(ctx context.Context) { |
| if err := s.jobs.Run(ctx, "StartMediaPass", s.mediaPass); err != nil { |
| log.Printf("console: media pass: %v", err) |
| } |
| + if s.mediaPassDone != nil { |
| + select { |
| + case s.mediaPassDone <- struct{}{}: |
| + case <-ctx.Done(): |
| + return |
| + } |
| + } |
| select { |
| case <-ctx.Done(): |
| return |
diff --git a/internal/console/mediapass_test.go b/internal/console/mediapass_test.go| index ba6efc243..d7a469c43 100644 |
| --- a/internal/console/mediapass_test.go |
| +++ b/internal/console/mediapass_test.go |
| @@ -19,18 +19,20 @@ import ( |
| ) |
| // mediaPassWorker is StartMediaPass running on f's console through |
| -// RunClaimWorker, its passes driven by tick. |
| +// RunClaimWorker, its passes driven by tick; done receives once each pass |
| +// has finished (Server.mediaPassDone). |
| type mediaPassWorker struct { |
| f *mediaDoorFixture |
| ticks chan time.Time |
| + done chan struct{} |
| } |
| // startMediaPass starts the worker; it runs its first pass at once. The |
| // test's cleanup stops it and waits for it to return. |
| func startMediaPass(f *mediaDoorFixture) *mediaPassWorker { |
| f.t.Helper() |
| - w := &mediaPassWorker{f: f, ticks: make(chan time.Time)} |
| - f.srv.mediaPassTicks = w.ticks |
| + w := &mediaPassWorker{f: f, ticks: make(chan time.Time), done: make(chan struct{})} |
| + f.srv.mediaPassTicks, f.srv.mediaPassDone = w.ticks, w.done |
| ctx, cancel := context.WithCancel(context.Background()) |
| done := make(chan struct{}) |
| go func() { |
| @@ -50,26 +52,28 @@ func (w *mediaPassWorker) tick(n int64, d time.Duration) { |
| w.wait(n) |
| } |
| -// wait blocks until the worker has finished n passes, and fails if the |
| -// last one failed. |
| +// wait blocks until the worker signals that pass n has finished, and |
| +// fails if it failed. |
| func (w *mediaPassWorker) wait(n int64) { |
| w.f.t.Helper() |
| - deadline := time.Now().Add(10 * time.Second) |
| - for { |
| - for _, st := range w.f.srv.jobs.Snapshot() { |
| - if st.Name != "StartMediaPass" || st.Runs < n { |
| - continue |
| - } |
| - if st.State != JobOK { |
| - w.f.t.Fatalf("pass %d: %s", n, st.Err) |
| - } |
| - return |
| + select { |
| + case <-w.done: |
| + case <-time.After(10 * time.Second): |
| + w.f.t.Fatalf("the worker did not finish pass %d", n) |
| + } |
| + for _, st := range w.f.srv.jobs.Snapshot() { |
| + if st.Name != "StartMediaPass" { |
| + continue |
| + } |
| + if st.Runs != n { |
| + w.f.t.Fatalf("pass %d finished as run %d", n, st.Runs) |
| } |
| - if time.Now().After(deadline) { |
| - w.f.t.Fatalf("the worker did not finish pass %d", n) |
| + if st.State != JobOK { |
| + w.f.t.Fatalf("pass %d: %s", n, st.Err) |
| } |
| - time.Sleep(5 * time.Millisecond) |
| + return |
| } |
| + w.f.t.Fatalf("no StartMediaPass job after pass %d", n) |
| } |
| // mediaPassRow is the one job row's facts the codec needs. |
diff --git a/internal/console/mediawire.go b/internal/console/mediawire.go| index e83692f78..01e9db788 100644 |
| --- a/internal/console/mediawire.go |
| +++ b/internal/console/mediawire.go |
| @@ -5,12 +5,89 @@ import ( |
| "errors" |
| "fmt" |
| "log" |
| + "time" |
| "github.com/carlosframework/platform/internal/media" |
| "github.com/carlosframework/platform/internal/mediajobs" |
| "github.com/carlosframework/platform/internal/plans" |
| + "github.com/carlosframework/platform/internal/storecfg" |
| ) |
| +// MediaConfig is the part of Config media conversion and browser uploads |
| +// read, embedded in Config so its fields are Config's own |
| +// (cfg.MediaEngine, cfg.StoreBuckets). |
| +type MediaConfig struct { |
| + // 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 |
| + // StoreConversion is CARLOS_STORE_CONVERSION=1: this deployment can read |
| + // and set its stores' bucket settings, which media conversion and |
| + // browser uploads need (media conversion spec §5.2, §5.6). Off, the |
| + // uploads verbs refuse. |
| + StoreConversion bool |
| + // StoreBuckets reads a store's bucket settings for the provenance check |
| + // (mediaStoreEligible) and writes the uploads rules. nil when |
| + // StoreConversion is off. Never called inside a SQLite transaction. |
| + StoreBuckets storecfg.Buckets |
| + // StoreAccountID is the deployment's cloud account id, the owner every |
| + // store bucket must have to pass verification. "" fails that check. |
| + StoreAccountID string |
| +} |
| + |
| +// settle is NewServer's check of the media configuration: zero limits |
| +// become media.DefaultLimits(), and limits it cannot run with are refused |
| +// (validMediaLimits). |
| +func (c *MediaConfig) settle() error { |
| + if c.MediaLimits == (media.Limits{}) { |
| + c.MediaLimits = media.DefaultLimits() |
| + } |
| + return validMediaLimits(c.MediaLimits) |
| +} |
| + |
| +// mediaRuntime is the Server's media state, embedded in Server. |
| +type mediaRuntime 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 |
| + // 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() |
| + // mediaPassTicks drives StartMediaPass in place of its ticker |
| + // (mediapass.go): nil is a tick every media.PassEvery. Tests set it; |
| + // nothing in production does. |
| + mediaPassTicks <-chan time.Time |
| + // mediaPassDone, when set, receives once each StartMediaPass pass has |
| + // finished, so a test waits on the pass rather than polling. Tests set |
| + // it; nothing in production does. |
| + mediaPassDone chan<- struct{} |
| + // mediaCallTimeout, when positive, replaces the mediajobs bound on each |
| + // engine, grants and store call (newMediaJobs). Tests set it; nothing |
| + // in production does. |
| + mediaCallTimeout time.Duration |
| +} |
| + |
| +// initMedia builds the door's limiter and the job table from s.cfg, once |
| +// NewServer has settled it (MediaConfig.settle). |
| +func (s *Server) initMedia() { |
| + s.mediaLimiter = newMediaLimiter(s.cfg.MediaLimits) |
| + s.media = s.newMediaJobs() |
| +} |
| + |
| // 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 |
diff --git a/internal/console/meteredlimits.go b/internal/console/meteredlimits.go| new file mode 100644 |
| index 000000000..fea8d3f44 |
| --- /dev/null |
| +++ b/internal/console/meteredlimits.go |
| @@ -0,0 +1,17 @@ |
| +package console |
| + |
| +import "errors" |
| + |
| +// settleMeteredLimits is NewServer's check of the per-request metered |
| +// engines' limits, PDF and media: zero limits become each engine's |
| +// defaults, and limits a limiter cannot run with are refused, before |
| +// anything is built from them. |
| +func (c *Config) settleMeteredLimits() error { |
| + if c.PDFLimits == (pdfLimits{}) { |
| + c.PDFLimits, _ = parsePDFLimits("") |
| + } |
| + if c.PDFLimits.PerAccountInflight <= 0 || c.PDFLimits.PerMinute <= 0 || c.PDFLimits.Burst <= 0 || c.PDFLimits.TotalInflight <= 0 { |
| + return errors.New("CARLOS_PDF_LIMITS must contain four positive integers") |
| + } |
| + return c.MediaConfig.settle() |
| +} |
diff --git a/internal/console/planmedia_test.go b/internal/console/planmedia_test.go| index a83617158..69a199435 100644 |
| --- a/internal/console/planmedia_test.go |
| +++ b/internal/console/planmedia_test.go |
| @@ -491,7 +491,7 @@ func TestLaunchSponsorshipCarriesMedia(t *testing.T) { |
| if err != nil { |
| t.Fatal(err) |
| } |
| - n, err := carryLaunchFiguresTx(tx, sponsorUnlimited(), planSponsorReason, planDefaultActor, planNow.Add(2*time.Hour)) |
| + n, err := carryLaunchFiguresTx(context.Background(), tx, sponsorUnlimited(), planSponsorReason, planDefaultActor, planNow.Add(2*time.Hour)) |
| if cerr := tx.Commit(); err != nil || cerr != nil || n != 0 { |
| t.Fatalf("second carry = %d, %v, %v", n, err, cerr) |
| } |
diff --git a/internal/console/plansponsor.go b/internal/console/plansponsor.go| index f83ceed4c..e5552d766 100644 |
| --- a/internal/console/plansponsor.go |
| +++ b/internal/console/plansponsor.go |
| @@ -1,6 +1,7 @@ |
| package console |
| import ( |
| + "context" |
| "database/sql" |
| "encoding/json" |
| "errors" |
| @@ -131,11 +132,20 @@ func sponsorUnlimited() plans.Limits { |
| // this one, and its row is carried here, or after, and it reads the new |
| // rule or none. No insert can see the old rule once any row is carried, |
| // and no row is left uncarried once the new rule is visible. |
| +// |
| +// It is SettleLaunchSponsorshipContext for a caller with no context to |
| +// follow: the console's start, which runs it before it serves. |
| func SettleLaunchSponsorship(st *Store, cat *plans.Catalog, now time.Time) (int, error) { |
| + return SettleLaunchSponsorshipContext(context.Background(), st, cat, now) |
| +} |
| + |
| +// SettleLaunchSponsorshipContext is SettleLaunchSponsorship whose carry |
| +// transaction runs under ctx. |
| +func SettleLaunchSponsorshipContext(ctx context.Context, st *Store, cat *plans.Catalog, now time.Time) (int, error) { |
| if cat == nil { |
| return 0, clearLaunchRule(st) |
| } |
| - n, carried, err := settleLaunchRule(st, cat, now) |
| + n, carried, err := settleLaunchRule(ctx, st, cat, now) |
| if err != nil { |
| return 0, err |
| } |
| @@ -155,10 +165,10 @@ var launchSettledHook func() |
| // settleLaunchRule is SettleLaunchSponsorship with a catalog: the rule |
| // recorded or cleared, and the launch rows carried, in one transaction. |
| -func settleLaunchRule(st *Store, cat *plans.Catalog, now time.Time) (int, int, error) { |
| +func settleLaunchRule(ctx context.Context, st *Store, cat *plans.Catalog, now time.Time) (int, int, error) { |
| launch := sponsorUnlimited() |
| if cat.SponsorCutoff().IsZero() { |
| - carried, err := st.clearLaunchRuleCarrying(launch, planSponsorReason, planDefaultActor, now) |
| + carried, err := st.clearLaunchRuleCarrying(ctx, launch, planSponsorReason, planDefaultActor, now) |
| if err != nil { |
| return 0, 0, errors.Join(fmt.Errorf("carrying the launch sponsorships forward: %w", err), clearLaunchRule(st)) |
| } |
| @@ -169,7 +179,7 @@ func settleLaunchRule(st *Store, cat *plans.Catalog, now time.Time) (int, int, e |
| return 0, 0, errors.Join(fmt.Errorf("sponsor_accounts_before %s is after the console's start (%s): set it to when plans go on, not later", |
| cutoff.UTC().Format(time.RFC3339), now.UTC().Format(time.RFC3339)), clearLaunchRule(st)) |
| } |
| - n, carried, err := st.StartLaunchSponsorship(cat, cutoff, launch, planSponsorReason, planDefaultActor, now) |
| + n, carried, err := st.StartLaunchSponsorship(ctx, cat, cutoff, launch, planSponsorReason, planDefaultActor, now) |
| if err != nil { |
| return 0, 0, errors.Join(fmt.Errorf("writing the sponsored plans: %w", err), clearLaunchRule(st)) |
| } |
| @@ -179,16 +189,16 @@ func settleLaunchRule(st *Store, cat *plans.Catalog, now time.Time) (int, int, e |
| // clearLaunchRuleCarrying removes the recorded rule (plans on without a |
| // cutoff) and carries the launch rows that still sponsor their accounts, |
| // in one transaction (the carry invariant, SettleLaunchSponsorship). |
| -func (s *Store) clearLaunchRuleCarrying(launch plans.Limits, reason, by string, now time.Time) (int, error) { |
| - tx, err := s.db.Begin() |
| +func (s *Store) clearLaunchRuleCarrying(ctx context.Context, launch plans.Limits, reason, by string, now time.Time) (int, error) { |
| + tx, err := s.db.BeginTx(ctx, nil) |
| if err != nil { |
| return 0, err |
| } |
| defer tx.Rollback() |
| - if _, err := tx.Exec(`DELETE FROM plan_launch_sponsorship`); err != nil { |
| + if _, err := tx.ExecContext(ctx, `DELETE FROM plan_launch_sponsorship`); err != nil { |
| return 0, err |
| } |
| - n, err := carryLaunchFiguresTx(tx, launch, reason, by, now) |
| + n, err := carryLaunchFiguresTx(ctx, tx, launch, reason, by, now) |
| if err != nil { |
| return 0, err |
| } |
| @@ -224,7 +234,7 @@ var launchCarried = []struct { |
| // missing launchCarried fields are added; a carried row's revision is |
| // bumped so the publish pass sends its limits record again; nothing else |
| // in it changes. |
| -func carryLaunchFiguresTx(tx *sql.Tx, launch plans.Limits, reason, by string, now time.Time) (int, error) { |
| +func carryLaunchFiguresTx(ctx context.Context, tx *sql.Tx, launch plans.Limits, reason, by string, now time.Time) (int, error) { |
| lj, err := json.Marshal(launch) |
| if err != nil { |
| return 0, err |
| @@ -238,7 +248,7 @@ func carryLaunchFiguresTx(tx *sql.Tx, launch plans.Limits, reason, by string, no |
| return 0, fmt.Errorf("console: the launch figures have no %s to carry", c.key) |
| } |
| } |
| - rows, err := tx.Query(`SELECT account_id, sponsored FROM account_plans |
| + rows, err := tx.QueryContext(ctx, `SELECT account_id, sponsored FROM account_plans |
| WHERE source = ? AND reason = ? AND updated_by = ? ORDER BY account_id`, PlanSourceSponsored, reason, by) |
| if err != nil { |
| return 0, err |
| @@ -301,7 +311,7 @@ func carryLaunchFiguresTx(tx *sql.Tx, launch plans.Limits, reason, by string, no |
| if err != nil { |
| return 0, err |
| } |
| - res, err := tx.Exec(`UPDATE account_plans SET sponsored = ?, revision = revision + 1, updated_at = ? |
| + res, err := tx.ExecContext(ctx, `UPDATE account_plans SET sponsored = ?, revision = revision + 1, updated_at = ? |
| WHERE account_id = ? AND sponsored = ?`, string(nj), now.Unix(), r.id, r.sponsored) |
| if err != nil { |
| return 0, err |
diff --git a/internal/console/server.go b/internal/console/server.go| index 6c97c2097..8ea17bb61 100644 |
| --- a/internal/console/server.go |
| +++ b/internal/console/server.go |
| @@ -55,8 +55,6 @@ 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" |
| @@ -70,7 +68,6 @@ import ( |
| "github.com/carlosframework/platform/internal/release" |
| "github.com/carlosframework/platform/internal/replicas" |
| "github.com/carlosframework/platform/internal/status" |
| - "github.com/carlosframework/platform/internal/storecfg" |
| "github.com/carlosframework/platform/internal/svcrole" |
| "github.com/carlosframework/platform/internal/telemetry" |
| "github.com/carlosframework/platform/internal/usage" |
| @@ -815,22 +812,9 @@ 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 |
| + // MediaConfig is media conversion's and browser uploads' configuration |
| + // (mediawire.go). |
| + MediaConfig |
| // 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 |
| @@ -872,18 +856,6 @@ type Config struct { |
| // lives — a walk that guessed would create the next bucket somewhere |
| // else, and the record would say so afterwards. |
| StoreDeployment objstore.Deployment |
| - // StoreConversion is CARLOS_STORE_CONVERSION=1: this deployment can read |
| - // and set its stores' bucket settings, which media conversion and |
| - // browser uploads need (media conversion spec §5.2, §5.6). Off, the |
| - // uploads verbs refuse. |
| - StoreConversion bool |
| - // StoreBuckets reads a store's bucket settings for the provenance check |
| - // (mediaStoreEligible) and writes the uploads rules. nil when |
| - // StoreConversion is off. Never called inside a SQLite transaction. |
| - StoreBuckets storecfg.Buckets |
| - // StoreAccountID is the deployment's cloud account id, the owner every |
| - // store bucket must have to pass verification. "" fails that check. |
| - StoreAccountID string |
| // StoreMaxPerApp caps how many ENVIRONMENT stores one app may have |
| // (CARLOS_STORE_MAX_PER_APP; 0 = storeMaxPerAppDefault). The app's own |
| // store is not one of them and is never capped. |
| @@ -1099,14 +1071,9 @@ 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 |
| - // 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() |
| + // mediaRuntime is the media job table, the door's limiter and their |
| + // test seams (mediawire.go). |
| + mediaRuntime |
| // manifestSeen is the sqids whose accounts/<sqid>/account.json this |
| // process has seen exist (read, or written by the backfill), so an app |
| @@ -1710,14 +1677,6 @@ type Server struct { |
| // opNow is the operator pages' clock seam (Server.now, opboxes.go): |
| // nil means time.Now. Tests set it; nothing in production does. |
| opNow func() time.Time |
| - // mediaPassTicks drives StartMediaPass in place of its ticker |
| - // (mediapass.go): nil is a tick every media.PassEvery. Tests set it; |
| - // nothing in production does. |
| - mediaPassTicks <-chan time.Time |
| - // mediaCallTimeout, when positive, replaces the mediajobs bound on each |
| - // engine, grants and store call (newMediaJobs). Tests set it; nothing |
| - // in production does. |
| - mediaCallTimeout time.Duration |
| // recordView is the record view the run and seed sweeps read through |
| // (recordview.go), set by SetRecordView when CARLOS_CHANGE_INDEX=read |
| @@ -1999,16 +1958,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| return nil, err |
| } |
| st.managedRegistry = managedRegistryPath(cfg.Registry) |
| - if cfg.PDFLimits == (pdfLimits{}) { |
| - cfg.PDFLimits, _ = parsePDFLimits("") |
| - } |
| - 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 err := validMediaLimits(cfg.MediaLimits); err != nil { |
| + if err := cfg.settleMeteredLimits(); err != nil { |
| return nil, err |
| } |
| if cfg.Billing != nil && cfg.PlanCatalog == nil { |
| @@ -2055,9 +2005,8 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| } |
| km.SetSigningKey(key) |
| s := &Server{ |
| - pdfTimeout: 60 * time.Second, |
| - pdfLimiter: newPDFLimiter(cfg.PDFLimits), |
| - mediaLimiter: newMediaLimiter(cfg.MediaLimits), |
| + pdfTimeout: 60 * time.Second, |
| + pdfLimiter: newPDFLimiter(cfg.PDFLimits), |
| recordPDF: func(ctx context.Context, row pdfRenderRow) { |
| if err := st.RecordPDFRender(ctx, row); err != nil { |
| log.Printf("console: record PDF request: %v", err) |
| @@ -2104,7 +2053,7 @@ func NewServer(cfg Config, st *Store) (*Server, error) { |
| billing: newBillingRuntime(cfg.Billing), |
| seen: map[string]time.Time{}, |
| } |
| - s.media = s.newMediaJobs() |
| + s.initMedia() |
| 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 ffada56fa..987ef3ace 100644 |
| --- a/internal/console/store.go |
| +++ b/internal/console/store.go |
| @@ -166,7 +166,10 @@ func (s *Store) Close() error { |
| // in the ALTER list, whose "duplicate column" error is swallowed so the list |
| // stays idempotent. |
| func (s *Store) migrate() error { |
| - for _, stmt := range []string{ |
| + // The media conversion job table (internal/mediajobs owns its shape) |
| + // is created last, beside pdf_renders as the other per-request metered |
| + // work. |
| + for _, stmt := range append([]string{ |
| `CREATE TABLE IF NOT EXISTS analytics_prune_state ( |
| id INTEGER PRIMARY KEY CHECK(id = 1), |
| last_started INTEGER, |
| @@ -548,14 +551,7 @@ func (s *Store) migrate() error { |
| state TEXT, |
| created_at INTEGER |
| );`, |
| - } { |
| - if _, err := s.db.Exec(stmt); err != nil { |
| - 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 { |
| + }, mediajobs.Schema...) { |
| if _, err := s.db.Exec(stmt); err != nil { |
| return err |
| } |
diff --git a/internal/mediajobs/bounds_test.go b/internal/mediajobs/bounds_test.go| index c69ea7c1d..ccdb5db0f 100644 |
| --- a/internal/mediajobs/bounds_test.go |
| +++ b/internal/mediajobs/bounds_test.go |
| @@ -10,8 +10,12 @@ import ( |
| ) |
| // stall is every collaborator at once: each call waits until its context |
| -// ends and answers the context's error. It records the deadline it saw. |
| -type stall struct{ deadlines map[string]time.Duration } |
| +// ends and answers the context's error. It records the deadline it saw, |
| +// and then, when entered is set, says so on it. |
| +type stall struct { |
| + deadlines map[string]time.Duration |
| + entered chan struct{} |
| +} |
| func (s *stall) wait(ctx context.Context, name string) error { |
| dl, ok := ctx.Deadline() |
| @@ -20,6 +24,9 @@ func (s *stall) wait(ctx context.Context, name string) error { |
| } else { |
| s.deadlines[name] = time.Until(dl) |
| } |
| + if s.entered != nil { |
| + s.entered <- struct{}{} |
| + } |
| <-ctx.Done() |
| return ctx.Err() |
| } |
| @@ -107,12 +114,13 @@ func TestEveryCallIsBounded(t *testing.T) { |
| } |
| if tc.timeout == 0 { |
| // The defaults are too long to wait out: each call runs under |
| - // a caller context cancelled once it has recorded its |
| - // deadline. |
| + // a caller context cancelled once the stalled call says it |
| + // has recorded its deadline. |
| + s.entered = make(chan struct{}) |
| for name, call := range calls { |
| c, cancel := context.WithCancel(context.Background()) |
| ctx = c |
| - go func() { time.Sleep(10 * time.Millisecond); cancel() }() |
| + go func() { <-s.entered; cancel() }() |
| if err := call(); !errors.Is(err, context.Canceled) { |
| t.Errorf("%s answered %v, want the caller's cancellation", name, err) |
| } |