@testsprite/testsprite-cli 0.5.0 → 0.7.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.
Files changed (51) hide show
  1. package/README.md +39 -30
  2. package/dist/commands/agent.js +44 -42
  3. package/dist/commands/doctor.d.ts +1 -1
  4. package/dist/commands/doctor.js +4 -7
  5. package/dist/commands/project.js +3 -2
  6. package/dist/commands/schedule.d.ts +120 -0
  7. package/dist/commands/schedule.js +487 -0
  8. package/dist/commands/test.d.ts +55 -1
  9. package/dist/commands/test.js +714 -183
  10. package/dist/commands/testlist.d.ts +88 -0
  11. package/dist/commands/testlist.js +747 -0
  12. package/dist/index.js +6 -2
  13. package/dist/lib/agent-targets.d.ts +13 -4
  14. package/dist/lib/agent-targets.js +11 -2
  15. package/dist/lib/conflict-reason.d.ts +30 -0
  16. package/dist/lib/conflict-reason.js +45 -0
  17. package/dist/lib/credentials.js +42 -1
  18. package/dist/lib/cron.d.ts +40 -0
  19. package/dist/lib/cron.js +190 -0
  20. package/dist/lib/dry-run/samples.js +177 -55
  21. package/dist/lib/errors.d.ts +9 -0
  22. package/dist/lib/errors.js +11 -0
  23. package/dist/lib/gh-output.d.ts +51 -4
  24. package/dist/lib/gh-output.js +149 -19
  25. package/dist/lib/http.d.ts +25 -0
  26. package/dist/lib/http.js +201 -3
  27. package/dist/lib/junit-report.d.ts +20 -2
  28. package/dist/lib/junit-report.js +38 -5
  29. package/dist/lib/poll.js +72 -36
  30. package/dist/lib/proxy.d.ts +16 -0
  31. package/dist/lib/proxy.js +19 -1
  32. package/dist/lib/response-schemas.d.ts +7 -0
  33. package/dist/lib/response-schemas.js +46 -14
  34. package/dist/lib/runs.types.d.ts +8 -3
  35. package/dist/lib/secret-file.d.ts +15 -0
  36. package/dist/lib/secret-file.js +82 -0
  37. package/dist/lib/target-url-preflight.d.ts +91 -0
  38. package/dist/lib/target-url-preflight.js +259 -0
  39. package/dist/lib/target-url.d.ts +22 -5
  40. package/dist/lib/target-url.js +60 -28
  41. package/dist/lib/testlist.types.d.ts +77 -0
  42. package/dist/lib/testlist.types.js +9 -0
  43. package/dist/lib/v3-advisory.d.ts +37 -4
  44. package/dist/lib/v3-advisory.js +47 -4
  45. package/dist/lib/wait-exit.d.ts +29 -0
  46. package/dist/lib/wait-exit.js +103 -0
  47. package/dist/version-guard.d.ts +10 -7
  48. package/dist/version-guard.js +37 -9
  49. package/dist/version.d.ts +1 -1
  50. package/dist/version.js +1 -1
  51. package/package.json +2 -1
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, 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, } 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
@@ -41,6 +41,14 @@ const MAX_ATTEMPTS_INTERNAL = 2;
41
41
  const MAX_RATE_LIMITED_DELAY_MS = 60_000;
42
42
  const CONFLICT_DELAY_MS = 1000;
43
43
  const INTERNAL_DELAY_MS = 500;
44
+ // Upper bound on the size of a successful JSON response body the client will
45
+ // buffer into memory. `response.json()` reads the ENTIRE body before parsing,
46
+ // with no limit, so a large `test result --history` page or a run with a long
47
+ // `steps[]` array (getRun `includeSteps`) would grow the heap in proportion to
48
+ // the payload. 64 MiB sits far above any legitimate metadata/history/steps
49
+ // response yet still bounds a pathological — or hostile — one. Override per
50
+ // client via `HttpClientOptions.maxResponseBytes`.
51
+ const MAX_RESPONSE_BYTES_DEFAULT = 64 * 1024 * 1024;
44
52
  // Cap on how many valibot issues a shape-mismatch INTERNAL envelope carries in
45
53
  // `details.issues` (path + message each). Keeps the envelope readable and
46
54
  // guarantees the response body itself is never echoed back to the operator.
@@ -56,6 +64,7 @@ export class HttpClient {
56
64
  onServerVersion;
57
65
  requestTimeoutMs;
58
66
  shutdownSignal;
67
+ maxResponseBytes;
59
68
  constructor(options) {
60
69
  this.baseUrl = trimTrailingSlash(options.baseUrl);
61
70
  this.apiKey = options.apiKey;
@@ -67,6 +76,7 @@ export class HttpClient {
67
76
  this.onTransition = options.onTransition;
68
77
  this.onServerVersion = options.onServerVersion;
69
78
  this.requestTimeoutMs = options.requestTimeoutMs ?? REQUEST_TIMEOUT_DEFAULT_MS;
79
+ this.maxResponseBytes = options.maxResponseBytes ?? MAX_RESPONSE_BYTES_DEFAULT;
70
80
  }
71
81
  /**
72
82
  * Read the backend's supported-floor header off a response and forward it to
@@ -216,6 +226,24 @@ export class HttpClient {
216
226
  retryOnConflict: false,
217
227
  }).then(r => r.body);
218
228
  }
229
+ /**
230
+ * POST /api/cli/v1/testlist/{listId}/run
231
+ * Dispatch a test list's cases (optionally a `testIds` subset) per project
232
+ * with their configured environments; returns pollable runIds. `--wait` polls
233
+ * each `accepted[].runId`.
234
+ *
235
+ * `retryOnConflict: false` — a 409 here (every dispatched project is an
236
+ * MCP-mirrored view-only mirror) is a permanent condition, not a transient one.
237
+ */
238
+ async triggerTestListRun(listId, body, options) {
239
+ return this.postWithMeta(`/testlist/${encodeURIComponent(listId)}/run`, {
240
+ body,
241
+ headers: { 'idempotency-key': options.idempotencyKey },
242
+ signal: options.signal,
243
+ schema: TESTLIST_RUN_RESPONSE_SCHEMA,
244
+ retryOnConflict: false,
245
+ }).then(r => r.body);
246
+ }
219
247
  /**
220
248
  * GET /api/cli/v1/tests/{testId}/runs
221
249
  * List a test's prior run history, newest-first.
@@ -345,7 +373,17 @@ export class HttpClient {
345
373
  // letting a long-poll drain its window before the interrupt surfaces.
346
374
  if (this.shutdownSignal != null)
347
375
  composedSignals.push(this.shutdownSignal);
348
- const effectiveSignal = composedSignals.length > 1 ? AbortSignal.any(composedSignals) : timeoutSignal;
376
+ // Composed via `composeAbortSignals` (manual listeners), NOT the native
377
+ // `AbortSignal.any` — see that function's doc comment. `this.shutdownSignal`
378
+ // is process-lifetime (`globalShutdown.signal`, `client-factory.ts`) and is
379
+ // pushed into `composedSignals` on essentially every request, so
380
+ // `AbortSignal.any` here was measured to register ~330K dependent-signal
381
+ // trackings against that one long-lived signal over a single request-heavy
382
+ // test file — the same `FinalizationRegistry` backlog mechanism already
383
+ // fixed once in `poll.ts`, just recreated per-request instead of
384
+ // per-poll-iteration. `cleanupAbortComposition` MUST be called once the
385
+ // request settles (below, alongside `requestTimeout.clear()`).
386
+ const { signal: effectiveSignal, cleanup: cleanupAbortComposition } = composeAbortSignals(composedSignals);
349
387
  try {
350
388
  try {
351
389
  response = await this.fetchImpl(url, {
@@ -425,12 +463,20 @@ export class HttpClient {
425
463
  });
426
464
  let raw;
427
465
  try {
428
- raw = await response.json();
466
+ // Bounded read, then parse — assigning to `raw` rather than returning
467
+ // here keeps the schema validation below on the success path.
468
+ const text = await readBoundedText(response, this.maxResponseBytes, requestId);
469
+ raw = JSON.parse(text);
429
470
  }
430
471
  catch (err) {
431
472
  // Interrupt passthrough (see the fetch catch above).
432
473
  if (err instanceof InterruptError)
433
474
  throw err;
475
+ // A bounded-read rejection (PAYLOAD_TOO_LARGE) — or any typed ApiError —
476
+ // is a real, actionable outcome; surface it unchanged rather than
477
+ // masking it as a malformed-body error below.
478
+ if (err instanceof ApiError)
479
+ throw err;
434
480
  // A timeout/abort can fire mid-body-read (headers received, stream stalls).
435
481
  this.rethrowIfAbort(err, timeoutSignal, options.signal, requestId, effectiveSignal);
436
482
  // Otherwise the successful response body was not valid JSON — a
@@ -564,6 +610,11 @@ export class HttpClient {
564
610
  }
565
611
  finally {
566
612
  requestTimeout.clear();
613
+ // Remove the manually-added abort listeners now, synchronously —
614
+ // see `composeAbortSignals`. Runs on every path out of the try
615
+ // (return, throw, or `continue` into the next attempt), so nothing
616
+ // outlives the request it was created for.
617
+ cleanupAbortComposition();
567
618
  }
568
619
  }
569
620
  }
@@ -658,6 +709,63 @@ export function buildUrl(baseUrl, path, query) {
658
709
  function newRequestId() {
659
710
  return `cli_${randomUUID()}`;
660
711
  }
712
+ /**
713
+ * Compose multiple `AbortSignal`s into one — abort on whichever fires first —
714
+ * WITHOUT using the native `AbortSignal.any`.
715
+ *
716
+ * `AbortSignal.any` builds a persistent "dependent signal" relationship: the
717
+ * signal it returns is tracked (via a `WeakRef` + `FinalizationRegistry`)
718
+ * against EVERY source signal passed in, including any long-lived one. Every
719
+ * outgoing request here composes `this.shutdownSignal` — process-lifetime
720
+ * (`globalShutdown.signal`, wired by `client-factory.ts` on essentially every
721
+ * command invocation) — into `composedSignals`, so each request added one
722
+ * more tracked dependent against that single long-lived signal, reclaimed
723
+ * only whenever V8 next got around to running ITS `FinalizationRegistry`
724
+ * cleanup pass. Under a request-heavy path (retries, a wide closure/batch
725
+ * fan-out, RATE_LIMITED backoff) this reproduces — per HTTP request instead
726
+ * of per poll-iteration — the exact backlog mechanism already fixed once in
727
+ * `poll.ts` (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
728
+ * `OrderedHashSet::Add` pegging the CPU once the deferred backlog is finally
729
+ * walked). Measured directly: the RATE_LIMITED closure-fanout scenario in
730
+ * `test.rerun.spec.ts` alone drives ~330K `AbortSignal.any` calls against the
731
+ * one process-lifetime `globalShutdown.signal` over the life of that single
732
+ * test file.
733
+ *
734
+ * This performs the identical "first one wins, propagate its `.reason`"
735
+ * composition with a plain `AbortController` and ordinary
736
+ * `addEventListener`/`removeEventListener` — no dependent-signal tracking, no
737
+ * `WeakRef`, no GC-deferred cleanup. The caller MUST invoke the returned
738
+ * `cleanup()` once the request settles (success, error, or retry) so the
739
+ * listeners are removed immediately rather than left for a cleanup pass that,
740
+ * for this composition, no longer exists.
741
+ */
742
+ function composeAbortSignals(signals) {
743
+ if (signals.length <= 1) {
744
+ return { signal: signals[0], cleanup: () => { } };
745
+ }
746
+ // Mirror AbortSignal.any's already-aborted short-circuit: if a source is
747
+ // already aborted at composition time, propagate its reason immediately —
748
+ // no listeners are ever added, so cleanup is a no-op.
749
+ const alreadyAborted = signals.find(s => s.aborted);
750
+ const controller = new AbortController();
751
+ if (alreadyAborted) {
752
+ controller.abort(alreadyAborted.reason);
753
+ return { signal: controller.signal, cleanup: () => { } };
754
+ }
755
+ const removers = [];
756
+ for (const source of signals) {
757
+ const onAbort = () => controller.abort(source.reason);
758
+ source.addEventListener('abort', onAbort, { once: true });
759
+ removers.push(() => source.removeEventListener('abort', onAbort));
760
+ }
761
+ return {
762
+ signal: controller.signal,
763
+ cleanup: () => {
764
+ for (const remove of removers)
765
+ remove();
766
+ },
767
+ };
768
+ }
661
769
  function createRequestTimeout(timeoutMs) {
662
770
  const controller = new AbortController();
663
771
  const timer = setTimeout(() => {
@@ -733,6 +841,96 @@ export function malformedResponseError(response, requestId, cause) {
733
841
  },
734
842
  }, response.status);
735
843
  }
844
+ /**
845
+ * Read a successful response body as text, bounded to `maxBytes`.
846
+ *
847
+ * `response.json()` buffers the ENTIRE body into memory before parsing, with no
848
+ * upper limit — a large `test result --history` page, or a run with a long
849
+ * `steps[]` array (getRun `includeSteps`), grows the heap in proportion to the
850
+ * payload. This reads the body incrementally and stops once the accumulated
851
+ * size crosses `maxBytes`, so a pathological (or hostile) response fails fast
852
+ * with a typed PAYLOAD_TOO_LARGE error instead of exhausting memory.
853
+ *
854
+ * A declared `Content-Length` over the cap is rejected before any body is read.
855
+ * Chunked bodies (no `Content-Length`) are bounded by counting bytes as they
856
+ * stream. Decoding happens once, at the end, so multi-byte UTF-8 sequences that
857
+ * straddle a chunk boundary still decode correctly.
858
+ */
859
+ async function readBoundedText(response, maxBytes, requestId) {
860
+ const declared = Number(response.headers.get('content-length'));
861
+ if (Number.isFinite(declared) && declared > maxBytes) {
862
+ throw responseTooLargeError(requestId, maxBytes, declared);
863
+ }
864
+ const stream = response.body;
865
+ if (stream === null) {
866
+ // No readable stream exposed (some runtimes / test doubles): fall back to a
867
+ // buffered read, then enforce the cap on the materialized text.
868
+ const text = await response.text();
869
+ if (new TextEncoder().encode(text).length > maxBytes) {
870
+ throw responseTooLargeError(requestId, maxBytes);
871
+ }
872
+ return text;
873
+ }
874
+ const reader = stream.getReader();
875
+ const chunks = [];
876
+ let total = 0;
877
+ try {
878
+ for (;;) {
879
+ const { done, value } = await reader.read();
880
+ if (done)
881
+ break;
882
+ if (value === undefined)
883
+ continue;
884
+ total += value.byteLength;
885
+ if (total > maxBytes) {
886
+ await reader.cancel();
887
+ throw responseTooLargeError(requestId, maxBytes, total);
888
+ }
889
+ chunks.push(value);
890
+ }
891
+ }
892
+ finally {
893
+ try {
894
+ reader.releaseLock();
895
+ }
896
+ catch {
897
+ // The reader may already be released after cancel(); releasing twice is a
898
+ // no-op we don't want surfacing over the original error.
899
+ }
900
+ }
901
+ return new TextDecoder('utf-8').decode(concatChunks(chunks, total));
902
+ }
903
+ /** Concatenate byte chunks into a single `Uint8Array` of known total length. */
904
+ function concatChunks(chunks, total) {
905
+ const out = new Uint8Array(total);
906
+ let offset = 0;
907
+ for (const chunk of chunks) {
908
+ out.set(chunk, offset);
909
+ offset += chunk.byteLength;
910
+ }
911
+ return out;
912
+ }
913
+ /**
914
+ * Typed error for a response body that exceeds the client-side buffering cap.
915
+ * Reuses PAYLOAD_TOO_LARGE (exit 5, validation family) — the same code the
916
+ * backend returns for oversized request bodies — so machine consumers route on
917
+ * it uniformly. `nextAction` names the knobs that shrink the result set.
918
+ */
919
+ function responseTooLargeError(requestId, maxBytes, observedBytes) {
920
+ const limitMiB = Math.round(maxBytes / (1024 * 1024));
921
+ return new ApiError({
922
+ code: 'PAYLOAD_TOO_LARGE',
923
+ message: `The server response exceeded the client-side ${limitMiB} MiB limit and was not ` +
924
+ `buffered, to avoid unbounded memory use.`,
925
+ nextAction: 'Narrow the result set and retry — e.g. a smaller --page-size, a tighter --since ' +
926
+ 'window, or scope --history to a single run.',
927
+ requestId,
928
+ details: {
929
+ maxBytes,
930
+ ...(observedBytes !== undefined ? { observedBytes } : {}),
931
+ },
932
+ });
933
+ }
736
934
  export function parseRetryAfter(headerValue) {
737
935
  if (!headerValue)
738
936
  return undefined;
@@ -11,7 +11,24 @@ export interface JUnitTestResult {
11
11
  message: string;
12
12
  exitCode?: number;
13
13
  };
14
+ /**
15
+ * Human-readable test name for the `testcase name` attribute. Falls back to
16
+ * `testId` when absent (older data / a run whose name could not be resolved).
17
+ * A CI test tab renders this, not the UUID.
18
+ */
19
+ name?: string;
20
+ /**
21
+ * Wall-clock duration of the run in seconds, for `testcase time`. Derived from
22
+ * the poll result's `startedAt`/`finishedAt`; omitted when timing is absent
23
+ * (rendered as `0`, the pre-fix behaviour).
24
+ */
25
+ durationSeconds?: number;
14
26
  }
27
+ /**
28
+ * Duration in seconds between two ISO timestamps, or `undefined` when either is
29
+ * missing / unparseable / negative (clock skew). Kept ≥ 0.
30
+ */
31
+ export declare function durationSecondsBetween(startedAt: string | null | undefined, finishedAt: string | null | undefined): number | undefined;
15
32
  export interface JUnitReportBuildOptions {
16
33
  suiteName: string;
17
34
  classname: string;
@@ -48,8 +65,9 @@ export declare function resolveBatchReportProjectId(opts: {
48
65
  */
49
66
  export declare function escapeXml(text: string): string;
50
67
  /**
51
- * Build a JUnit XML document from batch poll results. Duration is `0` in v1
52
- * because batch poll envelopes do not carry per-run timing.
68
+ * Build a JUnit XML document from batch poll results. Per-`testcase` `time` is
69
+ * the run's wall-clock duration (from `startedAt`/`finishedAt`); the `testsuite`
70
+ * `time` is their sum. `time` falls back to `0` for a run with no timing.
53
71
  */
54
72
  export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
55
73
  /**
@@ -3,6 +3,26 @@ import { rename, stat, unlink } from 'node:fs/promises';
3
3
  import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
4
4
  import { randomUUID } from 'node:crypto';
5
5
  import { localValidationError, TransportError } from './errors.js';
6
+ /**
7
+ * Duration in seconds between two ISO timestamps, or `undefined` when either is
8
+ * missing / unparseable / negative (clock skew). Kept ≥ 0.
9
+ */
10
+ export function durationSecondsBetween(startedAt, finishedAt) {
11
+ if (!startedAt || !finishedAt)
12
+ return undefined;
13
+ const start = Date.parse(startedAt);
14
+ const end = Date.parse(finishedAt);
15
+ if (Number.isNaN(start) || Number.isNaN(end))
16
+ return undefined;
17
+ const seconds = (end - start) / 1000;
18
+ return seconds >= 0 ? seconds : undefined;
19
+ }
20
+ /** Format a duration for the JUnit `time` attribute (3 dp; absent → `0`). */
21
+ function formatTime(seconds) {
22
+ if (seconds === undefined || Number.isNaN(seconds))
23
+ return '0';
24
+ return (Math.round(seconds * 1000) / 1000).toString();
25
+ }
6
26
  const XML_DECL = '<?xml version="1.0" encoding="UTF-8"?>';
7
27
  /**
8
28
  * Parse `--report <format>`. Only `junit` is accepted in v1.
@@ -79,9 +99,17 @@ function failureMessage(result) {
79
99
  }
80
100
  function renderTestcase(result, classname) {
81
101
  const outcome = classifyJUnitOutcome(result.status, result.error);
82
- const name = escapeXml(result.testId);
102
+ // A readable CI test tab keys on `name`: prefer the human test name, fall back
103
+ // to the id. The UUID is preserved as a `testId` attribute (ignored by
104
+ // renderers, read by machine consumers) so the switch loses no information.
105
+ const name = escapeXml(result.name?.trim() || result.testId);
83
106
  const cls = escapeXml(classname);
84
- const lines = [` <testcase classname="${cls}" name="${name}" time="0">`];
107
+ const time = formatTime(result.durationSeconds);
108
+ const idAttr = ` testId="${escapeXml(result.testId)}"`;
109
+ const runAttr = result.runId ? ` runId="${escapeXml(result.runId)}"` : '';
110
+ const lines = [
111
+ ` <testcase classname="${cls}" name="${name}"${idAttr}${runAttr} time="${time}">`,
112
+ ];
85
113
  if (outcome === 'failure') {
86
114
  const message = escapeXml(failureMessage(result));
87
115
  const type = escapeXml(result.status);
@@ -114,14 +142,16 @@ function renderTestcase(result, classname) {
114
142
  return lines.join('\n');
115
143
  }
116
144
  /**
117
- * Build a JUnit XML document from batch poll results. Duration is `0` in v1
118
- * because batch poll envelopes do not carry per-run timing.
145
+ * Build a JUnit XML document from batch poll results. Per-`testcase` `time` is
146
+ * the run's wall-clock duration (from `startedAt`/`finishedAt`); the `testsuite`
147
+ * `time` is their sum. `time` falls back to `0` for a run with no timing.
119
148
  */
120
149
  export function buildJUnitReport(opts) {
121
150
  const results = opts.results;
122
151
  let failures = 0;
123
152
  let errors = 0;
124
153
  let skipped = 0;
154
+ let totalSeconds = 0;
125
155
  for (const result of results) {
126
156
  const outcome = classifyJUnitOutcome(result.status, result.error);
127
157
  if (outcome === 'failure')
@@ -130,13 +160,16 @@ export function buildJUnitReport(opts) {
130
160
  errors++;
131
161
  else if (outcome === 'skipped')
132
162
  skipped++;
163
+ if (typeof result.durationSeconds === 'number' && result.durationSeconds >= 0) {
164
+ totalSeconds += result.durationSeconds;
165
+ }
133
166
  }
134
167
  const suiteName = escapeXml(opts.suiteName);
135
168
  const testcases = results.map(r => renderTestcase(r, opts.classname)).join('\n');
136
169
  return [
137
170
  XML_DECL,
138
171
  '<testsuites>',
139
- ` <testsuite name="${suiteName}" tests="${results.length}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="0">`,
172
+ ` <testsuite name="${suiteName}" tests="${results.length}" failures="${failures}" errors="${errors}" skipped="${skipped}" time="${formatTime(totalSeconds)}">`,
140
173
  testcases,
141
174
  ' </testsuite>',
142
175
  '</testsuites>',
package/dist/lib/poll.js CHANGED
@@ -56,7 +56,7 @@ export async function pollRunUntilTerminal(client, runId, options) {
56
56
  }
57
57
  }
58
58
  async function pollLoop(client, runId, options) {
59
- const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
59
+ const { timeoutSeconds, resolveAlternate } = options;
60
60
  const shutdownSignal = options.shutdown?.signal;
61
61
  const rawSleep = options.sleep ?? defaultSleep;
62
62
  // Every sleep site (retryAfterSeconds, backoff schedule, not_yet_visible,
@@ -65,6 +65,68 @@ async function pollLoop(client, runId, options) {
65
65
  const sleep = (ms) => sleepUnlessInterrupted(rawSleep, ms, shutdownSignal);
66
66
  const startMs = Date.now();
67
67
  const deadlineMs = startMs + timeoutSeconds * 1000;
68
+ // Hoisted ONCE per poll *session* rather than re-minted every iteration.
69
+ // The abort target here — deadlineMs + a transport cushion — is a fixed
70
+ // absolute instant that does not change from one iteration to the next
71
+ // (remainingMs shrinks, but remainingMs + TRANSPORT_CUSHION_MS measured
72
+ // from "now" always lands on the same deadlineMs + cushion point). Minting
73
+ // a fresh AbortController + setTimeout + `AbortSignal.any` composite every
74
+ // iteration was therefore pure churn with no behavioral purpose: on a
75
+ // `--wait` fan-out over many concurrent runIds, each polling for many
76
+ // iterations, this created thousands of composite signals per invocation.
77
+ // Every `AbortSignal.any` call registers an internal dependency listener
78
+ // on the long-lived `shutdownSignal`, tracked via a WeakRef +
79
+ // FinalizationRegistry so the listener can be reclaimed once the derived
80
+ // signal is garbage-collected without leaking on the long-lived source —
81
+ // but under a high allocation rate with no macrotask yield between
82
+ // iterations (`TestDeps.sleep` in tests resolves via a bare microtask),
83
+ // V8 can fall behind on running that reclamation incrementally, and the
84
+ // eventual cleanup pass then has to walk a large backlog in one go
85
+ // (`JSFinalizationRegistry::Cleanup` → `KeepDuringJob` →
86
+ // `OrderedHashSet::Add`), pegging the CPU for minutes. One controller,
87
+ // one timer, and one composed signal — created once, reused for every
88
+ // iteration and every retry, cleared once when the session ends —
89
+ // removes that per-iteration scaling factor entirely; the deadline
90
+ // semantics are unchanged, since the abort target was already the same
91
+ // absolute instant on every iteration.
92
+ const TRANSPORT_CUSHION_MS = 2000;
93
+ const deadlineController = new AbortController();
94
+ const deadlineTimer = setTimeout(() => deadlineController.abort(), deadlineMs - startMs + TRANSPORT_CUSHION_MS);
95
+ const sessionSignal = shutdownSignal != null
96
+ ? AbortSignal.any([deadlineController.signal, shutdownSignal])
97
+ : deadlineController.signal;
98
+ // Same hoisting rationale for the `resolveAlternate` abort target
99
+ // (deadlineMs, no cushion — also a fixed absolute instant). Allocated
100
+ // lazily so callers that never pass `resolveAlternate` pay nothing for it.
101
+ let altAbort;
102
+ let altTimer;
103
+ let altSignal;
104
+ if (resolveAlternate) {
105
+ altAbort = new AbortController();
106
+ const controller = altAbort;
107
+ altTimer = setTimeout(() => controller.abort(), deadlineMs - startMs);
108
+ altSignal =
109
+ shutdownSignal != null ? AbortSignal.any([altAbort.signal, shutdownSignal]) : altAbort.signal;
110
+ }
111
+ try {
112
+ return await pollIterations(client, runId, options, {
113
+ startMs,
114
+ deadlineMs,
115
+ sessionSignal,
116
+ altSignal,
117
+ sleep,
118
+ });
119
+ }
120
+ finally {
121
+ clearTimeout(deadlineTimer);
122
+ if (altTimer !== undefined)
123
+ clearTimeout(altTimer);
124
+ }
125
+ }
126
+ async function pollIterations(client, runId, options, ctx) {
127
+ const { timeoutSeconds, onTick, onTransition, resolveAlternate } = options;
128
+ const shutdownSignal = options.shutdown?.signal;
129
+ const { startMs, deadlineMs, sessionSignal, altSignal, sleep } = ctx;
68
130
  // Track whether the server supports ?waitSeconds. Start optimistic.
69
131
  let useBackoff = false;
70
132
  let backoffIndex = 0;
@@ -82,36 +144,20 @@ async function pollLoop(client, runId, options) {
82
144
  }
83
145
  const remainingMs = deadlineMs - now;
84
146
  const remainingSeconds = Math.ceil(remainingMs / 1000);
85
- // Mint a per-iteration AbortController. The signal fires at the remaining
86
- // deadline plus a small transport cushion (2 s) so a hung fetch does not
87
- // block the CLI past --timeout.
88
- const TRANSPORT_CUSHION_MS = 2000;
89
- const abortController = new AbortController();
90
- const abortTimer = setTimeout(() => {
91
- abortController.abort();
92
- }, remainingMs + TRANSPORT_CUSHION_MS);
93
- // Compose the interrupt into the per-iteration signal: a `--wait` can sit
94
- // inside one <=25s long-poll fetch (and the auto-raised per-request
95
- // timeout means even longer for slow backends) — checking the flag
96
- // between iterations is not enough, the in-flight fetch must abort.
97
- const iterationSignal = shutdownSignal != null
98
- ? AbortSignal.any([abortController.signal, shutdownSignal])
99
- : abortController.signal;
100
147
  let run;
101
148
  try {
102
149
  if (useBackoff) {
103
- run = await client.getRun(runId, { signal: iterationSignal });
150
+ run = await client.getRun(runId, { signal: sessionSignal });
104
151
  }
105
152
  else {
106
153
  const waitSeconds = Math.min(remainingSeconds, LONG_POLL_WAIT_SECONDS);
107
- run = await client.getRun(runId, { waitSeconds, signal: iterationSignal });
154
+ run = await client.getRun(runId, { waitSeconds, signal: sessionSignal });
108
155
  }
109
156
  // Successful GET resets the consecutive-error counter.
110
157
  consecutiveErrors = 0;
111
158
  notYetVisibleRetries = 0;
112
159
  }
113
160
  catch (err) {
114
- clearTimeout(abortTimer);
115
161
  // Interrupt classification precedes the timeout mapping: the composed
116
162
  // signal makes the fetch reject on Ctrl-C, and that abort must surface
117
163
  // as the InterruptError — not as a spurious TimeoutError.
@@ -119,8 +165,8 @@ async function pollLoop(client, runId, options) {
119
165
  throw err;
120
166
  if (shutdownSignal?.aborted)
121
167
  throw shutdownSignal.reason;
122
- // An AbortError from our per-iteration controller means the deadline
123
- // passed while the fetch was in flight — surface as TimeoutError.
168
+ // An AbortError from the session controller means the deadline passed
169
+ // while the fetch was in flight — surface as TimeoutError.
124
170
  if (isAbortError(err)) {
125
171
  throw new TimeoutError(runId, timeoutSeconds);
126
172
  }
@@ -170,8 +216,6 @@ async function pollLoop(client, runId, options) {
170
216
  // Everything else propagates.
171
217
  throw err;
172
218
  }
173
- // fetch completed — cancel the per-iteration abort timer.
174
- clearTimeout(abortTimer);
175
219
  const elapsedMs = Date.now() - startMs;
176
220
  onTick?.(run, elapsedMs);
177
221
  if (isTerminalStatus(run.status)) {
@@ -188,21 +232,13 @@ async function pollLoop(client, runId, options) {
188
232
  if (altRemainingMs <= 0) {
189
233
  throw new TimeoutError(runId, timeoutSeconds);
190
234
  }
191
- const altAbort = new AbortController();
192
- const altTimer = setTimeout(() => altAbort.abort(), altRemainingMs);
193
235
  // The alternate lookup aborts on interrupt too; its errors are swallowed
194
236
  // by the fallback (best-effort), so the loop-top interrupt check above
195
- // surfaces the InterruptError on the next iteration.
196
- const altSignal = shutdownSignal != null
197
- ? AbortSignal.any([altAbort.signal, shutdownSignal])
198
- : altAbort.signal;
199
- let alternate;
200
- try {
201
- alternate = await resolveAlternate(run, elapsedMs, altSignal);
202
- }
203
- finally {
204
- clearTimeout(altTimer);
205
- }
237
+ // surfaces the InterruptError on the next iteration. `altSignal` is the
238
+ // hoisted per-session signal (allocated once, above, whenever
239
+ // `resolveAlternate` is present) — reused across every non-terminal
240
+ // tick rather than re-composed each time.
241
+ const alternate = await resolveAlternate(run, elapsedMs, altSignal);
206
242
  // Enforce the hard cap: reject a terminal alternate that only arrived
207
243
  // at/after the deadline, same as the run-row long-poll path below.
208
244
  if (Date.now() >= deadlineMs) {
@@ -27,3 +27,19 @@ export interface ProxyDeps {
27
27
  * Returns whether an agent was installed (observable for tests/debugging).
28
28
  */
29
29
  export declare function maybeInstallProxyAgent(deps?: ProxyDeps): boolean;
30
+ /**
31
+ * Whether the currently-installed global dispatcher is the proxy-aware
32
+ * agent `maybeInstallProxyAgent` installs — i.e., whether a proxy is
33
+ * actually wired up for outgoing `fetch()` calls in this process, not
34
+ * merely whether an `HTTP(S)_PROXY` env var happens to be set.
35
+ *
36
+ * This distinction matters: a CI runner can export `HTTPS_PROXY` for
37
+ * unrelated registry/package-manager egress without that value ever
38
+ * reaching this CLI's proxy path (e.g. it ran before `maybeInstallProxyAgent`
39
+ * executed, or `install()` threw and fell back to the default dispatcher).
40
+ * Consumers that need to know "is my request actually going through a
41
+ * proxy" — the target-url reachability preflight's refuse→warn downgrade,
42
+ * specifically — must check this, not the env var, or an unrelated,
43
+ * unexercised proxy variable silently defangs their guard.
44
+ */
45
+ export declare function isProxyAgentActive(): boolean;
package/dist/lib/proxy.js CHANGED
@@ -1,4 +1,4 @@
1
- import { EnvHttpProxyAgent, setGlobalDispatcher } from 'undici';
1
+ import { EnvHttpProxyAgent, getGlobalDispatcher, setGlobalDispatcher } from 'undici';
2
2
  /**
3
3
  * Install the env-driven proxy dispatcher when any proxy variable is set
4
4
  * (both canonical upper-case and conventional lower-case spellings).
@@ -27,4 +27,22 @@ export function maybeInstallProxyAgent(deps = {}) {
27
27
  return false;
28
28
  }
29
29
  }
30
+ /**
31
+ * Whether the currently-installed global dispatcher is the proxy-aware
32
+ * agent `maybeInstallProxyAgent` installs — i.e., whether a proxy is
33
+ * actually wired up for outgoing `fetch()` calls in this process, not
34
+ * merely whether an `HTTP(S)_PROXY` env var happens to be set.
35
+ *
36
+ * This distinction matters: a CI runner can export `HTTPS_PROXY` for
37
+ * unrelated registry/package-manager egress without that value ever
38
+ * reaching this CLI's proxy path (e.g. it ran before `maybeInstallProxyAgent`
39
+ * executed, or `install()` threw and fell back to the default dispatcher).
40
+ * Consumers that need to know "is my request actually going through a
41
+ * proxy" — the target-url reachability preflight's refuse→warn downgrade,
42
+ * specifically — must check this, not the env var, or an unrelated,
43
+ * unexercised proxy variable silently defangs their guard.
44
+ */
45
+ export function isProxyAgentActive() {
46
+ return getGlobalDispatcher() instanceof EnvHttpProxyAgent;
47
+ }
30
48
  //# sourceMappingURL=proxy.js.map
@@ -33,6 +33,7 @@
33
33
  */
34
34
  import * as v from 'valibot';
35
35
  import type { BatchRerunResponse, BatchRunFreshResponse, ListRunsResponse, RerunResponse, RunResponse, TriggerRunResponse } from './runs.types.js';
36
+ import type { CliTestListRunResponse } from './testlist.types.js';
36
37
  /** Mirrors `RunResponse` (runs.types.ts): `GET /api/cli/v1/runs/{runId}`. */
37
38
  export declare const RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RunResponse>;
38
39
  /** Mirrors `TriggerRunResponse` (runs.types.ts): `POST /tests/{testId}/runs`. */
@@ -43,6 +44,12 @@ export declare const RERUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, RerunRespon
43
44
  export declare const BATCH_RERUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, BatchRerunResponse>;
44
45
  /** Mirrors `BatchRunFreshResponse` (runs.types.ts): `POST /tests/batch/run`. */
45
46
  export declare const BATCH_RUN_FRESH_RESPONSE_SCHEMA: v.GenericSchema<unknown, BatchRunFreshResponse>;
47
+ /**
48
+ * `POST /api/cli/v1/testlist/{listId}/run`. Mirrors the batch-run-fresh shape so
49
+ * the `--wait` fan-out reuses the same poll tail; `conflicts[]` additionally
50
+ * carry the in-flight `currentRunId`, and `reason` marks a nothing-dispatched run.
51
+ */
52
+ export declare const TESTLIST_RUN_RESPONSE_SCHEMA: v.GenericSchema<unknown, CliTestListRunResponse>;
46
53
  /** Mirrors `ListRunsResponse` (runs.types.ts): `GET /tests/{testId}/runs`. */
47
54
  export declare const LIST_RUNS_RESPONSE_SCHEMA: v.GenericSchema<unknown, ListRunsResponse>;
48
55
  /**