@ultimat3/testing 31.29.0 → 31.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CLAUDE.md +1 -1
- package/README.md +2 -0
- package/package.json +22 -22
- package/src/drill-fleet.ts +42 -23
- package/src/e2e-spawn.ts +61 -49
- package/src/errors.ts +2 -0
- package/src/free-port-bind.ts +101 -0
- package/src/free-port.ts +7 -2
- package/src/index.ts +22 -0
- package/src/temp-tree-error.ts +15 -0
- package/src/temp-tree.ts +257 -0
package/CLAUDE.md
CHANGED
|
@@ -24,7 +24,7 @@ the off-barrel entry points `registry-isolation.ts`, `conformance.ts`. Full rule
|
|
|
24
24
|
| One way offline | the `network` fixture. `setNetworkState` is the gate's only writer and is not exported — setting it from a test body skips the fixture's disposal and leaves every later file offline |
|
|
25
25
|
| The seal key is a test process's, and nobody's export | `test-seal-key.ts`: installed by the preload only when `NODE_ENV === 'test'` and neither `ULTIMATE_SECRETS_KEY` nor `.secrets.key` exists. Full rule: `docs/history/testing.md` |
|
|
26
26
|
| `toEqualRow` never prints a server-only value | `matcher-row.ts` compares every OWN property (`toEqual` cannot see a `.sealed()` column — empty diff). Full rule: `docs/history/testing.md` |
|
|
27
|
-
| No retries | a flake is fixed or deleted the day it flakes; there is no `retry: 3` |
|
|
27
|
+
| No retries | a flake is fixed or deleted the day it flakes; there is no `retry: 3`. `bindFreePorts` asking again for a port another process took is a bind, not a test retry |
|
|
28
28
|
| A mutator's `local()` runs against `memoryLocalTx()` | `local-tx.ts`: keyed rows with the record store's rules (update invents nothing, `undefined` leaves a column, rows frozen). Never a hand-rolled table per test |
|
|
29
29
|
| A page test RENDERS, with no cast | `renderRoute(module, { url, actor })` / `renderView(Component, props)` (`render-view.ts`) † |
|
|
30
30
|
| `toBeUltimateError` reads THREE fields | an `X_` code plus a `cause` plus a `fix`, all through core's `stringField`. `typeof value.code === 'string'` alone passed a Node `ENOENT` |
|
package/README.md
CHANGED
|
@@ -79,6 +79,8 @@ unitTest('the clock moves only when the test moves it', ({ clock }) => {
|
|
|
79
79
|
| `local-tx.ts` | `memoryLocalTx()` — the client store a mutator's `local()` half writes into under test, with the record store's own rules |
|
|
80
80
|
| `render-view.ts` | `renderView()` / `renderRoute()` — what the server renders, for a unit test: one component, or a whole route module with its `load`, `meta` and islands |
|
|
81
81
|
| `retry.ts` | the one retry loop every waiting assertion is built from — a budget, a fixed interval, and an injectable sleep |
|
|
82
|
+
| `free-port-bind.ts` | `bindFreePorts(bind, { count?, pair?, apart?, clashed? })` — the ONE way a test takes a port it cannot bind as 0: `bind` binds (or spawns and awaits the child's listen or exit), and a port another process took first (`isPortClash`: `EADDRINUSE`, `X_PORT_IN_USE`, a child's printed refusal) is asked again on fresh ports, `PORT_BIND_ATTEMPTS` (5) at most, the last clash rethrown. A probe — bind 0, release, hand the number on — is `X_TEST_PORT_PROBED` (`scripts/port-probe.ts`) |
|
|
83
|
+
| `temp-tree.ts` | `tempTree(prefix, { inPackage? })` — a temp directory with one owner: `tree.git([...])` runs git under `tree.gitEnv` (`TEMP_TREE_GIT_ENV`: no auto gc or maintenance, an identity, discovery stopped at the tree's parent; overlay it on any child that may run git), `tree.track(child)` hands a child over, and `await tree.dispose()` (or `await using`) ends and awaits every child before it removes the tree and proves it gone (`X_TEST_TEMP_TREE_LEFT`). `inPackage: <package dir>` makes it under that package's git-ignored `.x/fixtures/` (`IN_PACKAGE_TEMP_ROOT`), for a child that must resolve `@ultimat3/*`; `tempTrees(options)` is many trees, one `dispose()`. A bare `mkdtemp` beside git or inside the checkout is `X_TEST_TEMP_TREE_UNOWNED` (`scripts/temp-tree.ts`) |
|
|
82
84
|
| `fixtures.ts` | the registry + `test('…', ({ clock }) => …)` injection |
|
|
83
85
|
| `fixture-{clock,mail,jobs,network,statements}.ts` | the five fixtures the framework builds in-process |
|
|
84
86
|
| `fixture-drivers.ts` | the five it declares but a driver must build — `page` `budget` `signIn` `deploy` `subscribe` |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/testing",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.30.0",
|
|
4
4
|
"description": "Test harness: cloned template DBs per worker, frozen clock, sealed network, 6 test types",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -47,27 +47,27 @@
|
|
|
47
47
|
"test": "bun test"
|
|
48
48
|
},
|
|
49
49
|
"dependencies": {
|
|
50
|
-
"@ultimat3/action": "31.
|
|
51
|
-
"@ultimat3/ai": "31.
|
|
52
|
-
"@ultimat3/auth": "31.
|
|
53
|
-
"@ultimat3/cache": "31.
|
|
54
|
-
"@ultimat3/core": "31.
|
|
55
|
-
"@ultimat3/db": "31.
|
|
56
|
-
"@ultimat3/entity": "31.
|
|
57
|
-
"@ultimat3/http": "31.
|
|
58
|
-
"@ultimat3/i18n": "31.
|
|
59
|
-
"@ultimat3/jobs": "31.
|
|
60
|
-
"@ultimat3/mail": "31.
|
|
61
|
-
"@ultimat3/notify": "31.
|
|
62
|
-
"@ultimat3/policy": "31.
|
|
63
|
-
"@ultimat3/pwa": "31.
|
|
64
|
-
"@ultimat3/query": "31.
|
|
65
|
-
"@ultimat3/realtime": "31.
|
|
66
|
-
"@ultimat3/render": "31.
|
|
67
|
-
"@ultimat3/schema": "31.
|
|
68
|
-
"@ultimat3/scraping": "31.
|
|
69
|
-
"@ultimat3/seo": "31.
|
|
70
|
-
"@ultimat3/time": "31.
|
|
50
|
+
"@ultimat3/action": "31.30.0",
|
|
51
|
+
"@ultimat3/ai": "31.30.0",
|
|
52
|
+
"@ultimat3/auth": "31.30.0",
|
|
53
|
+
"@ultimat3/cache": "31.30.0",
|
|
54
|
+
"@ultimat3/core": "31.30.0",
|
|
55
|
+
"@ultimat3/db": "31.30.0",
|
|
56
|
+
"@ultimat3/entity": "31.30.0",
|
|
57
|
+
"@ultimat3/http": "31.30.0",
|
|
58
|
+
"@ultimat3/i18n": "31.30.0",
|
|
59
|
+
"@ultimat3/jobs": "31.30.0",
|
|
60
|
+
"@ultimat3/mail": "31.30.0",
|
|
61
|
+
"@ultimat3/notify": "31.30.0",
|
|
62
|
+
"@ultimat3/policy": "31.30.0",
|
|
63
|
+
"@ultimat3/pwa": "31.30.0",
|
|
64
|
+
"@ultimat3/query": "31.30.0",
|
|
65
|
+
"@ultimat3/realtime": "31.30.0",
|
|
66
|
+
"@ultimat3/render": "31.30.0",
|
|
67
|
+
"@ultimat3/schema": "31.30.0",
|
|
68
|
+
"@ultimat3/scraping": "31.30.0",
|
|
69
|
+
"@ultimat3/seo": "31.30.0",
|
|
70
|
+
"@ultimat3/time": "31.30.0"
|
|
71
71
|
},
|
|
72
72
|
"peerDependencies": {
|
|
73
73
|
"solid-js": "^1.9.18"
|
package/src/drill-fleet.ts
CHANGED
|
@@ -15,7 +15,7 @@ import type { DrillRole, DrillService } from './drills';
|
|
|
15
15
|
import { E2eAppFailedError } from './e2e-errors';
|
|
16
16
|
import type { FaultProxy } from './fault-proxy';
|
|
17
17
|
import { faultProxy, faultTarget, throughFaultProxy } from './fault-proxy';
|
|
18
|
-
import {
|
|
18
|
+
import { bindFreePorts, isPortClash } from './free-port-bind';
|
|
19
19
|
import { dropSql, urlFor } from './template-db';
|
|
20
20
|
import { testSealKeyEnv } from './test-seal-key';
|
|
21
21
|
|
|
@@ -200,31 +200,52 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
|
|
|
200
200
|
}
|
|
201
201
|
|
|
202
202
|
const taken: number[] = [...[...proxies.values()].map((proxy) => proxy.port)];
|
|
203
|
-
const take = (): number => {
|
|
204
|
-
const port = freePortApartFrom(taken);
|
|
205
|
-
taken.push(port);
|
|
206
|
-
return port;
|
|
207
|
-
};
|
|
208
203
|
let webBase = '';
|
|
209
204
|
// Each role's CURRENT process, read through: what the rollout reports on.
|
|
210
205
|
const outputs = new Map<DrillRole, { exitCode(): number | null; watched(): number }>();
|
|
211
206
|
for (const role of options.roles) {
|
|
212
|
-
|
|
213
|
-
//
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
207
|
+
// Whether the last refusal was the role meeting a port another process took after it was
|
|
208
|
+
// handed out — read off the full tail, which the refusal's cause holds a bounded copy of.
|
|
209
|
+
let clashed = false;
|
|
210
|
+
const started = await bindFreePorts(
|
|
211
|
+
async ([port = 0, metricsPort = 0]) => {
|
|
212
|
+
clashed = false;
|
|
213
|
+
const origin = `http://127.0.0.1:${String(port)}`;
|
|
214
|
+
const env = {
|
|
215
|
+
ROLE: role,
|
|
216
|
+
PORT: String(port),
|
|
217
|
+
METRICS_PORT: String(metricsPort),
|
|
218
|
+
APP_URL: origin,
|
|
219
|
+
};
|
|
220
|
+
const readyz =
|
|
221
|
+
role === 'web' ? `${origin}/readyz` : `http://127.0.0.1:${String(metricsPort)}/readyz`;
|
|
222
|
+
const child = spawnRole(env);
|
|
223
|
+
const output = tailOf([child.stdout, child.stderr], before?.watch);
|
|
224
|
+
// Before migrate, a role is not ready by design: what it does instead is the drill's
|
|
225
|
+
// evidence, so its bind is proven by that evidence rather than here.
|
|
226
|
+
if (before === undefined) {
|
|
227
|
+
const ready = await waitReady(
|
|
228
|
+
readyz,
|
|
229
|
+
options.readyTimeoutMs,
|
|
230
|
+
() => child.exitCode === null,
|
|
231
|
+
);
|
|
232
|
+
if (!ready) {
|
|
233
|
+
clashed = isPortClash(output.log());
|
|
234
|
+
children.delete(child);
|
|
235
|
+
child.kill('SIGKILL');
|
|
236
|
+
await child.exited;
|
|
237
|
+
throw refuse(`ROLE=${role} never answered ${readyz}`, output.log());
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
// The sync node listens on PORT + 1 (`syncPortFor`): held too, so no other role is handed it.
|
|
241
|
+
taken.push(port, metricsPort, ...(role === 'sync' ? [port + 1] : []));
|
|
242
|
+
return { origin, env, readyz, child, output };
|
|
243
|
+
},
|
|
244
|
+
{ count: 2, pair: role === 'sync', apart: taken, clashed: () => clashed },
|
|
245
|
+
);
|
|
246
|
+
const { origin, env, readyz } = started;
|
|
247
|
+
let { child, output } = started;
|
|
217
248
|
if (role === 'web') webBase = origin;
|
|
218
|
-
const env = {
|
|
219
|
-
ROLE: role,
|
|
220
|
-
PORT: String(port),
|
|
221
|
-
METRICS_PORT: String(metricsPort),
|
|
222
|
-
APP_URL: origin,
|
|
223
|
-
};
|
|
224
|
-
const readyz =
|
|
225
|
-
role === 'web' ? `${origin}/readyz` : `http://127.0.0.1:${String(metricsPort)}/readyz`;
|
|
226
|
-
let child = spawnRole(env);
|
|
227
|
-
let output = tailOf([child.stdout, child.stderr], before?.watch);
|
|
228
249
|
const boot = async (): Promise<void> => {
|
|
229
250
|
const ready = await waitReady(
|
|
230
251
|
readyz,
|
|
@@ -233,8 +254,6 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
|
|
|
233
254
|
);
|
|
234
255
|
if (!ready) throw refuse(`ROLE=${role} never answered ${readyz}`, output.log());
|
|
235
256
|
};
|
|
236
|
-
// Before migrate, a role is not ready by design: what it does instead is the drill's evidence.
|
|
237
|
-
if (before === undefined) await boot();
|
|
238
257
|
outputs.set(role, { exitCode: () => child.exitCode, watched: () => output.watched() });
|
|
239
258
|
roles.set(role, {
|
|
240
259
|
role,
|
package/src/e2e-spawn.ts
CHANGED
|
@@ -10,7 +10,7 @@ import { get } from 'node:http';
|
|
|
10
10
|
import { dirname, join } from 'node:path';
|
|
11
11
|
import { assert, DRAIN_DEADLINE_DEFAULT_MS, READINESS_GRACE_DEFAULT_MS } from '@ultimat3/core';
|
|
12
12
|
import { E2eAppFailedError } from './e2e-errors';
|
|
13
|
-
import {
|
|
13
|
+
import { bindFreePorts, isPortClash } from './free-port-bind';
|
|
14
14
|
|
|
15
15
|
/** `x dev` (sync included), or the production entry `apps/web/server.ts` under `ROLE=web`. */
|
|
16
16
|
export type E2eAppMode = 'dev' | 'serve';
|
|
@@ -113,64 +113,75 @@ export const refuse = (step: string, output: string): E2eAppFailedError =>
|
|
|
113
113
|
/** Spawn the app and answer once `/readyz` does; refuses with the app's own output tail. */
|
|
114
114
|
export async function spawnE2eApp(options: SpawnE2eAppOptions): Promise<SpawnedE2eApp> {
|
|
115
115
|
const deadline = options.readyTimeoutMs;
|
|
116
|
+
const termGraceMs = options.termGraceMs ?? TERM_GRACE_MS;
|
|
117
|
+
const bin = options.mode === 'serve' ? undefined : (options.bin ?? (await xBin(options.root)));
|
|
118
|
+
// Whether the last refusal was the app meeting a port another process took after it was handed
|
|
119
|
+
// out: read off the FULL tail, since the refusal's own cause carries a bounded copy of it.
|
|
120
|
+
let clashed = false;
|
|
116
121
|
// A PAIR: `x dev` binds its sync node on `port + 1`, and a held neighbour exited the app at boot.
|
|
117
|
-
const port = freePortPair();
|
|
118
122
|
// Its own scrape port too: every role opens one, the default is a fixed 9090, and a second app —
|
|
119
123
|
// or a developer's `x dev` — already holding it is an app that dies at boot with X_PORT_IN_USE.
|
|
120
|
-
//
|
|
121
|
-
//
|
|
122
|
-
const
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
124
|
+
// Both are bound by the app, never probed here and trusted: a port taken between the ask and
|
|
125
|
+
// the bind is an app that exits at boot, and `bindFreePorts` boots it again on fresh ports.
|
|
126
|
+
const booted = await bindFreePorts(
|
|
127
|
+
async ([port = 0, metricsPort = 0]) => {
|
|
128
|
+
clashed = false;
|
|
129
|
+
const base = `http://localhost:${String(port)}`;
|
|
130
|
+
const command =
|
|
131
|
+
bin === undefined
|
|
132
|
+
? ['bun', 'apps/web/server.ts']
|
|
133
|
+
: ['bun', bin, 'dev', '--port', String(port)];
|
|
134
|
+
const spawnApp = (extra: Readonly<Record<string, string>>) =>
|
|
135
|
+
Bun.spawn(command, {
|
|
136
|
+
cwd: options.root,
|
|
137
|
+
env: {
|
|
138
|
+
...inherited(),
|
|
139
|
+
...options.env,
|
|
140
|
+
METRICS_PORT: String(metricsPort),
|
|
141
|
+
// The origin the app is actually reachable at. A page that renders a typed client builds
|
|
142
|
+
// its absolute URLs from it, and without it `/feed` answered 500 with X_ENV_MISSING APP_URL.
|
|
143
|
+
APP_URL: base,
|
|
144
|
+
...(options.mode === 'serve' ? { ROLE: 'web', PORT: String(port) } : {}),
|
|
145
|
+
...extra,
|
|
146
|
+
},
|
|
147
|
+
stdout: 'pipe',
|
|
148
|
+
stderr: 'pipe',
|
|
149
|
+
});
|
|
150
|
+
// On the monotonic clock: counted in polls, every probe an app wedged mid-boot held for its
|
|
151
|
+
// whole `READY_PROBE_MS` stretched a 90 s deadline to 450 s, past any hook derived from it.
|
|
152
|
+
const ready = async (
|
|
153
|
+
child: ReturnType<typeof spawnApp>,
|
|
154
|
+
tail: () => string,
|
|
155
|
+
): Promise<void> => {
|
|
156
|
+
const until = performance.now() + deadline;
|
|
157
|
+
while (performance.now() < until) {
|
|
158
|
+
if (child.exitCode !== null) break;
|
|
159
|
+
if (await answersOk(`${base}/readyz`)) return;
|
|
160
|
+
await Bun.sleep(POLL_MS);
|
|
161
|
+
}
|
|
162
|
+
await end(child, termGraceMs);
|
|
163
|
+
const output = tail();
|
|
164
|
+
clashed = isPortClash(output);
|
|
165
|
+
throw refuse(`${command.join(' ')} never answered ${base}/readyz`, output);
|
|
166
|
+
};
|
|
167
|
+
const child = spawnApp({});
|
|
168
|
+
// Drained from the start and kept bounded: an app's log is unbounded, and a pipe nobody reads
|
|
169
|
+
// fills its buffer and blocks the child on its next write — an app that "never got ready".
|
|
170
|
+
const tail = drainTail(child.stdout, child.stderr);
|
|
171
|
+
await ready(child, tail);
|
|
172
|
+
return { base, spawnApp, ready, child, tail };
|
|
173
|
+
},
|
|
174
|
+
{ count: 2, pair: true, clashed: () => clashed },
|
|
175
|
+
);
|
|
157
176
|
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
// fills its buffer and blocks the child on its next write — an app that "never got ready".
|
|
161
|
-
let tail = drainTail(child.stdout, child.stderr);
|
|
177
|
+
const { base, spawnApp, ready } = booted;
|
|
178
|
+
let { child, tail } = booted;
|
|
162
179
|
let stopped = false;
|
|
163
180
|
const stop = async (): Promise<void> => {
|
|
164
181
|
if (stopped) return;
|
|
165
182
|
stopped = true;
|
|
166
183
|
await end(child, termGraceMs);
|
|
167
184
|
};
|
|
168
|
-
try {
|
|
169
|
-
await ready(child, tail);
|
|
170
|
-
} catch (error) {
|
|
171
|
-
await stop();
|
|
172
|
-
throw error;
|
|
173
|
-
}
|
|
174
185
|
return {
|
|
175
186
|
base,
|
|
176
187
|
log: () => tail(),
|
|
@@ -185,6 +196,7 @@ export async function spawnE2eApp(options: SpawnE2eAppOptions): Promise<SpawnedE
|
|
|
185
196
|
);
|
|
186
197
|
// The same port and the same state directory — a deploy, not a second app: a tab already
|
|
187
198
|
// open on `base` sees the new build on its next request, and the data it wrote is still there.
|
|
199
|
+
// A deploy cannot move: the port is the one this app held a moment ago, never a fresh ask.
|
|
188
200
|
await end(child, termGraceMs);
|
|
189
201
|
child = spawnApp(next);
|
|
190
202
|
tail = drainTail(child.stdout, child.stderr);
|
package/src/errors.ts
CHANGED
|
@@ -81,6 +81,7 @@ export const TESTING_ERROR_CODES = [
|
|
|
81
81
|
'X_EXERCISE_EMPTY_REACH',
|
|
82
82
|
'X_TEST_PROPERTY_FAILED',
|
|
83
83
|
'X_TEST_SOAK_HEAP_GROWTH',
|
|
84
|
+
'X_TEST_TEMP_TREE_LEFT',
|
|
84
85
|
] as const;
|
|
85
86
|
|
|
86
87
|
export type TestingErrorCode = (typeof TESTING_ERROR_CODES)[number];
|
|
@@ -165,6 +166,7 @@ export const TESTING_ERROR_TITLES: Readonly<Record<TestingErrorCode, string>> =
|
|
|
165
166
|
'an exercised primitive was reached and sent no statement and had no effect',
|
|
166
167
|
X_TEST_PROPERTY_FAILED: 'a property() run found an input its claim refuses',
|
|
167
168
|
X_TEST_SOAK_HEAP_GROWTH: 'a soak() run grew the live heap past its stated bound',
|
|
169
|
+
X_TEST_TEMP_TREE_LEFT: 'a temp tree survived its own remove',
|
|
168
170
|
};
|
|
169
171
|
|
|
170
172
|
// Titles must be registered for `format()` to render the contract's first line. Every code above is
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
// One responsibility: hand a binder free ports, and when another process took one between the ask
|
|
2
|
+
// and the bind, ask again. A port asked of the OS and released is a promise nothing keeps: the
|
|
3
|
+
// probe-then-bind race lost on CI more than once (`092c7cd38`, `3ea39eebb`). The bind is the proof.
|
|
4
|
+
|
|
5
|
+
import { finiteCount } from '@ultimat3/core';
|
|
6
|
+
import type { PortProbe } from './free-port';
|
|
7
|
+
import { freePortApartFrom, freePortPair } from './free-port';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* How many binds one call makes before the last clash is the caller's answer. A clash is another
|
|
11
|
+
* process winning a race it rarely wins: a second loss is already rare, a fifth is a box whose
|
|
12
|
+
* ephemeral range is exhausted, and asking again would only hide that.
|
|
13
|
+
*/
|
|
14
|
+
export const PORT_BIND_ATTEMPTS = 5;
|
|
15
|
+
|
|
16
|
+
/** What a lost race says: Bun's listener (`EADDRINUSE`) and the CLI's own refusal (`X_PORT_IN_USE`). */
|
|
17
|
+
const CLASH_CODES: ReadonlySet<string> = new Set(['EADDRINUSE', 'X_PORT_IN_USE']);
|
|
18
|
+
const CLASH_TEXT = /\b(?:EADDRINUSE|X_PORT_IN_USE)\b|Is port \d+ in use\?/;
|
|
19
|
+
|
|
20
|
+
const field = (value: object, key: string): unknown => Reflect.get(value, key);
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Whether `failure` says a port was already taken: an error carrying the code, or text — a child's
|
|
24
|
+
* output, an error's message or cause — naming it. A child process has no error object to hand
|
|
25
|
+
* over, only what it printed, so text is read the same way.
|
|
26
|
+
*/
|
|
27
|
+
export const isPortClash = (failure: unknown): boolean => {
|
|
28
|
+
if (typeof failure === 'string') return CLASH_TEXT.test(failure);
|
|
29
|
+
if (typeof failure !== 'object' || failure === null) return false;
|
|
30
|
+
const code = field(failure, 'code');
|
|
31
|
+
if (typeof code === 'string' && CLASH_CODES.has(code)) return true;
|
|
32
|
+
return ['message', 'cause'].some((key) => {
|
|
33
|
+
const text = field(failure, key);
|
|
34
|
+
return typeof text === 'string' && CLASH_TEXT.test(text);
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
export interface BindFreePortsOptions {
|
|
39
|
+
/** How many distinct ports `bind` is handed. Default 1. */
|
|
40
|
+
readonly count?: number;
|
|
41
|
+
/** The first port's neighbour is free too — `x dev` binds its sync node on `port + 1`. */
|
|
42
|
+
readonly pair?: boolean;
|
|
43
|
+
/** Whether a failure `bind` threw is a lost race. Default `isPortClash`. */
|
|
44
|
+
readonly clashed?: (failure: unknown) => boolean;
|
|
45
|
+
/** Ports the caller already holds or handed out (a sync node's `port + 1` too): none is handed again. */
|
|
46
|
+
readonly apart?: readonly number[];
|
|
47
|
+
/** Default `PORT_BIND_ATTEMPTS`. */
|
|
48
|
+
readonly attempts?: number;
|
|
49
|
+
/** The OS's listener, for a test of the walk itself. */
|
|
50
|
+
readonly listen?: () => PortProbe;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** One attempt's ports: never one an earlier attempt was handed, nor a pair's neighbour. */
|
|
54
|
+
const portsFor = (
|
|
55
|
+
count: number,
|
|
56
|
+
pair: boolean,
|
|
57
|
+
tried: number[],
|
|
58
|
+
listen: (() => PortProbe) | undefined,
|
|
59
|
+
): number[] => {
|
|
60
|
+
const ports: number[] = [];
|
|
61
|
+
for (let index = 0; index < count; index += 1) {
|
|
62
|
+
const port =
|
|
63
|
+
index === 0 && pair
|
|
64
|
+
? freePortPair(listen, undefined, tried)
|
|
65
|
+
: freePortApartFrom(tried, listen);
|
|
66
|
+
ports.push(port);
|
|
67
|
+
tried.push(port);
|
|
68
|
+
if (index === 0 && pair) tried.push(port + 1);
|
|
69
|
+
}
|
|
70
|
+
return ports;
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Run `bind` on free ports until it binds them. `bind` must BIND — listen in this process, or spawn
|
|
75
|
+
* the child and wait until it listens or exits — and throw what it met: a failure `clashed` reads
|
|
76
|
+
* as a lost race is answered with fresh ports, apart from every port already tried; anything else,
|
|
77
|
+
* and the last clash, is rethrown as it was. The ONE way a test takes a port it cannot bind as 0.
|
|
78
|
+
*/
|
|
79
|
+
export async function bindFreePorts<T>(
|
|
80
|
+
bind: (ports: readonly number[]) => T | Promise<T>,
|
|
81
|
+
options: BindFreePortsOptions = {},
|
|
82
|
+
): Promise<T> {
|
|
83
|
+
// A `NaN` attempts is a bind never retried, a `NaN` count is no port at all: both are refused.
|
|
84
|
+
const attempts = finiteCount(
|
|
85
|
+
'bindFreePorts',
|
|
86
|
+
'attempts',
|
|
87
|
+
options.attempts ?? PORT_BIND_ATTEMPTS,
|
|
88
|
+
1,
|
|
89
|
+
);
|
|
90
|
+
const count = finiteCount('bindFreePorts', 'count', options.count ?? 1, 1);
|
|
91
|
+
const clashed = options.clashed ?? isPortClash;
|
|
92
|
+
const tried: number[] = [...(options.apart ?? [])];
|
|
93
|
+
for (let attempt = 1; ; attempt += 1) {
|
|
94
|
+
const ports = portsFor(count, options.pair ?? false, tried, options.listen);
|
|
95
|
+
try {
|
|
96
|
+
return await bind(ports);
|
|
97
|
+
} catch (failure) {
|
|
98
|
+
if (attempt >= attempts || !clashed(failure)) throw failure;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
package/src/free-port.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// One responsibility: a port the e2e app can listen on AND a browser will open. The OS hands out
|
|
2
2
|
// whatever is free in its ephemeral range, and a box whose range starts at 1024 hands out ports
|
|
3
|
-
// Chrome refuses outright — every navigation of the run then fails `net::ERR_UNSAFE_PORT`.
|
|
3
|
+
// Chrome refuses outright — every navigation of the run then fails `net::ERR_UNSAFE_PORT`. A port
|
|
4
|
+
// asked here is released before its caller binds it: callers go through `bindFreePorts`.
|
|
4
5
|
|
|
5
6
|
/** What `freePort` needs of a listener: the port the OS gave it, and a way to give it back. */
|
|
6
7
|
export interface PortProbe {
|
|
@@ -90,11 +91,13 @@ export const loopbackFree = (
|
|
|
90
91
|
* was an e2e app that listened, failed its sync bind and exited before `/readyz` — the CLI's own
|
|
91
92
|
* `freeDevPort` rule (`dev-supervisor.ts`), which this package cannot import. A candidate is held
|
|
92
93
|
* while the next is asked for, as a refused port is, so the walk ends. The candidate itself is held
|
|
93
|
-
* on Bun's dual-stack `::`, which covers both loopbacks; the neighbour is asked of each.
|
|
94
|
+
* on Bun's dual-stack `::`, which covers both loopbacks; the neighbour is asked of each. Neither
|
|
95
|
+
* is one of `taken` — the ports an earlier, clashed attempt was handed (`bindFreePorts`).
|
|
94
96
|
*/
|
|
95
97
|
export const freePortPair = (
|
|
96
98
|
listen: () => PortProbe = listenOnAnyPort,
|
|
97
99
|
canBind: (port: number) => boolean = loopbackFree,
|
|
100
|
+
taken: readonly number[] = [],
|
|
98
101
|
): number => {
|
|
99
102
|
const held: PortProbe[] = [];
|
|
100
103
|
try {
|
|
@@ -104,6 +107,8 @@ export const freePortPair = (
|
|
|
104
107
|
if (
|
|
105
108
|
BROWSER_REFUSED_PORTS.has(probe.port) ||
|
|
106
109
|
BROWSER_REFUSED_PORTS.has(next) ||
|
|
110
|
+
taken.includes(probe.port) ||
|
|
111
|
+
taken.includes(next) ||
|
|
107
112
|
!canBind(next)
|
|
108
113
|
) {
|
|
109
114
|
held.push(probe);
|
package/src/index.ts
CHANGED
|
@@ -278,6 +278,10 @@ export {
|
|
|
278
278
|
FRAMEWORK_FIXTURE_NAMES,
|
|
279
279
|
registerFrameworkFixtures,
|
|
280
280
|
} from './framework-fixtures';
|
|
281
|
+
// A port a test cannot bind as 0 is bound through this, never probed and released: a port taken
|
|
282
|
+
// between the ask and the bind is asked again (`scripts/port-probe.ts` refuses the probe).
|
|
283
|
+
export type { BindFreePortsOptions } from './free-port-bind';
|
|
284
|
+
export { bindFreePorts, isPortClash, PORT_BIND_ATTEMPTS } from './free-port-bind';
|
|
281
285
|
export type { AppHandle, AppOptions, BootedApp } from './harness';
|
|
282
286
|
export { describeApp, testApp } from './harness';
|
|
283
287
|
// Type-only: the micro-DOM is the fixture's to build, and a test only ever names what it handed back.
|
|
@@ -443,6 +447,24 @@ export type { SubjectProofOptions, SubjectProofResult } from './subject-proof';
|
|
|
443
447
|
export { subjectProof } from './subject-proof';
|
|
444
448
|
export type { SwappableAdapters, SwappablePort } from './swap-adapter';
|
|
445
449
|
export { swapAdapter, UNSWAPPED } from './swap-adapter';
|
|
450
|
+
// A temp tree with one owner: its git runs no background work, and `dispose()` awaits every child
|
|
451
|
+
// before it removes anything (`scripts/temp-tree.ts` refuses a bare `mkdtemp` beside git).
|
|
452
|
+
export type {
|
|
453
|
+
TempTree,
|
|
454
|
+
TempTreeGitResult,
|
|
455
|
+
TempTreeOptions,
|
|
456
|
+
TempTreeSpawnOptions,
|
|
457
|
+
TempTrees,
|
|
458
|
+
TrackedChild,
|
|
459
|
+
} from './temp-tree';
|
|
460
|
+
export {
|
|
461
|
+
IN_PACKAGE_TEMP_ROOT,
|
|
462
|
+
TEMP_TREE_GIT_ENV,
|
|
463
|
+
TEMP_TREE_GIT_TIMEOUT_MS,
|
|
464
|
+
tempTree,
|
|
465
|
+
tempTrees,
|
|
466
|
+
} from './temp-tree';
|
|
467
|
+
export { TempTreeLeftError } from './temp-tree-error';
|
|
446
468
|
export type {
|
|
447
469
|
DisposableWorkerDatabase,
|
|
448
470
|
SqlRunner,
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Single responsibility: `X_TEST_TEMP_TREE_LEFT`'s message — a temp tree `dispose()` removed and
|
|
2
|
+
// found still on disk. The shape that leaves one is a process the tree never awaited, still writing
|
|
3
|
+
// under it while the remove walked it (`e407c015a`); the fix is to hand that process to the tree.
|
|
4
|
+
|
|
5
|
+
import { renderCauseValue, UltimateError } from '@ultimat3/core';
|
|
6
|
+
|
|
7
|
+
export class TempTreeLeftError extends UltimateError {
|
|
8
|
+
constructor(input: { readonly path: string; readonly left: readonly string[] }) {
|
|
9
|
+
super({
|
|
10
|
+
code: 'X_TEST_TEMP_TREE_LEFT',
|
|
11
|
+
cause: `${renderCauseValue(input.path)} was removed and still holds ${renderCauseValue(input.left)}: a process the tree never awaited wrote under it while the remove walked it`,
|
|
12
|
+
fix: "tree.track(Bun.spawn(['…'], { cwd: tree.path, env: { ...Bun.env, ...tree.gitEnv } })) # every child that writes under the tree, or tree.git([...]) for git: dispose() awaits them before it removes anything",
|
|
13
|
+
});
|
|
14
|
+
}
|
|
15
|
+
}
|
package/src/temp-tree.ts
ADDED
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// One responsibility: a temp directory with ONE owner, who makes it, runs its children, and removes
|
|
2
|
+
// it only once they have exited. A `rmSync` racing a child still writing under the tree — git's
|
|
3
|
+
// detached `maintenance run --auto` unlinking a lock after `git commit` returned — stopped silently
|
|
4
|
+
// and left `HEAD`, `refs/` and `config` behind on CI (run 43546649352; red `main`, `e407c015a`).
|
|
5
|
+
|
|
6
|
+
// why: Bun has no mkdtemp, no recursive remove and no existence check for a directory.
|
|
7
|
+
import { existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync } from 'node:fs';
|
|
8
|
+
// why: Bun exposes no tmpdir(), so only node:os answers the platform temp root.
|
|
9
|
+
import { tmpdir } from 'node:os';
|
|
10
|
+
// why: Bun exposes no path-join primitive.
|
|
11
|
+
import { join, resolve } from 'node:path';
|
|
12
|
+
import { finiteCount } from '@ultimat3/core';
|
|
13
|
+
import { killTree } from '@ultimat3/scraping/cdp';
|
|
14
|
+
import { TempTreeLeftError } from './temp-tree-error';
|
|
15
|
+
|
|
16
|
+
/** A read or a commit in a temp repository does no work worth 30 s: past it, git has hung. */
|
|
17
|
+
export const TEMP_TREE_GIT_TIMEOUT_MS = 30_000;
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* The configuration every git in a tree runs under, as `GIT_CONFIG_*` so it reaches a git the code
|
|
21
|
+
* under test spawns too: none of the background work that outlives a command (auto gc, auto
|
|
22
|
+
* maintenance, fsmonitor), an identity so a commit cannot fail on a bare CI box, no signing.
|
|
23
|
+
*/
|
|
24
|
+
const GIT_CONFIG: readonly (readonly [string, string])[] = [
|
|
25
|
+
['maintenance.auto', 'false'],
|
|
26
|
+
['gc.auto', '0'],
|
|
27
|
+
['core.fsmonitor', 'false'],
|
|
28
|
+
['user.name', 'test'],
|
|
29
|
+
['user.email', 'test@example.com'],
|
|
30
|
+
['commit.gpgsign', 'false'],
|
|
31
|
+
];
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* git steered at the tree and nothing else: an inherited `GIT_DIR`/`GIT_WORK_TREE`/`GIT_INDEX_FILE`
|
|
35
|
+
* (a hook exports them) unset, discovery stopped at the temp root, no prompt and no optional locks.
|
|
36
|
+
*/
|
|
37
|
+
export const TEMP_TREE_GIT_ENV: Readonly<Record<string, string | undefined>> = {
|
|
38
|
+
GIT_DIR: undefined,
|
|
39
|
+
GIT_WORK_TREE: undefined,
|
|
40
|
+
GIT_INDEX_FILE: undefined,
|
|
41
|
+
GIT_CEILING_DIRECTORIES: tmpdir(),
|
|
42
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
43
|
+
GIT_OPTIONAL_LOCKS: '0',
|
|
44
|
+
GIT_CONFIG_COUNT: String(GIT_CONFIG.length),
|
|
45
|
+
...Object.fromEntries(
|
|
46
|
+
GIT_CONFIG.flatMap(([key, value], index) => [
|
|
47
|
+
[`GIT_CONFIG_KEY_${String(index)}`, key],
|
|
48
|
+
[`GIT_CONFIG_VALUE_${String(index)}`, value],
|
|
49
|
+
]),
|
|
50
|
+
),
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
/** What `tree.track` needs of a child: its exit, and a way to end one still running. */
|
|
54
|
+
export interface TrackedChild {
|
|
55
|
+
readonly exited: Promise<number>;
|
|
56
|
+
readonly exitCode: number | null;
|
|
57
|
+
kill(signal?: number | NodeJS.Signals): void;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export interface TempTreeGitResult {
|
|
61
|
+
readonly code: number;
|
|
62
|
+
readonly stdout: string;
|
|
63
|
+
readonly stderr: string;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface TempTree extends AsyncDisposable {
|
|
67
|
+
/**
|
|
68
|
+
* The directory, made empty under the platform temp root — or under `<pkg>/.x/fixtures/` when
|
|
69
|
+
* `inPackage` names the package.
|
|
70
|
+
*/
|
|
71
|
+
readonly path: string;
|
|
72
|
+
/** Overlay it on `Bun.env` for any child that may run git here — the code under test's too. */
|
|
73
|
+
readonly gitEnv: Readonly<Record<string, string | undefined>>;
|
|
74
|
+
/** git in `cwd` (default `path`), under `gitEnv`, tracked and awaited; the exit is the caller's to read. */
|
|
75
|
+
git(args: readonly string[], options?: { readonly cwd?: string }): Promise<TempTreeGitResult>;
|
|
76
|
+
/**
|
|
77
|
+
* Spawn a child as its own process group (POSIX) and hand it to the tree: `dispose()` ends it
|
|
78
|
+
* with everything it started — a `sh -c` line's grandchild included — and awaits its exit.
|
|
79
|
+
*/
|
|
80
|
+
spawn(
|
|
81
|
+
argv: readonly string[],
|
|
82
|
+
options?: TempTreeSpawnOptions,
|
|
83
|
+
): Bun.Subprocess<'ignore', 'pipe', 'pipe'>;
|
|
84
|
+
/**
|
|
85
|
+
* Hand a child spawned elsewhere to the tree: `dispose()` ends it if it still runs, and awaits
|
|
86
|
+
* its exit. Only the child itself: what it started is out of reach — prefer `spawn`.
|
|
87
|
+
*/
|
|
88
|
+
track<T extends TrackedChild>(child: T): T;
|
|
89
|
+
/** Await every child, remove the tree, and prove it is gone (`X_TEST_TEMP_TREE_LEFT`). Idempotent. */
|
|
90
|
+
dispose(): Promise<void>;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** `Bun.env` with `overlay` on top, an `undefined` value deleting the key. */
|
|
94
|
+
const overlaid = (
|
|
95
|
+
overlay: Readonly<Record<string, string | undefined>>,
|
|
96
|
+
): Record<string, string> => {
|
|
97
|
+
const env = new Map(Object.entries(Bun.env));
|
|
98
|
+
for (const [key, value] of Object.entries(overlay)) {
|
|
99
|
+
if (value === undefined) env.delete(key);
|
|
100
|
+
else env.set(key, value);
|
|
101
|
+
}
|
|
102
|
+
return Object.fromEntries(
|
|
103
|
+
[...env].filter((entry): entry is [string, string] => entry[1] !== undefined),
|
|
104
|
+
);
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Where a tree made `inPackage` lives: `<package>/.x/fixtures/`, which the repository's `.x/`
|
|
109
|
+
* ignore rule already covers. A tree there was swept into a commit as `.<name>-fixture-XXXXXX/`.
|
|
110
|
+
*/
|
|
111
|
+
export const IN_PACKAGE_TEMP_ROOT = '.x/fixtures';
|
|
112
|
+
|
|
113
|
+
export interface TempTreeOptions {
|
|
114
|
+
/**
|
|
115
|
+
* A package directory: the tree is made under its `IN_PACKAGE_TEMP_ROOT` instead of the platform
|
|
116
|
+
* temp root, for a child that must resolve `@ultimat3/*` from the workspace. Never anywhere else
|
|
117
|
+
* in the checkout (`scripts/temp-tree.ts` refuses an in-repo `mkdtemp`).
|
|
118
|
+
*/
|
|
119
|
+
readonly inPackage?: string;
|
|
120
|
+
/** The recursive remove, for a test of the check after it; default `rmSync(…, { recursive, force })`. */
|
|
121
|
+
readonly remove?: (path: string) => void;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
const removeTree = (path: string): void => rmSync(path, { recursive: true, force: true });
|
|
125
|
+
|
|
126
|
+
/** What `tree.spawn` takes: the tree's own directory by default, and `Bun.env` under `env`. */
|
|
127
|
+
export interface TempTreeSpawnOptions {
|
|
128
|
+
readonly cwd?: string;
|
|
129
|
+
readonly env?: Readonly<Record<string, string | undefined>>;
|
|
130
|
+
readonly stdout?: 'pipe' | 'ignore';
|
|
131
|
+
readonly stderr?: 'pipe' | 'ignore';
|
|
132
|
+
/** Default `TEMP_TREE_GIT_TIMEOUT_MS`: a child still running past it is killed by Bun. */
|
|
133
|
+
readonly timeout?: number;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** One child and how it is ended: its whole group, or only itself when spawned elsewhere. */
|
|
137
|
+
interface Held {
|
|
138
|
+
readonly child: TrackedChild;
|
|
139
|
+
readonly group: boolean;
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/** A temp tree named `<prefix><random>`; `await using tree = tempTree('x-')` removes it at scope end. */
|
|
143
|
+
export function tempTree(prefix: string, options: TempTreeOptions = {}): TempTree {
|
|
144
|
+
// Absolute, always: git ignores a relative `GIT_CEILING_DIRECTORIES` entry, and a tree inside a
|
|
145
|
+
// package would then answer for the checkout around it.
|
|
146
|
+
const parent =
|
|
147
|
+
options.inPackage === undefined ? tmpdir() : resolve(options.inPackage, IN_PACKAGE_TEMP_ROOT);
|
|
148
|
+
mkdirSync(parent, { recursive: true });
|
|
149
|
+
const path = mkdtempSync(join(parent, prefix));
|
|
150
|
+
// Discovery stops at the tree's own parent: inside a package, git would otherwise find the
|
|
151
|
+
// checkout itself and run there.
|
|
152
|
+
const gitEnv = { ...TEMP_TREE_GIT_ENV, GIT_CEILING_DIRECTORIES: parent };
|
|
153
|
+
const children = new Set<Held>();
|
|
154
|
+
let disposed: Promise<void> | undefined;
|
|
155
|
+
|
|
156
|
+
const track = <T extends TrackedChild>(child: T): T => {
|
|
157
|
+
children.add({ child, group: false });
|
|
158
|
+
return child;
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
const spawn = (argv: readonly string[], spawnOptions: TempTreeSpawnOptions = {}) => {
|
|
162
|
+
const child = Bun.spawn([...argv], {
|
|
163
|
+
cwd: spawnOptions.cwd ?? path,
|
|
164
|
+
env: overlaid(spawnOptions.env ?? {}),
|
|
165
|
+
stdin: 'ignore',
|
|
166
|
+
stdout: spawnOptions.stdout ?? 'pipe',
|
|
167
|
+
stderr: spawnOptions.stderr ?? 'pipe',
|
|
168
|
+
timeout: finiteCount(
|
|
169
|
+
'tree.spawn',
|
|
170
|
+
'timeout',
|
|
171
|
+
spawnOptions.timeout ?? TEMP_TREE_GIT_TIMEOUT_MS,
|
|
172
|
+
1,
|
|
173
|
+
),
|
|
174
|
+
// Its own process group on POSIX, so the group is what `dispose()` ends; on Windows
|
|
175
|
+
// `detached` is a console flag, and `taskkill /T` walks the tree instead.
|
|
176
|
+
detached: process.platform !== 'win32',
|
|
177
|
+
}) as Bun.Subprocess<'ignore', 'pipe', 'pipe'>;
|
|
178
|
+
children.add({ child, group: true });
|
|
179
|
+
return child;
|
|
180
|
+
};
|
|
181
|
+
|
|
182
|
+
/** End one child — its whole group when the tree spawned it, even after it exited — and await it. */
|
|
183
|
+
const end = async ({ child, group }: Held): Promise<void> => {
|
|
184
|
+
const pid = Reflect.get(child, 'pid');
|
|
185
|
+
if (group && typeof pid === 'number') await killTree(pid);
|
|
186
|
+
else if (child.exitCode === null) child.kill('SIGKILL');
|
|
187
|
+
await child.exited.catch(() => undefined);
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
const git = async (
|
|
191
|
+
args: readonly string[],
|
|
192
|
+
options: { readonly cwd?: string } = {},
|
|
193
|
+
): Promise<TempTreeGitResult> => {
|
|
194
|
+
const child = spawn(['git', ...args], { cwd: options.cwd ?? path, env: gitEnv });
|
|
195
|
+
const [stdout, stderr, code] = await Promise.all([
|
|
196
|
+
new Response(child.stdout).text(),
|
|
197
|
+
new Response(child.stderr).text(),
|
|
198
|
+
child.exited,
|
|
199
|
+
]);
|
|
200
|
+
return { code, stdout, stderr };
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
const remove = async (): Promise<void> => {
|
|
204
|
+
// Pass by pass: a child handed over while an earlier pass waited is ended by the next one.
|
|
205
|
+
while (children.size > 0) {
|
|
206
|
+
const pass = [...children];
|
|
207
|
+
for (const held of pass) children.delete(held);
|
|
208
|
+
await Promise.all(pass.map(end));
|
|
209
|
+
}
|
|
210
|
+
(options.remove ?? removeTree)(path);
|
|
211
|
+
// Bun's recursive remove can stop at an entry that vanished under it and report success.
|
|
212
|
+
if (existsSync(path)) throw new TempTreeLeftError({ path, left: readdirSync(path) });
|
|
213
|
+
};
|
|
214
|
+
|
|
215
|
+
// A failed removal is no answer to keep: the next `dispose()` tries again.
|
|
216
|
+
const dispose = (): Promise<void> => {
|
|
217
|
+
disposed ??= remove().catch((error: unknown) => {
|
|
218
|
+
disposed = undefined;
|
|
219
|
+
throw error;
|
|
220
|
+
});
|
|
221
|
+
return disposed;
|
|
222
|
+
};
|
|
223
|
+
|
|
224
|
+
return {
|
|
225
|
+
path,
|
|
226
|
+
gitEnv,
|
|
227
|
+
git,
|
|
228
|
+
spawn,
|
|
229
|
+
track,
|
|
230
|
+
dispose,
|
|
231
|
+
[Symbol.asyncDispose]: dispose,
|
|
232
|
+
};
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Trees one file makes and removes together: `make(prefix)` answers a path, `dispose()` all of them. */
|
|
236
|
+
export interface TempTrees {
|
|
237
|
+
make(prefix: string): string;
|
|
238
|
+
dispose(): Promise<void>;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Many trees, one owner — the shape a file with an `afterAll` takes: `const trees = tempTrees();
|
|
243
|
+
* afterAll(() => trees.dispose());`, then `trees.make('x-')` wherever a test needs a directory.
|
|
244
|
+
*/
|
|
245
|
+
export function tempTrees(options: TempTreeOptions = {}): TempTrees {
|
|
246
|
+
const made: TempTree[] = [];
|
|
247
|
+
return {
|
|
248
|
+
make(prefix) {
|
|
249
|
+
const tree = tempTree(prefix, options);
|
|
250
|
+
made.push(tree);
|
|
251
|
+
return tree.path;
|
|
252
|
+
},
|
|
253
|
+
async dispose() {
|
|
254
|
+
await Promise.all(made.splice(0).map((tree) => tree.dispose()));
|
|
255
|
+
},
|
|
256
|
+
};
|
|
257
|
+
}
|