carlos / platform Public

console: retire media jobs before any store teardown

Store destroy, app purge (purgeOneStore) and seed finish call
mediaStoreRetire under the store walk lock, after every refusal a person
can answer and before objstore.TeardownIn; account deletion calls
mediaAccountRetire (Scope App "", pre-flight F2) before the tombstone.
While a retired row's task is not confirmed stopped, each refuses with
the deck's media.retire_pending (or media.retire_pending_account, F23)
through its existing failure path. Config environment stores carry no
media jobs and answer at once. The store record's media block is left
to the teardown.

TestEveryStoreTeardownRetiresMedia is an AST guard (F24): every objstore
Teardown/TeardownIn call and every store DeleteAccount call in the
package's non-test files is preceded in its FuncDecl by the retire call,
taken after a store walk lock; claim_purge.go is exempt (spec A1).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev e7a3f2289de3ac0655c71bedc908f683c30f5223 parent 5806f54
6 files changed, +738 −4
  • internal/console/appsettings.go +15 −0
  • internal/console/media_copy.go +6 −0
  • internal/console/mediaretire.go +69 −0
  • internal/console/mediaretire_test.go +610 −0
  • internal/console/ownership.go +28 −4
  • internal/console/seedfinish.go +10 −0
diff --git a/internal/console/appsettings.go b/internal/console/appsettings.go
index 5cce435fc..193556828 100644
--- a/internal/console/appsettings.go
+++ b/internal/console/appsettings.go
@@ -1626,6 +1626,21 @@ func (s *Server) handleStoreDestroy(w http.ResponseWriter, r *http.Request) {
if !s.requireFreshAuth(w, r, addr, raw) {
return
}
+ // The store's media jobs are retired first, under the walk lock taken
+ // above and after every refusal a person can answer, so a mistyped word
+ // retires nothing; while one of their tasks can still write, the store
+ // stands (media conversion spec §5.3, I7). Outside claimAppMutation's
+ // closure (pre-flight F24): no transaction is open, and the engine
+ // stops are network calls.
+ if refusal, err := s.mediaStoreRetire(ctx, acct.Sqid, app, env); err != nil {
+ log.Printf("console: store destroy %s/%s%s: retire media jobs: %v", acct.Sqid, app, storeEnvSuffix(env), err)
+ fail("Could not destroy “" + app + "”'s object store — it is still there; try again once the " +
+ "backend is reachable.")
+ return
+ } else if refusal != "" {
+ fail(refusal)
+ return
+ }
// R3 (review follow-up): this door tears down ONLY the object store.
// It used to also tear down the app's email estate — the SES identity,
// the IAM principal, delivered credentials, published DNS and,
diff --git a/internal/console/media_copy.go b/internal/console/media_copy.go
index c69760994..5f901f650 100644
--- a/internal/console/media_copy.go
+++ b/internal/console/media_copy.go
@@ -67,6 +67,12 @@ var mediaCopy = map[string]string{
"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",
+
+ // Store teardown (browser): a store destroy, an app purge or a seed
+ // finish while a conversion is still stopping (the app's name), and
+ // account deletion (pre-flight F23).
+ "media.retire_pending": "Conversions for “%s” are still stopping. Try again in a minute.",
+ "media.retire_pending_account": "This account’s conversions are still stopping. Try again in a minute.",
}
// mediaJobAliases are the deck's "door copy" job rows: a failed job's
diff --git a/internal/console/mediaretire.go b/internal/console/mediaretire.go
new file mode 100644
index 000000000..6e7ec0e28
--- /dev/null
+++ b/internal/console/mediaretire.go
@@ -0,0 +1,69 @@
+package console
+
+import (
+ "context"
+
+ "github.com/carlosframework/platform/internal/mediajobs"
+)
+
+// Retirement at every store teardown (media conversion spec §5.3, I7).
+// Every console path that destroys or replaces a store, purges an app or
+// deletes an account retires that scope's media jobs first and refuses the
+// teardown while any of their tasks can still write: a queued row fails
+// retired, uncharged, at once; a running row's task is stopped, and the
+// row settles (charged ECS's time) on a later Track. Its place and its
+// reservation count until ECS confirms the stop.
+// TestEveryStoreTeardownRetiresMedia holds every objstore teardown call to
+// this.
+//
+// Neither function touches the store record: its conversion block is the
+// teardown's to delete with the record (Task 3), and a store made again
+// gets a fresh incarnation from its bucket's tag (spec §11 A3), so a
+// retired row can never match it.
+
+// mediaStoreRetire retires the media jobs of the store a teardown is about
+// to remove, and answers the deck's refusal while any of them may still
+// write; "" lets the teardown go ahead. The caller holds the store's walk
+// lock (storeWalks.lock(acct, app, env)), so no submission or dispatch can
+// land between this and the teardown, and no transaction is open: the
+// engine stops are network calls.
+//
+// Only the app's own store (env "") carries media jobs: the door and
+// dispatch use no other (mediaStoreCheck), so a config environment's store
+// answers "" at once.
+//
+// On a host-claim console media_jobs is gated with Refuse and the door
+// refuses before writing (spec §11 A1), so no row exists and Retire writes
+// nothing. A row left from before the flag went on would make the gate
+// refuse Retire's write: an error, and the teardown refused, never a
+// teardown over a task that could still write.
+func (s *Server) mediaStoreRetire(ctx context.Context, acct, app, env string) (refusal string, err error) {
+ if env != "" {
+ return "", nil
+ }
+ pending, err := s.media.Retire(ctx, mediajobs.Scope{Account: acct, App: app}, s.now())
+ if err != nil {
+ return "", err
+ }
+ if pending > 0 {
+ return mediaText("media.retire_pending", app), nil
+ }
+ return "", nil
+}
+
+// mediaAccountRetire is mediaStoreRetire for account deletion: every media
+// job of the account, whatever its app (pre-flight F2), with the deck's
+// account sentence (F23). It takes no lock: the account holds no apps by
+// then (deletionRefused), so no store of it is left for a submission or a
+// dispatch to use, and a dispatch that raced it holds a row whose task is
+// not confirmed stopped, which pending counts.
+func (s *Server) mediaAccountRetire(ctx context.Context, acct string) (refusal string, err error) {
+ pending, err := s.media.Retire(ctx, mediajobs.Scope{Account: acct}, s.now())
+ if err != nil {
+ return "", err
+ }
+ if pending > 0 {
+ return mediaText("media.retire_pending_account"), nil
+ }
+ return "", nil
+}
diff --git a/internal/console/mediaretire_test.go b/internal/console/mediaretire_test.go
new file mode 100644
index 000000000..f008c02e1
--- /dev/null
+++ b/internal/console/mediaretire_test.go
@@ -0,0 +1,610 @@
+package console
+
+import (
+ "context"
+ "go/ast"
+ "go/parser"
+ "go/token"
+ "html"
+ "net/http"
+ "net/url"
+ "os"
+ "path/filepath"
+ "sort"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/media"
+ "github.com/carlosframework/platform/internal/media/mediatest"
+ "github.com/carlosframework/platform/internal/objstore"
+)
+
+// mediaRow is one media_jobs row as the retirement tests read it, straight
+// from the table (Lookup hides retired rows).
+type mediaRow struct {
+ incarnation, state, code string
+ retiredAt, endedAt, cleanup int64
+ chargedMS int64
+ settled, taskStopped bool
+}
+
+func readMediaRows(t *testing.T, fx *consoleFixture, account, app, id string) []mediaRow {
+ t.Helper()
+ rows, err := fx.st.db.Query(`SELECT incarnation, state, error, retired_at, ended_at, cleanup_due, charged_ms, settled, task_stopped
+ FROM media_jobs WHERE account = ? AND app = ? AND job_id = ?`, account, app, id)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer rows.Close()
+ var out []mediaRow
+ for rows.Next() {
+ var r mediaRow
+ if err := rows.Scan(&r.incarnation, &r.state, &r.code, &r.retiredAt, &r.endedAt, &r.cleanup, &r.chargedMS, &r.settled, &r.taskStopped); err != nil {
+ t.Fatal(err)
+ }
+ out = append(out, r)
+ }
+ if err := rows.Err(); err != nil {
+ t.Fatal(err)
+ }
+ return out
+}
+
+// mediaRowOf is the one row of id.
+func (f *mediaDoorFixture) mediaRowOf(id string) mediaRow {
+ f.t.Helper()
+ rows := readMediaRows(f.t, f.consoleFixture, f.sqid, "titogo", id)
+ if len(rows) != 1 {
+ f.t.Fatalf("job %s: %d rows, want 1: %+v", id, len(rows), rows)
+ }
+ return rows[0]
+}
+
+// running submits key and drives it to a running task: the pass dispatches
+// and launches it, the fake engine starts it, and the clock moves on 30 s.
+func (f *mediaDoorFixture) running(key string) (id, arn string) {
+ f.t.Helper()
+ sub := f.submit(key)
+ if sub.status != http.StatusAccepted {
+ f.t.Fatalf("submit %s: %d %s", key, sub.status, sub.raw)
+ }
+ before := len(f.engine.Tasks())
+ if err := f.srv.media.Pass(context.Background(), f.clock); err != nil {
+ f.t.Fatal(err)
+ }
+ tasks := f.engine.Tasks()
+ if len(tasks) != before+1 {
+ f.t.Fatalf("pass started %d tasks, want 1", len(tasks)-before)
+ }
+ arn = tasks[len(tasks)-1].ARN
+ if err := f.engine.Start(arn, f.clock); err != nil {
+ f.t.Fatal(err)
+ }
+ f.clock = f.clock.Add(30 * time.Second)
+ return sub.job.ID, arn
+}
+
+func (f *mediaDoorFixture) taskStopped(arn string) bool {
+ f.t.Helper()
+ for _, task := range f.engine.Tasks() {
+ if task.ARN == arn {
+ return task.Stopped
+ }
+ }
+ f.t.Fatalf("no task %s", arn)
+ return false
+}
+
+func (f *mediaDoorFixture) track() {
+ f.t.Helper()
+ if err := f.srv.media.Track(context.Background(), f.clock); err != nil {
+ f.t.Fatal(err)
+ }
+}
+
+// destroyPage posts the store destroy form for titogo's own store, through
+// the passkey, and answers the page the redirect shows.
+func (f *mediaDoorFixture) destroyPage(c *http.Client, csrf, confirm string) string {
+ f.t.Helper()
+ status, loc, body := postGated(f.t, f.consoleFixture, c, f.u("/apps/titogo/store/destroy"),
+ url.Values{"csrf": {csrf}, "confirm": {confirm}})
+ if status != http.StatusSeeOther || loc != f.path("/apps/titogo/settings/storage") {
+ f.t.Fatalf("destroy = %d -> %q:\n%s", status, loc, body)
+ }
+ return flashAfter(f.t, f.consoleFixture, c, status, loc, body)
+}
+
+// owner signs Paul, the account's owner, into a browser: the fixture's
+// last sign-in was alice, a member, for her CLI token.
+func (f *mediaDoorFixture) owner() (*http.Client, string) {
+ f.t.Helper()
+ f.setUser("paul@keymail.dev")
+ c := signInPaul(f.t, f.consoleFixture)
+ return c, sessionToken(f.t, f.consoleFixture, c)
+}
+
+func (f *mediaDoorFixture) provisioner() *objstore.MemProvisioner {
+ return f.srv.cfg.StoreProvisioner.(*objstore.MemProvisioner)
+}
+
+// The store standing: its record naming the bucket, and the bucket.
+func (f *mediaDoorFixture) storeStanding(what string) {
+ f.t.Helper()
+ if rec := storedRecord(f.t, f.consoleFixture, "titogo"); rec == nil || rec.Provisioned == nil {
+ f.t.Fatalf("%s: the store record went: %+v", what, rec)
+ }
+ if _, ok := f.provisioner().Buckets[f.bucket]; !ok {
+ f.t.Fatalf("%s: bucket %s went", what, f.bucket)
+ }
+}
+
+// TestStoreDestroyRefusedWhileATaskRuns (spec §9): a store whose job is
+// running is not destroyed. The destroy page retires the row and stops its
+// task, refuses with the deck's sentence and leaves the store standing
+// (TeardownIn never ran); a mistyped confirmation retires nothing. Once
+// the task's stop is confirmed (Finish, then Track), the destroy goes
+// through.
+func TestStoreDestroyRefusedWhileATaskRuns(t *testing.T) {
+ f := newMediaDoor(t, "code-media-destroy-running")
+ id, arn := f.running(mediaTestKey)
+ c, csrf := f.owner()
+
+ f.destroyPage(c, csrf, "titogo")
+ if r := f.mediaRowOf(id); r.retiredAt != 0 || f.taskStopped(arn) {
+ t.Fatalf("a mistyped destroy retired the job: %+v", r)
+ }
+
+ page := f.destroyPage(c, csrf, f.bucket)
+ if want := mediaText("media.retire_pending", "titogo"); !strings.Contains(page, html.EscapeString(want)) {
+ t.Fatalf("the refusal is not the deck's %q:\n%s", want, page)
+ }
+ f.storeStanding("a destroy refused while a task runs")
+ if !f.taskStopped(arn) {
+ t.Fatal("the destroy did not stop the running task")
+ }
+ r := f.mediaRowOf(id)
+ if r.retiredAt == 0 || r.state != "running" || r.taskStopped || r.settled {
+ t.Fatalf("the running row after the refusal: %+v", r)
+ }
+
+ // Asked again before ECS confirms: still refused.
+ f.destroyPage(c, csrf, f.bucket)
+ f.storeStanding("a second destroy before the stop was confirmed")
+
+ 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)
+ f.track()
+ if r := f.mediaRowOf(id); r.state != "failed" || r.code != media.CodeRetired || !r.taskStopped || !r.settled {
+ t.Fatalf("the row after Track: %+v", r)
+ }
+ page = f.destroyPage(c, csrf, f.bucket)
+ if !strings.Contains(page, html.EscapeString("Destroyed “titogo”'s object store")) {
+ t.Fatalf("the destroy after the stop did not go through:\n%s", page)
+ }
+ if rec := storedRecord(t, f.consoleFixture, "titogo"); rec != nil {
+ t.Fatalf("the record survived the destroy: %+v", rec)
+ }
+ if _, ok := f.provisioner().Buckets[f.bucket]; ok {
+ t.Fatal("the bucket survived the destroy")
+ }
+}
+
+// TestRecreatedStoreMakesANewJob (spec §9): destroy, recreate, the same
+// key and bytes. The job id is the same hash, but the submission makes a
+// new row under the new store's incarnation (202, queued), and the old
+// row, retired with the old store, is invisible to GET.
+func TestRecreatedStoreMakesANewJob(t *testing.T) {
+ f := newMediaDoor(t, "code-media-recreate-job")
+ first := f.submit(mediaTestKey)
+ if first.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", first.status, first.raw)
+ }
+ oldInc := storedRecord(t, f.consoleFixture, "titogo").Conversion.Incarnation
+ c, csrf := f.owner()
+ page := f.destroyPage(c, csrf, f.bucket)
+ if !strings.Contains(page, html.EscapeString("Destroyed “titogo”'s object store")) {
+ t.Fatalf("a destroy with only a queued job was refused:\n%s", page)
+ }
+ if r := f.mediaRowOf(first.job.ID); r.state != "failed" || r.code != media.CodeRetired || r.chargedMS != 0 || !r.settled || r.retiredAt == 0 {
+ t.Fatalf("the queued row after the destroy: %+v", r)
+ }
+
+ f.buckets.DropBucket(f.bucket)
+ grantStore(t, f.consoleFixture, f.member)
+ f.buckets.Facts[f.bucket] = goodBucket()
+ again := f.submit(mediaTestKey)
+ if again.status != http.StatusAccepted || again.job.State != "queued" {
+ t.Fatalf("the same key on the recreated store: %d %s, want 202 queued", again.status, again.raw)
+ }
+ newInc := storedRecord(t, f.consoleFixture, "titogo").Conversion.Incarnation
+ if newInc == oldInc {
+ t.Fatalf("the recreated store kept incarnation %s", oldInc)
+ }
+ rows := readMediaRows(t, f.consoleFixture, f.sqid, "titogo", again.job.ID)
+ byInc := map[string]mediaRow{}
+ for _, r := range rows {
+ byInc[r.incarnation] = r
+ }
+ if old, cur := byInc[oldInc], byInc[newInc]; len(rows) != 2 || len(byInc) != 2 ||
+ old.state != "failed" || old.retiredAt == 0 || cur.state != "queued" || cur.retiredAt != 0 {
+ t.Fatalf("rows of job %s: %+v, want the old incarnation's retired and the new one's queued", again.job.ID, rows)
+ }
+ if r := f.get(again.job.ID); r.status != http.StatusOK || r.job.State != "queued" || r.job.Error != nil {
+ t.Fatalf("GET shows %d %s, want the new queued row", r.status, r.raw)
+ }
+}
+
+// TestAppPurgeRetiresQueuedAndRunning (spec §9): an app purged with one job
+// queued and one running. The queued row fails retired, uncharged, at
+// once; the running one's task is stopped and the purge refused until ECS
+// confirms it, when the row is charged ECS's time and cleaned. The store
+// made again under the app's name sees neither through GET.
+func TestAppPurgeRetiresQueuedAndRunning(t *testing.T) {
+ f := newMediaDoor(t, "code-media-purge")
+ ctx := context.Background()
+ f.put("uploads/b.mov", 5<<20, "bbbb")
+ f.put("uploads/c.mov", 5<<20, "cccc")
+ runID, arn := f.running(mediaTestKey)
+ queued := f.submit("uploads/b.mov")
+ if queued.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", queued.status, queued.raw)
+ }
+ acct := mediaAcct(f.consoleFixture)
+
+ if msg := f.srv.purgeAppStores(ctx, acct, "titogo", "paul@keymail.dev"); msg != mediaText("media.retire_pending", "titogo") {
+ t.Fatalf("purge with a running task = %q, want the deck's refusal", msg)
+ }
+ f.storeStanding("a purge refused while a task runs")
+ if r := f.mediaRowOf(queued.job.ID); r.state != "failed" || r.code != media.CodeRetired || r.chargedMS != 0 ||
+ !r.settled || r.retiredAt == 0 || r.endedAt == 0 || r.cleanup != 0 {
+ t.Fatalf("the queued row: %+v, want failed retired, uncharged, settled", r)
+ }
+ if !f.taskStopped(arn) {
+ t.Fatal("the purge did not stop the running task")
+ }
+ if r := f.mediaRowOf(runID); r.retiredAt == 0 || r.settled || r.taskStopped {
+ t.Fatalf("the running row before Track: %+v", r)
+ }
+
+ // The fake stopped the task at the retire, 30 s after it started.
+ f.clock = f.clock.Add(time.Minute)
+ f.track()
+ r := f.mediaRowOf(runID)
+ if r.state != "failed" || r.code != media.CodeRetired || !r.settled || !r.taskStopped {
+ t.Fatalf("the running row after Track: %+v", r)
+ }
+ var started, stopped time.Time
+ for _, task := range f.engine.Tasks() {
+ if task.ARN == arn {
+ started, stopped = task.StartedAt, task.StoppedAt
+ }
+ }
+ if want := stopped.Sub(started).Milliseconds(); want <= 0 || r.chargedMS != want {
+ t.Fatalf("charged %d ms, ECS ran it %d ms", r.chargedMS, want)
+ }
+ if r.cleanup == 0 {
+ t.Fatalf("no cleanup due on the stopped row: %+v", r)
+ }
+ if err := f.srv.media.Cleanup(ctx, f.clock); err != nil {
+ t.Fatal(err)
+ }
+ if r := f.mediaRowOf(runID); r.cleanup != 0 {
+ t.Fatalf("cleanup did not run: %+v", r)
+ }
+
+ if msg := f.srv.purgeAppStores(ctx, acct, "titogo", "paul@keymail.dev"); msg != "" {
+ t.Fatalf("purge after the stop was confirmed: %q", msg)
+ }
+ if rec := storedRecord(t, f.consoleFixture, "titogo"); rec != nil {
+ t.Fatalf("the store record survived the purge: %+v", rec)
+ }
+
+ f.buckets.DropBucket(f.bucket)
+ grantStore(t, f.consoleFixture, f.member)
+ f.buckets.Facts[f.bucket] = goodBucket()
+ if sub := f.submit("uploads/c.mov"); sub.status != http.StatusAccepted {
+ t.Fatalf("a job on the new store: %d %s", sub.status, sub.raw)
+ }
+ notFound := mediaText("media.job_not_found")
+ wantMediaRefusal(t, f.get(runID), 404, "job_not_found", notFound)
+ wantMediaRefusal(t, f.get(queued.job.ID), 404, "job_not_found", notFound)
+}
+
+// TestAppPurgeRetiresWithNoStoreLeft: purgeOneStore's order. A console
+// that cannot tear the store down refuses first and retires nothing (no
+// wait would change that answer); an app whose store record is already
+// gone still has its jobs retired by the purge.
+func TestAppPurgeRetiresWithNoStoreLeft(t *testing.T) {
+ f := newMediaDoor(t, "code-media-purge-nostore")
+ ctx := context.Background()
+ sub := f.submit(mediaTestKey)
+ if sub.status != http.StatusAccepted {
+ t.Fatalf("submit %d %s", sub.status, sub.raw)
+ }
+ acct := mediaAcct(f.consoleFixture)
+ prov := f.srv.cfg.StoreProvisioner
+ f.srv.cfg.StoreProvisioner = nil
+ if msg := f.srv.purgeAppStores(ctx, acct, "titogo", "paul@keymail.dev"); !strings.Contains(msg, "CARLOS_STORE_BACKEND") {
+ t.Fatalf("purge with no backend = %q", msg)
+ }
+ if r := f.mediaRowOf(sub.job.ID); r.retiredAt != 0 || r.state != "queued" {
+ t.Fatalf("a refused purge retired the job: %+v", r)
+ }
+ f.srv.cfg.StoreProvisioner = prov
+ func() {
+ defer f.srv.storeWalks.lock(f.sqid, "titogo", "")()
+ if err := objstore.TeardownIn(ctx, f.rel, prov, nil, f.sqid, "titogo", ""); err != nil {
+ t.Fatal(err)
+ }
+ }()
+ if msg := f.srv.purgeAppStores(ctx, acct, "titogo", "paul@keymail.dev"); msg != "" {
+ t.Fatalf("purge with no store left: %q", msg)
+ }
+ if r := f.mediaRowOf(sub.job.ID); r.retiredAt == 0 || r.state != "failed" || r.code != media.CodeRetired {
+ t.Fatalf("the purge left the job of an app with no store: %+v", r)
+ }
+}
+
+// TestSeedFinishRetires: a seed finish tearing down the app's own store
+// (env "") refuses with the deck's sentence while a job's task runs, and
+// stops it; once the stop is confirmed the finish tears the store down. A
+// config environment's store carries no media jobs, so its finish goes
+// ahead and retires nothing.
+func TestSeedFinishRetires(t *testing.T) {
+ f := newMediaDoor(t, "code-media-seed")
+ ctx := context.Background()
+ const seed, host = "s0123456789", "titogo-canary.example.com"
+ mark := func(env string) {
+ t.Helper()
+ rec, etag, err := objstore.GetIn(ctx, f.rel, f.sqid, "titogo", env)
+ if err != nil || rec == nil || rec.Declared == nil {
+ t.Fatalf("store %q: %+v %v", env, rec, err)
+ }
+ rec.Declared.Seed = seed
+ if _, err := objstore.PutIn(ctx, f.rel, f.sqid, "titogo", env, rec, etag); err != nil {
+ t.Fatal(err)
+ }
+ }
+ id, arn := f.running(mediaTestKey)
+
+ grantStoreIn(t, f.consoleFixture, f.member, "canary")
+ mark("canary")
+ if err := f.srv.finishSeedStore(ctx, f.sqid, "titogo", host, seed, "canary"); err != nil {
+ t.Fatalf("finish of a config environment's store: %v", err)
+ }
+ if rec, _, err := objstore.GetIn(ctx, f.rel, f.sqid, "titogo", "canary"); err != nil || rec != nil {
+ t.Fatalf("the canary store after its finish: %+v %v", rec, err)
+ }
+ if r := f.mediaRowOf(id); r.retiredAt != 0 || f.taskStopped(arn) {
+ t.Fatalf("a config environment's finish retired the app's job: %+v", r)
+ }
+
+ mark("")
+ err := f.srv.finishSeedStore(ctx, f.sqid, "titogo", host, seed, "")
+ if err == nil || err.Error() != mediaText("media.retire_pending", "titogo") {
+ t.Fatalf("finish with a running task = %v, want the deck's refusal", err)
+ }
+ f.storeStanding("a seed finish refused while a task runs")
+ if !f.taskStopped(arn) || f.mediaRowOf(id).retiredAt == 0 {
+ t.Fatal("the finish did not retire the job and stop its task")
+ }
+ f.clock = f.clock.Add(time.Minute)
+ f.track()
+ if err := f.srv.finishSeedStore(ctx, f.sqid, "titogo", host, seed, ""); err != nil {
+ t.Fatalf("finish after the stop was confirmed: %v", err)
+ }
+ if rec := storedRecord(t, f.consoleFixture, "titogo"); rec != nil {
+ t.Fatalf("the store survived the finish: %+v", rec)
+ }
+}
+
+// TestAccountDeletionRetires (pre-flight F2, F23): deleting an account
+// retires every media job of it, whatever its app. A queued row fails
+// retired at once; while a task still runs the deletion is refused with
+// the deck's account sentence and nothing is deleted. Once the stop is
+// confirmed the account goes. Another account's job is untouched.
+func TestAccountDeletionRetires(t *testing.T) {
+ fx, c, csrf, sqid := deletableFixture(t)
+ clock := time.Now().UTC().Truncate(time.Millisecond)
+ now := func() time.Time { return clock }
+ fx.srv.opNow = now
+ engine := mediatest.NewFakeEngine(now)
+ fx.srv.cfg.MediaEngine = engine
+ fx.srv.cfg.MediaGrants = mediatest.NewFakeGrants(now)
+ fx.srv.cfg.MediaRegion = "eu-west-1"
+ fx.srv.cfg.MediaLimits = media.DefaultLimits()
+ fx.srv.media = fx.srv.newMediaJobs()
+
+ ctx := context.Background()
+ exec := strings.Repeat("e", 32)
+ arn, err := engine.Run(ctx, media.RunRequest{Execution: exec, DeadlineS: 600, GrantExpiry: clock.Add(time.Hour)})
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := engine.Start(arn, clock.Add(time.Second)); err != nil {
+ t.Fatal(err)
+ }
+ insert := func(account, app, id, state, execution, taskARN string, stopped int) {
+ t.Helper()
+ if _, err := fx.st.db.Exec(`INSERT INTO media_jobs
+ (account, app, incarnation, job_id, key, etag, bytes, preset, class, bucket, state, submitted_at,
+ execution_id, task_arn, dispatched_at, granted_s, deadline_s, task_stopped)
+ VALUES (?, ?, 'inc', ?, 'uploads/a.mov', 'e', 1, 'video-720p', 'short', 'b', ?, ?, ?, ?, ?, 600, 600, ?)`,
+ account, app, id, state, clock.UnixMilli(), execution, taskARN, clock.UnixMilli(), stopped); err != nil {
+ t.Fatal(err)
+ }
+ }
+ insert(sqid, "shop", "q1", "queued", "", "", 1)
+ insert(sqid, "blog", "r1", "running", exec, arn, 0)
+ insert("bab", "shop", "q2", "queued", "", "", 1)
+
+ del := func() string {
+ t.Helper()
+ status, loc, body := postGated(t, fx, c, fx.ts.URL+"/a/"+sqid+"/delete",
+ url.Values{"csrf": {csrf}, "confirm": {"Testco"}})
+ if status != http.StatusSeeOther {
+ t.Fatalf("delete = %d:\n%s", status, body)
+ }
+ return flashAfter(t, fx, c, status, loc, body)
+ }
+ page := del()
+ if want := mediaText("media.retire_pending_account"); !strings.Contains(page, html.EscapeString(want)) {
+ t.Fatalf("the refusal is not the deck's %q:\n%s", want, page)
+ }
+ if a, _ := fx.st.AccountBySqid(sqid); a == nil {
+ t.Fatal("the account was deleted while a task ran")
+ }
+ if q := readMediaRows(t, fx, sqid, "shop", "q1"); len(q) != 1 || q[0].state != "failed" || q[0].code != media.CodeRetired || q[0].chargedMS != 0 {
+ t.Fatalf("the queued row: %+v", q)
+ }
+ if r := readMediaRows(t, fx, sqid, "blog", "r1"); len(r) != 1 || r[0].retiredAt == 0 {
+ t.Fatalf("the running row: %+v", r)
+ }
+ for _, task := range engine.Tasks() {
+ if task.ARN == arn && !task.Stopped {
+ t.Fatal("the deletion did not stop the running task")
+ }
+ }
+
+ clock = clock.Add(time.Minute)
+ if err := fx.srv.media.Track(ctx, clock); err != nil {
+ t.Fatal(err)
+ }
+ del()
+ if a, _ := fx.st.AccountBySqid(sqid); a != nil {
+ t.Fatal("the account was not deleted once the stop was confirmed")
+ }
+ if r := readMediaRows(t, fx, sqid, "blog", "r1"); len(r) != 1 || r[0].state != "failed" || r[0].code != media.CodeRetired || !r[0].settled {
+ t.Fatalf("the running row after Track: %+v", r)
+ }
+ if o := readMediaRows(t, fx, "bab", "shop", "q2"); len(o) != 1 || o[0].state != "queued" || o[0].retiredAt != 0 {
+ t.Fatalf("another account's row: %+v", o)
+ }
+}
+
+// mediaRetireExempt are the files whose store teardown needs no
+// retirement, each with its reason. A file listed here that no longer
+// tears a store down fails the guard, so the list cannot go stale.
+var mediaRetireExempt = map[string]string{
+ // The host-claim purge. Media conversion refuses claims mode (spec §11
+ // A1): the door answers claims_console before writing and media_jobs is
+ // gated with Refuse, so no media row exists on a console that runs it.
+ "claim_purge.go": "media refuses claims mode (spec §11 A1), so no media_jobs row exists there",
+}
+
+// TestEveryStoreTeardownRetiresMedia (pre-flight F24) is a source guard
+// over every non-test file of this package, by AST: every call of
+// objstore.TeardownIn or objstore.Teardown sits in a function (its
+// FuncDecl, closures included) that calls mediaStoreRetire before it,
+// after taking a store walk lock; and every store DeleteAccount call sits
+// in a function that calls mediaAccountRetire before it. Calls, not text:
+// a comment naming the function satisfies nothing.
+func TestEveryStoreTeardownRetiresMedia(t *testing.T) {
+ files, err := filepath.Glob("*.go")
+ if err != nil {
+ t.Fatal(err)
+ }
+ fset := token.NewFileSet()
+ var found []string // file: function: call
+ exemptUsed := map[string]bool{}
+ for _, name := range files {
+ if strings.HasSuffix(name, "_test.go") {
+ continue
+ }
+ src, err := os.ReadFile(name)
+ if err != nil {
+ t.Fatal(err)
+ }
+ f, err := parser.ParseFile(fset, name, src, 0)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, d := range f.Decls {
+ fd, ok := d.(*ast.FuncDecl)
+ if !ok || fd.Body == nil {
+ continue
+ }
+ first := map[string]token.Pos{} // the first call of each guard name
+ var teardowns, deletes []token.Pos
+ ast.Inspect(fd.Body, func(n ast.Node) bool {
+ call, ok := n.(*ast.CallExpr)
+ if !ok {
+ return true
+ }
+ sel, ok := call.Fun.(*ast.SelectorExpr)
+ if !ok {
+ return true
+ }
+ note := func(k string) {
+ if _, seen := first[k]; !seen {
+ first[k] = call.Pos()
+ }
+ }
+ switch sel.Sel.Name {
+ case "mediaStoreRetire", "mediaAccountRetire":
+ note(sel.Sel.Name)
+ case "lock":
+ if inner, ok := sel.X.(*ast.SelectorExpr); ok && inner.Sel.Name == "storeWalks" {
+ note("storeWalks.lock")
+ }
+ case "Teardown", "TeardownIn":
+ if pkg, ok := sel.X.(*ast.Ident); ok && pkg.Name == "objstore" {
+ teardowns = append(teardowns, call.Pos())
+ }
+ case "DeleteAccount":
+ if inner, ok := sel.X.(*ast.SelectorExpr); ok && inner.Sel.Name == "store" {
+ deletes = append(deletes, call.Pos())
+ }
+ }
+ return true
+ })
+ before := func(k string, at token.Pos) bool {
+ p, ok := first[k]
+ return ok && p < at
+ }
+ for _, at := range teardowns {
+ where := fset.Position(at)
+ found = append(found, name+": "+fd.Name.Name+": objstore teardown")
+ if _, ok := mediaRetireExempt[name]; ok {
+ exemptUsed[name] = true
+ continue
+ }
+ if !before("mediaStoreRetire", at) {
+ t.Errorf("%s: %s tears a store down with no mediaStoreRetire call before it in its function", where, fd.Name.Name)
+ continue
+ }
+ if !before("storeWalks.lock", first["mediaStoreRetire"]) {
+ t.Errorf("%s: %s calls mediaStoreRetire without a store walk lock taken before it", where, fd.Name.Name)
+ }
+ }
+ for _, at := range deletes {
+ found = append(found, name+": "+fd.Name.Name+": DeleteAccount")
+ if !before("mediaAccountRetire", at) {
+ t.Errorf("%s: %s deletes an account with no mediaAccountRetire call before it in its function", fset.Position(at), fd.Name.Name)
+ }
+ }
+ }
+ }
+ for name, why := range mediaRetireExempt {
+ if !exemptUsed[name] {
+ t.Errorf("%s is exempt (%s) but tears no store down: drop it from mediaRetireExempt", name, why)
+ }
+ }
+ // The sites as found today: a new one must be read and guarded, not
+ // slip in under the loop above unseen.
+ sort.Strings(found)
+ got := strings.Join(found, "\n")
+ want := strings.Join([]string{
+ "appsettings.go: handleStoreDestroy: objstore teardown",
+ "claim_purge.go: teardown: objstore teardown",
+ "ownership.go: deleteAccountNow: DeleteAccount",
+ "ownership.go: purgeOneStore: objstore teardown",
+ "seedfinish.go: finishSeedStore: objstore teardown",
+ }, "\n")
+ if got != want {
+ t.Errorf("teardown sites:\n got\n%s\nwant\n%s", got, want)
+ }
+}
diff --git a/internal/console/ownership.go b/internal/console/ownership.go
index 6157b416d..ee84a63b7 100644
--- a/internal/console/ownership.go
+++ b/internal/console/ownership.go
@@ -184,6 +184,19 @@ func (s *Server) deleteAccountNow(w http.ResponseWriter, r *http.Request, addr s
if s.deletionRefused(w, r, acct) {
return false
}
+ // Every media job of the account is retired before anything is marked,
+ // whatever app it belonged to, and while one of their tasks can still
+ // write the deletion is refused with nothing deleted (media conversion
+ // spec §5.3; pre-flight F2, F23).
+ if refusal, err := s.mediaAccountRetire(r.Context(), acct.Sqid); err != nil || refusal != "" {
+ if err != nil {
+ log.Printf("console: delete account %s: retire media jobs: %v", acct.Sqid, err)
+ refusal = "Could not delete this account." // deletionAdvice's own sentence for any other error
+ }
+ s.setFlash(w, "err", refusal)
+ http.Redirect(w, r, "/a/"+acct.Sqid+"/settings", http.StatusSeeOther)
+ return false
+ }
// The bucket first, and the deletion is abandoned if it will not take.
//
// This console's rows are not where account identity lives — every console
@@ -873,12 +886,23 @@ func (s *Server) purgeOneStore(ctx context.Context, acct *Account, app, env, add
log.Printf("console: purge store read %s/%s%s: %v", acct.Sqid, app, storeEnvSuffix(env), rerr)
return "Could not read “" + app + "”'s object-store record — nothing was deleted; try again."
}
- if rec == nil || (rec.Provisioned == nil && rec.Grant == nil) {
- return ""
- }
- if s.cfg.StoreProvisioner == nil {
+ estate := rec != nil && (rec.Provisioned != nil || rec.Grant != nil)
+ if estate && s.cfg.StoreProvisioner == nil {
return "“" + app + "” has a provisioned object store, and this console has no storage backend configured (CARLOS_STORE_BACKEND) — it cannot be deleted here until the store is torn down."
}
+ // The app is going, so its media jobs are retired under this lock even
+ // when it has no store left to tear down, and while one of their tasks
+ // can still write the purge stops here (media conversion spec §5.3).
+ // After the refusals above, which no wait would change.
+ if refusal, err := s.mediaStoreRetire(ctx, acct.Sqid, app, env); err != nil {
+ log.Printf("console: purge store %s/%s%s: retire media jobs: %v", acct.Sqid, app, storeEnvSuffix(env), err)
+ return "Could not tear down “" + app + "”'s object store — nothing was deleted; try again."
+ } else if refusal != "" {
+ return refusal
+ }
+ if !estate {
+ return ""
+ }
// The walk gets its own ceiling rather than the request's open-ended
// context: a teardown is many round trips (EmptyBucket is paginated), and
// it must not be able to hold this handler open indefinitely.
diff --git a/internal/console/seedfinish.go b/internal/console/seedfinish.go
index cf6491ee2..7daf34f2f 100644
--- a/internal/console/seedfinish.go
+++ b/internal/console/seedfinish.go
@@ -174,6 +174,16 @@ func (s *Server) finishSeedStore(ctx context.Context, sqid, app, host, seedID, e
if s.cfg.StoreProvisioner == nil {
return fmt.Errorf("finish seed %s of %s: this console has no storage backend to tear its store down with", seedID, host)
}
+ // The store's media jobs first, under this lock: while one of their
+ // tasks can still write, the store stands and the finish answers the
+ // deck's sentence; the next finish resumes (media conversion spec
+ // §5.3). A seed's store is a config environment's, which carries no
+ // media jobs, so this answers "" at once unless env is the app's own.
+ if refusal, err := s.mediaStoreRetire(ctx, sqid, app, env); err != nil {
+ return fmt.Errorf("finish seed %s of %s: retire the media jobs of its store: %w", seedID, host, err)
+ } else if refusal != "" {
+ return errors.New(refusal)
+ }
tctx, cancel := context.WithTimeout(ctx, storeTeardownTimeout)
defer cancel()
if err := objstore.TeardownIn(tctx, s.cfg.Releases, s.cfg.StoreProvisioner, s.cfg.StoreScanner, sqid, app, env); err != nil {