@testsprite/testsprite-cli 0.7.0 → 0.8.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/README.md +51 -38
- package/dist/commands/agent.js +47 -3
- package/dist/commands/ci.d.ts +88 -0
- package/dist/commands/ci.js +429 -0
- package/dist/commands/doctor.js +100 -1
- package/dist/commands/init.js +8 -0
- package/dist/commands/project.d.ts +78 -0
- package/dist/commands/project.js +426 -3
- package/dist/commands/test.d.ts +162 -2
- package/dist/commands/test.js +1814 -392
- package/dist/commands/testlist.js +15 -9
- package/dist/commands/tunnel.d.ts +72 -0
- package/dist/commands/tunnel.js +367 -0
- package/dist/index.js +107 -38
- package/dist/lib/dry-run/samples.d.ts +9 -0
- package/dist/lib/dry-run/samples.js +116 -0
- package/dist/lib/gh-output.d.ts +7 -0
- package/dist/lib/gh-output.js +50 -7
- package/dist/lib/http.d.ts +94 -0
- package/dist/lib/http.js +120 -5
- package/dist/lib/interrupt.d.ts +38 -13
- package/dist/lib/interrupt.js +130 -15
- package/dist/lib/local-target.d.ts +95 -0
- package/dist/lib/local-target.js +184 -0
- package/dist/lib/plan-poll.d.ts +171 -0
- package/dist/lib/plan-poll.js +442 -0
- package/dist/lib/plans.types.d.ts +130 -0
- package/dist/lib/plans.types.js +31 -0
- package/dist/lib/poll-support.d.ts +26 -0
- package/dist/lib/poll-support.js +65 -0
- package/dist/lib/poll.d.ts +1 -0
- package/dist/lib/poll.js +2 -40
- package/dist/lib/response-schemas.d.ts +13 -0
- package/dist/lib/response-schemas.js +32 -0
- package/dist/lib/run-progress.d.ts +41 -0
- package/dist/lib/run-progress.js +56 -0
- package/dist/lib/runs.types.d.ts +24 -0
- package/dist/lib/target-url-preflight.js +3 -3
- package/dist/lib/target-url.d.ts +44 -7
- package/dist/lib/target-url.js +250 -61
- package/dist/lib/telemetry.d.ts +11 -0
- package/dist/lib/telemetry.js +1 -0
- package/dist/lib/ticker.d.ts +8 -0
- package/dist/lib/ticker.js +3 -0
- package/dist/lib/tunnel-session.d.ts +129 -0
- package/dist/lib/tunnel-session.js +232 -0
- package/dist/lib/tunnel.types.d.ts +54 -0
- package/dist/lib/tunnel.types.js +8 -0
- package/dist/vendor/tunnel-client/client.d.ts +83 -0
- package/dist/vendor/tunnel-client/client.js +871 -0
- package/dist/vendor/tunnel-client/config.d.ts +41 -0
- package/dist/vendor/tunnel-client/config.js +42 -0
- package/dist/vendor/tunnel-client/index.d.ts +9 -0
- package/dist/vendor/tunnel-client/index.js +9 -0
- package/dist/vendor/tunnel-client/lodash-lite.d.ts +14 -0
- package/dist/vendor/tunnel-client/lodash-lite.js +24 -0
- package/dist/vendor/tunnel-client/protocol.d.ts +60 -0
- package/dist/vendor/tunnel-client/protocol.js +143 -0
- package/dist/vendor/tunnel-client/types.d.ts +96 -0
- package/dist/vendor/tunnel-client/types.js +10 -0
- package/dist/vendor/tunnel-client/ws-compat.d.ts +206 -0
- package/dist/vendor/tunnel-client/ws-compat.js +316 -0
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +2 -1
- package/skills/testsprite-onboard.skill.md +60 -4
- package/skills/testsprite-verify.codex.md +22 -16
- package/skills/testsprite-verify.skill.md +27 -18
package/dist/lib/http.js
CHANGED
|
@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
2
2
|
import * as v from 'valibot';
|
|
3
3
|
import { ApiError, InterruptError, RequestTimeoutError, TransportError } from './errors.js';
|
|
4
4
|
import { VERSION } from '../version.js';
|
|
5
|
-
import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, } from './response-schemas.js';
|
|
5
|
+
import { BATCH_RERUN_RESPONSE_SCHEMA, BATCH_RUN_FRESH_RESPONSE_SCHEMA, LIST_RUNS_RESPONSE_SCHEMA, RERUN_RESPONSE_SCHEMA, RUN_RESPONSE_SCHEMA, TESTLIST_RUN_RESPONSE_SCHEMA, TRIGGER_RUN_RESPONSE_SCHEMA, TUNNEL_MINT_RESPONSE_SCHEMA, TUNNEL_STATUS_RESPONSE_SCHEMA, } from './response-schemas.js';
|
|
6
6
|
/**
|
|
7
7
|
* Default per-request timeout (120s). Comfortably covers every metadata/read
|
|
8
8
|
* request and every <=25s long-poll request (`?waitSeconds` is capped at 25
|
|
@@ -78,6 +78,13 @@ export class HttpClient {
|
|
|
78
78
|
this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
|
|
79
79
|
this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES_DEFAULT;
|
|
80
80
|
}
|
|
81
|
+
/** The resolved facade base URL (trailing slash trimmed). Read-only —
|
|
82
|
+
* callers that bypass the client for a side-channel request (e.g. the
|
|
83
|
+
* presigned S3 PUT) use it to reason about the facade's locality
|
|
84
|
+
* (DEV-384 review F3). */
|
|
85
|
+
get resolvedBaseUrl() {
|
|
86
|
+
return this.baseUrl;
|
|
87
|
+
}
|
|
81
88
|
/**
|
|
82
89
|
* Read the backend's supported-floor header off a response and forward it to
|
|
83
90
|
* `onServerVersion` when present. Never throws — a bad header must not break
|
|
@@ -294,6 +301,56 @@ export class HttpClient {
|
|
|
294
301
|
schema: RUN_RESPONSE_SCHEMA,
|
|
295
302
|
});
|
|
296
303
|
}
|
|
304
|
+
/**
|
|
305
|
+
* POST /api/cli/v1/tunnel — mint a tunnel client for `test run --local`.
|
|
306
|
+
*
|
|
307
|
+
* The ONLY response on this surface that carries a secret. Deliberately NOT
|
|
308
|
+
* sent with an `Idempotency-Key`: the interceptor persists the response body
|
|
309
|
+
* for the whole replay window, so an idempotent mint would put a live
|
|
310
|
+
* credential in the idempotency store — the exact copy the server-side
|
|
311
|
+
* binding exists to avoid. The server rate-limits this route instead.
|
|
312
|
+
*
|
|
313
|
+
* `retryOnConflict: false` for the same reason `triggerRun` opts out: a 409
|
|
314
|
+
* here means the per-principal live-binding cap is reached, which is a
|
|
315
|
+
* standing condition, not a transient snapshot conflict.
|
|
316
|
+
*/
|
|
317
|
+
async mintTunnel(body, options = {}) {
|
|
318
|
+
return this.postWithMeta('/tunnel', {
|
|
319
|
+
body,
|
|
320
|
+
signal: options.signal,
|
|
321
|
+
schema: TUNNEL_MINT_RESPONSE_SCHEMA,
|
|
322
|
+
retryOnConflict: false,
|
|
323
|
+
}).then(r => r.body);
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* GET /api/cli/v1/tunnel/{clientId} — is this binding's client connected?
|
|
327
|
+
*
|
|
328
|
+
* A 404 covers unknown, another tenant's, and expired alike; the surface is
|
|
329
|
+
* deliberately not an existence oracle for client ids. Callers must not
|
|
330
|
+
* translate a transport failure or a non-200 into `offline` — "the tunnel is
|
|
331
|
+
* down" and "we could not reach TestSprite to ask" are different answers,
|
|
332
|
+
* and collapsing them is what DEV-1005 was.
|
|
333
|
+
*/
|
|
334
|
+
async getTunnelStatus(clientId, options = {}) {
|
|
335
|
+
return this.get(`/tunnel/${encodeURIComponent(clientId)}`, {
|
|
336
|
+
signal: options.signal,
|
|
337
|
+
schema: TUNNEL_STATUS_RESPONSE_SCHEMA,
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
/**
|
|
341
|
+
* DELETE /api/cli/v1/tunnel/{clientId} — destroy a binding. 204, idempotent.
|
|
342
|
+
*
|
|
343
|
+
* No body, no `Idempotency-Key`: the operation is idempotent by definition
|
|
344
|
+
* and this is the call made from a `finally` block, including after a
|
|
345
|
+
* signal, where there is least room for extra ceremony.
|
|
346
|
+
*/
|
|
347
|
+
async deleteTunnel(clientId, options = {}) {
|
|
348
|
+
await this.deleteWithMeta(`/tunnel/${encodeURIComponent(clientId)}`, {
|
|
349
|
+
signal: options.signal,
|
|
350
|
+
allowNoContent: true,
|
|
351
|
+
retryOnConflict: false,
|
|
352
|
+
});
|
|
353
|
+
}
|
|
297
354
|
/**
|
|
298
355
|
* POST /api/cli/v1/runs/{runId}/cancel
|
|
299
356
|
* User-initiated cancel of a queued/running run (DEV-331 piece 3). No
|
|
@@ -311,6 +368,56 @@ export class HttpClient {
|
|
|
311
368
|
retryOnConflict: false,
|
|
312
369
|
});
|
|
313
370
|
}
|
|
371
|
+
/**
|
|
372
|
+
* POST /api/cli/v1/projects/{projectId}/plans/generate (DEV-384 V3-B)
|
|
373
|
+
* Start whichever generation stage the project is missing next. The body
|
|
374
|
+
* is empty by contract — the server decides which rung fires. 202 both
|
|
375
|
+
* for `accepted` (a stage started) and `nothing_to_start` (proposals are
|
|
376
|
+
* already staged; the facade's no-restart guard refuses a duplicate
|
|
377
|
+
* append because it would wipe the batch and re-bill 2 credits).
|
|
378
|
+
*
|
|
379
|
+
* `retryOnConflict: false` — a 409 here is `stage_in_flight`, a flow
|
|
380
|
+
* signal the ladder answers by attaching and polling, never a transient
|
|
381
|
+
* snapshot conflict to paper over with a retry.
|
|
382
|
+
*/
|
|
383
|
+
async generatePlans(projectId, options) {
|
|
384
|
+
return this.post(`/projects/${encodeURIComponent(projectId)}/plans/generate`, {
|
|
385
|
+
body: {},
|
|
386
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
387
|
+
signal: options.signal,
|
|
388
|
+
retryOnConflict: false,
|
|
389
|
+
});
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* GET /api/cli/v1/projects/{projectId}/plans (DEV-384 V3-B)
|
|
393
|
+
* Pure read: the facade-synthesized generation status, the staged
|
|
394
|
+
* proposal list (stable proposalIds — what `accept --only` consumes),
|
|
395
|
+
* and a best-effort credits block. When `waitSeconds` (1–25) is
|
|
396
|
+
* provided the server long-polls: one request per window, answered
|
|
397
|
+
* early on any change.
|
|
398
|
+
*/
|
|
399
|
+
async getPlans(projectId, options) {
|
|
400
|
+
return this.get(`/projects/${encodeURIComponent(projectId)}/plans`, {
|
|
401
|
+
query: options?.waitSeconds !== undefined ? { waitSeconds: options.waitSeconds } : undefined,
|
|
402
|
+
signal: options?.signal,
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* POST /api/cli/v1/projects/{projectId}/plans/accept (DEV-384 V3-B)
|
|
407
|
+
* Convert staged proposals into real test cases. `only` is ALWAYS an
|
|
408
|
+
* explicit, non-empty id list — the caller enforces the two §3.3 safety
|
|
409
|
+
* rules (full list when the user didn't subset; an empty selection is a
|
|
410
|
+
* client-side validation error because `[]` is server-destructive:
|
|
411
|
+
* it means "reject everything" and clears the staged batch).
|
|
412
|
+
*/
|
|
413
|
+
async acceptPlans(projectId, only, options) {
|
|
414
|
+
return this.post(`/projects/${encodeURIComponent(projectId)}/plans/accept`, {
|
|
415
|
+
body: { only },
|
|
416
|
+
headers: { 'idempotency-key': options.idempotencyKey },
|
|
417
|
+
signal: options.signal,
|
|
418
|
+
retryOnConflict: false,
|
|
419
|
+
});
|
|
420
|
+
}
|
|
314
421
|
/**
|
|
315
422
|
* Classify an error thrown while issuing OR reading a request. When it is an
|
|
316
423
|
* abort/timeout and our per-request timeout signal fired (and the caller had
|
|
@@ -463,10 +570,18 @@ export class HttpClient {
|
|
|
463
570
|
});
|
|
464
571
|
let raw;
|
|
465
572
|
try {
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
573
|
+
if (response.status === 204 && options.allowNoContent === true) {
|
|
574
|
+
// Only explicitly bodyless endpoints may bypass the historical
|
|
575
|
+
// JSON-envelope contract. Every other 204 still falls through
|
|
576
|
+
// to JSON.parse('') and becomes a typed malformed-response error.
|
|
577
|
+
raw = undefined;
|
|
578
|
+
}
|
|
579
|
+
else {
|
|
580
|
+
// Bounded read, then parse — assigning to `raw` rather than returning
|
|
581
|
+
// here keeps the schema validation below on the success path.
|
|
582
|
+
const text = await readBoundedText(response, this.maxResponseBytes, requestId);
|
|
583
|
+
raw = JSON.parse(text);
|
|
584
|
+
}
|
|
470
585
|
}
|
|
471
586
|
catch (err) {
|
|
472
587
|
// Interrupt passthrough (see the fetch catch above).
|
package/dist/lib/interrupt.d.ts
CHANGED
|
@@ -12,8 +12,10 @@
|
|
|
12
12
|
* Broken pipe: when output is piped to a reader that closes early
|
|
13
13
|
* (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
|
|
14
14
|
* Node turns an `'error'` with no listener into an uncaughtException and dumps a
|
|
15
|
-
* raw `write EPIPE` stack (exit 1).
|
|
16
|
-
* conventional SIGPIPE-equivalent result
|
|
15
|
+
* raw `write EPIPE` stack (exit 1). Outside an armed lifetime the guard exits
|
|
16
|
+
* 0 immediately, the conventional SIGPIPE-equivalent result. While armed it
|
|
17
|
+
* first requests coordinated shutdown so tunnel cleanup can finish, then the
|
|
18
|
+
* same synthetic interrupt reason preserves exit 0.
|
|
17
19
|
*
|
|
18
20
|
* `process` and the streams are injectable so the wiring is unit-testable
|
|
19
21
|
* without spawning a subprocess or sending a real signal.
|
|
@@ -28,10 +30,12 @@ export declare const SIGINT_EXIT_CODE: 130;
|
|
|
28
30
|
* only these members, and tests can supply a lightweight fake.
|
|
29
31
|
*/
|
|
30
32
|
export interface ShutdownHandle {
|
|
31
|
-
/** Aborts
|
|
33
|
+
/** Aborts with the graceful-stop reason when a signal/EPIPE arrives while armed. */
|
|
32
34
|
readonly signal: AbortSignal;
|
|
33
35
|
/** Enter a graceful-detach scope. Returns the disposer that leaves it. */
|
|
34
36
|
arm(): () => void;
|
|
37
|
+
/** Run and track cleanup that a repeated signal may briefly wait for. */
|
|
38
|
+
runCriticalOperation<T>(operation: () => Promise<T>): Promise<T>;
|
|
35
39
|
}
|
|
36
40
|
/**
|
|
37
41
|
* Process-lifetime coordinator between the signal handler and the `--wait`
|
|
@@ -40,7 +44,7 @@ export interface ShutdownHandle {
|
|
|
40
44
|
* Two modes, chosen by whether a graceful-detach scope is armed when the
|
|
41
45
|
* signal arrives:
|
|
42
46
|
*
|
|
43
|
-
* - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
|
|
47
|
+
* - **Armed** (inside `pollRunUntilTerminal` or a tunnel lifetime): the handler only aborts
|
|
44
48
|
* `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
|
|
45
49
|
* and every backoff sleep bail immediately; the `--wait` catch blocks own
|
|
46
50
|
* the cleanup (finalize the ticker, print the honest partial envelope +
|
|
@@ -50,25 +54,42 @@ export interface ShutdownHandle {
|
|
|
50
54
|
* immediately, preserving the pre-DEV-331 behavior. An abort nobody
|
|
51
55
|
* observes must never leave the process hanging at e.g. a readline prompt.
|
|
52
56
|
*
|
|
53
|
-
* A
|
|
54
|
-
*
|
|
57
|
+
* A repeated signal still provides a bounded escape hatch: the second waits
|
|
58
|
+
* briefly only when critical cleanup is in flight, and the third exits at once.
|
|
55
59
|
*/
|
|
56
60
|
export declare class ShutdownController {
|
|
57
61
|
private readonly controller;
|
|
62
|
+
private readonly criticalOperations;
|
|
58
63
|
private armedCount;
|
|
59
|
-
private
|
|
64
|
+
private receivedCause;
|
|
60
65
|
constructor();
|
|
61
66
|
get signal(): AbortSignal;
|
|
62
|
-
/** The first
|
|
63
|
-
get received(): TerminationSignal | null;
|
|
67
|
+
/** The first graceful-shutdown cause received, or null if none yet. */
|
|
68
|
+
get received(): TerminationSignal | 'EPIPE' | null;
|
|
64
69
|
get isArmed(): boolean;
|
|
65
70
|
/**
|
|
66
71
|
* Enter a graceful-detach scope (re-entrant: fan-out members overlap).
|
|
67
72
|
* Returns an idempotent disposer.
|
|
68
73
|
*/
|
|
69
74
|
arm(): () => void;
|
|
75
|
+
/** Whether teardown currently has work whose abrupt loss is security-sensitive. */
|
|
76
|
+
get hasCriticalOperations(): boolean;
|
|
77
|
+
/**
|
|
78
|
+
* Register cleanup before it starts and remove it automatically when it
|
|
79
|
+
* settles. Rejections retain their original semantics for the caller.
|
|
80
|
+
*/
|
|
81
|
+
runCriticalOperation<T>(operation: () => Promise<T>): Promise<T>;
|
|
82
|
+
/** Wait until all current and directly chained critical cleanup settles. */
|
|
83
|
+
waitForCriticalOperations(): Promise<void>;
|
|
70
84
|
/** Record the signal and abort with an `InterruptError` carrying it. */
|
|
71
85
|
interrupt(signal: TerminationSignal): void;
|
|
86
|
+
/**
|
|
87
|
+
* Abort an armed lifetime after stdout's reader closes. The InterruptError
|
|
88
|
+
* subtype deliberately keeps the existing graceful-detach catch paths in
|
|
89
|
+
* play (including tunnel cancellation), while its exit code stays the
|
|
90
|
+
* SIGPIPE-equivalent success code 0.
|
|
91
|
+
*/
|
|
92
|
+
brokenPipe(): void;
|
|
72
93
|
}
|
|
73
94
|
/**
|
|
74
95
|
* The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
|
|
@@ -95,8 +116,9 @@ export interface InterruptDeps {
|
|
|
95
116
|
* First signal, armed scope: abort-only — the `--wait` catch paths own the
|
|
96
117
|
* honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
|
|
97
118
|
* First signal, disarmed: print the generic explanation + exit `128+signum`.
|
|
98
|
-
* Second signal
|
|
99
|
-
*
|
|
119
|
+
* Second signal: exit immediately unless critical cleanup is registered; when
|
|
120
|
+
* it is, wait at most two seconds before exiting. Third signal: always exit
|
|
121
|
+
* immediately, including while that grace period is active.
|
|
100
122
|
*/
|
|
101
123
|
export declare function installSignalHandlers(deps?: InterruptDeps): void;
|
|
102
124
|
export interface BrokenPipeDeps {
|
|
@@ -106,11 +128,14 @@ export interface BrokenPipeDeps {
|
|
|
106
128
|
stderr?: NodeJS.EventEmitter;
|
|
107
129
|
/** Process exit. Defaults to `process.exit`. */
|
|
108
130
|
exit?: (code: number) => void;
|
|
131
|
+
/** Shutdown coordinator. Defaults to {@link globalShutdown}. */
|
|
132
|
+
shutdown?: ShutdownController;
|
|
109
133
|
}
|
|
110
134
|
/**
|
|
111
135
|
* Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
|
|
112
136
|
* early (`testsprite ... | head`) exits cleanly instead of crashing with an
|
|
113
|
-
* unhandled `write EPIPE` stack.
|
|
114
|
-
*
|
|
137
|
+
* unhandled `write EPIPE` stack. An armed stdout path requests graceful
|
|
138
|
+
* shutdown before exiting 0; a disarmed one exits 0 immediately. Only `EPIPE`
|
|
139
|
+
* is swallowed; any other stream error is left to surface normally.
|
|
115
140
|
*/
|
|
116
141
|
export declare function installBrokenPipeGuard(deps?: BrokenPipeDeps): void;
|
package/dist/lib/interrupt.js
CHANGED
|
@@ -12,8 +12,10 @@
|
|
|
12
12
|
* Broken pipe: when output is piped to a reader that closes early
|
|
13
13
|
* (`testsprite ... | head`), the kernel raises `EPIPE` on the next stdout write.
|
|
14
14
|
* Node turns an `'error'` with no listener into an uncaughtException and dumps a
|
|
15
|
-
* raw `write EPIPE` stack (exit 1).
|
|
16
|
-
* conventional SIGPIPE-equivalent result
|
|
15
|
+
* raw `write EPIPE` stack (exit 1). Outside an armed lifetime the guard exits
|
|
16
|
+
* 0 immediately, the conventional SIGPIPE-equivalent result. While armed it
|
|
17
|
+
* first requests coordinated shutdown so tunnel cleanup can finish, then the
|
|
18
|
+
* same synthetic interrupt reason preserves exit 0.
|
|
17
19
|
*
|
|
18
20
|
* `process` and the streams are injectable so the wiring is unit-testable
|
|
19
21
|
* without spawning a subprocess or sending a real signal.
|
|
@@ -31,7 +33,7 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
|
|
|
31
33
|
* Two modes, chosen by whether a graceful-detach scope is armed when the
|
|
32
34
|
* signal arrives:
|
|
33
35
|
*
|
|
34
|
-
* - **Armed** (inside `pollRunUntilTerminal`): the handler only aborts
|
|
36
|
+
* - **Armed** (inside `pollRunUntilTerminal` or a tunnel lifetime): the handler only aborts
|
|
35
37
|
* `signal` with an `InterruptError` — no I/O, no exit. The in-flight fetch
|
|
36
38
|
* and every backoff sleep bail immediately; the `--wait` catch blocks own
|
|
37
39
|
* the cleanup (finalize the ticker, print the honest partial envelope +
|
|
@@ -41,13 +43,14 @@ export const SIGINT_EXIT_CODE = TERMINATION_EXIT_CODES.SIGINT;
|
|
|
41
43
|
* immediately, preserving the pre-DEV-331 behavior. An abort nobody
|
|
42
44
|
* observes must never leave the process hanging at e.g. a readline prompt.
|
|
43
45
|
*
|
|
44
|
-
* A
|
|
45
|
-
*
|
|
46
|
+
* A repeated signal still provides a bounded escape hatch: the second waits
|
|
47
|
+
* briefly only when critical cleanup is in flight, and the third exits at once.
|
|
46
48
|
*/
|
|
47
49
|
export class ShutdownController {
|
|
48
50
|
controller = new AbortController();
|
|
51
|
+
criticalOperations = new Set();
|
|
49
52
|
armedCount = 0;
|
|
50
|
-
|
|
53
|
+
receivedCause = null;
|
|
51
54
|
constructor() {
|
|
52
55
|
// Every fetch and every poll iteration composes this signal via
|
|
53
56
|
// AbortSignal.any — a 50-run batch fan-out legitimately holds >10
|
|
@@ -57,9 +60,9 @@ export class ShutdownController {
|
|
|
57
60
|
get signal() {
|
|
58
61
|
return this.controller.signal;
|
|
59
62
|
}
|
|
60
|
-
/** The first
|
|
63
|
+
/** The first graceful-shutdown cause received, or null if none yet. */
|
|
61
64
|
get received() {
|
|
62
|
-
return this.
|
|
65
|
+
return this.receivedCause;
|
|
63
66
|
}
|
|
64
67
|
get isArmed() {
|
|
65
68
|
return this.armedCount > 0;
|
|
@@ -78,11 +81,56 @@ export class ShutdownController {
|
|
|
78
81
|
this.armedCount -= 1;
|
|
79
82
|
};
|
|
80
83
|
}
|
|
84
|
+
/** Whether teardown currently has work whose abrupt loss is security-sensitive. */
|
|
85
|
+
get hasCriticalOperations() {
|
|
86
|
+
return this.criticalOperations.size > 0;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Register cleanup before it starts and remove it automatically when it
|
|
90
|
+
* settles. Rejections retain their original semantics for the caller.
|
|
91
|
+
*/
|
|
92
|
+
runCriticalOperation(operation) {
|
|
93
|
+
const started = Promise.resolve().then(operation);
|
|
94
|
+
const tracked = started.finally(() => {
|
|
95
|
+
this.criticalOperations.delete(tracked);
|
|
96
|
+
});
|
|
97
|
+
this.criticalOperations.add(tracked);
|
|
98
|
+
return tracked;
|
|
99
|
+
}
|
|
100
|
+
/** Wait until all current and directly chained critical cleanup settles. */
|
|
101
|
+
async waitForCriticalOperations() {
|
|
102
|
+
while (this.criticalOperations.size > 0) {
|
|
103
|
+
await Promise.allSettled([...this.criticalOperations]);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
81
106
|
/** Record the signal and abort with an `InterruptError` carrying it. */
|
|
82
107
|
interrupt(signal) {
|
|
83
|
-
this.
|
|
108
|
+
this.receivedCause = signal;
|
|
84
109
|
this.controller.abort(new InterruptError(signal));
|
|
85
110
|
}
|
|
111
|
+
/**
|
|
112
|
+
* Abort an armed lifetime after stdout's reader closes. The InterruptError
|
|
113
|
+
* subtype deliberately keeps the existing graceful-detach catch paths in
|
|
114
|
+
* play (including tunnel cancellation), while its exit code stays the
|
|
115
|
+
* SIGPIPE-equivalent success code 0.
|
|
116
|
+
*/
|
|
117
|
+
brokenPipe() {
|
|
118
|
+
if (this.receivedCause !== null)
|
|
119
|
+
return;
|
|
120
|
+
this.receivedCause = 'EPIPE';
|
|
121
|
+
this.controller.abort(new BrokenPipeInterruptError());
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
class BrokenPipeInterruptError extends InterruptError {
|
|
125
|
+
exitCode = 0;
|
|
126
|
+
constructor() {
|
|
127
|
+
// Existing graceful-detach consumers read `.signal` to render their
|
|
128
|
+
// partial status. The distinct name/message and exitCode carry the real
|
|
129
|
+
// cause without widening the OS-signal contract in errors.ts.
|
|
130
|
+
super('SIGINT');
|
|
131
|
+
this.name = 'BrokenPipeInterruptError';
|
|
132
|
+
this.message = 'Output pipe closed.';
|
|
133
|
+
}
|
|
86
134
|
}
|
|
87
135
|
/**
|
|
88
136
|
* The process-wide instance: `index.ts` hands it to `installSignalHandlers`,
|
|
@@ -95,6 +143,38 @@ export function formatInterruptMessage(signal = 'SIGINT') {
|
|
|
95
143
|
return (`Interrupted (${signal}). Any run already started keeps executing on the server; ` +
|
|
96
144
|
'check it with `testsprite test list` or `testsprite test wait <runId>`.');
|
|
97
145
|
}
|
|
146
|
+
const CRITICAL_OPERATION_GRACE_MS = 2_000;
|
|
147
|
+
/** How often the grace period re-checks whether teardown is still running. */
|
|
148
|
+
const CRITICAL_OPERATION_POLL_MS = 10;
|
|
149
|
+
function afterDelay(ms) {
|
|
150
|
+
return new Promise(resolve => {
|
|
151
|
+
const timer = setTimeout(resolve, ms);
|
|
152
|
+
timer.unref?.();
|
|
153
|
+
});
|
|
154
|
+
}
|
|
155
|
+
async function waitForCriticalOperationsWithGrace(shutdown) {
|
|
156
|
+
const graceExpired = afterDelay(CRITICAL_OPERATION_GRACE_MS);
|
|
157
|
+
const teardownFinished = (async () => {
|
|
158
|
+
// An armed scope is the honest signal that teardown has not finished. On a
|
|
159
|
+
// tunnel run it spans the whole unwind — cancel, then close, then the
|
|
160
|
+
// credential delete — and those register one at a time with gaps between
|
|
161
|
+
// them, so "no critical operation right now" does not mean "done". A fixed
|
|
162
|
+
// settle window is the wrong shape: measured against the real command, the
|
|
163
|
+
// first registration lands well after any window short enough to keep the
|
|
164
|
+
// escape hatch snappy. Waiting for the scope to close instead tracks the
|
|
165
|
+
// actual work, and the caller's overall cap keeps it bounded.
|
|
166
|
+
while (shutdown.isArmed) {
|
|
167
|
+
if (shutdown.hasCriticalOperations) {
|
|
168
|
+
await shutdown.waitForCriticalOperations();
|
|
169
|
+
}
|
|
170
|
+
else {
|
|
171
|
+
await afterDelay(CRITICAL_OPERATION_POLL_MS);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
await shutdown.waitForCriticalOperations();
|
|
175
|
+
})();
|
|
176
|
+
await Promise.race([graceExpired, teardownFinished]);
|
|
177
|
+
}
|
|
98
178
|
/**
|
|
99
179
|
* Register handlers for SIGINT, SIGTERM and SIGHUP. Idempotent enough for a
|
|
100
180
|
* single top-level call in `index.ts`; not designed to be installed twice.
|
|
@@ -102,8 +182,9 @@ export function formatInterruptMessage(signal = 'SIGINT') {
|
|
|
102
182
|
* First signal, armed scope: abort-only — the `--wait` catch paths own the
|
|
103
183
|
* honest-detach UX and the exit (DEV-331 D1: Ctrl-C = detach, never cancel).
|
|
104
184
|
* First signal, disarmed: print the generic explanation + exit `128+signum`.
|
|
105
|
-
* Second signal
|
|
106
|
-
*
|
|
185
|
+
* Second signal: exit immediately unless critical cleanup is registered; when
|
|
186
|
+
* it is, wait at most two seconds before exiting. Third signal: always exit
|
|
187
|
+
* immediately, including while that grace period is active.
|
|
107
188
|
*/
|
|
108
189
|
export function installSignalHandlers(deps = {}) {
|
|
109
190
|
const on = deps.on ??
|
|
@@ -124,13 +205,38 @@ export function installSignalHandlers(deps = {}) {
|
|
|
124
205
|
});
|
|
125
206
|
const exit = deps.exit ?? ((code) => process.exit(code));
|
|
126
207
|
const shutdown = deps.shutdown ?? globalShutdown;
|
|
208
|
+
let signalCount = 0;
|
|
209
|
+
let graceGeneration = 0;
|
|
127
210
|
for (const signal of Object.keys(TERMINATION_EXIT_CODES)) {
|
|
128
211
|
on(signal, () => {
|
|
129
|
-
|
|
130
|
-
|
|
212
|
+
signalCount += 1;
|
|
213
|
+
if (signalCount >= 3) {
|
|
214
|
+
// Invalidate any second-signal grace continuation before hard exit.
|
|
215
|
+
graceGeneration += 1;
|
|
131
216
|
exit(TERMINATION_EXIT_CODES[signal]);
|
|
132
217
|
return;
|
|
133
218
|
}
|
|
219
|
+
if (signalCount === 2) {
|
|
220
|
+
// `isArmed` matters as much as an already-registered operation: on a
|
|
221
|
+
// tunnel run the lifecycle scope stays armed across teardown, and the
|
|
222
|
+
// credential delete is registered only after the poll loop unwinds. A
|
|
223
|
+
// second signal that arrives in between — which is what a reflexive
|
|
224
|
+
// double Ctrl-C actually does — would otherwise hard-exit and strand a
|
|
225
|
+
// live inbound credential until its TTL, the exact outcome the grace
|
|
226
|
+
// period exists to prevent.
|
|
227
|
+
if (!shutdown.hasCriticalOperations && !shutdown.isArmed) {
|
|
228
|
+
exit(TERMINATION_EXIT_CODES[signal]);
|
|
229
|
+
return;
|
|
230
|
+
}
|
|
231
|
+
const generation = ++graceGeneration;
|
|
232
|
+
void waitForCriticalOperationsWithGrace(shutdown).then(() => {
|
|
233
|
+
// A third signal already took the immediate path.
|
|
234
|
+
if (graceGeneration !== generation)
|
|
235
|
+
return;
|
|
236
|
+
exit(TERMINATION_EXIT_CODES[signal]);
|
|
237
|
+
});
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
134
240
|
if (shutdown.isArmed) {
|
|
135
241
|
// Graceful detach: abort only (sync, signal-safe — no I/O here so a
|
|
136
242
|
// pending stdout `drain` wait can settle); the armed catch paths
|
|
@@ -154,18 +260,27 @@ export function installSignalHandlers(deps = {}) {
|
|
|
154
260
|
/**
|
|
155
261
|
* Guard against `EPIPE` on stdout/stderr so piping to a reader that closes
|
|
156
262
|
* early (`testsprite ... | head`) exits cleanly instead of crashing with an
|
|
157
|
-
* unhandled `write EPIPE` stack.
|
|
158
|
-
*
|
|
263
|
+
* unhandled `write EPIPE` stack. An armed stdout path requests graceful
|
|
264
|
+
* shutdown before exiting 0; a disarmed one exits 0 immediately. Only `EPIPE`
|
|
265
|
+
* is swallowed; any other stream error is left to surface normally.
|
|
159
266
|
*/
|
|
160
267
|
export function installBrokenPipeGuard(deps = {}) {
|
|
161
268
|
const stdout = deps.stdout ?? process.stdout;
|
|
162
269
|
const stderr = deps.stderr ?? process.stderr;
|
|
163
270
|
const exit = deps.exit ?? ((code) => process.exit(code));
|
|
271
|
+
const shutdown = deps.shutdown ?? globalShutdown;
|
|
164
272
|
stdout.on('error', (error) => {
|
|
165
273
|
// Reader went away (`| head`, `| less` then q): exit cleanly like SIGPIPE
|
|
166
274
|
// rather than dumping an unhandled `write EPIPE` stack. Any other stdout
|
|
167
275
|
// error is a genuine, actionable failure, so re-throw it (Node's default).
|
|
168
276
|
if (error.code === 'EPIPE') {
|
|
277
|
+
if (shutdown.isArmed) {
|
|
278
|
+
// A tunnel lifetime owns credential teardown in its `finally`. Abort
|
|
279
|
+
// through the same coordinator as the first signal and let that
|
|
280
|
+
// cleanup finish; the synthetic reason exits 0 once it propagates.
|
|
281
|
+
shutdown.brokenPipe();
|
|
282
|
+
return;
|
|
283
|
+
}
|
|
169
284
|
exit(0);
|
|
170
285
|
return;
|
|
171
286
|
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `--local <port>` argument handling and the pre-charge port probe.
|
|
3
|
+
*
|
|
4
|
+
* Separate from `target-url-preflight.ts` on purpose, even though both answer
|
|
5
|
+
* "is the thing I am about to bill a run against actually there". They probe
|
|
6
|
+
* two different mechanisms and must not share one:
|
|
7
|
+
*
|
|
8
|
+
* - `--target-url` is fetched by a browser inside a Lambda, so probing it
|
|
9
|
+
* with `fetch()` (proxy dispatcher and all) is the closest local analogue,
|
|
10
|
+
* and an ambiguous result downgrades to a warning because the CLI is not
|
|
11
|
+
* the machine that will do the fetching.
|
|
12
|
+
* - `--local <port>` is dialled by the vendored tunnel client running *in
|
|
13
|
+
* this very process*, with `net.connect`, against the candidate set
|
|
14
|
+
* {@link resolveDialCandidates} produces. So the probe uses that same
|
|
15
|
+
* function and the same kind of socket. A pass means at least one TCP
|
|
16
|
+
* connection actually completed; every other result refuses. In
|
|
17
|
+
* particular, `ETIMEDOUT` can be a dropped SYN with no listener at all,
|
|
18
|
+
* so it is not evidence that something is bound. That is why this one is
|
|
19
|
+
* allowed to be the gate that runs BEFORE the mint and therefore before
|
|
20
|
+
* any run row or credit spend exists.
|
|
21
|
+
*/
|
|
22
|
+
/**
|
|
23
|
+
* The loopback spellings a tunnel target may use.
|
|
24
|
+
*
|
|
25
|
+
* This is a MIRROR of the server's `isLoopbackString`
|
|
26
|
+
* (backend-v2.0 `libs/net/private-address.ts`), which accepts exactly
|
|
27
|
+
* `localhost`, `127.0.0.1` and `::1` — not "anything in 127.0.0.0/8". Keeping
|
|
28
|
+
* the two identical is the whole point of validating client-side at all: a
|
|
29
|
+
* value this accepts and the server rejects would fail with
|
|
30
|
+
* `tunnel-target-not-local` AFTER a tunnel had already been minted, and a
|
|
31
|
+
* value this rejects but the server accepts is a capability silently withheld.
|
|
32
|
+
*/
|
|
33
|
+
export declare const LOOPBACK_HOSTS: readonly ["localhost", "127.0.0.1", "::1"];
|
|
34
|
+
export type LoopbackHost = (typeof LOOPBACK_HOSTS)[number];
|
|
35
|
+
/** Default `--local-host`. An IP literal, so no resolver is involved at all. */
|
|
36
|
+
export declare const DEFAULT_LOCAL_HOST: LoopbackHost;
|
|
37
|
+
/**
|
|
38
|
+
* Per-candidate dial budget. Deliberately short: this is a loopback connect on
|
|
39
|
+
* the caller's own machine, where a live listener answers in microseconds. A
|
|
40
|
+
* long budget would only lengthen the wait before an honest refusal.
|
|
41
|
+
*/
|
|
42
|
+
export declare const LOCAL_PORT_PROBE_TIMEOUT_MS = 2000;
|
|
43
|
+
export type LocalPortProbeOutcome = {
|
|
44
|
+
verdict: 'ok';
|
|
45
|
+
} | {
|
|
46
|
+
verdict: 'refuse';
|
|
47
|
+
reason: string;
|
|
48
|
+
};
|
|
49
|
+
export interface LocalPortProbeDeps {
|
|
50
|
+
/**
|
|
51
|
+
* Dial one candidate; resolve on connect, reject on failure. Defaults to a
|
|
52
|
+
* real `net.connect`. Injectable so a test can prove the
|
|
53
|
+
* `--skip-preflight` path makes ZERO attempts — the assertion that matters
|
|
54
|
+
* for the pre-charge guarantee.
|
|
55
|
+
*/
|
|
56
|
+
connect?: (host: string, port: number, timeoutMs: number) => Promise<void>;
|
|
57
|
+
/** Candidate resolver. Defaults to the vendored client's own. */
|
|
58
|
+
resolveCandidates?: (host: string, port: number) => Promise<Array<{
|
|
59
|
+
host: string;
|
|
60
|
+
port: number;
|
|
61
|
+
}>>;
|
|
62
|
+
}
|
|
63
|
+
/** Parse `--local <port>`. Strict: this becomes part of a URL a run is billed against. */
|
|
64
|
+
export declare function parseLocalPort(raw: string): number;
|
|
65
|
+
/**
|
|
66
|
+
* Normalise and validate `--local-host`. Rejects everything outside
|
|
67
|
+
* {@link LOOPBACK_HOSTS} with zero network calls — a tunnel reaches the
|
|
68
|
+
* caller's own machine and nothing else, so a non-loopback value here is a
|
|
69
|
+
* misunderstanding to correct immediately, not a request to forward.
|
|
70
|
+
*/
|
|
71
|
+
export declare function normalizeLocalHost(raw: string | undefined): LoopbackHost;
|
|
72
|
+
/** `http://<host>:<port>`, with IPv6 bracketed as the URL grammar requires. */
|
|
73
|
+
export declare function buildLocalTargetUrl(host: LoopbackHost, port: number): string;
|
|
74
|
+
/**
|
|
75
|
+
* Dial every candidate {@link resolveDialCandidates} produces for
|
|
76
|
+
* `host:port`. ANY successful connect is a pass — `localhost` resolves to both
|
|
77
|
+
* `127.0.0.1` and `::1`, and a dev server bound to one family must never be
|
|
78
|
+
* reported dead because the other refused.
|
|
79
|
+
*/
|
|
80
|
+
export declare function probeLocalPort(host: string, port: number, deps?: LocalPortProbeDeps): Promise<LocalPortProbeOutcome>;
|
|
81
|
+
/**
|
|
82
|
+
* Run {@link probeLocalPort} and either throw (refuse) or no-op (ok / skipped).
|
|
83
|
+
*
|
|
84
|
+
* Call this BEFORE minting a tunnel. That ordering is the feature: DEV-243
|
|
85
|
+
* measured 1,003 blocked-with-URL CLI runs, 55.5% of the third-party-tunnel
|
|
86
|
+
* ones blocked, every one of them charged, because the run row and its credit
|
|
87
|
+
* spend happen before the Lambda ever discovers the target is dead. A dev
|
|
88
|
+
* server that is not running is the single most likely `--local` mistake, and
|
|
89
|
+
* this is the only place it can be caught for free.
|
|
90
|
+
*
|
|
91
|
+
* `skipPreflight: true` is a pure no-op with ZERO connection attempts.
|
|
92
|
+
*/
|
|
93
|
+
export declare function assertLocalPortListening(host: LoopbackHost | string, port: number, opts: {
|
|
94
|
+
skipPreflight?: boolean;
|
|
95
|
+
}, _stderrFn: (line: string) => void, deps?: LocalPortProbeDeps): Promise<void>;
|