@testsprite/testsprite-cli 0.13.0 → 0.14.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 -48
- package/dist/commands/doctor.js +12 -11
- package/dist/commands/project-env.d.ts +11 -1
- package/dist/commands/project-env.js +399 -61
- package/dist/commands/project-sign-in.d.ts +60 -0
- package/dist/commands/project-sign-in.js +289 -0
- package/dist/commands/project.d.ts +9 -0
- package/dist/commands/project.js +68 -28
- package/dist/commands/schedule.d.ts +12 -0
- package/dist/commands/schedule.js +175 -5
- package/dist/commands/test.d.ts +53 -20
- package/dist/commands/test.js +1356 -342
- package/dist/commands/testlist.d.ts +10 -5
- package/dist/commands/testlist.js +170 -30
- package/dist/commands/tunnel.js +11 -5
- package/dist/index.js +12 -37
- package/dist/lib/client-factory.d.ts +12 -1
- package/dist/lib/client-factory.js +14 -4
- package/dist/lib/dry-run/samples.js +53 -0
- package/dist/lib/environment-tunnel.d.ts +109 -0
- package/dist/lib/environment-tunnel.js +465 -0
- package/dist/lib/errors.js +12 -1
- package/dist/lib/gh-output.js +3 -0
- package/dist/lib/http.d.ts +2 -0
- package/dist/lib/junit-report.d.ts +11 -7
- package/dist/lib/junit-report.js +13 -7
- package/dist/lib/local-target.d.ts +13 -3
- package/dist/lib/local-target.js +47 -12
- package/dist/lib/output.js +15 -1
- package/dist/lib/plan-poll.js +3 -4
- package/dist/lib/redact.d.ts +38 -0
- package/dist/lib/redact.js +140 -0
- package/dist/lib/render-error.d.ts +19 -5
- package/dist/lib/render-error.js +31 -0
- package/dist/lib/runs.types.d.ts +9 -1
- package/dist/lib/target-url.js +5 -5
- package/dist/lib/telemetry.d.ts +6 -7
- package/dist/lib/telemetry.js +11 -4
- package/dist/lib/testlist.types.d.ts +1 -0
- package/dist/lib/ticker.d.ts +9 -0
- package/dist/lib/ticker.js +18 -0
- package/dist/lib/tunnel-session.d.ts +3 -4
- package/dist/lib/tunnel-session.js +3 -4
- package/dist/lib/v3-advisory.js +0 -1
- package/dist/vendor/tunnel-client/client.d.ts +15 -8
- package/dist/vendor/tunnel-client/client.js +477 -407
- package/dist/vendor/tunnel-client/config.d.ts +5 -5
- package/dist/vendor/tunnel-client/config.js +5 -5
- package/dist/vendor/tunnel-client/index.d.ts +4 -4
- package/dist/vendor/tunnel-client/index.js +4 -4
- package/dist/vendor/tunnel-client/types.d.ts +19 -34
- package/dist/vendor/tunnel-client/types.js +1 -0
- package/dist/vendor/tunnel-client/ws-compat.d.ts +13 -3
- package/dist/vendor/tunnel-client/ws-compat.js +70 -12
- package/dist/version.d.ts +1 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
- package/skills/testsprite-onboard.skill.md +4 -4
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { type CommonOptions, type ClientFactoryDeps } from './client-factory.js';
|
|
2
|
+
import { type ShutdownHandle } from './interrupt.js';
|
|
3
|
+
import { openTunnelSession, type TunnelClientHandle } from './tunnel-session.js';
|
|
4
|
+
import { type TunnelClientOptions } from '../vendor/tunnel-client/index.js';
|
|
5
|
+
import type { HttpClient } from './http.js';
|
|
6
|
+
import type { RunResponse } from './runs.types.js';
|
|
7
|
+
import { ApiError } from './errors.js';
|
|
8
|
+
import { type LoopbackHost, type StoredLocalTarget } from './local-target.js';
|
|
9
|
+
export interface RunTargetTest {
|
|
10
|
+
type: 'frontend' | 'backend';
|
|
11
|
+
projectId: string;
|
|
12
|
+
}
|
|
13
|
+
interface Environment {
|
|
14
|
+
name: string;
|
|
15
|
+
url: string;
|
|
16
|
+
isDefault?: boolean;
|
|
17
|
+
isTemporary?: boolean;
|
|
18
|
+
}
|
|
19
|
+
export interface ResolvedRunTarget extends StoredLocalTarget {
|
|
20
|
+
targetUrl: string;
|
|
21
|
+
automatic: boolean;
|
|
22
|
+
environmentName?: string;
|
|
23
|
+
}
|
|
24
|
+
export declare const ENVIRONMENT_PREFLIGHT_TIMEOUT_MS = 5000;
|
|
25
|
+
/** Advisory-only reads must not inherit the run's long wait or retry budget. */
|
|
26
|
+
export declare function readEnvironmentPreflight<T>(client: Pick<HttpClient, 'get'>, path: string): Promise<T>;
|
|
27
|
+
export declare function assertNoTunnelOptions(args: {
|
|
28
|
+
tunnelClientId?: string;
|
|
29
|
+
cancelOnInterrupt?: boolean;
|
|
30
|
+
}): void;
|
|
31
|
+
export declare function severalIdsWithoutTunnel(): never;
|
|
32
|
+
/** One resolver for fresh runs, replay, chained creation and test-list runs. */
|
|
33
|
+
export declare function resolveEnvironmentRunTarget(args: {
|
|
34
|
+
client: Pick<HttpClient, 'get'>;
|
|
35
|
+
testId?: string;
|
|
36
|
+
knownTest?: RunTargetTest;
|
|
37
|
+
skipTestLookup?: boolean;
|
|
38
|
+
includeBackend?: boolean;
|
|
39
|
+
dryRun?: boolean;
|
|
40
|
+
projectId?: string;
|
|
41
|
+
environment?: string;
|
|
42
|
+
localPort?: number;
|
|
43
|
+
localHost?: LoopbackHost;
|
|
44
|
+
targetUrl?: string;
|
|
45
|
+
tunnelClientId?: string;
|
|
46
|
+
noWait?: boolean;
|
|
47
|
+
verbose?: boolean;
|
|
48
|
+
stderr: (line: string) => void;
|
|
49
|
+
cache?: Map<string, Environment[] | undefined>;
|
|
50
|
+
}): Promise<ResolvedRunTarget | undefined>;
|
|
51
|
+
export declare function tunnelScopeError(err: unknown): unknown;
|
|
52
|
+
export declare function unsupportedTunnelError(command: string): ApiError;
|
|
53
|
+
export interface EnvironmentTunnelContext {
|
|
54
|
+
client: HttpClient;
|
|
55
|
+
clientId: string;
|
|
56
|
+
targets?: ReadonlyMap<string, ResolvedRunTarget>;
|
|
57
|
+
maxConcurrency: number;
|
|
58
|
+
deadlineMs: number;
|
|
59
|
+
session: Awaited<ReturnType<typeof openTunnelSession>>;
|
|
60
|
+
cancellation: (runId: string) => 'cancelled' | 'cancel-failed' | undefined;
|
|
61
|
+
skipped?: Array<{
|
|
62
|
+
testId: string;
|
|
63
|
+
reason: 'backend-test';
|
|
64
|
+
}>;
|
|
65
|
+
terminalRun: (runId: string) => RunResponse | undefined;
|
|
66
|
+
waitForCapacity: (incoming: number) => Promise<void>;
|
|
67
|
+
confirm: (response: {
|
|
68
|
+
tunnelClientId?: string;
|
|
69
|
+
}, runIds: string[], requireEcho?: boolean) => Promise<void>;
|
|
70
|
+
onPoll: (run: {
|
|
71
|
+
runId: string;
|
|
72
|
+
status: string;
|
|
73
|
+
}) => void;
|
|
74
|
+
}
|
|
75
|
+
/** Replay and list dispatch keep their existing envelopes under one owned tunnel. */
|
|
76
|
+
export declare function withEnvironmentTunnel<T>(opts: CommonOptions & {
|
|
77
|
+
skipPreflight?: boolean;
|
|
78
|
+
maxConcurrency?: number;
|
|
79
|
+
timeoutSeconds?: number;
|
|
80
|
+
}, deps: ClientFactoryDeps & {
|
|
81
|
+
shutdown?: ShutdownHandle;
|
|
82
|
+
createTunnelClient?: (options: TunnelClientOptions) => TunnelClientHandle;
|
|
83
|
+
sleep?: (ms: number) => Promise<void>;
|
|
84
|
+
}, targets: ResolvedRunTarget[], command: string, operation: (context: EnvironmentTunnelContext) => Promise<T>): Promise<T>;
|
|
85
|
+
/** Keep each dispatch on one verbatim loopback URL; public runs omit tunnel fields. */
|
|
86
|
+
export declare function groupEnvironmentTargets(ids: string[], targets: ReadonlyMap<string, ResolvedRunTarget>, maxLocalGroupSize?: number): string[][];
|
|
87
|
+
export declare function quoteEnvironmentName(name: string): string;
|
|
88
|
+
export declare function emitEnvironmentDispatchPartial(responses: Array<{
|
|
89
|
+
accepted: Array<{
|
|
90
|
+
testId: string;
|
|
91
|
+
runId: string;
|
|
92
|
+
}>;
|
|
93
|
+
conflicts: Array<{
|
|
94
|
+
testId: string;
|
|
95
|
+
}>;
|
|
96
|
+
deferred: Array<{
|
|
97
|
+
testId: string;
|
|
98
|
+
}>;
|
|
99
|
+
notFound?: string[];
|
|
100
|
+
}>, testIds: string[], opts: CommonOptions & {
|
|
101
|
+
report?: 'junit';
|
|
102
|
+
reportFile?: string;
|
|
103
|
+
reportSuiteName?: string;
|
|
104
|
+
ghOutput?: boolean;
|
|
105
|
+
summaryFile?: string;
|
|
106
|
+
}, deps: ClientFactoryDeps & {
|
|
107
|
+
stdout?: (line: string) => void;
|
|
108
|
+
}, label: string, error: unknown, context: EnvironmentTunnelContext): Promise<void>;
|
|
109
|
+
export {};
|
|
@@ -0,0 +1,465 @@
|
|
|
1
|
+
import { makeHttpClient, resolveRequestTimeoutMs, } from './client-factory.js';
|
|
2
|
+
import { globalShutdown } from './interrupt.js';
|
|
3
|
+
import { openTunnelSession, TunnelLostError } from './tunnel-session.js';
|
|
4
|
+
import { TunnelClient } from '../vendor/tunnel-client/index.js';
|
|
5
|
+
import { assertLocalPortListening } from './local-target.js';
|
|
6
|
+
import { recordTelemetryTunnelOpened } from './telemetry.js';
|
|
7
|
+
import { Output } from './output.js';
|
|
8
|
+
import { emitCiArtifacts, summarizeAcceptedPayload } from './gh-output.js';
|
|
9
|
+
import { buildJUnitReport, writeJUnitReportFile } from './junit-report.js';
|
|
10
|
+
import { pollRunUntilTerminal, TimeoutError, isTerminalStatus } from './poll.js';
|
|
11
|
+
import { ApiError, InterruptError, RequestTimeoutError, localValidationError } from './errors.js';
|
|
12
|
+
import { buildLocalTargetUrl, DEFAULT_LOCAL_HOST, parseLoopbackTargetUrl, } from './local-target.js';
|
|
13
|
+
export const ENVIRONMENT_PREFLIGHT_TIMEOUT_MS = 5_000;
|
|
14
|
+
/** Advisory-only reads must not inherit the run's long wait or retry budget. */
|
|
15
|
+
export function readEnvironmentPreflight(client, path) {
|
|
16
|
+
return client.get(path, {
|
|
17
|
+
retry: false,
|
|
18
|
+
signal: AbortSignal.timeout(ENVIRONMENT_PREFLIGHT_TIMEOUT_MS),
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
export function assertNoTunnelOptions(args) {
|
|
22
|
+
if (args.tunnelClientId !== undefined)
|
|
23
|
+
throw localValidationError('tunnel-client', '--tunnel-client only applies with --local (it attaches the run to an already-running ' +
|
|
24
|
+
'tunnel). Add --local <port>, or remove --tunnel-client');
|
|
25
|
+
if (args.cancelOnInterrupt === false)
|
|
26
|
+
throw localValidationError('cancel-on-interrupt', '--no-cancel-on-interrupt only applies with --local. An ordinary run is never ' +
|
|
27
|
+
'cancelled when this command stops waiting — Ctrl-C detaches, and `testsprite test ' +
|
|
28
|
+
'cancel <run-id>` is the way to stop one');
|
|
29
|
+
}
|
|
30
|
+
export function severalIdsWithoutTunnel() {
|
|
31
|
+
throw localValidationError('test-id', 'several test ids run through one tunnel with --local <port>. For tests the runner can already reach, use `testsprite test run --all --project <id> [--filter <text>]`, or run them one at a time.');
|
|
32
|
+
}
|
|
33
|
+
const announcedEnvironments = new WeakMap();
|
|
34
|
+
/** One resolver for fresh runs, replay, chained creation and test-list runs. */
|
|
35
|
+
export async function resolveEnvironmentRunTarget(args) {
|
|
36
|
+
const explicitUrl = args.targetUrl === undefined ? undefined : parseLoopbackTargetUrl(args.targetUrl);
|
|
37
|
+
const explicit = args.localPort !== undefined || explicitUrl !== undefined;
|
|
38
|
+
if (args.targetUrl !== undefined && !explicitUrl)
|
|
39
|
+
return undefined;
|
|
40
|
+
let test = args.knownTest;
|
|
41
|
+
if (!test && args.testId && !args.skipTestLookup) {
|
|
42
|
+
try {
|
|
43
|
+
test = await readEnvironmentPreflight(args.client, `/tests/${encodeURIComponent(args.testId)}`);
|
|
44
|
+
}
|
|
45
|
+
catch (err) {
|
|
46
|
+
if (err instanceof InterruptError)
|
|
47
|
+
throw err;
|
|
48
|
+
if (explicit) {
|
|
49
|
+
if (err instanceof ApiError &&
|
|
50
|
+
(err.httpStatus === 403 || err.httpStatus === 404 || err.code === 'UNAVAILABLE')) {
|
|
51
|
+
throw new ApiError({
|
|
52
|
+
code: err.code,
|
|
53
|
+
message: `Cannot read test ${args.testId} for --local preflight.`,
|
|
54
|
+
nextAction: 'Check the test ID and read:tests permission, then retry.',
|
|
55
|
+
requestId: err.requestId,
|
|
56
|
+
details: {},
|
|
57
|
+
}, err.httpStatus);
|
|
58
|
+
}
|
|
59
|
+
throw err;
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
if (test?.type === 'backend' && !args.includeBackend) {
|
|
65
|
+
if (explicit)
|
|
66
|
+
throw localValidationError('local', `backend tests don't open a browser; the tunnel is not used. Run: testsprite test run ${args.testId}`);
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
const projectId = test?.projectId ?? args.projectId;
|
|
70
|
+
let environments;
|
|
71
|
+
if (projectId) {
|
|
72
|
+
if (args.cache?.has(projectId))
|
|
73
|
+
environments = args.cache.get(projectId);
|
|
74
|
+
else {
|
|
75
|
+
try {
|
|
76
|
+
const listing = await readEnvironmentPreflight(args.client, `/projects/${encodeURIComponent(projectId)}/env`);
|
|
77
|
+
if (Array.isArray(listing.environments))
|
|
78
|
+
environments = listing.environments;
|
|
79
|
+
}
|
|
80
|
+
catch (err) {
|
|
81
|
+
if (err instanceof InterruptError)
|
|
82
|
+
throw err;
|
|
83
|
+
// Read scope, old routes and transient failures do not change legacy runs.
|
|
84
|
+
if (args.verbose)
|
|
85
|
+
args.stderr('[verbose] environment preflight skipped: project environments unavailable; the server will validate this run.');
|
|
86
|
+
}
|
|
87
|
+
args.cache?.set(projectId, environments);
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const selected = args.environment === undefined
|
|
91
|
+
? (environments?.find(row => row.isDefault) ?? environments?.find(row => !row.isTemporary))
|
|
92
|
+
: environments?.find(row => row.name === args.environment);
|
|
93
|
+
if (explicit && args.environment !== undefined && environments && !selected) {
|
|
94
|
+
const available = environments.map(row => row.name).sort();
|
|
95
|
+
throw localValidationError('env', `unknown environment '${args.environment}'; use one of: ${available.join(', ')}`, available);
|
|
96
|
+
}
|
|
97
|
+
const localOf = (row) => {
|
|
98
|
+
if (!row || typeof row.url !== 'string')
|
|
99
|
+
return undefined;
|
|
100
|
+
try {
|
|
101
|
+
return parseLoopbackTargetUrl(row.url);
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return undefined;
|
|
105
|
+
}
|
|
106
|
+
};
|
|
107
|
+
const announced = args.cache
|
|
108
|
+
? (announcedEnvironments.get(args.cache) ?? new Set())
|
|
109
|
+
: new Set();
|
|
110
|
+
if (args.cache)
|
|
111
|
+
announcedEnvironments.set(args.cache, announced);
|
|
112
|
+
const announce = (key, line) => {
|
|
113
|
+
if (!announced.has(key))
|
|
114
|
+
args.stderr(line);
|
|
115
|
+
announced.add(key);
|
|
116
|
+
};
|
|
117
|
+
const explicitTarget = (target) => {
|
|
118
|
+
if (args.environment !== undefined && selected && !localOf(selected))
|
|
119
|
+
announce(`sign-in:${projectId}:${selected.name}:${target.targetUrl}`, `Using environment "${selected.name}" sign-in against ${target.targetUrl} through a tunnel.`);
|
|
120
|
+
return target;
|
|
121
|
+
};
|
|
122
|
+
if (explicitUrl)
|
|
123
|
+
return explicitTarget({ ...explicitUrl, targetUrl: args.targetUrl, automatic: false });
|
|
124
|
+
if (args.localPort !== undefined) {
|
|
125
|
+
const selectedHost = localOf(selected)?.host;
|
|
126
|
+
const matching = environments?.filter(row => !row.isTemporary && localOf(row)?.port === args.localPort) ?? [];
|
|
127
|
+
const hosts = new Set(matching.map(row => localOf(row).host));
|
|
128
|
+
const host = args.localHost ??
|
|
129
|
+
selectedHost ??
|
|
130
|
+
(hosts.size === 1 ? [...hosts][0] : undefined) ??
|
|
131
|
+
(environments === undefined ? '127.0.0.1' : DEFAULT_LOCAL_HOST);
|
|
132
|
+
return explicitTarget({
|
|
133
|
+
host,
|
|
134
|
+
port: args.localPort,
|
|
135
|
+
targetUrl: buildLocalTargetUrl(host, args.localPort),
|
|
136
|
+
automatic: false,
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
const local = localOf(selected);
|
|
140
|
+
if (!local)
|
|
141
|
+
return undefined;
|
|
142
|
+
if (args.noWait) {
|
|
143
|
+
announce(`no-wait:${projectId}:${selected.name}:${selected.url}`, '[hint] This environment needs a tunnel; drop --no-wait to run through a tunnel.');
|
|
144
|
+
return undefined;
|
|
145
|
+
}
|
|
146
|
+
if (!args.tunnelClientId && test?.type !== 'backend') {
|
|
147
|
+
const key = `${projectId}:${selected.name}:${selected.url}`;
|
|
148
|
+
announce(key, args.dryRun
|
|
149
|
+
? `Would open a tunnel to ${selected.url} (environment "${selected.name}").`
|
|
150
|
+
: `Environment "${selected.name}" is on this machine (${selected.url}) — opening a tunnel.`);
|
|
151
|
+
}
|
|
152
|
+
return {
|
|
153
|
+
...local,
|
|
154
|
+
targetUrl: selected.url,
|
|
155
|
+
automatic: args.tunnelClientId === undefined,
|
|
156
|
+
environmentName: selected.name,
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
export function tunnelScopeError(err) {
|
|
160
|
+
if (!(err instanceof ApiError) || err.httpStatus !== 403)
|
|
161
|
+
return err;
|
|
162
|
+
return new ApiError({
|
|
163
|
+
code: err.code,
|
|
164
|
+
message: err.message,
|
|
165
|
+
requestId: err.requestId,
|
|
166
|
+
details: err.details,
|
|
167
|
+
nextAction: `${err.nextAction ?? ''} A tunnel is required for this environment; use an API key with run:tunnel permission.`,
|
|
168
|
+
}, err.httpStatus);
|
|
169
|
+
}
|
|
170
|
+
export function unsupportedTunnelError(command) {
|
|
171
|
+
return new ApiError({
|
|
172
|
+
code: 'UNSUPPORTED',
|
|
173
|
+
message: `This server did not confirm tunnel use for ${command}. Cancellation was attempted for the started runs; no tunnel-free result can be trusted.`,
|
|
174
|
+
nextAction: 'Update the server, or use testsprite test run <id> with the saved environment.',
|
|
175
|
+
requestId: 'local',
|
|
176
|
+
details: {},
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
/** Replay and list dispatch keep their existing envelopes under one owned tunnel. */
|
|
180
|
+
export async function withEnvironmentTunnel(opts, deps, targets, command, operation) {
|
|
181
|
+
const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
|
|
182
|
+
const shutdown = deps.shutdown ?? globalShutdown;
|
|
183
|
+
const seen = new Set();
|
|
184
|
+
for (const target of targets) {
|
|
185
|
+
if (seen.has(target.targetUrl))
|
|
186
|
+
continue;
|
|
187
|
+
seen.add(target.targetUrl);
|
|
188
|
+
await assertLocalPortListening(target.host, target.port, { ...opts, ...(target.automatic ? { environmentName: target.environmentName } : {}) }, stderr);
|
|
189
|
+
}
|
|
190
|
+
const requestTimeoutMs = resolveRequestTimeoutMs(opts, deps.env ?? process.env);
|
|
191
|
+
const request = async (timeoutMs, operation) => {
|
|
192
|
+
const deadline = new AbortController();
|
|
193
|
+
const timer = setTimeout(() => deadline.abort(new RequestTimeoutError(timeoutMs)), timeoutMs);
|
|
194
|
+
timer.unref?.();
|
|
195
|
+
try {
|
|
196
|
+
return await operation(makeHttpClient({ ...opts, requestTimeoutMs: timeoutMs }, { ...deps, shutdownSignal: deadline.signal, shutdown }));
|
|
197
|
+
}
|
|
198
|
+
finally {
|
|
199
|
+
clearTimeout(timer);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
const cleanup = (operation) => request(10_000, operation);
|
|
203
|
+
const client = makeHttpClient(opts, { ...deps, shutdownSignal: shutdown.signal, shutdown });
|
|
204
|
+
const active = new Set();
|
|
205
|
+
const terminalRuns = new Map();
|
|
206
|
+
const getRun = client.getRun.bind(client);
|
|
207
|
+
client.getRun = async (runId, options) => {
|
|
208
|
+
const cached = terminalRuns.get(runId);
|
|
209
|
+
if (cached)
|
|
210
|
+
return cached;
|
|
211
|
+
const run = await getRun(runId, options);
|
|
212
|
+
if (isTerminalStatus(run.status))
|
|
213
|
+
terminalRuns.set(runId, run);
|
|
214
|
+
return run;
|
|
215
|
+
};
|
|
216
|
+
const cancellations = new Map();
|
|
217
|
+
let failure;
|
|
218
|
+
let context;
|
|
219
|
+
const cancel = async () => {
|
|
220
|
+
for (const runId of active) {
|
|
221
|
+
try {
|
|
222
|
+
await cleanup(transport => transport.cancelRun(runId));
|
|
223
|
+
cancellations.set(runId, 'cancelled');
|
|
224
|
+
stderr(`[tunnel] Cancellation requested for ${runId}; the owned tunnel is closing.`);
|
|
225
|
+
}
|
|
226
|
+
catch (err) {
|
|
227
|
+
cancellations.set(runId, 'failed');
|
|
228
|
+
stderr(`[tunnel] Could not cancel ${runId}: ${err instanceof Error ? err.message : String(err)}. Use testsprite test cancel ${runId}.`);
|
|
229
|
+
}
|
|
230
|
+
active.delete(runId);
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
const disarm = shutdown.arm();
|
|
234
|
+
let session;
|
|
235
|
+
try {
|
|
236
|
+
try {
|
|
237
|
+
session = await openTunnelSession({ log: stderr, logLevel: opts.debug ? 'debug' : opts.verbose ? 'info' : 'error' }, {
|
|
238
|
+
mint: ttlSeconds => request(requestTimeoutMs, transport => transport.mintTunnel({ ...(ttlSeconds ? { ttlSeconds } : {}) })),
|
|
239
|
+
destroy: clientId => cleanup(transport => transport.deleteTunnel(clientId)),
|
|
240
|
+
createClient: shutdownAwareTunnelClient(deps.createTunnelClient ?? (options => new TunnelClient(options)), shutdown.signal),
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
catch (err) {
|
|
244
|
+
throw tunnelScopeError(err);
|
|
245
|
+
}
|
|
246
|
+
recordTelemetryTunnelOpened(true);
|
|
247
|
+
if (shutdown.signal.aborted)
|
|
248
|
+
throw shutdown.signal.reason;
|
|
249
|
+
const checkDispatch = () => {
|
|
250
|
+
if (shutdown.signal.aborted)
|
|
251
|
+
throw shutdown.signal.reason;
|
|
252
|
+
if (session.fatalReason())
|
|
253
|
+
throw new TunnelLostError(session.fatalReason(), '', session.fatalMessage());
|
|
254
|
+
};
|
|
255
|
+
// Retain a charged response across the first interrupt, with a total retry deadline.
|
|
256
|
+
const dispatch = (operation) => {
|
|
257
|
+
checkDispatch();
|
|
258
|
+
return request(requestTimeoutMs, operation);
|
|
259
|
+
};
|
|
260
|
+
client.triggerRerun = (...args) => dispatch(transport => transport.triggerRerun(...args));
|
|
261
|
+
client.triggerBatchRerun = (...args) => dispatch(transport => transport.triggerBatchRerun(...args));
|
|
262
|
+
client.triggerTestListRun = (...args) => dispatch(transport => transport.triggerTestListRun(...args));
|
|
263
|
+
client.triggerRunWithMeta = (...args) => dispatch(transport => transport.triggerRunWithMeta(...args));
|
|
264
|
+
const deadlineMs = Date.now() + (opts.timeoutSeconds ?? 600) * 1000;
|
|
265
|
+
const assertCapacityDeadline = () => {
|
|
266
|
+
if (Date.now() >= deadlineMs)
|
|
267
|
+
throw new ApiError({
|
|
268
|
+
code: 'UNSUPPORTED',
|
|
269
|
+
message: `Timed out after ${opts.timeoutSeconds ?? 600}s waiting for tunnel batch capacity.`,
|
|
270
|
+
nextAction: 'The owned tunnel is closing; inspect cancellation with testsprite test cancel <run-id>.',
|
|
271
|
+
requestId: 'local',
|
|
272
|
+
details: {},
|
|
273
|
+
});
|
|
274
|
+
};
|
|
275
|
+
context = {
|
|
276
|
+
client,
|
|
277
|
+
session,
|
|
278
|
+
deadlineMs,
|
|
279
|
+
cancellation: id => {
|
|
280
|
+
const outcome = cancellations.get(id);
|
|
281
|
+
return outcome === 'failed' ? 'cancel-failed' : outcome;
|
|
282
|
+
},
|
|
283
|
+
clientId: session.clientId,
|
|
284
|
+
maxConcurrency: opts.maxConcurrency ?? 5,
|
|
285
|
+
terminalRun: runId => terminalRuns.get(runId),
|
|
286
|
+
waitForCapacity: async (incoming) => {
|
|
287
|
+
assertCapacityDeadline();
|
|
288
|
+
while (active.size + incoming > (opts.maxConcurrency ?? 5)) {
|
|
289
|
+
const runId = active.values().next().value;
|
|
290
|
+
try {
|
|
291
|
+
await pollRunUntilTerminal(client, runId, {
|
|
292
|
+
timeoutSeconds: Math.max(0, (deadlineMs - Date.now()) / 1000),
|
|
293
|
+
shutdown,
|
|
294
|
+
sleep: deps.sleep,
|
|
295
|
+
onTick: run => context.onPoll(run),
|
|
296
|
+
});
|
|
297
|
+
}
|
|
298
|
+
catch (err) {
|
|
299
|
+
if (!(err instanceof TimeoutError))
|
|
300
|
+
throw err;
|
|
301
|
+
throw new ApiError({
|
|
302
|
+
code: 'UNSUPPORTED',
|
|
303
|
+
message: err.message,
|
|
304
|
+
nextAction: `The owned tunnel is closing; inspect cancellation with testsprite test cancel ${runId}.`,
|
|
305
|
+
requestId: 'local',
|
|
306
|
+
details: { runId },
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
assertCapacityDeadline();
|
|
311
|
+
},
|
|
312
|
+
confirm: async (response, runIds, requireEcho = true) => {
|
|
313
|
+
for (const id of runIds)
|
|
314
|
+
active.add(id);
|
|
315
|
+
if (requireEcho && runIds.length && response.tunnelClientId !== session.clientId) {
|
|
316
|
+
await cancel();
|
|
317
|
+
throw unsupportedTunnelError(command);
|
|
318
|
+
}
|
|
319
|
+
},
|
|
320
|
+
onPoll: run => {
|
|
321
|
+
if (['passed', 'failed', 'blocked', 'cancelled'].includes(run.status))
|
|
322
|
+
active.delete(run.runId);
|
|
323
|
+
else if (active.has(run.runId) && session.fatalReason())
|
|
324
|
+
throw new TunnelLostError(session.fatalReason(), run.runId, session.fatalMessage());
|
|
325
|
+
},
|
|
326
|
+
};
|
|
327
|
+
return await operation(context);
|
|
328
|
+
}
|
|
329
|
+
catch (err) {
|
|
330
|
+
failure = err;
|
|
331
|
+
throw err;
|
|
332
|
+
}
|
|
333
|
+
finally {
|
|
334
|
+
const closing = [...active];
|
|
335
|
+
await cancel();
|
|
336
|
+
if (failure instanceof InterruptError && closing.length) {
|
|
337
|
+
const runId = closing[0];
|
|
338
|
+
const cancelOutcome = closing.every(id => cancellations.get(id) === 'cancelled')
|
|
339
|
+
? 'cancelled'
|
|
340
|
+
: 'failed';
|
|
341
|
+
const retry = [...(context?.targets ?? [])]
|
|
342
|
+
.map(([id, target]) => `testsprite test run ${id}${target.environmentName ? ` --env ${quoteEnvironmentName(target.environmentName)}` : ''}`)
|
|
343
|
+
.join('; ') || 'testsprite test run <id>';
|
|
344
|
+
const nextAction = `The owned tunnel is closing; cancellation was ${cancelOutcome === 'cancelled' ? 'requested' : 'attempted'} for ${closing.join(' ')}. Inspect with testsprite test cancel ${closing.join(' ')}. Start a new run with ${retry}.`;
|
|
345
|
+
Object.assign(failure, {
|
|
346
|
+
runWaitContext: true,
|
|
347
|
+
tunnelDetach: { runId, cancel: cancelOutcome, nextAction },
|
|
348
|
+
});
|
|
349
|
+
}
|
|
350
|
+
try {
|
|
351
|
+
await session?.close();
|
|
352
|
+
}
|
|
353
|
+
finally {
|
|
354
|
+
disarm();
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
function shutdownAwareTunnelClient(create, signal) {
|
|
359
|
+
return options => {
|
|
360
|
+
const client = create(options);
|
|
361
|
+
return {
|
|
362
|
+
start: async () => {
|
|
363
|
+
if (signal.aborted)
|
|
364
|
+
throw signal.reason;
|
|
365
|
+
await new Promise((resolve, reject) => {
|
|
366
|
+
const abort = () => reject(signal.reason);
|
|
367
|
+
signal.addEventListener('abort', abort, { once: true });
|
|
368
|
+
client
|
|
369
|
+
.start()
|
|
370
|
+
.then(resolve, reject)
|
|
371
|
+
.finally(() => signal.removeEventListener('abort', abort));
|
|
372
|
+
});
|
|
373
|
+
},
|
|
374
|
+
stop: () => {
|
|
375
|
+
const stopped = client.stop();
|
|
376
|
+
if (!signal.aborted)
|
|
377
|
+
return stopped;
|
|
378
|
+
void stopped.catch(() => { });
|
|
379
|
+
return Promise.resolve();
|
|
380
|
+
},
|
|
381
|
+
};
|
|
382
|
+
};
|
|
383
|
+
}
|
|
384
|
+
/** Keep each dispatch on one verbatim loopback URL; public runs omit tunnel fields. */
|
|
385
|
+
export function groupEnvironmentTargets(ids, targets, maxLocalGroupSize = Infinity) {
|
|
386
|
+
const groups = new Map();
|
|
387
|
+
for (const id of ids) {
|
|
388
|
+
const key = targets.get(id)?.targetUrl;
|
|
389
|
+
const group = groups.get(key) ?? [];
|
|
390
|
+
group.push(id);
|
|
391
|
+
groups.set(key, group);
|
|
392
|
+
}
|
|
393
|
+
return [...groups.values()].flatMap(group => {
|
|
394
|
+
if (!targets.has(group[0]) || !Number.isFinite(maxLocalGroupSize))
|
|
395
|
+
return [group];
|
|
396
|
+
const chunks = [];
|
|
397
|
+
for (let index = 0; index < group.length; index += maxLocalGroupSize)
|
|
398
|
+
chunks.push(group.slice(index, index + maxLocalGroupSize));
|
|
399
|
+
return chunks;
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
export function quoteEnvironmentName(name) {
|
|
403
|
+
return "'" + name.replaceAll("'", "'\\''") + "'";
|
|
404
|
+
}
|
|
405
|
+
export async function emitEnvironmentDispatchPartial(responses, testIds, opts, deps, label, error, context) {
|
|
406
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
407
|
+
const timedOut = error instanceof RequestTimeoutError ||
|
|
408
|
+
(error instanceof ApiError && error.code === 'UNSUPPORTED' && message.startsWith('Timed out'));
|
|
409
|
+
const accepted = responses
|
|
410
|
+
.flatMap(response => response.accepted)
|
|
411
|
+
.map(row => ({
|
|
412
|
+
...row,
|
|
413
|
+
status: context.cancellation(row.runId) ??
|
|
414
|
+
context.terminalRun(row.runId)?.status ??
|
|
415
|
+
(timedOut ? 'timeout' : 'running'),
|
|
416
|
+
}));
|
|
417
|
+
const conflicts = responses.flatMap(response => response.conflicts);
|
|
418
|
+
const deferred = responses.flatMap(response => response.deferred);
|
|
419
|
+
const notFound = responses.flatMap(response => response.notFound ?? []);
|
|
420
|
+
const seen = new Set([...accepted, ...conflicts, ...deferred].map(row => row.testId));
|
|
421
|
+
for (const id of notFound)
|
|
422
|
+
seen.add(id);
|
|
423
|
+
const notRunTestIds = testIds.filter(id => !seen.has(id));
|
|
424
|
+
const partial = {
|
|
425
|
+
accepted,
|
|
426
|
+
conflicts,
|
|
427
|
+
deferred,
|
|
428
|
+
...(context.skipped?.length ? { skipped: context.skipped } : {}),
|
|
429
|
+
notRunTestIds,
|
|
430
|
+
...(responses.some(response => response.notFound) ? { notFound } : {}),
|
|
431
|
+
};
|
|
432
|
+
const stderr = deps.stderr ?? (line => process.stderr.write(`${line}\n`));
|
|
433
|
+
new Output(opts.output, { stdout: deps.stdout, stderr: deps.stderr }).print(partial, () => accepted.map(row => `${row.runId} ${row.status}`).join('\n'));
|
|
434
|
+
const summary = summarizeAcceptedPayload(JSON.stringify(partial));
|
|
435
|
+
summary.runs.push(...notRunTestIds.map(testId => ({
|
|
436
|
+
testId,
|
|
437
|
+
status: 'skipped',
|
|
438
|
+
error: 'not dispatched before the owned tunnel closed',
|
|
439
|
+
})));
|
|
440
|
+
summary.total += notRunTestIds.length;
|
|
441
|
+
summary.skipped += notRunTestIds.length;
|
|
442
|
+
emitCiArtifacts(summary, opts, {
|
|
443
|
+
env: deps.env ?? process.env,
|
|
444
|
+
stdout: deps.stdout ?? (line => process.stdout.write(`${line}\n`)),
|
|
445
|
+
stderr,
|
|
446
|
+
}, label);
|
|
447
|
+
if (opts.report === 'junit' && opts.reportFile !== undefined) {
|
|
448
|
+
try {
|
|
449
|
+
await writeJUnitReportFile(opts.reportFile, buildJUnitReport({
|
|
450
|
+
suiteName: opts.reportSuiteName ?? `testsprite:${label}`,
|
|
451
|
+
classname: label,
|
|
452
|
+
results: summary.runs.map(row => ({
|
|
453
|
+
testId: row.testId,
|
|
454
|
+
runId: row.runId,
|
|
455
|
+
status: row.status,
|
|
456
|
+
error: { code: error instanceof ApiError ? error.code : 'UNSUPPORTED', message },
|
|
457
|
+
})),
|
|
458
|
+
}));
|
|
459
|
+
}
|
|
460
|
+
catch (err) {
|
|
461
|
+
stderr(`Could not write the partial JUnit report: ${err instanceof Error ? err.message : String(err)}`);
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
//# sourceMappingURL=environment-tunnel.js.map
|
package/dist/lib/errors.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { resolvePortalBase } from './facade.js';
|
|
2
|
+
import { redactDeep } from './redact.js';
|
|
2
3
|
import { classifyBillingRefusal, gateRefusalOf } from './billing-refusal.js';
|
|
3
4
|
/**
|
|
4
5
|
* Error codes shared with the backend facade and the MCP plugin.
|
|
@@ -227,7 +228,17 @@ export class ApiError extends CLIError {
|
|
|
227
228
|
this.requestId = envelope.requestId;
|
|
228
229
|
this.nextAction = envelope.nextAction;
|
|
229
230
|
this.serverNextAction = serverNextAction ?? envelope.nextAction;
|
|
230
|
-
|
|
231
|
+
// Redact at the single point every ApiError is constructed — server
|
|
232
|
+
// envelopes (fromEnvelope), locally-fabricated ones (authRequired,
|
|
233
|
+
// localValidationError), and any future direct `new ApiError(...)` — so
|
|
234
|
+
// `.details` and `.getDetail(...)` are already clean everywhere they are
|
|
235
|
+
// read: `Output.error`'s JSON envelope, `index.ts`'s hand-built ApiError
|
|
236
|
+
// envelope, and the AUTH_FORBIDDEN/CLIENT_TOO_OLD/AMBIGUOUS_ORG text-mode
|
|
237
|
+
// blocks in `index.ts` that print specific detail keys directly (those
|
|
238
|
+
// never go through `Output.error` at all, so redacting only at the
|
|
239
|
+
// render call sites would miss them). Server envelopes are already
|
|
240
|
+
// redacted server-side; this is defence in depth, not the only layer.
|
|
241
|
+
this.details = redactDeep(envelope.details);
|
|
231
242
|
this.httpStatus = httpStatus;
|
|
232
243
|
this.apiUrl = apiUrl;
|
|
233
244
|
this.retryAfterMs = retryAfterMs;
|
package/dist/lib/gh-output.js
CHANGED
|
@@ -84,6 +84,9 @@ export function summarizeAcceptedPayload(capturedJson, opts = {}) {
|
|
|
84
84
|
: [];
|
|
85
85
|
const rows = [
|
|
86
86
|
...acceptedRows,
|
|
87
|
+
...bucketRows(payload.skipped, 'skipped', item => typeof item?.reason === 'string'
|
|
88
|
+
? item.reason
|
|
89
|
+
: 'not dispatched'),
|
|
87
90
|
...bucketRows(payload.deferred, 'deferred', 'rate-deferred (not dispatched)'),
|
|
88
91
|
...bucketRows(payload.conflicts, 'conflict', item => {
|
|
89
92
|
const conflict = item;
|
package/dist/lib/http.d.ts
CHANGED
|
@@ -22,16 +22,17 @@ export interface JUnitTestResult {
|
|
|
22
22
|
name?: string;
|
|
23
23
|
/**
|
|
24
24
|
* Wall-clock duration of the run in seconds, for `testcase time`. Derived from
|
|
25
|
-
* the poll result's `startedAt
|
|
25
|
+
* the poll result's `startedAt` (or `createdAt`) and `finishedAt`; omitted when timing is absent
|
|
26
26
|
* (rendered as `0`, the pre-fix behaviour).
|
|
27
27
|
*/
|
|
28
28
|
durationSeconds?: number;
|
|
29
29
|
}
|
|
30
30
|
/**
|
|
31
31
|
* Duration in seconds between two ISO timestamps, or `undefined` when either is
|
|
32
|
-
* missing / unparseable / negative (clock skew).
|
|
32
|
+
* missing / unparseable / negative (clock skew). Prefer startedAt, falling back
|
|
33
|
+
* to createdAt on servers that do not record a start. Kept ≥ 0.
|
|
33
34
|
*/
|
|
34
|
-
export declare function durationSecondsBetween(startedAt: string | null | undefined, finishedAt: string | null | undefined): number | undefined;
|
|
35
|
+
export declare function durationSecondsBetween(startedAt: string | null | undefined, finishedAt: string | null | undefined, createdAt?: string | null): number | undefined;
|
|
35
36
|
export interface JUnitReportBuildOptions {
|
|
36
37
|
suiteName: string;
|
|
37
38
|
classname: string;
|
|
@@ -75,11 +76,14 @@ export declare function escapeXml(text: string): string;
|
|
|
75
76
|
export declare function buildJUnitReport(opts: JUnitReportBuildOptions): string;
|
|
76
77
|
/**
|
|
77
78
|
* The summary's non-dispatched rows (deferred / conflict / not-found) as
|
|
78
|
-
* skipped JUnit results. Accepted rows carry run statuses and never
|
|
79
|
-
* `isNonDispatchedStatus`,
|
|
80
|
-
*
|
|
79
|
+
* skipped JUnit results. Accepted rows carry run statuses and today never
|
|
80
|
+
* match `isNonDispatchedStatus`, but the two vocabularies are only disjoint
|
|
81
|
+
* by convention: `skipped` is a word both could use. So a member already in
|
|
82
|
+
* `dispatched` (the polled results the caller is writing) is left out here
|
|
83
|
+
* rather than trusted to stay apart, which keeps `tests` from counting one
|
|
84
|
+
* member twice if the server ever reports such a status for an admitted run.
|
|
81
85
|
*/
|
|
82
|
-
export declare function skippedJUnitResultsFromSummary(summary: CiSummary): JUnitTestResult[];
|
|
86
|
+
export declare function skippedJUnitResultsFromSummary(summary: CiSummary, dispatched?: ReadonlyArray<Pick<JUnitTestResult, 'testId'>>): JUnitTestResult[];
|
|
83
87
|
/**
|
|
84
88
|
* Atomically write JUnit XML to `--report-file` (temp sibling + rename).
|
|
85
89
|
*/
|