Public: anyone can read this; the crew can change it.

After a data import or its undo the running app is restarted for you, and the page says so #15280

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/15266-after-a-data-import-or-its-undo-the-runn → main 0 commits fork 2 threads · 2 unresolved

  • Merged. mason/15266-after-a-data-import-or-its-undo-the-runn was merged into main as 73a87b3.

Review

Sign in to review this change.
7 files changed +215 −16
docs/features/data-move.md +8 −1
@@ -31,6 +31,14 @@ checklist (`docs/features/migration-mode.md`); the engine under it is the databa
3131 and has its old DNS recorded (the cut-over, `app_domain.old_records`); then an import and an undo
3232 are both refused, since the old data is no longer the way back.
3333
34 6. **The restart** (#15266): a running app holds the file it opened at start, and the import
35 renames a new one over it, so once the file is in place an import or an undo deploys production
36 again at its own commit, the same `redeploy` the app page's button asks for
37 (`restartAfterMove`, `src/actions/migrate_data.ts`). Only a running (or coming-up) production
38 is restarted; one asleep or stopped opens the new file when it next starts, so nothing in flight
39 is dropped for it. The result line, the API's and MCP's `restart` (`restarted`, `asleep`,
40 `not_running`) and the terminal say which.
41
3442 The record is the `app.data_imported` and `app.data_undone` events (the first carries the snapshot's
3543 name and each table's rows and checksum): no state of its own.
3644
@@ -44,6 +52,5 @@ name and each table's rows and checksum): no state of its own.
4452 `a` imports it, `u` undoes after a y/n.
4553
4654 ## Not done
47 - The running app keeps its old file open until it restarts: restart it after an import or an undo.
4855 - Only the store `app.db` in production; files and uploads are `scripts/copy-app-files.ts`.
4956 - Types are not translated: SQLite keeps the Postgres type names as declared and is loose about them.
src/actions/migrate_data.ts +38 −3
@@ -12,11 +12,12 @@
1212 import { readFileSync, statSync } from "node:fs";
1313 import type { App } from "../app.ts";
1414 import { envDataDir } from "../apps/data.ts";
15 import { appsRuntime } from "../apps/runtime.ts";
1516 import { DUMP_MAX } from "../apps/dump_file.ts";
1617 import type { ImportReport } from "../apps/dump_import.ts";
1718 import { undoImport } from "../apps/dump_undo.ts";
1819 import { EXPORT_COMMAND, fromPostgres, skippedWords, type Skipped } from "../apps/pg_dump.ts";
19 import { getAppByRepo } from "../core/apps.ts";
20 import { getAppByRepo, type AppRecord } from "../core/apps.ts";
2021 import { listDomains } from "../core/domains.ts";
2122 import { listEvents } from "../core/events.ts";
2223 import { canAdmin, type Repo } from "../core/repos.ts";
@@ -49,6 +50,37 @@ export interface ReceiptRow {
4950 readonly counted: number;
5051 }
5152
53 /**
54 * What became of the running app once the store was replaced (#15266). A process holds the file
55 * it opened at start, so a running production is deployed again at its own commit, the same
56 * `redeploy` the app page's button asks for; one asleep or stopped opens the new file when it next
57 * starts, and nothing in flight is dropped for it.
58 */
59 export type AfterMove = "restarted" | "asleep" | "not_running";
60
61 /** Restart production once, after the file is in place, only when it is running or coming up. */
62 export function restartAfterMove(app: App, record: AppRecord, repo: Repo, actorId: string): AfterMove {
63 const runtime = appsRuntime(app);
64 const status = runtime?.envStatus(record, "production");
65 if (runtime === undefined || status === undefined) return "not_running";
66 if (status.state === "asleep") return "asleep";
67 if (status.state !== "running" && status.state !== "deploying") return "not_running";
68 const run = runtime.requestDeploy(record, repo, "production", status.commitOid, "redeploy", actorId);
69 return run === undefined ? "not_running" : "restarted";
70 }
71
72 /** The result line's words for `AfterMove`. */
73 export function afterMoveWords(after: AfterMove): string {
74 switch (after) {
75 case "restarted":
76 return "The app was restarted to read it.";
77 case "asleep":
78 return "The app is asleep: it reads the new store when it wakes, so nothing was restarted.";
79 case "not_running":
80 return "The app is not running: it reads the new store when it next starts, so nothing was restarted.";
81 }
82 }
83
5284 export interface MoveReceipt {
5385 readonly applied: boolean;
5486 /** The drop file the dump was read from. */
@@ -60,6 +92,8 @@ export interface MoveReceipt {
6092 readonly skipped: readonly Skipped[];
6193 /** The snapshot the import took of the store it replaced; null when there was none. */
6294 readonly snapshot: string | null;
95 /** What became of the running app; null on a check, which changes nothing. */
96 readonly restart: AfterMove | null;
6397 }
6498
6599 const rowsOf = (report: ImportReport): ReceiptRow[] =>
@@ -117,6 +151,7 @@ export function moveData(
117151 tables: rowsOf(done.value),
118152 skipped: read.skipped,
119153 snapshot: done.value.kept ?? null,
154 restart: apply ? restartAfterMove(app, record, repo, user.value.id) : null,
120155 });
121156 }
122157
@@ -189,7 +224,7 @@ export function undoMove(
189224 app: App,
190225 actor: User | undefined,
191226 repo: Repo,
192 ): Result<{ readonly file: string; readonly restored: boolean; readonly setAside: string }, MoveError> {
227 ): Result<{ readonly file: string; readonly restored: boolean; readonly setAside: string; readonly restart: AfterMove }, MoveError> {
193228 const user = requireUser(actor);
194229 if (!user.ok) return user;
195230 const state = dataMoveState(app, user.value, repo);
@@ -206,7 +241,7 @@ export function undoMove(
206241 actorId: user.value.id,
207242 payload: { env: "production", file: last.file, restored: done.value.restored, setAside: done.value.setAside },
208243 });
209 return ok({ file: last.file, restored: done.value.restored, setAside: done.value.setAside });
244 return ok({ file: last.file, restored: done.value.restored, setAside: done.value.setAside, restart: restartAfterMove(app, record, repo, user.value.id) });
210245 }
211246
212247 /** A refusal in words a person can act on. */
src/contract/openapi/routes/postApiV1ReposOwnerNameDataMove.ts +1 −1
@@ -6,7 +6,7 @@ export const route: Route = {
66 summary:
77 "Move a platform app's Postgres dump from its drop into its SQLite store",
88 detail:
9 "Move a platform app's Postgres dump from its drop into its SQLite store: { dump } checks (nothing changes) and { dump, apply: true } imports, keeping the store it replaces as the snapshot; { undo: true } puts the snapshot back until a domain has been cut over. Answers the receipt { applied, dump, file, statements, tables: [{ table, rows, dump, store, counted }], skipped, snapshot }; needs an admin-scope token and the right to administer the repository",
9 "Move a platform app's Postgres dump from its drop into its SQLite store: { dump } checks (nothing changes) and { dump, apply: true } imports, keeping the store it replaces as the snapshot; { undo: true } puts the snapshot back until a domain has been cut over. Answers the receipt { applied, dump, file, statements, tables: [{ table, rows, dump, store, counted }], skipped, snapshot, restart } (restart: restarted, asleep or not_running: a running production is restarted once after an import or an undo); needs an admin-scope token and the right to administer the repository",
1010 auth: true,
1111 role: "member",
1212 body: { dump: "string?", apply: "boolean?", undo: "boolean?" },
src/tui/screens/datamove.ts +6 −5
@@ -4,10 +4,11 @@
44 * the name of a `.sql` file in the app's drop and checks it (nothing is changed), `a` imports it,
55 * keeping the store it replaces, and `u` puts that store back after a y/n, until a domain has been
66 * cut over. The rows are the receipt's: per table, the dump's rows and checksum, the store's, and
7 * whether they match. A running app still holds the old file: restart it after an import or undo.
7 * whether they match. A running app is restarted after an import or undo, so it reads the new
outdated

Stale: this header still says a running app holds the old file and to restart it after an import or undo. The screen now restarts it. Update the comment.

8 * store; the result line says whether it was.
89 */
910
10 import { dataMoveState, moveData, moveMessage, undoMove, type MoveReceipt } from "../../actions/migrate_data.ts";
11 import { afterMoveWords, dataMoveState, moveData, moveMessage, undoMove, type MoveReceipt } from "../../actions/migrate_data.ts";
1112 import { lostKeys, skippedWords } from "../../apps/pg_dump.ts";
1213 import { canAdmin, type Repo } from "../../core/repos.ts";
1314 import type { Ctx, Screen } from "../app/app.ts";
@@ -42,7 +43,7 @@ export function leftOut(receipt: MoveReceipt): string {
4243 export function dataMoveScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
4344 const state = new ListState();
4445 let rows: ListRow[] = [];
45 let note = "m checks a dump in the app's drop, a imports it, u undoes it. Restart the app after an import or undo.";
46 let note = "m checks a dump in the app's drop, a imports it, u undoes it; a running app is restarted after either.";
4647 const move = (apply: boolean): Screen =>
4748 promptScreen(ctx, screen, {
4849 title: apply ? "Import from the drop" : "Check a dump in the drop",
@@ -53,7 +54,7 @@ export function dataMoveScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
5354 const done = moveData(f.app, f.user, repo, { dump: name, apply });
5455 if (!done.ok) return moveMessage(done.error);
5556 rows = moveRows(done.value);
56 note = `${apply ? "Imported" : "Checked, nothing changed:"} ${done.value.tables.length} tables${leftOut(done.value)}.`;
57 note = `${apply ? "Imported" : "Checked, nothing changed:"} ${done.value.tables.length} tables${leftOut(done.value)}.${apply ? ` ${afterMoveWords(done.value.restart ?? "not_running")}` : ""}`;
5758 ctx.invalidate();
5859 return undefined;
5960 },
@@ -71,7 +72,7 @@ export function dataMoveScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
7172 if (!undone.ok) ctx.toast(moveMessage(undone.error), "danger");
7273 else {
7374 rows = [];
74 note = `${undone.value.file} is back as it was; writes since the import are not in it. The imported store is kept as ${undone.value.setAside}. Restart the app.`;
75 note = `${undone.value.file} is back as it was; writes since the import are not in it. The imported store is kept as ${undone.value.setAside}. ${afterMoveWords(undone.value.restart)}`;
7576 ctx.invalidate();
7677 }
7778 },
src/web/studio/data_move.ts +5 −5
@@ -8,7 +8,7 @@
88 * the gate are `actions/migrate_data.ts`'s, the same the API, the MCP tool and the terminal use.
99 */
1010
11 import { dataMoveState, moveData, moveMessage, undoMove, type MoveReceipt, type DataMoveState } from "../../actions/migrate_data.ts";
11 import { afterMoveWords, dataMoveState, moveData, moveMessage, undoMove, type MoveReceipt, type DataMoveState } from "../../actions/migrate_data.ts";
1212 import { lostKeys, skippedWords } from "../../apps/pg_dump.ts";
1313 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1414 import type { Ctx } from "../../http/context.ts";
@@ -107,14 +107,14 @@ function body(base: string, state: DataMoveState, shown: MoveReceipt | undefined
107107 ${form}
108108 ${state.cutOver || state.files.length === 0
109109 ? null
110 : html`<p class="muted small">Check changes nothing. Import keeps the store it replaces for Undo. Restart the app afterwards: it still holds the old file open until it does, and anything it writes in between is lost.</p>`}
110 : html`<p class="muted small">Check changes nothing; Import keeps the old store for Undo.</p>`}
outdated

Principle 1: this hint explains the restart, and the result line then says it again. Keep one short sentence here (e.g. "Check changes nothing; Import keeps the old store for Undo."), and let the result line report the restart. The Undo hint below has the same duplication.

111111 </section>
112112 ${shown === undefined ? null : receiptCard(shown)}
113113 ${lastCard(state)}
114114 <div class="row">
115115 ${state.canUndo
116116 ? html`<form method="post" action="${base}/data-move"><input type="hidden" name="do" value="undo" />${btn("Undo the import", { variant: "outline" })}</form>
117 <p class="muted small">Undo puts the earlier store back; writes the app made since the import are not in it (they stay in the set-aside file). Restart the app after.</p>`
117 <p class="muted small">Undo puts the earlier store back; writes the app made since the import are not in it (they stay in the set-aside file).</p>`
118118 : null}
119119 ${btn("Back to the checklist", { href: `${base}#app-migration`, variant: "outline" })}
120120 </div>`;
@@ -164,7 +164,7 @@ export async function dataMoveAct(ctx: Ctx): Promise<Response> {
164164 ctx,
165165 to,
166166 done.ok
167 ? { message: done.value.restored ? `${done.value.file} is back as it was before the import; writes the app made since are not in it. Restart the app. The imported store is kept as ${done.value.setAside}.` : `The imported ${done.value.file} is set aside as ${done.value.setAside}; the app starts empty, as it was.` }
167 ? { message: `${done.value.restored ? `${done.value.file} is back as it was before the import; writes the app made since are not in it. The imported store is kept as ${done.value.setAside}.` : `The imported ${done.value.file} is set aside as ${done.value.setAside}; the app starts empty, as it was.`} ${afterMoveWords(done.value.restart)}` }
168168 : { tone: "danger", message: moveMessage(done.error) },
169169 );
170170 }
@@ -173,6 +173,6 @@ export async function dataMoveAct(ctx: Ctx): Promise<Response> {
173173 const apply = what === "import";
174174 const done = moveData(ctx.app, ctx.auth.user, repo, { dump: field(form, "dump"), apply });
175175 if (!done.ok) return flashTo(ctx, to, { tone: "danger", message: moveMessage(done.error) });
176 if (apply) return flashTo(ctx, to, { message: `Imported ${done.value.tables.length} tables from ${done.value.dump}: every table's rows and checksum match.` });
176 if (apply) return flashTo(ctx, to, { message: `Imported ${done.value.tables.length} tables from ${done.value.dump}: every table's rows and checksum match. ${afterMoveWords(done.value.restart ?? "not_running")}` });
177177 return draw(ctx, done.value);
178178 }
test/apps-data-move-restart.test.ts added +137
@@ -0,0 +1,137 @@
1 /**
2 * After a data import or its undo the running app is restarted for you (#15266): a process holds
3 * the store it opened at start, and the import renames a new file over it, so without the restart
4 * the app keeps answering from the old rows. Here a real app opens `app.db` once and serves its
5 * `items`; after the import and after the undo it answers the new rows with nobody pressing
6 * Redeploy, and the restart was the app's one `redeploy` run.
7 */
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdirSync, writeFileSync } from "node:fs";
10 import { join } from "node:path";
11 import { commitToBranch } from "../src/actions/repos.ts";
12 import { moveData, undoMove } from "../src/actions/migrate_data.ts";
13 import type { AppRecord } from "../src/core/apps.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { listRuns } from "../src/core/runs.ts";
16 import { dropDir } from "../src/drop/store.ts";
17 import {
18 APPS_DOMAIN,
19 deploySettled,
20 fetchAsHost,
21 startAppsForge,
22 startHello,
23 stopAppsForge,
24 type AppsForge,
25 } from "./helpers/apps-forge.ts";
26
27 /** Opens the store once, at start, as an app does; `/items` reads it on every request. */
28 const ITEMS_SERVER = `import { Database } from "bun:sqlite";
29 const db = new Database(\`\${process.env.FORGE_APP_DATA ?? "."}/app.db\`);
30 export const server = Bun.serve({
31 port: Number(process.env.PORT ?? "0"),
32 fetch(request) {
33 if (new URL(request.url).pathname !== "/items") return new Response("items app");
34 try {
35 return Response.json(db.query("SELECT name FROM items ORDER BY id").values().map((r) => r[0]));
36 } catch {
37 return Response.json([]);
38 }
39 },
40 });
41 `;
42
43 const DUMP = `--
44 -- PostgreSQL database dump
45 --
46 CREATE TABLE public.items (id integer NOT NULL, name text);
47 INSERT INTO public.items (id, name) VALUES (1, 'bolt');
48 INSERT INTO public.items (id, name) VALUES (2, 'nut');
49 `;
50
51 describe("a data move restarts the running app", () => {
52 let forge: AppsForge;
53 let repo: Repo;
54 let record: AppRecord;
55 const items = async (): Promise<unknown> =>
56 (await fetchAsHost(forge.servers, `hello.${APPS_DOMAIN}`, "/items")).json();
57 const deploys = () => listRuns(forge.app.db, repo.id, { kind: "deploy", limit: 50 });
58 const redeploys = () =>
59 listRuns(forge.app.db, repo.id, { kind: "deploy", limit: 50 }).filter((r) => r.env === "production" && r.reason === "redeploy");
60
61 beforeAll(async () => {
62 forge = await startAppsForge();
63 ({ repo, record } = await startHello(forge));
64 const committed = await commitToBranch(forge.app, forge.alice, repo, {
65 message: "Serve the items",
66 files: [
67 { path: "src/server.ts", content: ITEMS_SERVER },
68 { path: "src/server.test.ts", content: 'import { expect, test } from "bun:test";\ntest("passes", () => { expect(1).toBe(1); });\n' },
69 { path: "src/audit.test.ts", content: null },
70 { path: "src/openapi.test.ts", content: null },
71 { path: "src/security.test.ts", content: null },
72 { path: "src/site.test.ts", content: null },
73 ],
74 });
75 if (!committed.ok) throw new Error(String(committed.error));
76 const run = await deploySettled(forge.app, repo.id, (r) => r.env === "production" && r.commitOid === committed.value.commitOid);
77 if (run.state !== "ok") throw new Error(`deploy failed: ${run.summary}`);
78 mkdirSync(dropDir(forge.dataDir, repo.id), { recursive: true });
79 writeFileSync(join(dropDir(forge.dataDir, repo.id), "dump.sql"), DUMP);
80 }, 180_000);
81
82 afterAll(async () => {
83 await forge.runtime.stop();
84 await stopAppsForge(forge);
85 });
86
87 test("an import restarts it once and it serves the imported rows; an undo does it again", async () => {
88 expect(forge.runtime.envStatus(record, "production")?.state).toBe("running");
89 expect(await items()).toEqual([]);
90 expect(redeploys()).toHaveLength(0);
91
92 const done = moveData(forge.app, forge.alice, repo, { dump: "dump.sql", apply: true });
93 if (!done.ok) throw new Error(JSON.stringify(done.error));
94 expect(done.value.restart).toBe("restarted");
95 expect(redeploys()).toHaveLength(1);
96 const first = await deploySettled(forge.app, repo.id, (r) => r.env === "production" && r.reason === "redeploy");
97 expect(first.state).toBe("ok");
98 expect(await items()).toEqual(["bolt", "nut"]);
99
100 const undone = undoMove(forge.app, forge.alice, repo);
101 if (!undone.ok) throw new Error(JSON.stringify(undone.error));
102 expect(undone.value.restart).toBe("restarted");
103 expect(redeploys()).toHaveLength(2);
104 await deploySettled(forge.app, repo.id, (r) => r.env === "production" && r.reason === "redeploy" && r.id !== first.id);
105 expect(await items()).toEqual([]);
106 }, 120_000);
107
108 test("a check restarts nothing", () => {
109 const before = redeploys().length;
110 const done = moveData(forge.app, forge.alice, repo, { dump: "dump.sql" });
111 if (!done.ok) throw new Error(JSON.stringify(done.error));
112 expect(done.value.restart).toBeNull();
113 expect(redeploys()).toHaveLength(before);
114 });
115
116 // Last: it leaves production stopped, then asleep.
117 test("a stopped app is not restarted, nor is an asleep one, and no run is started for either", async () => {
118 const commitOid = forge.runtime.envStatus(record, "production")?.commitOid;
119 if (commitOid === undefined) throw new Error("production has no commit");
120 await forge.runtime.stopEnv(record, "production");
121 expect(forge.runtime.envStatus(record, "production")?.state ?? "stopped").not.toBe("running");
122 const before = deploys().length;
123
124 const done = moveData(forge.app, forge.alice, repo, { dump: "dump.sql", apply: true });
125 if (!done.ok) throw new Error(JSON.stringify(done.error));
126 expect(done.value.restart).toBe("not_running");
127 expect(deploys()).toHaveLength(before);
128
129 expect(forge.runtime.settleAsleep(record, "production", commitOid)).toBe(true);
130 expect(forge.runtime.envStatus(record, "production")?.state).toBe("asleep");
131 const undone = undoMove(forge.app, forge.alice, repo);
132 if (!undone.ok) throw new Error(JSON.stringify(undone.error));
133 expect(undone.value.restart).toBe("asleep");
134 expect(deploys()).toHaveLength(before);
135 expect(forge.runtime.envStatus(record, "production")?.state).toBe("asleep");
136 });
137 });
test/data-move.test.ts +20 −1
@@ -11,7 +11,7 @@ import { tmpdir } from "node:os";
1111 import { join } from "node:path";
1212 import { createApp, type App } from "../src/app.ts";
1313 import { createRepo } from "../src/actions/repos.ts";
14 import { dataMoveState, moveData, undoMove } from "../src/actions/migrate_data.ts";
14 import { afterMoveWords, dataMoveState, moveData, undoMove } from "../src/actions/migrate_data.ts";
1515 import { envDataDir } from "../src/apps/data.ts";
1616 import { EXPORT_COMMAND, fromPostgres, lostKeys } from "../src/apps/pg_dump.ts";
1717 import { createApp as insertApp } from "../src/core/apps.ts";
@@ -222,6 +222,25 @@ describe("moving the data", () => {
222222 expect(dataMoveState(app, cy, repo)).toMatchObject({ ok: true, value: { canUndo: false, last: { undone: true } } });
223223 });
224224
225 test("the result line says what became of the app: with none running, nothing was restarted", async () => {
226 // No apps runtime here, so no app is running: an import and an undo restart nothing, and say
227 // so.
228 const flashOf = async (form: Record<string, string>) => {
229 const posted = await fetch(`${servers.url}/cy/shop/data-move`, { method: "POST", headers: { cookie }, body: new URLSearchParams(form), redirect: "manual" });
230 expect(posted.status).toBe(303);
231 const flash = (posted.headers.get("set-cookie") ?? "").split(";")[0]!;
232 return (await fetch(`${servers.url}/cy/shop/data-move`, { headers: { cookie: `${cookie}; ${flash}` } })).text();
233 };
234 const imported = await flashOf({ do: "import", dump: "dump.sql" });
235 expect(imported).toContain("every table&#39;s rows and checksum match. The app is not running: it reads the new store when it next starts, so nothing was restarted.");
236 const undone = await flashOf({ do: "undo" });
237 expect(undone).toContain("so nothing was restarted.");
238 expect(afterMoveWords("restarted")).toBe("The app was restarted to read it.");
239 expect(afterMoveWords("asleep")).toContain("asleep");
240 const check = moveData(app, cy, repo, { dump: "dump.sql" });
241 expect(check.ok && check.value.restart).toBeNull();
242 });
243
225244 test("a POST without do, or with an unknown do, changes nothing; the buttons carry their do", async () => {
226245 const before = readdirSync(prod()).sort();
227246 for (const form of [{ dump: "dump.sql" }, { dump: "dump.sql", do: "" }, { dump: "dump.sql", do: "drop" }]) {

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs