@ultimat3/testing 31.48.0 → 31.50.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.
@@ -9,6 +9,7 @@ import type { E2eTab } from './cdp-e2e-page';
9
9
  import { cdpE2eTab } from './cdp-e2e-page';
10
10
  import { isNetworkProbe, networkAgrees } from './cdp-network-probe';
11
11
  import { offlineScripts } from './cdp-offline-script';
12
+ import { registerSessionPort } from './cdp-ports';
12
13
  import type { AuditedTab } from './e2e-a11y-tabs';
13
14
  import { auditTab } from './e2e-a11y-tabs';
14
15
 
@@ -127,6 +128,9 @@ export async function cdpE2eSession(options: CdpE2eSessionOptions): Promise<E2eS
127
128
  );
128
129
  }
129
130
  if (cut) configured.push(condition(session));
131
+ // A cross-site frame runs in its own process and reports its console on its own session:
132
+ // `Runtime` on, so its tab's console capture hears it (`cdp-console-capture.ts`).
133
+ if (type === 'iframe') configured.push(send('Runtime.enable', {}, session));
130
134
  if (type === 'page') {
131
135
  configured.push(send('Page.enable', {}, session), send('Runtime.enable', {}, session));
132
136
  pageSessions.add(session);
@@ -302,40 +306,46 @@ export async function cdpE2eSession(options: CdpE2eSessionOptions): Promise<E2eS
302
306
  });
303
307
  };
304
308
 
305
- return {
306
- async newTab(): Promise<E2eTab> {
307
- const created = await send('Target.createTarget', { url: 'about:blank' });
308
- const targetId = field(created.result, 'targetId');
309
- if (targetId === undefined) {
310
- throw new CdpCallFailedError({
311
- method: 'Target.createTarget',
312
- detail: 'the browser created a tab and answered no targetId',
313
- });
314
- }
315
- const sessionId = await attached(targetId);
316
- // Every tab is audited: built here, so no suite can hold one the audit does not see. The
317
- // tab is alive while the browser still knows its target — a closed one has no page to read.
318
- let audit: AuditedTab | undefined;
319
- const tab = cdpE2eTab({
320
- connection,
321
- sessionId,
322
- targetId,
323
- loadTimeoutMs: options.loadTimeoutMs,
324
- offline,
325
- audit: {
326
- navigated: () => audit?.navigated() ?? Promise.resolve(),
327
- used: () => audit?.used(),
328
- closed: () => audit?.closed(),
329
- },
309
+ /** A tab in the first profile, or in `browserContextId`'s (`newBrowserContext`). */
310
+ const openTab = async (browserContextId?: string): Promise<E2eTab> => {
311
+ const created = await send('Target.createTarget', {
312
+ url: 'about:blank',
313
+ ...(browserContextId === undefined ? {} : { browserContextId }),
314
+ });
315
+ const targetId = field(created.result, 'targetId');
316
+ if (targetId === undefined) {
317
+ throw new CdpCallFailedError({
318
+ method: 'Target.createTarget',
319
+ detail: 'the browser created a tab and answered no targetId',
330
320
  });
331
- audit = auditTab(tab, () =>
332
- send('Target.getTargetInfo', { targetId }).then(
333
- () => true,
334
- () => false,
335
- ),
336
- );
337
- return tab;
338
- },
321
+ }
322
+ const sessionId = await attached(targetId);
323
+ // Every tab is audited: built here, so no suite can hold one the audit does not see. The
324
+ // tab is alive while the browser still knows its target — a closed one has no page to read.
325
+ let audit: AuditedTab | undefined;
326
+ const tab = cdpE2eTab({
327
+ connection,
328
+ sessionId,
329
+ targetId,
330
+ loadTimeoutMs: options.loadTimeoutMs,
331
+ offline,
332
+ audit: {
333
+ navigated: () => audit?.navigated() ?? Promise.resolve(),
334
+ used: () => audit?.used(),
335
+ closed: () => audit?.closed(),
336
+ },
337
+ });
338
+ audit = auditTab(tab, () =>
339
+ send('Target.getTargetInfo', { targetId }).then(
340
+ () => true,
341
+ () => false,
342
+ ),
343
+ );
344
+ return tab;
345
+ };
346
+
347
+ const handle: E2eSession = {
348
+ newTab: () => openTab(),
339
349
  async addInitScript(source: string): Promise<void> {
340
350
  scripts.push(source);
341
351
  // A closed tab refuses every call; it is dropped rather than taking the open tabs down with
@@ -355,4 +365,10 @@ export async function cdpE2eSession(options: CdpE2eSessionOptions): Promise<E2eS
355
365
  sockets: () => [...sockets],
356
366
  requests: () => [...requests],
357
367
  };
368
+ // What `newBrowserContext(session)` drives: a tab opened into another profile, attached as these.
369
+ registerSessionPort(handle, {
370
+ connection,
371
+ openTab: (browserContextId) => openTab(browserContextId),
372
+ });
373
+ return handle;
358
374
  }
@@ -0,0 +1,91 @@
1
+ // Single responsibility: a virtual WebAuthn authenticator on one tab (CDP's `WebAuthn` domain), so a
2
+ // passkey registration and sign-in run end to end in the e2e harness with no device: the page's own
3
+ // `navigator.credentials.create/get` is answered by it, user presence and verification included.
4
+
5
+ import type { E2eTab } from './cdp-e2e-page';
6
+ import { tabPortOf } from './cdp-ports';
7
+
8
+ /** What the authenticator is. The defaults are a platform passkey: resident key, user verified. */
9
+ export interface VirtualAuthenticatorOptions {
10
+ /** Default `'internal'` — a platform authenticator, as a laptop's or a phone's. */
11
+ readonly transport?: 'internal' | 'usb' | 'nfc' | 'ble' | undefined;
12
+ /** Default `true`: discoverable credentials, what a usernameless sign-in needs. */
13
+ readonly residentKey?: boolean | undefined;
14
+ /** Default `true`: the person passes the PIN or biometric. `false` answers every UV as failed. */
15
+ readonly userVerified?: boolean | undefined;
16
+ }
17
+
18
+ /** One credential the authenticator holds, as CDP reports it. */
19
+ export interface VirtualCredential {
20
+ /** base64 of the raw credential id. */
21
+ readonly credentialId: string;
22
+ readonly rpId: string;
23
+ readonly resident: boolean;
24
+ readonly signCount: number;
25
+ /** base64 of the user handle the relying party registered; absent for a non-resident one. */
26
+ readonly userHandle: string | undefined;
27
+ }
28
+
29
+ export interface VirtualAuthenticator {
30
+ readonly id: string;
31
+ /** Every credential registered on it, in the order the browser lists them. */
32
+ credentials(): Promise<readonly VirtualCredential[]>;
33
+ /** The person's verification from here on: `false` makes the next ceremony fail UV. */
34
+ setUserVerified(verified: boolean): Promise<void>;
35
+ /** Detaches this authenticator only: another added to the same tab keeps answering ceremonies. */
36
+ remove(): Promise<void>;
37
+ }
38
+
39
+ const field = (from: unknown, key: string): unknown =>
40
+ typeof from === 'object' && from !== null ? (from as Record<string, unknown>)[key] : undefined;
41
+
42
+ const toCredential = (raw: unknown): VirtualCredential => {
43
+ const handle = field(raw, 'userHandle');
44
+ return {
45
+ credentialId: String(field(raw, 'credentialId') ?? ''),
46
+ rpId: String(field(raw, 'rpId') ?? ''),
47
+ resident: field(raw, 'isResidentCredential') === true,
48
+ signCount: Number(field(raw, 'signCount') ?? 0),
49
+ userHandle: typeof handle === 'string' ? handle : undefined,
50
+ };
51
+ };
52
+
53
+ /**
54
+ * Adds a CTAP2 authenticator to `tab` with presence simulated, so a ceremony completes with no
55
+ * prompt. Per tab: another tab, or another context's, has none until it is given one.
56
+ */
57
+ export async function addVirtualAuthenticator(
58
+ tab: E2eTab,
59
+ options: VirtualAuthenticatorOptions = {},
60
+ ): Promise<VirtualAuthenticator> {
61
+ const { connection, sessionId } = tabPortOf(tab, 'addVirtualAuthenticator');
62
+ const send = (method: string, params: Record<string, unknown> = {}) =>
63
+ connection.send(method, params, sessionId);
64
+ await send('WebAuthn.enable', { enableUI: false });
65
+ const added = await send('WebAuthn.addVirtualAuthenticator', {
66
+ options: {
67
+ protocol: 'ctap2',
68
+ ctap2Version: 'ctap2_1',
69
+ transport: options.transport ?? 'internal',
70
+ hasResidentKey: options.residentKey ?? true,
71
+ hasUserVerification: true,
72
+ isUserVerified: options.userVerified ?? true,
73
+ automaticPresenceSimulation: true,
74
+ },
75
+ });
76
+ const id = String(field(added.result, 'authenticatorId') ?? '');
77
+ return {
78
+ id,
79
+ async credentials() {
80
+ const listed = await send('WebAuthn.getCredentials', { authenticatorId: id });
81
+ const raw = field(listed.result, 'credentials');
82
+ return Array.isArray(raw) ? raw.map(toCredential) : [];
83
+ },
84
+ async setUserVerified(verified) {
85
+ await send('WebAuthn.setUserVerified', { authenticatorId: id, isUserVerified: verified });
86
+ },
87
+ async remove() {
88
+ await send('WebAuthn.removeVirtualAuthenticator', { authenticatorId: id });
89
+ },
90
+ };
91
+ }
@@ -0,0 +1,108 @@
1
+ // One key press as `Input.dispatchKeyEvent` sends it: a chord (`Shift+Tab`, `Control+k`) parsed by
2
+ // `@ultimat3/scraping`'s one grammar, its key looked up, and the down and up events built — the
3
+ // modifiers as CDP's bitmask, the text a US keyboard would type, or none under Control/Meta/Alt.
4
+
5
+ import { type KeyModifier, parseKeyChord } from '@ultimat3/scraping';
6
+ import { CdpCallFailedError } from '@ultimat3/scraping/cdp';
7
+
8
+ /** Named keys `press()` knows, with the Windows virtual key code Chrome routes them by. */
9
+ export const PRESS_KEYS: Readonly<Record<string, number>> = {
10
+ Tab: 9,
11
+ Enter: 13,
12
+ Escape: 27,
13
+ ' ': 32,
14
+ PageUp: 33,
15
+ PageDown: 34,
16
+ End: 35,
17
+ Home: 36,
18
+ ArrowLeft: 37,
19
+ ArrowUp: 38,
20
+ ArrowRight: 39,
21
+ ArrowDown: 40,
22
+ Backspace: 8,
23
+ Delete: 46,
24
+ };
25
+
26
+ /** The key code of a printable character: its upper-case code point for a letter or digit. */
27
+ const charCode = (key: string): number | undefined =>
28
+ key.length === 1 && /[a-z0-9]/i.test(key) ? key.toUpperCase().charCodeAt(0) : undefined;
29
+
30
+ /**
31
+ * The text a key TYPES, as puppeteer's key table has it. A key with text goes down as `keyDown`
32
+ * carrying it, so Chrome raises the character event — what makes Enter submit a focused button's
33
+ * form. A key with none (Tab, the arrows) goes down as `rawKeyDown`.
34
+ */
35
+ const typedText = (key: string): string | undefined =>
36
+ key === 'Enter' ? '\r' : key.length === 1 ? key : undefined;
37
+
38
+ /** `KeyboardEvent.code`: `KeyA`, `Digit7`, `Space`; a named key is its own code. */
39
+ const keyCodeName = (key: string): string =>
40
+ key === ' '
41
+ ? 'Space'
42
+ : /^[a-z]$/i.test(key)
43
+ ? `Key${key.toUpperCase()}`
44
+ : /^[0-9]$/.test(key)
45
+ ? `Digit${key}`
46
+ : key;
47
+
48
+ /** CDP's `modifiers` bits (`Input.dispatchKeyEvent`). */
49
+ const MODIFIER_BITS: ReadonlyMap<KeyModifier, number> = new Map([
50
+ ['Alt', 1],
51
+ ['Control', 2],
52
+ ['Meta', 4],
53
+ ['Shift', 8],
54
+ ]);
55
+
56
+ /** What Shift turns a digit into on a US layout; its `code` and key code stay the digit's. */
57
+ const SHIFTED_DIGITS = ')!@#$%^&*(';
58
+
59
+ /** The key Shift makes of `base`: an upper-case letter, a digit's symbol, else `base` itself. */
60
+ const shifted = (base: string): string =>
61
+ /^[a-z]$/.test(base)
62
+ ? base.toUpperCase()
63
+ : /^[0-9]$/.test(base)
64
+ ? (SHIFTED_DIGITS[Number(base)] ?? base)
65
+ : base;
66
+
67
+ export interface KeyEvents {
68
+ readonly down: Record<string, unknown>;
69
+ readonly up: Record<string, unknown>;
70
+ }
71
+
72
+ /**
73
+ * The two events one press sends. A chord's grammar is refused as `X_SCRAPE_KEY_INVALID`; a key
74
+ * outside `PRESS_KEYS`, an ASCII letter or a digit as `X_CDP_CALL_FAILED`.
75
+ */
76
+ export function keyEvents(chord: string): KeyEvents {
77
+ const parsed = parseKeyChord(chord);
78
+ const base = parsed.key;
79
+ const code = (Object.hasOwn(PRESS_KEYS, base) ? PRESS_KEYS[base] : undefined) ?? charCode(base);
80
+ if (code === undefined) {
81
+ throw new CdpCallFailedError({
82
+ method: `press(${chord})`,
83
+ detail: `not a key press() knows: one of ${Object.keys(PRESS_KEYS).join(', ')}, or one ASCII letter or digit, optionally after Alt, Control, Meta or Shift joined by +`,
84
+ });
85
+ }
86
+ const modifiers = parsed.modifiers.reduce(
87
+ (bits, name) => bits | (MODIFIER_BITS.get(name) ?? 0),
88
+ 0,
89
+ );
90
+ const key = parsed.modifiers.includes('Shift') ? shifted(base) : base;
91
+ // Control, Meta and Alt make a shortcut, not a character: no text, so nothing is typed.
92
+ const typing = parsed.modifiers.every((name) => name === 'Shift');
93
+ const text = typing ? typedText(key) : undefined;
94
+ const common = {
95
+ key,
96
+ code: keyCodeName(base),
97
+ windowsVirtualKeyCode: code,
98
+ ...(modifiers === 0 ? {} : { modifiers }),
99
+ };
100
+ return {
101
+ down: {
102
+ type: text === undefined ? 'rawKeyDown' : 'keyDown',
103
+ ...common,
104
+ ...(text === undefined ? {} : { text }),
105
+ },
106
+ up: { type: 'keyUp', ...common },
107
+ };
108
+ }
@@ -0,0 +1,55 @@
1
+ // Single responsibility: the CDP behind a tab or a session the harness built, for the free
2
+ // functions that drive a domain neither port names (`WebAuthn`, `Target.createBrowserContext`).
3
+ // Kept beside the objects rather than on them: `E2eTab` and `E2eSession` are shapes an app may
4
+ // implement, and a member added to either would be a member every hand-rolled one lacks.
5
+
6
+ import type { CdpConnection } from '@ultimat3/scraping/cdp';
7
+ import type { E2eTab } from './cdp-e2e-page';
8
+ import type { E2eSession } from './cdp-e2e-session';
9
+ import { FixtureUnavailableError } from './errors';
10
+
11
+ export interface TabPort {
12
+ readonly connection: CdpConnection;
13
+ readonly sessionId: string;
14
+ }
15
+
16
+ export interface SessionPort {
17
+ readonly connection: CdpConnection;
18
+ /** A tab in `browserContextId`'s profile, attached and audited as `newTab()`'s is. */
19
+ openTab(browserContextId: string): Promise<E2eTab>;
20
+ }
21
+
22
+ const tabs = new WeakMap<object, TabPort>();
23
+ const sessions = new WeakMap<object, SessionPort>();
24
+
25
+ export const registerTabPort = (tab: E2eTab, port: TabPort): void => {
26
+ tabs.set(tab, port);
27
+ };
28
+
29
+ export const registerSessionPort = (session: E2eSession, port: SessionPort): void => {
30
+ sessions.set(session, port);
31
+ };
32
+
33
+ /** A tab `cdpE2eTab` built; a hand-rolled one is refused by name, never driven blind. */
34
+ export function tabPortOf(tab: E2eTab, what: string): TabPort {
35
+ const port = tabs.get(tab);
36
+ if (port === undefined) {
37
+ throw new FixtureUnavailableError({
38
+ name: what,
39
+ needs: 'a tab cdpE2eTab built — e2eBrowser().page or session.newTab()',
40
+ });
41
+ }
42
+ return port;
43
+ }
44
+
45
+ /** A session `cdpE2eSession` built — `e2eBrowser().session`. */
46
+ export function sessionPortOf(session: E2eSession, what: string): SessionPort {
47
+ const port = sessions.get(session);
48
+ if (port === undefined) {
49
+ throw new FixtureUnavailableError({
50
+ name: what,
51
+ needs: 'a session cdpE2eSession built — e2eBrowser().session',
52
+ });
53
+ }
54
+ return port;
55
+ }
@@ -1,6 +1,7 @@
1
- // The two ways a fault drill ends red. Declared in `errors.ts` with this package's codes, thrown
1
+ // The three ways a fault drill ends red. Declared in `errors.ts` with this package's codes, thrown
2
2
  // from here: a drill whose service is missing is REFUSED, never skipped — a green drill that ran
3
- // nothing is the vacuous pass — and a drill whose property failed names the property and evidence.
3
+ // nothing is the vacuous pass — a drill whose property failed names the property and evidence, and
4
+ // a scratch database the teardown could not drop is named with the paste that drops it.
4
5
 
5
6
  import { renderCauseValue, renderFixShellArg, UltimateError } from '@ultimat3/core';
6
7
  import type { DrillFailure } from './drill-verdict';
@@ -43,3 +44,37 @@ export class DrillFailedError extends UltimateError {
43
44
  });
44
45
  }
45
46
  }
47
+
48
+ /** A paste that does by hand what the drop could not: terminate the slot holder, then drop. */
49
+ function dropFix(adminUrl: string, database: string): string {
50
+ const url = new URL(adminUrl);
51
+ const db = renderFixShellArg(database, '<database>');
52
+ const host = renderFixShellArg(url.hostname, '<host>');
53
+ const port = renderFixShellArg(url.port || '5432', '<port>');
54
+ const user = renderFixShellArg(decodeURIComponent(url.username), '<user>');
55
+ const admin = renderFixShellArg(url.pathname.slice(1) || 'postgres', '<admin database>');
56
+ return (
57
+ `psql -h ${host} -p ${port} -U ${user} -d ${admin}` +
58
+ ` -c "select pg_terminate_backend(active_pid) from pg_replication_slots where database = '${db}'"` +
59
+ ` -c 'select pg_sleep(1)' -c 'DROP DATABASE IF EXISTS ${db} WITH (FORCE)'`
60
+ );
61
+ }
62
+
63
+ /**
64
+ * The fleet's scratch database outlived its drop: a slot still held after its holder was
65
+ * terminated, or the server refused. The password is never in the fix — psql asks for it.
66
+ */
67
+ export class DrillTeardownFailedError extends UltimateError {
68
+ constructor(input: {
69
+ readonly database: string;
70
+ readonly adminUrl: string;
71
+ readonly why: string;
72
+ }) {
73
+ super({
74
+ code: 'X_DRILL_TEARDOWN_FAILED',
75
+ cause: `x drill could not drop its scratch database ${renderCauseValue(input.database)}: ${input.why}; it is left on the server`,
76
+ fix: dropFix(input.adminUrl, input.database),
77
+ meta: { database: input.database },
78
+ });
79
+ }
80
+ }
@@ -11,12 +11,12 @@ import { tmpdir } from 'node:os';
11
11
  import { join } from 'node:path';
12
12
  import { tailOf } from './drill-output';
13
13
  import { probeStatus } from './drill-probe';
14
+ import { scratchDatabase } from './drill-scratch-db';
14
15
  import type { DrillRole, DrillService } from './drills';
15
16
  import { E2eAppFailedError } from './e2e-errors';
16
17
  import type { FaultProxy } from './fault-proxy';
17
18
  import { faultProxy, faultTarget, throughFaultProxy } from './fault-proxy';
18
19
  import { bindFreePorts, isPortClash } from './free-port-bind';
19
- import { dropSql, urlFor } from './template-db';
20
20
  import { testSealKeyEnv } from './test-seal-key';
21
21
 
22
22
  export interface DrillServiceUrls {
@@ -101,28 +101,6 @@ const refuse = (step: string, output: string): E2eAppFailedError =>
101
101
  fix: 'ROLE=web bun apps/web/server.ts # in the app root, with the same DATABASE_URL: read why the role will not start',
102
102
  });
103
103
 
104
- /** Create the scratch database on the admin URL; answers its own URL and its drop. */
105
- async function scratchDatabase(adminUrl: string) {
106
- const name = `x_drill_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
107
- const admin = new Bun.SQL(adminUrl);
108
- try {
109
- await admin.unsafe(`create database ${name}`);
110
- } finally {
111
- await admin.close();
112
- }
113
- return {
114
- url: urlFor(adminUrl, name),
115
- async drop(): Promise<void> {
116
- const again = new Bun.SQL(adminUrl);
117
- try {
118
- await again.unsafe(dropSql(name));
119
- } finally {
120
- await again.close();
121
- }
122
- },
123
- };
124
- }
125
-
126
104
  async function waitReady(url: string, deadlineMs: number, alive: () => boolean): Promise<boolean> {
127
105
  const until = performance.now() + deadlineMs;
128
106
  while (performance.now() < until && alive()) {
@@ -132,6 +110,21 @@ async function waitReady(url: string, deadlineMs: number, alive: () => boolean):
132
110
  return false;
133
111
  }
134
112
 
113
+ /**
114
+ * Before migrate a role is never ready, so its bind is proven by its first `watch` line — or it
115
+ * exits. Until this wait, a role that lost its port to another process (an outgoing Postgres
116
+ * connection's ephemeral port) between hand-out and bind died unseen and read as a failed drill
117
+ * (`ROLE=sync exited 1`, EADDRINUSE, PR #1286); now it reaches `bindFreePorts`' retry.
118
+ */
119
+ async function waitWatching(
120
+ watched: () => number,
121
+ deadlineMs: number,
122
+ alive: () => boolean,
123
+ ): Promise<void> {
124
+ const until = performance.now() + deadlineMs;
125
+ while (performance.now() < until && alive() && watched() === 0) await Bun.sleep(100);
126
+ }
127
+
135
128
  /** The fleet, ready: database created and migrated, every proxy listening, every role answering. */
136
129
  export async function startDrillFleet(options: DrillFleetOptions): Promise<DrillFleet> {
137
130
  const database = await scratchDatabase(options.services.postgres);
@@ -238,6 +231,17 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
238
231
  await child.exited;
239
232
  throw refuse(`ROLE=${role} never answered ${readyz}`, output.log());
240
233
  }
234
+ } else {
235
+ await waitWatching(
236
+ output.watched,
237
+ options.readyTimeoutMs,
238
+ () => child.exitCode === null,
239
+ );
240
+ if (child.exitCode !== null && isPortClash(output.log())) {
241
+ clashed = true;
242
+ children.delete(child);
243
+ throw refuse(`ROLE=${role} lost its port before migrate`, output.log());
244
+ }
241
245
  }
242
246
  // The sync node listens on PORT + 1 (`syncPortFor`): held too, so no other role is handed it.
243
247
  taken.push(port, metricsPort, ...(role === 'sync' ? [port + 1] : []));
@@ -282,11 +286,23 @@ export async function startDrillFleet(options: DrillFleetOptions): Promise<Drill
282
286
  };
283
287
  return { base: webBase, databaseUrl: database.url, proxies, roles, rollout, stop };
284
288
  } catch (error) {
285
- await stop();
286
- throw error;
289
+ return stopAfterFailedStart(error, stop);
287
290
  }
288
291
  }
289
292
 
293
+ /**
294
+ * A start that failed stops what it began, then rethrows ITS error: the stop's own failure (a
295
+ * scratch database left behind) is a later, smaller fact, and replacing the start's refusal with it
296
+ * hid why the drill never ran.
297
+ */
298
+ export async function stopAfterFailedStart(
299
+ error: unknown,
300
+ stop: () => Promise<void>,
301
+ ): Promise<never> {
302
+ await Promise.allSettled([stop()]);
303
+ throw error;
304
+ }
305
+
290
306
  /** A role's exit, or `null` past `withinMs`: SIGKILLed then, so a wedged drain ends the drill. */
291
307
  export async function exitWithin(role: DrillRoleProcess, withinMs: number): Promise<number | null> {
292
308
  const exited = await Promise.race([role.exited(), Bun.sleep(withinMs).then(() => null)]);
@@ -0,0 +1,125 @@
1
+ // A drill's scratch database: created on the admin URL, dropped when the fleet stops. The drop
2
+ // waits out a logical slot a role's walsender still holds — postgres refuses `DROP DATABASE` on a
3
+ // database with an ACTIVE slot before `WITH (FORCE)` terminates anyone — then terminates the holder.
4
+
5
+ import { renderCauseValue, renderThrowable } from '@ultimat3/core';
6
+ import { DrillTeardownFailedError } from './drill-errors';
7
+ import { dropSql, urlFor } from './template-db';
8
+
9
+ /** The admin connection the drop runs on; injected so the unit tests need no server. */
10
+ export interface ScratchAdminSql {
11
+ query(
12
+ statement: string,
13
+ params?: readonly unknown[],
14
+ ): Promise<readonly Record<string, unknown>[]>;
15
+ close(): Promise<void>;
16
+ }
17
+
18
+ /**
19
+ * How many times the slots are asked again per wait, each ask holding the SERVER 50 ms — ~5 s, as
20
+ * realtime's `SLOT_RELEASE_POLLS`: a walsender whose socket closed exits in milliseconds. A count,
21
+ * not a clock: nothing waits on this process's timers, and a slot nobody holds costs one ask.
22
+ */
23
+ export const SCRATCH_SLOT_POLLS = 100;
24
+
25
+ const NAME = /^x_drill_[0-9a-f]{16}$/;
26
+
27
+ /** The slots on the database still held, with who holds them; the sleep runs only per held row. */
28
+ const HELD_SQL =
29
+ 'select slot_name, active_pid, pg_sleep(0.05) from pg_replication_slots ' +
30
+ 'where database = $1 and active_pid is not null';
31
+
32
+ const TERMINATE_SQL =
33
+ 'select pg_terminate_backend(active_pid) from pg_replication_slots ' +
34
+ 'where database = $1 and active_pid is not null';
35
+
36
+ interface Holder {
37
+ readonly slot: string;
38
+ readonly pid: number;
39
+ }
40
+
41
+ const holdersOf = (rows: readonly Record<string, unknown>[]): readonly Holder[] =>
42
+ rows.map((row) => ({
43
+ slot: typeof row['slot_name'] === 'string' ? row['slot_name'] : '<unnamed>',
44
+ pid: Number(row['active_pid']),
45
+ }));
46
+
47
+ /** Polls until no slot on the database is active, or the bound: then the last holders seen. */
48
+ async function awaitInactive(sql: ScratchAdminSql, name: string): Promise<readonly Holder[]> {
49
+ let holders: readonly Holder[] = [];
50
+ for (let poll = 0; poll < SCRATCH_SLOT_POLLS; poll += 1) {
51
+ holders = holdersOf(await sql.query(HELD_SQL, [name]));
52
+ if (holders.length === 0) return holders;
53
+ }
54
+ return holders;
55
+ }
56
+
57
+ const refused = (adminUrl: string, database: string, why: string): DrillTeardownFailedError =>
58
+ new DrillTeardownFailedError({ database, adminUrl, why });
59
+
60
+ /**
61
+ * Drop `name`: wait (bounded) for its slots to go inactive, terminate a holder that outlived the
62
+ * wait and wait again, then `DROP DATABASE … WITH (FORCE)`, which removes the inactive slot too.
63
+ */
64
+ export async function dropScratchDatabase(
65
+ sql: ScratchAdminSql,
66
+ name: string,
67
+ adminUrl: string,
68
+ ): Promise<void> {
69
+ if (!NAME.test(name)) {
70
+ throw refused(adminUrl, name, `${renderCauseValue(name)} is not a drill scratch database`);
71
+ }
72
+ // Every statement in one `try`: the admin session can drop during the wait, and Bun.SQL then
73
+ // rejects a poll or the terminate with a raw error the drill would otherwise print uncoded.
74
+ let holders: readonly Holder[];
75
+ try {
76
+ holders = await awaitInactive(sql, name);
77
+ if (holders.length > 0) {
78
+ await sql.query(TERMINATE_SQL, [name]);
79
+ holders = await awaitInactive(sql, name);
80
+ }
81
+ if (holders.length === 0) await sql.query(dropSql(name));
82
+ } catch (error) {
83
+ throw refused(adminUrl, name, renderThrowable(error));
84
+ }
85
+ if (holders.length > 0) {
86
+ const named = holders.map((holder) => `slot ${holder.slot} (pid ${String(holder.pid)})`);
87
+ throw refused(
88
+ adminUrl,
89
+ name,
90
+ `still used by an active logical replication slot after its holder was terminated: ${named.join(', ')}`,
91
+ );
92
+ }
93
+ }
94
+
95
+ const bunAdmin = (url: string): ScratchAdminSql => {
96
+ // Bun.SQL is the blessed Postgres client: no driver package.
97
+ const sql = new Bun.SQL(url);
98
+ return {
99
+ query: async (statement, params = []) => [...(await sql.unsafe(statement, [...params]))],
100
+ close: () => sql.close(),
101
+ };
102
+ };
103
+
104
+ /** Create the scratch database on the admin URL; answers its name, its URL and its drop. */
105
+ export async function scratchDatabase(adminUrl: string, connect = bunAdmin) {
106
+ const name = `x_drill_${crypto.randomUUID().replaceAll('-', '').slice(0, 16)}`;
107
+ const admin = connect(adminUrl);
108
+ try {
109
+ await admin.query(`create database ${name}`);
110
+ } finally {
111
+ await admin.close();
112
+ }
113
+ return {
114
+ name,
115
+ url: urlFor(adminUrl, name),
116
+ async drop(): Promise<void> {
117
+ const again = connect(adminUrl);
118
+ try {
119
+ await dropScratchDatabase(again, name, adminUrl);
120
+ } finally {
121
+ await again.close();
122
+ }
123
+ },
124
+ };
125
+ }
@@ -0,0 +1,16 @@
1
+ // One console line an e2e page printed, as the port answers it: a `console.*` call or an uncaught
2
+ // exception. Its own file so the port (`e2e-page.ts`) and the CDP tab can share it.
3
+
4
+ /** `console.*`'s level as Chrome reports it (`console.warn` is `warning`). */
5
+ export type E2eConsoleLevel = 'debug' | 'log' | 'info' | 'warning' | 'error';
6
+
7
+ export interface E2eConsoleMessage {
8
+ readonly level: E2eConsoleLevel;
9
+ /**
10
+ * The call's raw arguments joined by one space: a primitive's value, an object's description. No
11
+ * format substitution — `console.log('n: %d', 2)` is `n: %d 2` — so assert on a fragment.
12
+ */
13
+ readonly text: string;
14
+ /** `console` for a `console.*` call; `exception` for a throw nothing caught (always `error`). */
15
+ readonly source: 'console' | 'exception';
16
+ }