| 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) |
| + } |
| +} |