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

A request during a forge's stop waits for the old process to be gone and starts it once: one data directory never has two forge processes #13897

Closed opened this
Closed without merging

trevato/one-process-per-forge → main 1 commit

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
2 files changed +184 −7
src/spawn/cell.ts +51 −7
@@ -73,6 +73,31 @@ function alive(pid: number): boolean {
7373 }
7474 }
7575
76 /** Starts and stops waiting their turn, by the child's data directory, for each parent. */
77 const turnsOf = new WeakMap<App, Map<string, Promise<void>>>();
78
79 /**
80 * One start or stop at a time for each child data directory, in the order they
81 * were asked. A start takes its turn before any process is made and a stop
82 * holds its turn until the old process is gone, so a request that arrives
83 * while a forge is leaving starts it after, never beside it: one data
84 * directory has one forge process (#13814).
85 */
86 export function inTurn<T>(parent: App, dir: string, run: () => Promise<T>): Promise<T> {
87 const turns = turnsOf.get(parent) ?? new Map<string, Promise<void>>();
88 turnsOf.set(parent, turns);
89 const mine = (turns.get(dir) ?? Promise.resolve()).then(run);
90 const tail = mine.then(
91 () => {},
92 () => {},
93 );
94 turns.set(dir, tail);
95 void tail.then(() => {
96 if (turns.get(dir) === tail) turns.delete(dir);
97 });
98 return mine;
99 }
100
76101 /** A forge started within this long is not put to sleep by the idle sweep (#11155). */
77102 export const NEW_FORGE_MS = 10 * 60_000;
78103
@@ -214,8 +239,16 @@ interface Held extends CellChild {
214239 }
215240
216241 export interface CellChildren {
217 /** Start the child (idempotent); resolves once it answers, or says why not. */
242 /**
243 * Start the child (idempotent); resolves once it answers, or says why not. Asked while the child
244 * is being stopped, it waits for the old process to be gone and then starts it once: every
245 * request in that time joins the one start.
246 */
218247 start(input: { bodyId: string; name: string; size: Size }): Promise<CellChild | undefined>;
248 /**
249 * Stop the child; resolves once its process is gone. Asked while it is starting, it waits for
250 * the start and stops what came up.
251 */
219252 stop(bodyId: string): Promise<void>;
220253 get(bodyId: string): CellChild | undefined;
221254 /** Why the last start failed, in a sentence a person can read; undefined when it did not. */
@@ -419,7 +452,9 @@ export function makeRegistry(parent: App, launcher?: Launcher): CellChildren {
419452 }
420453 return started.child;
421454 };
422 const launch = async (input: { bodyId: string; name: string; size: Size }): Promise<CellChild | undefined> => {
455 // The one place a child's process is made, and only in its directory's turn: a stop under way
456 // has its process gone before this runs (`inTurn`).
457 const launch = (input: { bodyId: string; name: string; size: Size }): Promise<CellChild | undefined> => inTurn(parent, childDirOf(parent, input.bodyId), async () => {
423458 const child = await (launcher ?? launchInCell)(input, failOf(input.bodyId));
424459 if (child === undefined) return undefined;
425460 held.set(input.bodyId, child);
@@ -432,7 +467,7 @@ export function makeRegistry(parent: App, launcher?: Launcher): CellChildren {
432467 }
433468 });
434469 return child;
435 };
470 });
436471
437472 return {
438473 start(input) {
@@ -458,12 +493,21 @@ export function makeRegistry(parent: App, launcher?: Launcher): CellChildren {
458493 }
459494 return flight;
460495 },
461 async stop(bodyId) {
462 const child = held.get(bodyId);
463 if (child === undefined) return;
496 stop(bodyId) {
497 // Forgotten at once, so nothing more is forwarded to a process on its way out. Its
498 // directory's turn is held until it is gone: a request in that time waits in `start`.
499 const leaving = held.get(bodyId);
464500 held.delete(bodyId);
465501 startedAt.delete(bodyId);
466 await stopGently(child);
502 return inTurn(parent, childDirOf(parent, bodyId), async () => {
503 // None was held when the stop was asked: a start in flight has had its turn, and what it
504 // brought up is the one to stop.
505 const child = leaving ?? held.get(bodyId);
506 if (child === undefined) return;
507 held.delete(bodyId);
508 startedAt.delete(bodyId);
509 await stopGently(child);
510 });
467511 },
468512 get: (bodyId) => held.get(bodyId),
469513 failure: (bodyId) => failed.get(bodyId)?.why,
test/one-process-per-forge.test.ts added +133
@@ -0,0 +1,133 @@
1 /**
2 * One data directory has one forge process (#13814): a request that arrives while a forge is being
3 * stopped waits for the old process to be gone and then starts it once, never beside it.
4 */
5 import { afterAll, describe, expect, test } from "bun:test";
6 import { mkdtempSync, rmSync } from "node:fs";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp } from "../src/app.ts";
10 import { cellLimits, inTurn, makeRegistry, type CellChild } from "../src/spawn/cell.ts";
11 import { quietLogs } from "./helpers/globals.ts";
12
13 quietLogs();
14 const tmp = mkdtempSync(join(tmpdir(), "one-process-"));
15 afterAll(() => rmSync(tmp, { recursive: true, force: true }));
16
17 /**
18 * A stand-in for a forge that is slow to leave: it says "ready" once it listens, says "term" when
19 * told to go, and goes (exit 7) only when the test closes its stdin.
20 */
21 function slowLeaver() {
22 const proc = Bun.spawn(
23 [process.execPath, "-e", "process.on('SIGTERM', () => console.log('term')); process.stdin.on('end', () => process.exit(7)); process.stdin.resume(); console.log('ready');"],
24 { stdin: "pipe", stdout: "pipe", stderr: "ignore" },
25 );
26 const reader = proc.stdout.getReader();
27 let said = "";
28 const says = async (word: string): Promise<void> => {
29 while (!said.includes(word)) {
30 const { value, done } = await reader.read();
31 if (done) throw new Error(`the process ended before it said "${word}"`);
32 said += new TextDecoder().decode(value);
33 }
34 };
35 return { proc, says, leave: () => void proc.stdin.end() };
36 }
37
38 /** A registry whose children are slow leavers, counting how many were alive each time one was made. */
39 function watched(name: string) {
40 const parent = createApp({ dataDir: join(tmp, name), url: "https://f.test" });
41 const made: ReturnType<typeof slowLeaver>[] = [];
42 const alive = new Set<number>();
43 /** How many processes held the directory at the moment each new one was made. */
44 const beside: number[] = [];
45 const cells = makeRegistry(parent, async (input): Promise<CellChild> => {
46 beside.push(alive.size);
47 const one = slowLeaver();
48 made.push(one);
49 alive.add(one.proc.pid);
50 void one.proc.exited.then(() => alive.delete(one.proc.pid));
51 await one.says("ready");
52 return { ...input, port: 1, limits: cellLimits("small"), pid: one.proc.pid, exited: one.proc.exited };
53 });
54 const end = (): void => {
55 for (const one of made) one.proc.kill("SIGKILL");
56 parent.close();
57 };
58 return { parent, cells, made, alive, beside, end };
59 }
60
61 const KID = { bodyId: "cell-one", name: "kid", size: "small" } as const;
62
63 describe("one forge process for one data directory", () => {
64 test("requests during a stop wait for the old process to be gone, then join one start", async () => {
65 const w = watched("stop");
66 try {
67 const first = await w.cells.start(KID);
68 expect(first?.pid).toBe(w.made[0]!.proc.pid);
69 const stopping = w.cells.stop(KID.bodyId);
70 await w.made[0]!.says("term");
71 // Told to go and still there: the forge reads as asleep, and eight requests ask for it.
72 expect(w.cells.get(KID.bodyId)).toBeUndefined();
73 expect(w.alive.size).toBe(1);
74 const asks = Array.from({ length: 8 }, () => w.cells.start(KID));
75 let stopped = false;
76 void stopping.then(() => (stopped = true));
77 // Each of them takes a turn behind the stop; a full round of turns later nothing was made.
78 await inTurn(w.parent, join(tmp, "elsewhere"), async () => {});
79 expect(w.made.length).toBe(1);
80 expect(stopped).toBe(false);
81 w.made[0]!.leave();
82 await stopping;
83 expect(await w.made[0]!.proc.exited).toBe(7);
84 const woke = await Promise.all(asks);
85 // One start for all eight, made when nothing else held the directory.
86 expect(w.made.length).toBe(2);
87 expect(w.beside).toEqual([0, 0]);
88 expect(new Set(woke.map((c) => c?.pid))).toEqual(new Set([w.made[1]!.proc.pid]));
89 expect([...w.alive]).toEqual([w.made[1]!.proc.pid]);
90 expect(w.cells.get(KID.bodyId)?.pid).toBe(w.made[1]!.proc.pid);
91 } finally {
92 w.end();
93 }
94 });
95
96 test("a stop asked while the forge is starting waits for the start and stops what came up", async () => {
97 const w = watched("start");
98 try {
99 const starting = w.cells.start(KID);
100 const stopping = w.cells.stop(KID.bodyId);
101 const child = await starting;
102 expect(child?.pid).toBe(w.made[0]!.proc.pid);
103 await w.made[0]!.says("term");
104 w.made[0]!.leave();
105 await stopping;
106 expect(w.alive.size).toBe(0);
107 expect(w.cells.get(KID.bodyId)).toBeUndefined();
108 expect(w.made.length).toBe(1);
109 } finally {
110 w.end();
111 }
112 });
113
114 test("a stop of a forge that is asleep is done at once, and a failed turn does not hold the next", async () => {
115 const w = watched("asleep");
116 try {
117 await w.cells.stop(KID.bodyId);
118 expect(w.made.length).toBe(0);
119 const dir = join(tmp, "turns");
120 const order: string[] = [];
121 const bad = inTurn(w.parent, dir, async () => {
122 order.push("first");
123 throw new Error("no");
124 });
125 const good = inTurn(w.parent, dir, async () => order.push("second"));
126 expect(bad).rejects.toThrow("no");
127 await good;
128 expect(order).toEqual(["first", "second"]);
129 } finally {
130 w.end();
131 }
132 });
133 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs