@devicecloud.dev/dcd 5.14.1 → 5.16.0-beta.1
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 +25 -2
- package/dist/commands/artifacts.d.ts +13 -0
- package/dist/commands/artifacts.js +43 -5
- package/dist/commands/device.d.ts +39 -0
- package/dist/commands/device.js +479 -101
- package/dist/e2e/index.d.ts +4 -0
- package/dist/e2e/index.js +41 -0
- package/dist/e2e/provider.d.ts +80 -0
- package/dist/e2e/provider.js +233 -0
- package/dist/gateways/api-gateway.d.ts +25 -3
- package/dist/gateways/api-gateway.js +68 -6
- package/dist/gateways/device-gateway.d.ts +34 -10
- package/dist/gateways/device-gateway.js +72 -17
- package/dist/mcp/bridge.d.ts +30 -16
- package/dist/mcp/bridge.js +201 -64
- package/dist/mcp/local-files.d.ts +14 -0
- package/dist/mcp/local-files.js +75 -0
- package/dist/mcp/tools/download-artifacts.d.ts +4 -1
- package/dist/mcp/tools/download-artifacts.js +44 -17
- package/dist/services/report-download.service.d.ts +32 -0
- package/dist/services/report-download.service.js +51 -2
- package/dist/services/telemetry.service.d.ts +20 -1
- package/dist/services/telemetry.service.js +27 -6
- package/dist/types/domain/device-session.types.d.ts +73 -3
- package/dist/types/domain/device-session.types.js +2 -0
- package/dist/utils/api-url.d.ts +20 -0
- package/dist/utils/api-url.js +49 -0
- package/dist/utils/app-upload.d.ts +6 -0
- package/dist/utils/app-upload.js +19 -0
- package/dist/utils/config-store.d.ts +5 -1
- package/dist/utils/config-store.js +18 -2
- package/dist/utils/device-artifacts.d.ts +5 -0
- package/dist/utils/device-artifacts.js +22 -0
- package/dist/utils/device-bundle.d.ts +39 -9
- package/dist/utils/device-bundle.js +153 -51
- package/dist/utils/device-flags.d.ts +17 -0
- package/dist/utils/device-flags.js +145 -0
- package/dist/utils/device-output.d.ts +53 -7
- package/dist/utils/device-output.js +148 -21
- package/dist/utils/device-run.d.ts +8 -3
- package/dist/utils/device-run.js +85 -8
- package/dist/utils/zip-integrity.d.ts +21 -0
- package/dist/utils/zip-integrity.js +45 -0
- package/package.json +10 -1
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type DeviceCloudOptions, type DeviceCloudProvider } from './provider.js';
|
|
2
|
+
export type { DeviceCloudOptions, DeviceCloudProvider, E2eDeviceLease, E2eDeviceRequest, E2eReleaseContext, } from './provider.js';
|
|
3
|
+
/** A DeviceCloud device provider, for `mobile({ device })` in an e2e config. */
|
|
4
|
+
export declare function deviceCloud(options?: DeviceCloudOptions): DeviceCloudProvider;
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@devicecloud.dev/dcd/e2e`: run e2e (https://github.com/e2e-inc/e2e) tests
|
|
3
|
+
* on DeviceCloud devices.
|
|
4
|
+
*
|
|
5
|
+
* import { mobile } from '@e2e-dev/mobile';
|
|
6
|
+
* import { deviceCloud } from '@devicecloud.dev/dcd/e2e';
|
|
7
|
+
*
|
|
8
|
+
* const engine = mobile({ platform: 'android', device: deviceCloud() });
|
|
9
|
+
*
|
|
10
|
+
* Each e2e worker gets its own DeviceCloud device session, which shows in the
|
|
11
|
+
* console, is recorded, and is billed like any other. Reads
|
|
12
|
+
* `DEVICE_CLOUD_API_KEY` from the run's environment. Early access: the
|
|
13
|
+
* organization needs it turned on by DeviceCloud.
|
|
14
|
+
*
|
|
15
|
+
* Importing this module has no side effects; it does not start the CLI.
|
|
16
|
+
*/
|
|
17
|
+
import { uploadLocalApp } from '../utils/app-upload.js';
|
|
18
|
+
import { getCliVersion } from '../utils/cli.js';
|
|
19
|
+
import { createProvider, } from './provider.js';
|
|
20
|
+
/** A DeviceCloud device provider, for `mobile({ device })` in an e2e config. */
|
|
21
|
+
export function deviceCloud(options = {}) {
|
|
22
|
+
return createProvider(options, {
|
|
23
|
+
fetch: (input, init) => fetch(input, init),
|
|
24
|
+
pollMs: 3000,
|
|
25
|
+
startTimeoutMs: 20 * 60_000,
|
|
26
|
+
upload: ({ apiKey, apiUrl, filePath, log }) => uploadLocalApp({
|
|
27
|
+
apiUrl,
|
|
28
|
+
auth: {
|
|
29
|
+
headers: {
|
|
30
|
+
'x-app-api-key': apiKey,
|
|
31
|
+
'x-dcd-cli-version': getCliVersion(),
|
|
32
|
+
},
|
|
33
|
+
mode: 'apiKey',
|
|
34
|
+
},
|
|
35
|
+
filePath,
|
|
36
|
+
log,
|
|
37
|
+
showProgress: false,
|
|
38
|
+
}),
|
|
39
|
+
version: getCliVersion(),
|
|
40
|
+
});
|
|
41
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/** What e2e asks for: one device for one worker slot of a run. */
|
|
2
|
+
export interface E2eDeviceRequest {
|
|
3
|
+
readonly platform: 'android' | 'ios';
|
|
4
|
+
/** The agent-device version the e2e client speaks. */
|
|
5
|
+
readonly agentDeviceVersion: string;
|
|
6
|
+
/** The target's `app.bundleId`, when the config names one. */
|
|
7
|
+
readonly app?: string | undefined;
|
|
8
|
+
/** The target's `app.appPath`, resolved to an absolute path, when the config names one. */
|
|
9
|
+
readonly appPath?: string | undefined;
|
|
10
|
+
/** The run's environment. A provider reads its credentials from here, never `process.env`. */
|
|
11
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
12
|
+
/** Aborts when the run is interrupted. */
|
|
13
|
+
readonly signal: AbortSignal;
|
|
14
|
+
/** One line of progress in the run's output. */
|
|
15
|
+
readonly log: (line: string) => void;
|
|
16
|
+
}
|
|
17
|
+
/** One leased device, as `acquire` returns it and `release` gets it back. */
|
|
18
|
+
export interface E2eDeviceLease {
|
|
19
|
+
/** The device session's id. */
|
|
20
|
+
readonly id: string;
|
|
21
|
+
readonly daemon?: {
|
|
22
|
+
readonly authToken: string;
|
|
23
|
+
readonly baseUrl: string;
|
|
24
|
+
} | undefined;
|
|
25
|
+
readonly deviceId?: string | undefined;
|
|
26
|
+
/** The bundle id or package of the build this provider installed from the request's `appPath`. */
|
|
27
|
+
readonly installedApp?: string | undefined;
|
|
28
|
+
}
|
|
29
|
+
/** Handed to `release`, once per lease at the end of the run. */
|
|
30
|
+
export interface E2eReleaseContext {
|
|
31
|
+
readonly env: Readonly<Record<string, string | undefined>>;
|
|
32
|
+
readonly signal: AbortSignal;
|
|
33
|
+
readonly log: (line: string) => void;
|
|
34
|
+
}
|
|
35
|
+
/** A source of DeviceCloud devices for e2e, the shape of `@e2e-dev/mobile`'s `DeviceProvider`. */
|
|
36
|
+
export interface DeviceCloudProvider {
|
|
37
|
+
readonly name: string;
|
|
38
|
+
acquire(request: E2eDeviceRequest): Promise<E2eDeviceLease>;
|
|
39
|
+
release(lease: E2eDeviceLease, context: E2eReleaseContext): Promise<void>;
|
|
40
|
+
}
|
|
41
|
+
export interface DeviceCloudOptions {
|
|
42
|
+
/**
|
|
43
|
+
* The DeviceCloud API key. Without it, `DEVICE_CLOUD_API_KEY` from the run's
|
|
44
|
+
* environment. The key needs access to device sessions.
|
|
45
|
+
*/
|
|
46
|
+
apiKey?: string;
|
|
47
|
+
/** The DeviceCloud API. Without it, `DCD_API_URL` from the run's environment, then https://api.devicecloud.dev. */
|
|
48
|
+
apiUrl?: string;
|
|
49
|
+
/**
|
|
50
|
+
* A build already uploaded (the id `dcd upload` prints). Without it, the
|
|
51
|
+
* provider uploads the target's `app.appPath`, when the config names one,
|
|
52
|
+
* once per run. Either way the session installs the build, and e2e
|
|
53
|
+
* installs nothing itself.
|
|
54
|
+
*/
|
|
55
|
+
appBinaryId?: string;
|
|
56
|
+
/** Device model, as `GET /device/models` lists them. The platform's default without. */
|
|
57
|
+
model?: string;
|
|
58
|
+
/** OS version for that model. Its default without. */
|
|
59
|
+
os?: string;
|
|
60
|
+
/** How long each session may last, in minutes. The organization's limit without. */
|
|
61
|
+
maxDurationMin?: number;
|
|
62
|
+
}
|
|
63
|
+
/** What the provider calls out to: the network, the upload, and the clock. */
|
|
64
|
+
export interface ProviderDeps {
|
|
65
|
+
fetch: typeof fetch;
|
|
66
|
+
/** Uploads a local build the way `dcd upload` does and answers its binary id. */
|
|
67
|
+
upload: (args: {
|
|
68
|
+
apiKey: string;
|
|
69
|
+
apiUrl: string;
|
|
70
|
+
filePath: string;
|
|
71
|
+
log: (line: string) => void;
|
|
72
|
+
}) => Promise<string>;
|
|
73
|
+
/** Sent as `x-dcd-cli-version`, so the API knows which provider version called. */
|
|
74
|
+
version: string;
|
|
75
|
+
/** Between polls. */
|
|
76
|
+
pollMs: number;
|
|
77
|
+
/** How long a session may take to be ready: queued, starting, installing. */
|
|
78
|
+
startTimeoutMs: number;
|
|
79
|
+
}
|
|
80
|
+
export declare function createProvider(options: DeviceCloudOptions, deps: ProviderDeps): DeviceCloudProvider;
|
|
@@ -0,0 +1,233 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The DeviceCloud device provider for e2e (https://github.com/e2e-inc/e2e),
|
|
3
|
+
* published as `@devicecloud.dev/dcd/e2e`. The public entry point is
|
|
4
|
+
* `./index.ts`; this module takes its dependencies as arguments so the unit
|
|
5
|
+
* tests can replace the network and the upload.
|
|
6
|
+
*
|
|
7
|
+
* Each e2e worker slot gets its own DeviceCloud device session. The provider
|
|
8
|
+
* starts it, waits until its device is up and the build is installed, then
|
|
9
|
+
* asks for the device's engine (`POST /device/sessions/:id/engine`). The
|
|
10
|
+
* answer is the address of the session's own agent-device daemon, reached
|
|
11
|
+
* through DeviceCloud's relay, and a token for it: that is what an e2e lease
|
|
12
|
+
* is. e2e then drives the device directly, so its calls do not pass through
|
|
13
|
+
* the API's command queue. `release` stops the session.
|
|
14
|
+
*
|
|
15
|
+
* The types below describe e2e's provider contract (`DeviceProvider` in
|
|
16
|
+
* `@e2e-dev/mobile`) by shape, for the fields this provider uses, so the
|
|
17
|
+
* package does not depend on e2e. An object of this type can be passed to
|
|
18
|
+
* `mobile({ device })`.
|
|
19
|
+
*/
|
|
20
|
+
import { checkApiUrl } from '../utils/api-url.js';
|
|
21
|
+
const DEFAULT_API_URL = 'https://api.devicecloud.dev';
|
|
22
|
+
const ENDED = new Set(['expired', 'failed', 'released']);
|
|
23
|
+
/** How many times to ask for the engine while the device is up but not quite ready for it (425). */
|
|
24
|
+
const ENGINE_ATTEMPTS = 10;
|
|
25
|
+
/**
|
|
26
|
+
* How many times a request that is safe to repeat is sent again after the
|
|
27
|
+
* network failed it (no answer at all). Polls run for minutes, and one lost
|
|
28
|
+
* request must not end a run. Never a session start: sent twice, it could
|
|
29
|
+
* start two sessions.
|
|
30
|
+
*/
|
|
31
|
+
const NETWORK_RETRIES = 4;
|
|
32
|
+
const wait = (ms, signal) => new Promise((resolve, reject) => {
|
|
33
|
+
if (signal?.aborted) {
|
|
34
|
+
reject(signal.reason ?? new Error('Interrupted'));
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const onAbort = () => {
|
|
38
|
+
clearTimeout(timer);
|
|
39
|
+
reject(signal?.reason ?? new Error('Interrupted'));
|
|
40
|
+
};
|
|
41
|
+
const timer = setTimeout(() => {
|
|
42
|
+
signal?.removeEventListener('abort', onAbort);
|
|
43
|
+
resolve();
|
|
44
|
+
}, ms);
|
|
45
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
46
|
+
});
|
|
47
|
+
/** The API's own words for a failed request: its message, or the start of the body. */
|
|
48
|
+
function failure(what, reply) {
|
|
49
|
+
const message = reply.json?.message;
|
|
50
|
+
const said = Array.isArray(message)
|
|
51
|
+
? message.join('; ')
|
|
52
|
+
: String(message ?? reply.text).slice(0, 300);
|
|
53
|
+
const code = typeof reply.json?.error === 'string' && reply.json.error !== said
|
|
54
|
+
? ` (${reply.json.error})`
|
|
55
|
+
: '';
|
|
56
|
+
return new Error(`DeviceCloud: ${what} answered ${reply.status}: ${said}${code}`);
|
|
57
|
+
}
|
|
58
|
+
/** Where to send requests, and with which key: checked before the key goes anywhere. */
|
|
59
|
+
function connection(options, env, log) {
|
|
60
|
+
const apiKey = (options.apiKey ?? env.DEVICE_CLOUD_API_KEY ?? '').trim();
|
|
61
|
+
if (!apiKey) {
|
|
62
|
+
throw new Error('DeviceCloud: no API key. Set DEVICE_CLOUD_API_KEY in the environment e2e runs with, or pass apiKey to deviceCloud().');
|
|
63
|
+
}
|
|
64
|
+
const raw = (options.apiUrl ?? env.DCD_API_URL ?? '').trim() || DEFAULT_API_URL;
|
|
65
|
+
const check = checkApiUrl(raw);
|
|
66
|
+
if (!check.ok)
|
|
67
|
+
throw new Error(`DeviceCloud: ${check.reason}`);
|
|
68
|
+
if (check.warning)
|
|
69
|
+
log(check.warning);
|
|
70
|
+
return { apiKey, apiUrl: check.origin };
|
|
71
|
+
}
|
|
72
|
+
export function createProvider(options, deps) {
|
|
73
|
+
// One upload per build per run: e2e acquires every worker slot at once.
|
|
74
|
+
const uploads = new Map();
|
|
75
|
+
const client = (apiKey, apiUrl) => async (method, path, body, signal, { repeatable = method !== 'POST' } = {}) => {
|
|
76
|
+
let response;
|
|
77
|
+
for (let attempt = 0;; attempt++) {
|
|
78
|
+
try {
|
|
79
|
+
response = await deps.fetch(`${apiUrl}${path}`, {
|
|
80
|
+
headers: {
|
|
81
|
+
'x-app-api-key': apiKey,
|
|
82
|
+
'x-dcd-cli-version': deps.version,
|
|
83
|
+
'x-dcd-source': 'cli',
|
|
84
|
+
...(body === undefined
|
|
85
|
+
? {}
|
|
86
|
+
: { 'content-type': 'application/json' }),
|
|
87
|
+
},
|
|
88
|
+
method,
|
|
89
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }),
|
|
90
|
+
...(signal ? { signal } : {}),
|
|
91
|
+
});
|
|
92
|
+
break;
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (signal?.aborted)
|
|
96
|
+
throw signal.reason ?? error;
|
|
97
|
+
if (!repeatable || attempt >= NETWORK_RETRIES) {
|
|
98
|
+
const cause = error.cause;
|
|
99
|
+
const why = cause?.code ?? cause?.message ?? error.message;
|
|
100
|
+
throw new Error(`DeviceCloud: ${method} ${path} could not reach ${apiUrl} (${why})`, { cause: error });
|
|
101
|
+
}
|
|
102
|
+
await wait(deps.pollMs * (attempt + 1), signal);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
const text = await response.text();
|
|
106
|
+
let json = null;
|
|
107
|
+
try {
|
|
108
|
+
json = JSON.parse(text);
|
|
109
|
+
}
|
|
110
|
+
catch {
|
|
111
|
+
// Not JSON: the status and the text say what happened.
|
|
112
|
+
}
|
|
113
|
+
return { json, status: response.status, text };
|
|
114
|
+
};
|
|
115
|
+
const binaryFor = async (request, apiKey, apiUrl) => {
|
|
116
|
+
if (options.appBinaryId) {
|
|
117
|
+
if (request.appPath)
|
|
118
|
+
request.log(`installing build ${options.appBinaryId}, not uploading ${request.appPath}`);
|
|
119
|
+
return options.appBinaryId;
|
|
120
|
+
}
|
|
121
|
+
if (!request.appPath)
|
|
122
|
+
return undefined;
|
|
123
|
+
let upload = uploads.get(request.appPath);
|
|
124
|
+
if (!upload) {
|
|
125
|
+
request.log(`uploading ${request.appPath}`);
|
|
126
|
+
upload = deps.upload({
|
|
127
|
+
apiKey,
|
|
128
|
+
apiUrl,
|
|
129
|
+
filePath: request.appPath,
|
|
130
|
+
log: request.log,
|
|
131
|
+
});
|
|
132
|
+
uploads.set(request.appPath, upload);
|
|
133
|
+
// A failed upload is tried again by the next run, not remembered.
|
|
134
|
+
upload.catch(() => uploads.delete(request.appPath));
|
|
135
|
+
}
|
|
136
|
+
return upload;
|
|
137
|
+
};
|
|
138
|
+
return {
|
|
139
|
+
async acquire(request) {
|
|
140
|
+
// e2e cannot install a build on a DeviceCloud device; the session does.
|
|
141
|
+
// e2e is told so (installedApp), which needs the build's bundle id.
|
|
142
|
+
if (request.appPath && !request.app) {
|
|
143
|
+
throw new Error("DeviceCloud: the target names app.appPath but not app.bundleId. Set app.bundleId to the build's bundle id or package name.");
|
|
144
|
+
}
|
|
145
|
+
const { apiKey, apiUrl } = connection(options, request.env, request.log);
|
|
146
|
+
const api = client(apiKey, apiUrl);
|
|
147
|
+
const binaryUploadId = await binaryFor(request, apiKey, apiUrl);
|
|
148
|
+
const started = await api('POST', '/device/sessions', {
|
|
149
|
+
clientLabel: 'e2e',
|
|
150
|
+
platform: request.platform,
|
|
151
|
+
...(binaryUploadId ? { binaryUploadId } : {}),
|
|
152
|
+
...(options.model ? { model: options.model } : {}),
|
|
153
|
+
...(options.os ? { os: options.os } : {}),
|
|
154
|
+
...(options.maxDurationMin
|
|
155
|
+
? { maxDurationMin: options.maxDurationMin }
|
|
156
|
+
: {}),
|
|
157
|
+
}, request.signal);
|
|
158
|
+
if (started.status >= 300 || !started.json?.session)
|
|
159
|
+
throw failure('starting a device session', started);
|
|
160
|
+
let session = started.json.session;
|
|
161
|
+
const path = `/device/sessions/${encodeURIComponent(session.id)}`;
|
|
162
|
+
// A session left running is billed until it idles out.
|
|
163
|
+
const stop = () => api('DELETE', path).catch(() => { });
|
|
164
|
+
try {
|
|
165
|
+
if (session.monitor_url)
|
|
166
|
+
request.log(`watch at ${session.monitor_url}`);
|
|
167
|
+
// Queued, then starting, then installing: minutes when the fleet is busy.
|
|
168
|
+
const deadline = Date.now() + deps.startTimeoutMs;
|
|
169
|
+
for (;;) {
|
|
170
|
+
if (ENDED.has(session.state)) {
|
|
171
|
+
throw new Error(`DeviceCloud: session ${session.id} ended before it was ready (${session.release_reason ?? session.state})`);
|
|
172
|
+
}
|
|
173
|
+
if (session.install?.status === 'failed') {
|
|
174
|
+
throw new Error(`DeviceCloud: the build could not be installed on session ${session.id}: ${session.install.error ?? 'no reason given'}`);
|
|
175
|
+
}
|
|
176
|
+
if ((session.state === 'ready' || session.state === 'active') &&
|
|
177
|
+
session.install?.status !== 'installing')
|
|
178
|
+
break;
|
|
179
|
+
if (Date.now() > deadline) {
|
|
180
|
+
throw new Error(`DeviceCloud: session ${session.id} was not ready within ${Math.round(deps.startTimeoutMs / 60_000)} minutes`);
|
|
181
|
+
}
|
|
182
|
+
await wait(deps.pollMs, request.signal);
|
|
183
|
+
const read = await api('GET', path, undefined, request.signal);
|
|
184
|
+
if (read.status >= 300 || !read.json?.session)
|
|
185
|
+
throw failure('reading the device session', read);
|
|
186
|
+
session = read.json.session;
|
|
187
|
+
}
|
|
188
|
+
// The device is up; its engine may need a moment more (425).
|
|
189
|
+
let engine = null;
|
|
190
|
+
for (let attempt = 0; attempt < ENGINE_ATTEMPTS && !engine; attempt++) {
|
|
191
|
+
// Asking again is safe: the session has one engine, and every answer names it.
|
|
192
|
+
const asked = await api('POST', `${path}/engine`, {}, request.signal, { repeatable: true });
|
|
193
|
+
if (asked.status === 425) {
|
|
194
|
+
await wait(deps.pollMs, request.signal);
|
|
195
|
+
continue;
|
|
196
|
+
}
|
|
197
|
+
if (asked.status >= 300 || !asked.json?.engine)
|
|
198
|
+
throw failure("asking for the device's engine", asked);
|
|
199
|
+
engine = asked.json.engine;
|
|
200
|
+
}
|
|
201
|
+
if (!engine)
|
|
202
|
+
throw new Error(`DeviceCloud: session ${session.id} never became ready for e2e`);
|
|
203
|
+
if (engine.agentDeviceVersion &&
|
|
204
|
+
engine.agentDeviceVersion !== request.agentDeviceVersion) {
|
|
205
|
+
// Same wire protocol; said so that a difference can be read off a report.
|
|
206
|
+
request.log(`the device runs agent-device ${engine.agentDeviceVersion}, this e2e ${request.agentDeviceVersion}`);
|
|
207
|
+
}
|
|
208
|
+
return {
|
|
209
|
+
daemon: engine.daemon,
|
|
210
|
+
deviceId: engine.deviceId,
|
|
211
|
+
id: session.id,
|
|
212
|
+
// Only when the target names a build (appPath): the session installed one, so e2e installs nothing.
|
|
213
|
+
...(request.appPath ? { installedApp: request.app } : {}),
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
catch (error) {
|
|
217
|
+
await stop();
|
|
218
|
+
throw error;
|
|
219
|
+
}
|
|
220
|
+
},
|
|
221
|
+
name: 'devicecloud',
|
|
222
|
+
async release(lease, context) {
|
|
223
|
+
const { apiKey, apiUrl } = connection(options, context.env, context.log);
|
|
224
|
+
const stopped = await client(apiKey, apiUrl)('DELETE', `/device/sessions/${encodeURIComponent(lease.id)}`, undefined, context.signal);
|
|
225
|
+
// 404 and 409: already gone, which is what was asked for.
|
|
226
|
+
if (stopped.status >= 300 &&
|
|
227
|
+
stopped.status !== 404 &&
|
|
228
|
+
stopped.status !== 409) {
|
|
229
|
+
throw failure(`stopping device session ${lease.id}`, stopped);
|
|
230
|
+
}
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
}
|
|
@@ -4,6 +4,16 @@ import type { AuthContext } from '../types/domain/auth.types.js';
|
|
|
4
4
|
import type { LiveCommandStatus, LiveExecResult, LiveSession, LiveSessionSummary } from '../types/domain/live.types.js';
|
|
5
5
|
import type { TeamSettings } from '../types/domain/team-settings.types.js';
|
|
6
6
|
import { components, paths } from '../types/generated/schema.types.js';
|
|
7
|
+
/** Extra checks a bundle download makes before it trusts the manifest. */
|
|
8
|
+
interface BundleDownloadOptions {
|
|
9
|
+
/**
|
|
10
|
+
* The manifest's `filename` must start with this, or the download throws
|
|
11
|
+
* `unsupportedMessage` instead of falling back: how a filtered request
|
|
12
|
+
* tells an API that applied the filter from an older one that ignored it.
|
|
13
|
+
*/
|
|
14
|
+
requiredFilenamePrefix?: string;
|
|
15
|
+
unsupportedMessage?: string;
|
|
16
|
+
}
|
|
7
17
|
/** What went wrong in a bundle attempt, minus the route/timing added later. */
|
|
8
18
|
type BundleFailure = Omit<BundleFallbackTelemetry, 'duration_ms' | 'route' | 'upload_id'>;
|
|
9
19
|
/**
|
|
@@ -68,12 +78,19 @@ export declare const ApiGateway: {
|
|
|
68
78
|
* back to the inline download endpoint. Definitive errors (e.g. not found)
|
|
69
79
|
* surface through that inline path instead.
|
|
70
80
|
*/
|
|
71
|
-
tryBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string): Promise<boolean>;
|
|
81
|
+
tryBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string, options?: BundleDownloadOptions): Promise<boolean>;
|
|
72
82
|
/**
|
|
73
83
|
* One bundle-download attempt. Resolves `true` once the ZIP is on disk, or
|
|
74
84
|
* with the reason it fell through, for {@link tryBundleDownload} to record.
|
|
75
85
|
*/
|
|
76
|
-
attemptBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string): Promise<BundleFailure | true>;
|
|
86
|
+
attemptBundleDownload(baseUrl: string, auth: AuthContext, manifestEndpoint: string, destinationPath: string, operation: string, options?: BundleDownloadOptions): Promise<BundleFailure | true>;
|
|
87
|
+
/**
|
|
88
|
+
* Fail an inline ZIP download that ended before its central directory: the
|
|
89
|
+
* API streams the ZIP as it builds it, so a failure after the headers can
|
|
90
|
+
* still close the response cleanly. Deletes the partial file, so nothing
|
|
91
|
+
* downstream (a CI artifact upload, say) picks up a corrupt ZIP.
|
|
92
|
+
*/
|
|
93
|
+
assertInlineZipComplete(destinationPath: string, operation: string, route: string, uploadId: string): Promise<void>;
|
|
77
94
|
/**
|
|
78
95
|
* Look for an already-uploaded binary to skip re-uploading.
|
|
79
96
|
*
|
|
@@ -99,7 +116,12 @@ export declare const ApiGateway: {
|
|
|
99
116
|
} & {
|
|
100
117
|
encrypted?: boolean;
|
|
101
118
|
}>;
|
|
102
|
-
|
|
119
|
+
/**
|
|
120
|
+
* Download an upload's artifacts ZIP. With `resultId`, only the attempts of
|
|
121
|
+
* the flow run that result belongs to; the parameter is sent only when set,
|
|
122
|
+
* so an unfiltered request is exactly what it always was.
|
|
123
|
+
*/
|
|
124
|
+
downloadArtifactsZip(baseUrl: string, auth: AuthContext, uploadId: string, results: "ALL" | "FAILED", artifactsPath?: string, resultId?: number): Promise<void>;
|
|
103
125
|
finaliseUpload(config: {
|
|
104
126
|
auth: AuthContext;
|
|
105
127
|
backblazeSuccess: boolean;
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { createWriteStream, mkdirSync } from 'node:fs';
|
|
2
|
+
import { rm } from 'node:fs/promises';
|
|
2
3
|
import { homedir } from 'node:os';
|
|
3
4
|
import * as path from 'node:path';
|
|
4
5
|
import { Readable } from 'node:stream';
|
|
5
6
|
import { pipeline } from 'node:stream/promises';
|
|
6
7
|
import { telemetry, } from '../services/telemetry.service.js';
|
|
8
|
+
import { assertCompleteZip, IncompleteZipError } from '../utils/zip-integrity.js';
|
|
7
9
|
/** Expand a leading `~` to the home directory, as the download paths allow. */
|
|
8
10
|
function expandHome(p) {
|
|
9
11
|
return p.replace(/^~(?=$|\/|\\)/, homedir());
|
|
@@ -202,9 +204,9 @@ export const ApiGateway = {
|
|
|
202
204
|
* back to the inline download endpoint. Definitive errors (e.g. not found)
|
|
203
205
|
* surface through that inline path instead.
|
|
204
206
|
*/
|
|
205
|
-
async tryBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation) {
|
|
207
|
+
async tryBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation, options = {}) {
|
|
206
208
|
const startedAt = Date.now();
|
|
207
|
-
const outcome = await this.attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation);
|
|
209
|
+
const outcome = await this.attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation, options);
|
|
208
210
|
if (outcome === true)
|
|
209
211
|
return true;
|
|
210
212
|
// The fallback is silent to the user (the inline download still delivers
|
|
@@ -223,7 +225,7 @@ export const ApiGateway = {
|
|
|
223
225
|
* One bundle-download attempt. Resolves `true` once the ZIP is on disk, or
|
|
224
226
|
* with the reason it fell through, for {@link tryBundleDownload} to record.
|
|
225
227
|
*/
|
|
226
|
-
async attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation) {
|
|
228
|
+
async attemptBundleDownload(baseUrl, auth, manifestEndpoint, destinationPath, operation, options = {}) {
|
|
227
229
|
let manifestRes;
|
|
228
230
|
try {
|
|
229
231
|
manifestRes = await fetch(`${baseUrl}${manifestEndpoint}`, {
|
|
@@ -249,6 +251,13 @@ export const ApiGateway = {
|
|
|
249
251
|
if (!bundle?.bundleUrl || !bundle?.manifest || !bundle?.sig) {
|
|
250
252
|
return failure('manifest_incomplete');
|
|
251
253
|
}
|
|
254
|
+
// An API that predates a filter ignores it and bundles the whole upload,
|
|
255
|
+
// named as such. Thrown, not a fallback: the inline route would ignore the
|
|
256
|
+
// filter just the same and save the wrong ZIP.
|
|
257
|
+
const prefix = options.requiredFilenamePrefix;
|
|
258
|
+
if (prefix !== undefined && !bundle.filename?.startsWith(prefix)) {
|
|
259
|
+
throw new Error(options.unsupportedMessage ?? `${operation}: the API ignored the request filter`);
|
|
260
|
+
}
|
|
252
261
|
let zipRes;
|
|
253
262
|
try {
|
|
254
263
|
zipRes = await fetch(bundle.bundleUrl, {
|
|
@@ -287,8 +296,43 @@ export const ApiGateway = {
|
|
|
287
296
|
bytes_received: bytesReceived,
|
|
288
297
|
});
|
|
289
298
|
}
|
|
299
|
+
// A bundle that fails after its 200 headers still ends cleanly, so the
|
|
300
|
+
// stream above succeeds and leaves a ZIP with no central directory. Check
|
|
301
|
+
// before calling it done; the inline path then overwrites the file.
|
|
302
|
+
try {
|
|
303
|
+
await assertCompleteZip(expandHome(destinationPath));
|
|
304
|
+
}
|
|
305
|
+
catch (error) {
|
|
306
|
+
return failure('bundle_truncated', {
|
|
307
|
+
...errorDetail(error),
|
|
308
|
+
bytes_received: bytesReceived,
|
|
309
|
+
});
|
|
310
|
+
}
|
|
290
311
|
return true;
|
|
291
312
|
},
|
|
313
|
+
/**
|
|
314
|
+
* Fail an inline ZIP download that ended before its central directory: the
|
|
315
|
+
* API streams the ZIP as it builds it, so a failure after the headers can
|
|
316
|
+
* still close the response cleanly. Deletes the partial file, so nothing
|
|
317
|
+
* downstream (a CI artifact upload, say) picks up a corrupt ZIP.
|
|
318
|
+
*/
|
|
319
|
+
async assertInlineZipComplete(destinationPath, operation, route, uploadId) {
|
|
320
|
+
const file = expandHome(destinationPath);
|
|
321
|
+
try {
|
|
322
|
+
await assertCompleteZip(file);
|
|
323
|
+
}
|
|
324
|
+
catch (error) {
|
|
325
|
+
if (!(error instanceof IncompleteZipError))
|
|
326
|
+
throw error;
|
|
327
|
+
await rm(file, { force: true }).catch(() => { });
|
|
328
|
+
telemetry.recordDownloadIncomplete({
|
|
329
|
+
bytes: error.bytes,
|
|
330
|
+
route,
|
|
331
|
+
upload_id: uploadId,
|
|
332
|
+
});
|
|
333
|
+
throw new Error(`${operation}: the download ended early and ${error.message}. Please retry.`, { cause: error });
|
|
334
|
+
}
|
|
335
|
+
},
|
|
292
336
|
/**
|
|
293
337
|
* Look for an already-uploaded binary to skip re-uploading.
|
|
294
338
|
*
|
|
@@ -328,14 +372,27 @@ export const ApiGateway = {
|
|
|
328
372
|
throw error;
|
|
329
373
|
}
|
|
330
374
|
},
|
|
331
|
-
|
|
375
|
+
/**
|
|
376
|
+
* Download an upload's artifacts ZIP. With `resultId`, only the attempts of
|
|
377
|
+
* the flow run that result belongs to; the parameter is sent only when set,
|
|
378
|
+
* so an unfiltered request is exactly what it always was.
|
|
379
|
+
*/
|
|
380
|
+
async downloadArtifactsZip(baseUrl, auth, uploadId, results, artifactsPath = './artifacts.zip', resultId) {
|
|
381
|
+
const filtered = resultId !== undefined;
|
|
332
382
|
// Prefer bundle delivery; fall back to the inline download below.
|
|
333
|
-
if (await this.tryBundleDownload(baseUrl, auth, `/results/${uploadId}/artifacts-bundle?results=${results}
|
|
383
|
+
if (await this.tryBundleDownload(baseUrl, auth, `/results/${uploadId}/artifacts-bundle?results=${results}` +
|
|
384
|
+
(filtered ? `&resultId=${resultId}` : ''), artifactsPath, 'Failed to download artifacts', filtered
|
|
385
|
+
? {
|
|
386
|
+
// What the API names a bundle it narrowed to one result.
|
|
387
|
+
requiredFilenamePrefix: 'artifacts-result-',
|
|
388
|
+
unsupportedMessage: 'Failed to download artifacts: this API does not support downloading one result yet. Download without --result-id or --flow.',
|
|
389
|
+
}
|
|
390
|
+
: {})) {
|
|
334
391
|
return;
|
|
335
392
|
}
|
|
336
393
|
try {
|
|
337
394
|
const res = await fetch(`${baseUrl}/results/${uploadId}/download`, {
|
|
338
|
-
body: JSON.stringify({ results }),
|
|
395
|
+
body: JSON.stringify(filtered ? { results, resultId } : { results }),
|
|
339
396
|
headers: {
|
|
340
397
|
'content-type': 'application/json',
|
|
341
398
|
...auth.headers,
|
|
@@ -346,6 +403,7 @@ export const ApiGateway = {
|
|
|
346
403
|
await this.handleApiError(res, 'Failed to download artifacts');
|
|
347
404
|
}
|
|
348
405
|
await this.streamResponseToFile(res, artifactsPath, 'Failed to download artifacts');
|
|
406
|
+
await this.assertInlineZipComplete(artifactsPath, 'Failed to download artifacts', 'download', uploadId);
|
|
349
407
|
}
|
|
350
408
|
catch (error) {
|
|
351
409
|
if (error instanceof TypeError && error.message === 'fetch failed') {
|
|
@@ -772,6 +830,10 @@ export const ApiGateway = {
|
|
|
772
830
|
throw new Error(`${errorPrefix}: ${res.status} ${errorText}`);
|
|
773
831
|
}
|
|
774
832
|
await this.streamResponseToFile(res, finalReportPath, errorPrefix);
|
|
833
|
+
// Only the HTML report is a ZIP; junit is XML and allure is one HTML file.
|
|
834
|
+
if (reportType === 'html') {
|
|
835
|
+
await this.assertInlineZipComplete(finalReportPath, errorPrefix, 'html-report', uploadId);
|
|
836
|
+
}
|
|
775
837
|
}
|
|
776
838
|
catch (error) {
|
|
777
839
|
if (error instanceof TypeError && error.message === 'fetch failed') {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AuthContext } from '../types/domain/auth.types.js';
|
|
2
|
-
import type { DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls, DeviceCatalogue, DeviceCommandResult, DeviceFlowBundle, DeviceHumanStatus, DeviceInstalledApp, DeviceLogs, DeviceRunResponse, DeviceScreen, DeviceScreenshot, DeviceSession, StartDeviceSessionRequest } from '../types/domain/device-session.types.js';
|
|
2
|
+
import type { DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls, DeviceCatalogue, DeviceCommandResult, DeviceFlowBundle, DeviceFullScreenshot, DeviceHumanStatus, DeviceInstalledApp, DeviceLogLevel, DeviceLogs, DeviceRunResponse, DeviceScreen, DeviceScreenshot, DeviceSession, StartDeviceSessionRequest } from '../types/domain/device-session.types.js';
|
|
3
3
|
/**
|
|
4
4
|
* An error answer from /device/sessions. Unlike ApiError it keeps the API's
|
|
5
5
|
* machine code (`LIVE_NOT_FOUND`, `LIVE_SPEND_CAP`, …) and the `session`
|
|
@@ -8,6 +8,13 @@ import type { DeviceActionRequest, DeviceArtifactsPage, DeviceBundleUploadUrls,
|
|
|
8
8
|
*/
|
|
9
9
|
export declare class DeviceApiError extends Error {
|
|
10
10
|
code: null | string;
|
|
11
|
+
/**
|
|
12
|
+
* What else the answer said that a script can act on: how long to wait
|
|
13
|
+
* (`retry_after_s`), the limit that was hit (`limit`, `spent`), how far
|
|
14
|
+
* the device got (`phase`), or the command a wait was for (`command_id`).
|
|
15
|
+
* Printed in the --json envelope's `error` beside `code` and `message`.
|
|
16
|
+
*/
|
|
17
|
+
details: Record<string, unknown>;
|
|
11
18
|
/**
|
|
12
19
|
* The API itself answered (its `{ statusCode, message }` envelope), not a
|
|
13
20
|
* proxy in front of it. A proxy's 502 can come after the API did the work.
|
|
@@ -15,8 +22,14 @@ export declare class DeviceApiError extends Error {
|
|
|
15
22
|
fromApi: boolean;
|
|
16
23
|
session: DeviceSession | null;
|
|
17
24
|
status: number;
|
|
18
|
-
constructor(message: string, status: number, code: null | string, session: DeviceSession | null, fromApi?: boolean);
|
|
25
|
+
constructor(message: string, status: number, code: null | string, session: DeviceSession | null, fromApi?: boolean, details?: Record<string, unknown>);
|
|
19
26
|
}
|
|
27
|
+
/**
|
|
28
|
+
* The message for an answer that is not the API's JSON: a proxy's page or
|
|
29
|
+
* plain text. An HTML page is cut to its title, as a whole page in a
|
|
30
|
+
* terminal, an envelope or a log says nothing a person can read.
|
|
31
|
+
*/
|
|
32
|
+
export declare function plainErrorText(text: string, status: number): string;
|
|
20
33
|
/** How recent an open session must be to count as one a failed start may have made. */
|
|
21
34
|
export declare const START_RECOVERY_WINDOW_MS: number;
|
|
22
35
|
/**
|
|
@@ -26,7 +39,6 @@ export declare const START_RECOVERY_WINDOW_MS: number;
|
|
|
26
39
|
* before any session exists.
|
|
27
40
|
*/
|
|
28
41
|
export declare function startOutcomeUnknown(error: unknown): boolean;
|
|
29
|
-
/** The Agent Devices session API (dcd docs/device-v1-plan.md, section 4.1). */
|
|
30
42
|
export declare const DeviceGateway: {
|
|
31
43
|
artifacts(baseUrl: string, auth: AuthContext, id: string, before?: string): Promise<DeviceArtifactsPage>;
|
|
32
44
|
bundleUploadUrls(baseUrl: string, auth: AuthContext, bytes: number): Promise<DeviceBundleUploadUrls>;
|
|
@@ -44,21 +56,25 @@ export declare const DeviceGateway: {
|
|
|
44
56
|
binaryUploadId: string;
|
|
45
57
|
} | {
|
|
46
58
|
url: string;
|
|
47
|
-
}): Promise<{
|
|
59
|
+
}, force?: boolean): Promise<{
|
|
48
60
|
app: DeviceInstalledApp;
|
|
49
61
|
session: DeviceSession;
|
|
50
62
|
}>;
|
|
51
63
|
launch(baseUrl: string, auth: AuthContext, id: string, body: {
|
|
52
64
|
appId?: string;
|
|
53
65
|
clearState?: boolean;
|
|
54
|
-
}): Promise<{
|
|
66
|
+
}, force?: boolean): Promise<{
|
|
55
67
|
result: DeviceCommandResult;
|
|
56
68
|
session: DeviceSession;
|
|
57
69
|
}>;
|
|
58
70
|
list(baseUrl: string, auth: AuthContext, all?: boolean): Promise<{
|
|
59
71
|
sessions: DeviceSession[];
|
|
60
72
|
}>;
|
|
61
|
-
|
|
73
|
+
/** The app's recent log lines; `level` and `grep` narrow them (the API ignores both before it knew them). */
|
|
74
|
+
logs(baseUrl: string, auth: AuthContext, id: string, lines: number, filter?: {
|
|
75
|
+
grep?: string;
|
|
76
|
+
level?: DeviceLogLevel;
|
|
77
|
+
}): Promise<{
|
|
62
78
|
logs: DeviceLogs;
|
|
63
79
|
session: DeviceSession;
|
|
64
80
|
}>;
|
|
@@ -79,12 +95,12 @@ export declare const DeviceGateway: {
|
|
|
79
95
|
bundle: DeviceFlowBundle;
|
|
80
96
|
}>;
|
|
81
97
|
/** Ask a person for help: the session moves to needs_human until they hand it back. */
|
|
82
|
-
requestHuman(baseUrl: string, auth: AuthContext, id: string, reason: string): Promise<{
|
|
98
|
+
requestHuman(baseUrl: string, auth: AuthContext, id: string, reason: string, force?: boolean): Promise<{
|
|
83
99
|
human: DeviceHumanStatus;
|
|
84
100
|
session: DeviceSession;
|
|
85
101
|
}>;
|
|
86
102
|
/** One typed action: tap, type, swipe, press_key, open_link or set_location. Synchronous: answers with the outcome. */
|
|
87
|
-
action(baseUrl: string, auth: AuthContext, id: string, body: DeviceActionRequest): Promise<{
|
|
103
|
+
action(baseUrl: string, auth: AuthContext, id: string, body: DeviceActionRequest, force?: boolean): Promise<{
|
|
88
104
|
result: DeviceCommandResult;
|
|
89
105
|
session: DeviceSession;
|
|
90
106
|
}>;
|
|
@@ -95,18 +111,26 @@ export declare const DeviceGateway: {
|
|
|
95
111
|
} | {
|
|
96
112
|
env?: Record<string, string>;
|
|
97
113
|
yaml: string;
|
|
98
|
-
}): Promise<DeviceRunResponse>;
|
|
114
|
+
}, force?: boolean): Promise<DeviceRunResponse>;
|
|
99
115
|
screenshot(baseUrl: string, auth: AuthContext, id: string): Promise<{
|
|
100
116
|
screenshot: DeviceScreenshot;
|
|
101
117
|
session: DeviceSession;
|
|
102
118
|
}>;
|
|
119
|
+
/**
|
|
120
|
+
* A PNG at the device's own resolution, as a link. A device whose runner
|
|
121
|
+
* is too old for it answers LIVE_NOT_SUPPORTED.
|
|
122
|
+
*/
|
|
123
|
+
fullScreenshot(baseUrl: string, auth: AuthContext, id: string): Promise<{
|
|
124
|
+
screenshot: DeviceFullScreenshot;
|
|
125
|
+
session: DeviceSession;
|
|
126
|
+
}>;
|
|
103
127
|
start(baseUrl: string, auth: AuthContext, body: StartDeviceSessionRequest): Promise<{
|
|
104
128
|
session: DeviceSession;
|
|
105
129
|
}>;
|
|
106
130
|
status(baseUrl: string, auth: AuthContext, id: string): Promise<{
|
|
107
131
|
session: DeviceSession;
|
|
108
132
|
}>;
|
|
109
|
-
stop(baseUrl: string, auth: AuthContext, id: string): Promise<{
|
|
133
|
+
stop(baseUrl: string, auth: AuthContext, id: string, force?: boolean): Promise<{
|
|
110
134
|
session: DeviceSession;
|
|
111
135
|
}>;
|
|
112
136
|
};
|