@ship.zone/runner 0.1.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/.smartconfig.json +48 -0
- package/changelog.md +12 -0
- package/deno.json +41 -0
- package/deno.lock +1843 -0
- package/dist_npm/mod.d.ts +689 -0
- package/dist_npm/mod.js +8980 -0
- package/dist_rust/runnerworkspace_linux_amd64_musl +0 -0
- package/dist_rust/runnerworkspace_linux_arm64_musl +0 -0
- package/license.md +18 -0
- package/mod.ts +8 -0
- package/musl-copyright.md +81 -0
- package/package.json +58 -0
- package/readme.md +274 -0
- package/rust/.cargo/config.toml +5 -0
- package/rust/Cargo.lock +144 -0
- package/rust/Cargo.toml +17 -0
- package/rust/src/lib.rs +1784 -0
- package/rust/src/main.rs +6 -0
- package/third-party-licenses.md +95 -0
- package/ts/00_commitinfo_data.ts +8 -0
- package/ts/api-client.ts +1059 -0
- package/ts/artifact-manager.ts +218 -0
- package/ts/attempt-state.ts +190 -0
- package/ts/cache-manager.ts +431 -0
- package/ts/cli.ts +239 -0
- package/ts/config.ts +724 -0
- package/ts/errors.ts +68 -0
- package/ts/index.ts +13 -0
- package/ts/interfaces.ts +547 -0
- package/ts/log-sender.ts +134 -0
- package/ts/oci-executor.ts +2472 -0
- package/ts/plugins.ts +11 -0
- package/ts/protocol-validator.ts +535 -0
- package/ts/redactor.ts +41 -0
- package/ts/registration-state.ts +253 -0
- package/ts/runner.ts +1036 -0
- package/ts/source-workspace.ts +161 -0
- package/ts/staging-scavenger.ts +62 -0
- package/ts/transfer-archive.ts +1605 -0
- package/ts/validation.ts +77 -0
package/ts/api-client.ts
ADDED
|
@@ -0,0 +1,1059 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AuthenticationError,
|
|
3
|
+
CoordinatorError,
|
|
4
|
+
LeaseLostError,
|
|
5
|
+
ProtocolError,
|
|
6
|
+
ResourceCleanupError,
|
|
7
|
+
} from './errors.ts';
|
|
8
|
+
import type {
|
|
9
|
+
IAbandonJobRequest,
|
|
10
|
+
IAcceptJobRequest,
|
|
11
|
+
ICacheDownloadHit,
|
|
12
|
+
IClaimJobRequest,
|
|
13
|
+
IClaimJobResponse,
|
|
14
|
+
ICompleteJobRequest,
|
|
15
|
+
ICompleteJobResponse,
|
|
16
|
+
IDiscoveryResponse,
|
|
17
|
+
IJobHeartbeatRequest,
|
|
18
|
+
IJobHeartbeatResponse,
|
|
19
|
+
IJobIdentity,
|
|
20
|
+
IJobSource,
|
|
21
|
+
ILogAcknowledgement,
|
|
22
|
+
ILogChunk,
|
|
23
|
+
IProtocolLimits,
|
|
24
|
+
IRecoverAttemptRequest,
|
|
25
|
+
IRegisterRunnerRequest,
|
|
26
|
+
IRegisterRunnerResponse,
|
|
27
|
+
IRunnerCredential,
|
|
28
|
+
IRunnerHeartbeatRequest,
|
|
29
|
+
IRunnerHeartbeatResponse,
|
|
30
|
+
IStartSessionRequest,
|
|
31
|
+
IStartSessionResponse,
|
|
32
|
+
ITransferDownload,
|
|
33
|
+
ITransferMetadata,
|
|
34
|
+
ITransferRecord,
|
|
35
|
+
TCacheDownload,
|
|
36
|
+
TOpenTransferBody,
|
|
37
|
+
} from './interfaces.ts';
|
|
38
|
+
import { ciSpecStatus, runnerProtocolBasePath, runnerProtocolIdentifier } from './plugins.ts';
|
|
39
|
+
import { isRecord, validateHttpUrl } from './validation.ts';
|
|
40
|
+
|
|
41
|
+
export type TRunnerFetch = (
|
|
42
|
+
input: RequestInfo | URL,
|
|
43
|
+
init?: RequestInit,
|
|
44
|
+
) => Promise<Response>;
|
|
45
|
+
|
|
46
|
+
export interface IRunnerApiClientOptions {
|
|
47
|
+
controlPlaneUrl: string;
|
|
48
|
+
allowInsecureLoopback: boolean;
|
|
49
|
+
requestTimeoutMs: number;
|
|
50
|
+
sourceTransferTimeoutMs?: number;
|
|
51
|
+
artifactUploadTimeoutMs?: number;
|
|
52
|
+
cacheTransferTimeoutMs?: number;
|
|
53
|
+
maximumResponseBytes: number;
|
|
54
|
+
runnerToken?: string;
|
|
55
|
+
fetch?: TRunnerFetch;
|
|
56
|
+
sleep?: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
interface IJsonRequestOptions {
|
|
60
|
+
token?: string;
|
|
61
|
+
signal?: AbortSignal;
|
|
62
|
+
fenced?: boolean;
|
|
63
|
+
expectedStatus?: number;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
interface ITransferFetchOptions {
|
|
67
|
+
signal?: AbortSignal;
|
|
68
|
+
timeoutMs: number;
|
|
69
|
+
fenced: boolean;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const retryableStatuses = new Set([429, 502, 503, 504]);
|
|
73
|
+
const maximumAttempts = 4;
|
|
74
|
+
const identifierPattern = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
75
|
+
const sha256Pattern = /^[a-f0-9]{64}$/;
|
|
76
|
+
const timestampPattern =
|
|
77
|
+
/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|[+-](\d{2}):(\d{2}))$/;
|
|
78
|
+
|
|
79
|
+
const defaultSleep = (milliseconds: number, signal?: AbortSignal): Promise<void> =>
|
|
80
|
+
new Promise((resolve, reject) => {
|
|
81
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
82
|
+
let settled = false;
|
|
83
|
+
const cleanup = (): void => signal?.removeEventListener('abort', onAbort);
|
|
84
|
+
const finish = (): void => {
|
|
85
|
+
if (settled) return;
|
|
86
|
+
settled = true;
|
|
87
|
+
cleanup();
|
|
88
|
+
resolve();
|
|
89
|
+
};
|
|
90
|
+
const onAbort = (): void => {
|
|
91
|
+
if (settled) return;
|
|
92
|
+
settled = true;
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
cleanup();
|
|
95
|
+
reject(signal?.reason);
|
|
96
|
+
};
|
|
97
|
+
const timer = setTimeout(finish, milliseconds);
|
|
98
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
99
|
+
});
|
|
100
|
+
|
|
101
|
+
const readBoundedBody = async (response: Response, maximumBytes: number): Promise<Uint8Array> => {
|
|
102
|
+
if (!response.body) return new Uint8Array();
|
|
103
|
+
const reader = response.body.getReader();
|
|
104
|
+
const chunks: Uint8Array[] = [];
|
|
105
|
+
let total = 0;
|
|
106
|
+
while (true) {
|
|
107
|
+
const { done, value } = await reader.read();
|
|
108
|
+
if (done) break;
|
|
109
|
+
total += value.byteLength;
|
|
110
|
+
if (total > maximumBytes) {
|
|
111
|
+
const error = new ProtocolError('Coordinator response exceeded the configured size limit');
|
|
112
|
+
try {
|
|
113
|
+
await reader.cancel(error);
|
|
114
|
+
} catch (cleanupError) {
|
|
115
|
+
throw new ResourceCleanupError('Coordinator response body cleanup failed', [
|
|
116
|
+
error,
|
|
117
|
+
cleanupError,
|
|
118
|
+
]);
|
|
119
|
+
}
|
|
120
|
+
throw error;
|
|
121
|
+
}
|
|
122
|
+
chunks.push(value);
|
|
123
|
+
}
|
|
124
|
+
const body = new Uint8Array(total);
|
|
125
|
+
let offset = 0;
|
|
126
|
+
for (const chunk of chunks) {
|
|
127
|
+
body.set(chunk, offset);
|
|
128
|
+
offset += chunk.byteLength;
|
|
129
|
+
}
|
|
130
|
+
return body;
|
|
131
|
+
};
|
|
132
|
+
|
|
133
|
+
const parseJsonBytes = (body: Uint8Array): unknown => {
|
|
134
|
+
if (body.byteLength === 0) throw new ProtocolError('Coordinator returned an empty JSON body');
|
|
135
|
+
try {
|
|
136
|
+
return JSON.parse(new TextDecoder().decode(body));
|
|
137
|
+
} catch (error) {
|
|
138
|
+
throw new ProtocolError('Coordinator returned invalid JSON', { cause: error });
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
const parseJsonResponse = async (response: Response, maximumBytes: number): Promise<unknown> => {
|
|
143
|
+
const contentType = response.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase();
|
|
144
|
+
if (contentType !== 'application/json') {
|
|
145
|
+
await readBoundedBody(response, maximumBytes);
|
|
146
|
+
throw new ProtocolError('Coordinator returned an invalid JSON content type');
|
|
147
|
+
}
|
|
148
|
+
return parseJsonBytes(await readBoundedBody(response, maximumBytes));
|
|
149
|
+
};
|
|
150
|
+
|
|
151
|
+
const parseRetryAfter = (value: string | null): number | undefined => {
|
|
152
|
+
if (!value) return undefined;
|
|
153
|
+
const seconds = Number(value);
|
|
154
|
+
if (Number.isFinite(seconds) && seconds >= 0) return Math.min(seconds * 1000, 30_000);
|
|
155
|
+
const timestamp = Date.parse(value);
|
|
156
|
+
if (!Number.isFinite(timestamp)) return undefined;
|
|
157
|
+
return Math.min(Math.max(0, timestamp - Date.now()), 30_000);
|
|
158
|
+
};
|
|
159
|
+
|
|
160
|
+
const exactRecord = (
|
|
161
|
+
value: unknown,
|
|
162
|
+
required: readonly string[],
|
|
163
|
+
optional: readonly string[] = [],
|
|
164
|
+
field = 'coordinator response',
|
|
165
|
+
): Record<string, unknown> => {
|
|
166
|
+
if (!isRecord(value)) throw new ProtocolError(`Invalid ${field}`);
|
|
167
|
+
const allowed = new Set([...required, ...optional]);
|
|
168
|
+
if (
|
|
169
|
+
required.some((key) => !Object.hasOwn(value, key)) ||
|
|
170
|
+
Object.keys(value).some((key) => !allowed.has(key))
|
|
171
|
+
) {
|
|
172
|
+
throw new ProtocolError(`Invalid ${field}`);
|
|
173
|
+
}
|
|
174
|
+
return value;
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
const stringField = (
|
|
178
|
+
value: unknown,
|
|
179
|
+
field: string,
|
|
180
|
+
minimumLength: number,
|
|
181
|
+
maximumLength: number,
|
|
182
|
+
pattern?: RegExp,
|
|
183
|
+
): string => {
|
|
184
|
+
if (
|
|
185
|
+
typeof value !== 'string' || value.length < minimumLength || value.length > maximumLength ||
|
|
186
|
+
(pattern && !pattern.test(value))
|
|
187
|
+
) {
|
|
188
|
+
throw new ProtocolError(`Invalid coordinator field: ${field}`);
|
|
189
|
+
}
|
|
190
|
+
return value;
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
const identifierField = (value: unknown, field: string): string =>
|
|
194
|
+
stringField(value, field, 1, 64, identifierPattern);
|
|
195
|
+
|
|
196
|
+
const sha256Field = (value: unknown, field: string): string =>
|
|
197
|
+
stringField(value, field, 64, 64, sha256Pattern);
|
|
198
|
+
|
|
199
|
+
const integerField = (
|
|
200
|
+
value: unknown,
|
|
201
|
+
field: string,
|
|
202
|
+
minimum: number,
|
|
203
|
+
maximum: number,
|
|
204
|
+
): number => {
|
|
205
|
+
if (
|
|
206
|
+
typeof value !== 'number' || !Number.isSafeInteger(value) || value < minimum ||
|
|
207
|
+
value > maximum
|
|
208
|
+
) {
|
|
209
|
+
throw new ProtocolError(`Invalid coordinator field: ${field}`);
|
|
210
|
+
}
|
|
211
|
+
return value;
|
|
212
|
+
};
|
|
213
|
+
|
|
214
|
+
const timestampField = (value: unknown, field: string): string => {
|
|
215
|
+
if (typeof value !== 'string') throw new ProtocolError(`Invalid coordinator field: ${field}`);
|
|
216
|
+
const match = timestampPattern.exec(value);
|
|
217
|
+
if (!match) throw new ProtocolError(`Invalid coordinator field: ${field}`);
|
|
218
|
+
const year = Number(match[1]);
|
|
219
|
+
const month = Number(match[2]);
|
|
220
|
+
const day = Number(match[3]);
|
|
221
|
+
const hour = Number(match[4]);
|
|
222
|
+
const minute = Number(match[5]);
|
|
223
|
+
const second = Number(match[6]);
|
|
224
|
+
const offsetHour = match[7] === undefined ? 0 : Number(match[7]);
|
|
225
|
+
const offsetMinute = match[8] === undefined ? 0 : Number(match[8]);
|
|
226
|
+
const lastDay = new Date(Date.UTC(year, month, 0)).getUTCDate();
|
|
227
|
+
if (
|
|
228
|
+
month < 1 || month > 12 || day < 1 || day > lastDay || hour > 23 || minute > 59 ||
|
|
229
|
+
second > 59 || offsetHour > 23 || offsetMinute > 59 || !Number.isFinite(Date.parse(value))
|
|
230
|
+
) {
|
|
231
|
+
throw new ProtocolError(`Invalid coordinator field: ${field}`);
|
|
232
|
+
}
|
|
233
|
+
return value;
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const parseCredential = (value: unknown, field = 'credential'): IRunnerCredential => {
|
|
237
|
+
const record = exactRecord(
|
|
238
|
+
value,
|
|
239
|
+
['credentialId', 'runnerId', 'token', 'expiresAt'],
|
|
240
|
+
['previousCredentialValidUntil'],
|
|
241
|
+
field,
|
|
242
|
+
);
|
|
243
|
+
return {
|
|
244
|
+
credentialId: identifierField(record.credentialId, `${field}.credentialId`),
|
|
245
|
+
runnerId: identifierField(record.runnerId, `${field}.runnerId`),
|
|
246
|
+
token: stringField(record.token, `${field}.token`, 32, 8192),
|
|
247
|
+
expiresAt: timestampField(record.expiresAt, `${field}.expiresAt`),
|
|
248
|
+
...(record.previousCredentialValidUntil === undefined ? {} : {
|
|
249
|
+
previousCredentialValidUntil: timestampField(
|
|
250
|
+
record.previousCredentialValidUntil,
|
|
251
|
+
`${field}.previousCredentialValidUntil`,
|
|
252
|
+
),
|
|
253
|
+
}),
|
|
254
|
+
};
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
const parseProtocolLimits = (value: unknown): IProtocolLimits => {
|
|
258
|
+
const record = exactRecord(
|
|
259
|
+
value,
|
|
260
|
+
[
|
|
261
|
+
'maximumJsonBytes',
|
|
262
|
+
'maximumLogChunkBytes',
|
|
263
|
+
'maximumTotalLogBytes',
|
|
264
|
+
'minimumLeaseSeconds',
|
|
265
|
+
'maximumLeaseSeconds',
|
|
266
|
+
],
|
|
267
|
+
[],
|
|
268
|
+
'discovery limits',
|
|
269
|
+
);
|
|
270
|
+
const limits: IProtocolLimits = {
|
|
271
|
+
maximumJsonBytes: integerField(
|
|
272
|
+
record.maximumJsonBytes,
|
|
273
|
+
'limits.maximumJsonBytes',
|
|
274
|
+
1,
|
|
275
|
+
2_097_152,
|
|
276
|
+
),
|
|
277
|
+
maximumLogChunkBytes: integerField(
|
|
278
|
+
record.maximumLogChunkBytes,
|
|
279
|
+
'limits.maximumLogChunkBytes',
|
|
280
|
+
1,
|
|
281
|
+
65_536,
|
|
282
|
+
),
|
|
283
|
+
maximumTotalLogBytes: integerField(
|
|
284
|
+
record.maximumTotalLogBytes,
|
|
285
|
+
'limits.maximumTotalLogBytes',
|
|
286
|
+
0,
|
|
287
|
+
1_073_741_824,
|
|
288
|
+
),
|
|
289
|
+
minimumLeaseSeconds: integerField(
|
|
290
|
+
record.minimumLeaseSeconds,
|
|
291
|
+
'limits.minimumLeaseSeconds',
|
|
292
|
+
30,
|
|
293
|
+
600,
|
|
294
|
+
),
|
|
295
|
+
maximumLeaseSeconds: integerField(
|
|
296
|
+
record.maximumLeaseSeconds,
|
|
297
|
+
'limits.maximumLeaseSeconds',
|
|
298
|
+
30,
|
|
299
|
+
600,
|
|
300
|
+
),
|
|
301
|
+
};
|
|
302
|
+
if (limits.minimumLeaseSeconds > limits.maximumLeaseSeconds) {
|
|
303
|
+
throw new ProtocolError('Coordinator discovery lease limits are incoherent');
|
|
304
|
+
}
|
|
305
|
+
return limits;
|
|
306
|
+
};
|
|
307
|
+
|
|
308
|
+
const parseTransferRecord = (value: unknown): ITransferRecord => {
|
|
309
|
+
const record = exactRecord(
|
|
310
|
+
value,
|
|
311
|
+
[
|
|
312
|
+
'name',
|
|
313
|
+
'format',
|
|
314
|
+
'sha256',
|
|
315
|
+
'sizeBytes',
|
|
316
|
+
'extractedSizeBytes',
|
|
317
|
+
'entryCount',
|
|
318
|
+
'createdAt',
|
|
319
|
+
],
|
|
320
|
+
[],
|
|
321
|
+
'transfer record',
|
|
322
|
+
);
|
|
323
|
+
if (record.format !== 'tar.gz') {
|
|
324
|
+
throw new ProtocolError('Invalid coordinator field: transferRecord.format');
|
|
325
|
+
}
|
|
326
|
+
return {
|
|
327
|
+
name: identifierField(record.name, 'transferRecord.name'),
|
|
328
|
+
format: 'tar.gz',
|
|
329
|
+
sha256: sha256Field(record.sha256, 'transferRecord.sha256'),
|
|
330
|
+
sizeBytes: integerField(record.sizeBytes, 'transferRecord.sizeBytes', 0, 17_179_869_184),
|
|
331
|
+
extractedSizeBytes: integerField(
|
|
332
|
+
record.extractedSizeBytes,
|
|
333
|
+
'transferRecord.extractedSizeBytes',
|
|
334
|
+
0,
|
|
335
|
+
137_438_953_472,
|
|
336
|
+
),
|
|
337
|
+
entryCount: integerField(record.entryCount, 'transferRecord.entryCount', 0, 1_000_000),
|
|
338
|
+
createdAt: timestampField(record.createdAt, 'transferRecord.createdAt'),
|
|
339
|
+
};
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
const responseHeader = (response: Response, name: string, maximumLength: number): string => {
|
|
343
|
+
const value = response.headers.get(name);
|
|
344
|
+
if (!value || value.length > maximumLength || value.includes('\0')) {
|
|
345
|
+
throw new ProtocolError(`Coordinator returned invalid ${name} header`);
|
|
346
|
+
}
|
|
347
|
+
return value;
|
|
348
|
+
};
|
|
349
|
+
|
|
350
|
+
const responseIntegerHeader = (
|
|
351
|
+
response: Response,
|
|
352
|
+
name: string,
|
|
353
|
+
maximum: number,
|
|
354
|
+
): number => {
|
|
355
|
+
const value = responseHeader(response, name, 32);
|
|
356
|
+
if (!/^\d+$/.test(value)) {
|
|
357
|
+
throw new ProtocolError(`Coordinator returned invalid ${name} header`);
|
|
358
|
+
}
|
|
359
|
+
const result = Number(value);
|
|
360
|
+
if (!Number.isSafeInteger(result) || result > maximum) {
|
|
361
|
+
throw new ProtocolError(`Coordinator returned invalid ${name} header`);
|
|
362
|
+
}
|
|
363
|
+
return result;
|
|
364
|
+
};
|
|
365
|
+
|
|
366
|
+
const validateTransferMetadata = (
|
|
367
|
+
metadata: ITransferMetadata,
|
|
368
|
+
maxima: { sizeBytes: number; extractedSizeBytes: number; entryCount: number },
|
|
369
|
+
): void => {
|
|
370
|
+
if (!sha256Pattern.test(metadata.sha256)) throw new ProtocolError('Invalid transfer SHA-256');
|
|
371
|
+
for (const [field, maximum] of Object.entries(maxima)) {
|
|
372
|
+
const value = metadata[field as keyof ITransferMetadata];
|
|
373
|
+
if (typeof value !== 'number' || !Number.isSafeInteger(value) || value < 0 || value > maximum) {
|
|
374
|
+
throw new ProtocolError(`Invalid transfer metadata ${field}`);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
};
|
|
378
|
+
|
|
379
|
+
const identityHeaders = (identity: IJobIdentity, includePathIdentity = false): Headers => {
|
|
380
|
+
for (const [field, value] of Object.entries(identity)) {
|
|
381
|
+
if (field === 'fencingToken') {
|
|
382
|
+
if (value.length < 16 || value.length > 512) {
|
|
383
|
+
throw new ProtocolError('Invalid job fencing token');
|
|
384
|
+
}
|
|
385
|
+
} else if (!identifierPattern.test(value)) {
|
|
386
|
+
throw new ProtocolError(`Invalid job identity ${field}`);
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
const headers = new Headers({
|
|
390
|
+
'x-runner-id': identity.runnerId,
|
|
391
|
+
'x-session-id': identity.sessionId,
|
|
392
|
+
'x-lease-id': identity.leaseId,
|
|
393
|
+
'x-fencing-token': identity.fencingToken,
|
|
394
|
+
});
|
|
395
|
+
if (includePathIdentity) {
|
|
396
|
+
headers.set('x-job-id', identity.jobId);
|
|
397
|
+
headers.set('x-attempt-id', identity.attemptId);
|
|
398
|
+
}
|
|
399
|
+
return headers;
|
|
400
|
+
};
|
|
401
|
+
|
|
402
|
+
const sanitizeErrorText = (value: string): string =>
|
|
403
|
+
[...value].map((character) => {
|
|
404
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
405
|
+
return codePoint < 0x20 || codePoint === 0x7f ? '?' : character;
|
|
406
|
+
}).join('');
|
|
407
|
+
|
|
408
|
+
const errorDetail = (body: Uint8Array): string | undefined => {
|
|
409
|
+
if (body.byteLength === 0) return undefined;
|
|
410
|
+
let parsed: unknown;
|
|
411
|
+
try {
|
|
412
|
+
parsed = JSON.parse(new TextDecoder().decode(body));
|
|
413
|
+
} catch {
|
|
414
|
+
return undefined;
|
|
415
|
+
}
|
|
416
|
+
if (!isRecord(parsed) || !isRecord(parsed.error)) return undefined;
|
|
417
|
+
const { code, message } = parsed.error;
|
|
418
|
+
if (
|
|
419
|
+
typeof code !== 'string' || !/^[a-z][a-z0-9_]{0,63}$/.test(code) ||
|
|
420
|
+
typeof message !== 'string' || message.length < 1 || message.length > 512
|
|
421
|
+
) {
|
|
422
|
+
return undefined;
|
|
423
|
+
}
|
|
424
|
+
return `${code}: ${sanitizeErrorText(message)}`;
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
export class RunnerApiClient {
|
|
428
|
+
private readonly origin: string;
|
|
429
|
+
private readonly baseUrl: URL;
|
|
430
|
+
private readonly fetchImplementation: TRunnerFetch;
|
|
431
|
+
private readonly sleep: (milliseconds: number, signal?: AbortSignal) => Promise<void>;
|
|
432
|
+
private runnerToken?: string;
|
|
433
|
+
|
|
434
|
+
constructor(private readonly options: IRunnerApiClientOptions) {
|
|
435
|
+
const controlPlane = validateHttpUrl(
|
|
436
|
+
options.controlPlaneUrl,
|
|
437
|
+
options.allowInsecureLoopback,
|
|
438
|
+
'controlPlaneUrl',
|
|
439
|
+
);
|
|
440
|
+
this.origin = controlPlane.origin;
|
|
441
|
+
this.baseUrl = new URL(`${runnerProtocolBasePath}/`, this.origin);
|
|
442
|
+
this.fetchImplementation = options.fetch ?? fetch;
|
|
443
|
+
this.sleep = options.sleep ?? defaultSleep;
|
|
444
|
+
this.runnerToken = options.runnerToken;
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
public setRunnerToken(token: string): void {
|
|
448
|
+
this.runnerToken = token;
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
public async discover(signal?: AbortSignal): Promise<IDiscoveryResponse> {
|
|
452
|
+
for (let attempt = 1; attempt <= maximumAttempts; attempt++) {
|
|
453
|
+
const timeoutSignal = AbortSignal.timeout(this.options.requestTimeoutMs);
|
|
454
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
455
|
+
let response: Response;
|
|
456
|
+
try {
|
|
457
|
+
response = await this.fetchImplementation(new URL(runnerProtocolBasePath, this.origin), {
|
|
458
|
+
method: 'GET',
|
|
459
|
+
headers: { accept: 'application/json' },
|
|
460
|
+
signal: requestSignal,
|
|
461
|
+
});
|
|
462
|
+
} catch (error) {
|
|
463
|
+
if (signal?.aborted) throw signal.reason;
|
|
464
|
+
throw new CoordinatorError('Coordinator discovery failed', undefined, { cause: error });
|
|
465
|
+
}
|
|
466
|
+
if (retryableStatuses.has(response.status) && attempt < maximumAttempts) {
|
|
467
|
+
await readBoundedBody(response, this.options.maximumResponseBytes);
|
|
468
|
+
await this.sleep(
|
|
469
|
+
parseRetryAfter(response.headers.get('retry-after')) ?? 250 * 2 ** (attempt - 1),
|
|
470
|
+
signal,
|
|
471
|
+
);
|
|
472
|
+
continue;
|
|
473
|
+
}
|
|
474
|
+
if (response.status !== 200) {
|
|
475
|
+
await this.throwResponseError(response, false, 'Coordinator discovery failed');
|
|
476
|
+
}
|
|
477
|
+
const value = exactRecord(
|
|
478
|
+
await parseJsonResponse(response, this.options.maximumResponseBytes),
|
|
479
|
+
['protocol', 'basePath', 'status', 'serverTime', 'limits'],
|
|
480
|
+
[],
|
|
481
|
+
'discovery response',
|
|
482
|
+
);
|
|
483
|
+
if (
|
|
484
|
+
value.protocol !== runnerProtocolIdentifier || value.basePath !== runnerProtocolBasePath ||
|
|
485
|
+
value.status !== ciSpecStatus
|
|
486
|
+
) {
|
|
487
|
+
throw new ProtocolError('Coordinator discovery is incompatible with this runner');
|
|
488
|
+
}
|
|
489
|
+
return {
|
|
490
|
+
protocol: runnerProtocolIdentifier,
|
|
491
|
+
basePath: runnerProtocolBasePath,
|
|
492
|
+
status: ciSpecStatus,
|
|
493
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
494
|
+
limits: parseProtocolLimits(value.limits),
|
|
495
|
+
};
|
|
496
|
+
}
|
|
497
|
+
throw new CoordinatorError('Coordinator discovery failed');
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
public async register(
|
|
501
|
+
request: IRegisterRunnerRequest,
|
|
502
|
+
bootstrapToken: string,
|
|
503
|
+
signal?: AbortSignal,
|
|
504
|
+
): Promise<IRegisterRunnerResponse> {
|
|
505
|
+
const value = exactRecord(
|
|
506
|
+
await this.requestJson('runners/register', request, { token: bootstrapToken, signal }),
|
|
507
|
+
['protocol', 'serverTime', 'registrationReplayUntil', 'credential'],
|
|
508
|
+
[],
|
|
509
|
+
'registration response',
|
|
510
|
+
);
|
|
511
|
+
if (value.protocol !== runnerProtocolIdentifier) {
|
|
512
|
+
throw new ProtocolError('Coordinator returned an incompatible registration protocol');
|
|
513
|
+
}
|
|
514
|
+
return {
|
|
515
|
+
protocol: runnerProtocolIdentifier,
|
|
516
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
517
|
+
registrationReplayUntil: timestampField(
|
|
518
|
+
value.registrationReplayUntil,
|
|
519
|
+
'registrationReplayUntil',
|
|
520
|
+
),
|
|
521
|
+
credential: parseCredential(value.credential),
|
|
522
|
+
};
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
public async startSession(
|
|
526
|
+
request: IStartSessionRequest,
|
|
527
|
+
signal?: AbortSignal,
|
|
528
|
+
): Promise<IStartSessionResponse> {
|
|
529
|
+
const value = exactRecord(
|
|
530
|
+
await this.requestJson(
|
|
531
|
+
`runners/${encodeURIComponent(request.runnerId)}/sessions`,
|
|
532
|
+
request,
|
|
533
|
+
{ signal },
|
|
534
|
+
),
|
|
535
|
+
['sessionId', 'protocol', 'serverTime'],
|
|
536
|
+
['credential'],
|
|
537
|
+
'session response',
|
|
538
|
+
);
|
|
539
|
+
if (value.protocol !== runnerProtocolIdentifier) {
|
|
540
|
+
throw new ProtocolError('Coordinator returned an incompatible session protocol');
|
|
541
|
+
}
|
|
542
|
+
return {
|
|
543
|
+
sessionId: identifierField(value.sessionId, 'sessionId'),
|
|
544
|
+
protocol: runnerProtocolIdentifier,
|
|
545
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
546
|
+
...(value.credential === undefined ? {} : { credential: parseCredential(value.credential) }),
|
|
547
|
+
};
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
public async heartbeatRunner(
|
|
551
|
+
request: IRunnerHeartbeatRequest,
|
|
552
|
+
signal?: AbortSignal,
|
|
553
|
+
): Promise<IRunnerHeartbeatResponse> {
|
|
554
|
+
const value = exactRecord(
|
|
555
|
+
await this.requestJson(
|
|
556
|
+
`runners/${encodeURIComponent(request.runnerId)}/heartbeat`,
|
|
557
|
+
request,
|
|
558
|
+
{ signal },
|
|
559
|
+
),
|
|
560
|
+
['serverTime', 'drainRequested'],
|
|
561
|
+
['credential'],
|
|
562
|
+
'runner heartbeat response',
|
|
563
|
+
);
|
|
564
|
+
if (typeof value.drainRequested !== 'boolean') {
|
|
565
|
+
throw new ProtocolError('Invalid coordinator field: drainRequested');
|
|
566
|
+
}
|
|
567
|
+
return {
|
|
568
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
569
|
+
drainRequested: value.drainRequested,
|
|
570
|
+
...(value.credential === undefined ? {} : { credential: parseCredential(value.credential) }),
|
|
571
|
+
};
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
public async claimJob(
|
|
575
|
+
request: IClaimJobRequest,
|
|
576
|
+
signal?: AbortSignal,
|
|
577
|
+
): Promise<IClaimJobResponse> {
|
|
578
|
+
const value = exactRecord(
|
|
579
|
+
await this.requestJson('jobs/claim', request, { signal }),
|
|
580
|
+
['serverTime', 'lease'],
|
|
581
|
+
['retryAfterMs'],
|
|
582
|
+
'claim response',
|
|
583
|
+
);
|
|
584
|
+
if (value.lease !== null && !isRecord(value.lease)) {
|
|
585
|
+
throw new ProtocolError('Invalid coordinator field: lease');
|
|
586
|
+
}
|
|
587
|
+
return {
|
|
588
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
589
|
+
...(value.retryAfterMs === undefined ? {} : {
|
|
590
|
+
retryAfterMs: integerField(value.retryAfterMs, 'retryAfterMs', 0, 30_000),
|
|
591
|
+
}),
|
|
592
|
+
lease: value.lease,
|
|
593
|
+
};
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
public async acceptJob(request: IAcceptJobRequest, signal?: AbortSignal): Promise<void> {
|
|
597
|
+
await this.requestJson(this.jobPath(request.identity, 'accept'), request, {
|
|
598
|
+
signal,
|
|
599
|
+
fenced: true,
|
|
600
|
+
expectedStatus: 204,
|
|
601
|
+
});
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
public async heartbeatJob(
|
|
605
|
+
request: IJobHeartbeatRequest,
|
|
606
|
+
signal?: AbortSignal,
|
|
607
|
+
): Promise<IJobHeartbeatResponse> {
|
|
608
|
+
const value = exactRecord(
|
|
609
|
+
await this.requestJson(this.jobPath(request.identity, 'heartbeat'), request, {
|
|
610
|
+
signal,
|
|
611
|
+
fenced: true,
|
|
612
|
+
}),
|
|
613
|
+
['serverTime', 'leaseExpiresAt'],
|
|
614
|
+
['cancellation'],
|
|
615
|
+
'job heartbeat response',
|
|
616
|
+
);
|
|
617
|
+
let cancellation: IJobHeartbeatResponse['cancellation'];
|
|
618
|
+
if (value.cancellation !== undefined) {
|
|
619
|
+
const directive = exactRecord(
|
|
620
|
+
value.cancellation,
|
|
621
|
+
['requestId', 'requestedAt', 'reason', 'terminateBy'],
|
|
622
|
+
[],
|
|
623
|
+
'cancellation directive',
|
|
624
|
+
);
|
|
625
|
+
if (
|
|
626
|
+
directive.reason !== 'user_requested' && directive.reason !== 'superseded' &&
|
|
627
|
+
directive.reason !== 'policy' && directive.reason !== 'coordinator_shutdown'
|
|
628
|
+
) {
|
|
629
|
+
throw new ProtocolError('Invalid coordinator field: cancellation.reason');
|
|
630
|
+
}
|
|
631
|
+
cancellation = {
|
|
632
|
+
requestId: identifierField(directive.requestId, 'cancellation.requestId'),
|
|
633
|
+
requestedAt: timestampField(directive.requestedAt, 'cancellation.requestedAt'),
|
|
634
|
+
reason: directive.reason,
|
|
635
|
+
terminateBy: timestampField(directive.terminateBy, 'cancellation.terminateBy'),
|
|
636
|
+
};
|
|
637
|
+
}
|
|
638
|
+
return {
|
|
639
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
640
|
+
leaseExpiresAt: timestampField(value.leaseExpiresAt, 'leaseExpiresAt'),
|
|
641
|
+
...(cancellation ? { cancellation } : {}),
|
|
642
|
+
};
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
public async appendLog(chunk: ILogChunk, signal?: AbortSignal): Promise<ILogAcknowledgement> {
|
|
646
|
+
const value = exactRecord(
|
|
647
|
+
await this.requestJson(this.jobPath(chunk.identity, 'logs'), chunk, {
|
|
648
|
+
signal,
|
|
649
|
+
fenced: true,
|
|
650
|
+
}),
|
|
651
|
+
['serverTime', 'nextSequence'],
|
|
652
|
+
[],
|
|
653
|
+
'log acknowledgement',
|
|
654
|
+
);
|
|
655
|
+
return {
|
|
656
|
+
serverTime: timestampField(value.serverTime, 'serverTime'),
|
|
657
|
+
nextSequence: integerField(value.nextSequence, 'nextSequence', 0, Number.MAX_SAFE_INTEGER),
|
|
658
|
+
};
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
public async completeJob(
|
|
662
|
+
request: ICompleteJobRequest,
|
|
663
|
+
signal?: AbortSignal,
|
|
664
|
+
): Promise<ICompleteJobResponse> {
|
|
665
|
+
const value = exactRecord(
|
|
666
|
+
await this.requestJson(this.jobPath(request.identity, 'complete'), request, {
|
|
667
|
+
signal,
|
|
668
|
+
fenced: true,
|
|
669
|
+
}),
|
|
670
|
+
['serverTime', 'accepted'],
|
|
671
|
+
[],
|
|
672
|
+
'completion response',
|
|
673
|
+
);
|
|
674
|
+
if (value.accepted !== true) {
|
|
675
|
+
throw new ProtocolError('Invalid coordinator field: accepted');
|
|
676
|
+
}
|
|
677
|
+
return { serverTime: timestampField(value.serverTime, 'serverTime'), accepted: true };
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
public async abandonJob(request: IAbandonJobRequest, signal?: AbortSignal): Promise<void> {
|
|
681
|
+
await this.requestJson(this.jobPath(request.identity, 'abandon'), request, {
|
|
682
|
+
signal,
|
|
683
|
+
fenced: true,
|
|
684
|
+
expectedStatus: 204,
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
public async recoverAttempt(
|
|
689
|
+
request: IRecoverAttemptRequest,
|
|
690
|
+
signal?: AbortSignal,
|
|
691
|
+
): Promise<void> {
|
|
692
|
+
await this.requestJson('jobs/recover', request, { signal, expectedStatus: 204 });
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
public async downloadSource(
|
|
696
|
+
identity: IJobIdentity,
|
|
697
|
+
source: IJobSource,
|
|
698
|
+
signal?: AbortSignal,
|
|
699
|
+
): Promise<ITransferDownload> {
|
|
700
|
+
const expectedMetadata: ITransferMetadata = {
|
|
701
|
+
sha256: source.sha256,
|
|
702
|
+
sizeBytes: source.sizeBytes,
|
|
703
|
+
extractedSizeBytes: source.extractedSizeBytes,
|
|
704
|
+
entryCount: source.entryCount,
|
|
705
|
+
};
|
|
706
|
+
validateTransferMetadata(expectedMetadata, {
|
|
707
|
+
sizeBytes: 8_589_934_592,
|
|
708
|
+
extractedSizeBytes: 68_719_476_736,
|
|
709
|
+
entryCount: 1_000_000,
|
|
710
|
+
});
|
|
711
|
+
const headers = identityHeaders(identity, true);
|
|
712
|
+
headers.set('authorization', `Bearer ${this.requireRunnerToken()}`);
|
|
713
|
+
headers.set('accept', 'application/gzip');
|
|
714
|
+
const response = await this.fetchTransfer(
|
|
715
|
+
`sources/${expectedMetadata.sha256}`,
|
|
716
|
+
{ method: 'GET', headers, redirect: 'error' },
|
|
717
|
+
{
|
|
718
|
+
signal,
|
|
719
|
+
timeoutMs: this.options.sourceTransferTimeoutMs ?? 10 * 60 * 1000,
|
|
720
|
+
fenced: true,
|
|
721
|
+
},
|
|
722
|
+
);
|
|
723
|
+
const result = await this.parseTransferDownload(response, {
|
|
724
|
+
sizeBytes: 8_589_934_592,
|
|
725
|
+
extractedSizeBytes: 68_719_476_736,
|
|
726
|
+
entryCount: 1_000_000,
|
|
727
|
+
});
|
|
728
|
+
if (
|
|
729
|
+
result.sha256 !== expectedMetadata.sha256 ||
|
|
730
|
+
result.sizeBytes !== expectedMetadata.sizeBytes ||
|
|
731
|
+
result.extractedSizeBytes !== expectedMetadata.extractedSizeBytes ||
|
|
732
|
+
result.entryCount !== expectedMetadata.entryCount
|
|
733
|
+
) {
|
|
734
|
+
const error = new ProtocolError('Coordinator returned mismatched source metadata');
|
|
735
|
+
try {
|
|
736
|
+
await result.body.cancel(error);
|
|
737
|
+
} catch (cleanupError) {
|
|
738
|
+
throw new ResourceCleanupError('Source transfer body cleanup failed', [
|
|
739
|
+
error,
|
|
740
|
+
cleanupError,
|
|
741
|
+
]);
|
|
742
|
+
}
|
|
743
|
+
throw error;
|
|
744
|
+
}
|
|
745
|
+
return result;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
public async downloadCache(
|
|
749
|
+
identity: IJobIdentity,
|
|
750
|
+
name: string,
|
|
751
|
+
signal?: AbortSignal,
|
|
752
|
+
): Promise<TCacheDownload> {
|
|
753
|
+
identifierField(name, 'cacheName');
|
|
754
|
+
const headers = identityHeaders(identity);
|
|
755
|
+
headers.set('authorization', `Bearer ${this.requireRunnerToken()}`);
|
|
756
|
+
headers.set('accept', 'application/gzip');
|
|
757
|
+
const response = await this.fetchTransfer(
|
|
758
|
+
this.jobPath(identity, `caches/${encodeURIComponent(name)}`),
|
|
759
|
+
{ method: 'GET', headers, redirect: 'error' },
|
|
760
|
+
{
|
|
761
|
+
signal,
|
|
762
|
+
timeoutMs: this.options.cacheTransferTimeoutMs ?? 10 * 60 * 1000,
|
|
763
|
+
fenced: true,
|
|
764
|
+
},
|
|
765
|
+
new Set([200, 204]),
|
|
766
|
+
);
|
|
767
|
+
if (response.status === 204) return { hit: false };
|
|
768
|
+
return {
|
|
769
|
+
hit: true,
|
|
770
|
+
...await this.parseTransferDownload(response, {
|
|
771
|
+
sizeBytes: 17_179_869_184,
|
|
772
|
+
extractedSizeBytes: 137_438_953_472,
|
|
773
|
+
entryCount: 1_000_000,
|
|
774
|
+
}),
|
|
775
|
+
} satisfies ICacheDownloadHit;
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
public async uploadArtifact(
|
|
779
|
+
identity: IJobIdentity,
|
|
780
|
+
name: string,
|
|
781
|
+
transferRequestId: string,
|
|
782
|
+
metadata: ITransferMetadata,
|
|
783
|
+
openBody: TOpenTransferBody,
|
|
784
|
+
signal?: AbortSignal,
|
|
785
|
+
): Promise<ITransferRecord> {
|
|
786
|
+
return await this.uploadTransfer(
|
|
787
|
+
this.jobPath(
|
|
788
|
+
identity,
|
|
789
|
+
`artifacts/${encodeURIComponent(identifierField(name, 'artifactName'))}`,
|
|
790
|
+
),
|
|
791
|
+
identity,
|
|
792
|
+
name,
|
|
793
|
+
transferRequestId,
|
|
794
|
+
metadata,
|
|
795
|
+
openBody,
|
|
796
|
+
this.options.artifactUploadTimeoutMs ?? 10 * 60 * 1000,
|
|
797
|
+
signal,
|
|
798
|
+
);
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
public async uploadCache(
|
|
802
|
+
identity: IJobIdentity,
|
|
803
|
+
name: string,
|
|
804
|
+
transferRequestId: string,
|
|
805
|
+
metadata: ITransferMetadata,
|
|
806
|
+
openBody: TOpenTransferBody,
|
|
807
|
+
signal?: AbortSignal,
|
|
808
|
+
): Promise<ITransferRecord> {
|
|
809
|
+
return await this.uploadTransfer(
|
|
810
|
+
this.jobPath(identity, `caches/${encodeURIComponent(identifierField(name, 'cacheName'))}`),
|
|
811
|
+
identity,
|
|
812
|
+
name,
|
|
813
|
+
transferRequestId,
|
|
814
|
+
metadata,
|
|
815
|
+
openBody,
|
|
816
|
+
this.options.cacheTransferTimeoutMs ?? 10 * 60 * 1000,
|
|
817
|
+
signal,
|
|
818
|
+
);
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
private requireRunnerToken(): string {
|
|
822
|
+
if (!this.runnerToken) {
|
|
823
|
+
throw new AuthenticationError('Runner credentials are not configured');
|
|
824
|
+
}
|
|
825
|
+
return this.runnerToken;
|
|
826
|
+
}
|
|
827
|
+
|
|
828
|
+
private jobPath(identity: IJobIdentity, operation: string): string {
|
|
829
|
+
return `jobs/${encodeURIComponent(identity.jobId)}/attempts/${
|
|
830
|
+
encodeURIComponent(identity.attemptId)
|
|
831
|
+
}/${operation}`;
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
private async requestJson(
|
|
835
|
+
path: string,
|
|
836
|
+
body: unknown,
|
|
837
|
+
options: IJsonRequestOptions = {},
|
|
838
|
+
): Promise<unknown> {
|
|
839
|
+
const token = options.token ?? this.requireRunnerToken();
|
|
840
|
+
let serializedBody: string;
|
|
841
|
+
try {
|
|
842
|
+
serializedBody = JSON.stringify(body);
|
|
843
|
+
} catch (error) {
|
|
844
|
+
throw new ProtocolError('Runner request is not valid JSON', { cause: error });
|
|
845
|
+
}
|
|
846
|
+
const expectedStatus = options.expectedStatus ?? 200;
|
|
847
|
+
for (let attempt = 1; attempt <= maximumAttempts; attempt++) {
|
|
848
|
+
const timeoutSignal = AbortSignal.timeout(this.options.requestTimeoutMs);
|
|
849
|
+
const signal = options.signal
|
|
850
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
851
|
+
: timeoutSignal;
|
|
852
|
+
let response: Response;
|
|
853
|
+
try {
|
|
854
|
+
response = await this.fetchImplementation(new URL(path, this.baseUrl), {
|
|
855
|
+
method: 'POST',
|
|
856
|
+
headers: {
|
|
857
|
+
authorization: `Bearer ${token}`,
|
|
858
|
+
'content-type': 'application/json',
|
|
859
|
+
accept: 'application/json',
|
|
860
|
+
},
|
|
861
|
+
body: serializedBody,
|
|
862
|
+
signal,
|
|
863
|
+
});
|
|
864
|
+
} catch (error) {
|
|
865
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
866
|
+
throw new CoordinatorError('Coordinator request failed', undefined, { cause: error });
|
|
867
|
+
}
|
|
868
|
+
if (retryableStatuses.has(response.status) && attempt < maximumAttempts) {
|
|
869
|
+
await readBoundedBody(response, this.options.maximumResponseBytes);
|
|
870
|
+
await this.sleep(
|
|
871
|
+
parseRetryAfter(response.headers.get('retry-after')) ?? 250 * 2 ** (attempt - 1),
|
|
872
|
+
options.signal,
|
|
873
|
+
);
|
|
874
|
+
continue;
|
|
875
|
+
}
|
|
876
|
+
if (response.status !== expectedStatus) {
|
|
877
|
+
await this.throwResponseError(
|
|
878
|
+
response,
|
|
879
|
+
options.fenced ?? false,
|
|
880
|
+
'Coordinator request failed',
|
|
881
|
+
);
|
|
882
|
+
}
|
|
883
|
+
if (expectedStatus === 204) {
|
|
884
|
+
if (response.body) await readBoundedBody(response, this.options.maximumResponseBytes);
|
|
885
|
+
return null;
|
|
886
|
+
}
|
|
887
|
+
return await parseJsonResponse(response, this.options.maximumResponseBytes);
|
|
888
|
+
}
|
|
889
|
+
throw new CoordinatorError('Coordinator request failed');
|
|
890
|
+
}
|
|
891
|
+
|
|
892
|
+
private async fetchTransfer(
|
|
893
|
+
path: string,
|
|
894
|
+
init: RequestInit,
|
|
895
|
+
options: ITransferFetchOptions,
|
|
896
|
+
expectedStatuses = new Set([200]),
|
|
897
|
+
): Promise<Response> {
|
|
898
|
+
for (let attempt = 1; attempt <= maximumAttempts; attempt++) {
|
|
899
|
+
const timeoutSignal = AbortSignal.timeout(options.timeoutMs);
|
|
900
|
+
const signal = options.signal
|
|
901
|
+
? AbortSignal.any([options.signal, timeoutSignal])
|
|
902
|
+
: timeoutSignal;
|
|
903
|
+
let response: Response;
|
|
904
|
+
try {
|
|
905
|
+
response = await this.fetchImplementation(new URL(path, this.baseUrl), { ...init, signal });
|
|
906
|
+
} catch (error) {
|
|
907
|
+
if (options.signal?.aborted) throw options.signal.reason;
|
|
908
|
+
throw new CoordinatorError('Coordinator transfer failed', undefined, { cause: error });
|
|
909
|
+
}
|
|
910
|
+
if (retryableStatuses.has(response.status) && attempt < maximumAttempts) {
|
|
911
|
+
await readBoundedBody(response, this.options.maximumResponseBytes);
|
|
912
|
+
await this.sleep(
|
|
913
|
+
parseRetryAfter(response.headers.get('retry-after')) ?? 250 * 2 ** (attempt - 1),
|
|
914
|
+
options.signal,
|
|
915
|
+
);
|
|
916
|
+
continue;
|
|
917
|
+
}
|
|
918
|
+
if (!expectedStatuses.has(response.status)) {
|
|
919
|
+
await this.throwResponseError(response, options.fenced, 'Coordinator transfer failed');
|
|
920
|
+
}
|
|
921
|
+
return response;
|
|
922
|
+
}
|
|
923
|
+
throw new CoordinatorError('Coordinator transfer failed');
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
private async uploadTransfer(
|
|
927
|
+
path: string,
|
|
928
|
+
identity: IJobIdentity,
|
|
929
|
+
name: string,
|
|
930
|
+
transferRequestId: string,
|
|
931
|
+
metadata: ITransferMetadata,
|
|
932
|
+
openBody: TOpenTransferBody,
|
|
933
|
+
timeoutMs: number,
|
|
934
|
+
signal?: AbortSignal,
|
|
935
|
+
): Promise<ITransferRecord> {
|
|
936
|
+
identifierField(transferRequestId, 'transferRequestId');
|
|
937
|
+
const stableMetadata: ITransferMetadata = { ...metadata };
|
|
938
|
+
validateTransferMetadata(stableMetadata, {
|
|
939
|
+
sizeBytes: 17_179_869_184,
|
|
940
|
+
extractedSizeBytes: 137_438_953_472,
|
|
941
|
+
entryCount: 1_000_000,
|
|
942
|
+
});
|
|
943
|
+
const headers = identityHeaders(identity);
|
|
944
|
+
headers.set('authorization', `Bearer ${this.requireRunnerToken()}`);
|
|
945
|
+
headers.set('accept', 'application/json');
|
|
946
|
+
headers.set('content-type', 'application/gzip');
|
|
947
|
+
headers.set('content-length', String(stableMetadata.sizeBytes));
|
|
948
|
+
headers.set('x-content-sha256', stableMetadata.sha256);
|
|
949
|
+
headers.set('x-transfer-request-id', transferRequestId);
|
|
950
|
+
headers.set('x-extracted-bytes', String(stableMetadata.extractedSizeBytes));
|
|
951
|
+
headers.set('x-archive-entries', String(stableMetadata.entryCount));
|
|
952
|
+
|
|
953
|
+
for (let attempt = 1; attempt <= maximumAttempts; attempt++) {
|
|
954
|
+
const timeoutSignal = AbortSignal.timeout(timeoutMs);
|
|
955
|
+
const requestSignal = signal ? AbortSignal.any([signal, timeoutSignal]) : timeoutSignal;
|
|
956
|
+
let response: Response;
|
|
957
|
+
let body: ReadableStream<Uint8Array> | undefined;
|
|
958
|
+
try {
|
|
959
|
+
body = await openBody();
|
|
960
|
+
response = await this.fetchImplementation(new URL(path, this.baseUrl), {
|
|
961
|
+
method: 'PUT',
|
|
962
|
+
headers,
|
|
963
|
+
body,
|
|
964
|
+
redirect: 'error',
|
|
965
|
+
signal: requestSignal,
|
|
966
|
+
});
|
|
967
|
+
} catch (error) {
|
|
968
|
+
if (body) {
|
|
969
|
+
try {
|
|
970
|
+
await body.cancel(error);
|
|
971
|
+
} catch (cleanupError) {
|
|
972
|
+
throw new ResourceCleanupError('Coordinator upload body cleanup failed', [
|
|
973
|
+
error,
|
|
974
|
+
cleanupError,
|
|
975
|
+
]);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
if (signal?.aborted) throw signal.reason;
|
|
979
|
+
throw new CoordinatorError('Coordinator upload failed', undefined, { cause: error });
|
|
980
|
+
}
|
|
981
|
+
if (retryableStatuses.has(response.status) && attempt < maximumAttempts) {
|
|
982
|
+
await readBoundedBody(response, this.options.maximumResponseBytes);
|
|
983
|
+
await this.sleep(
|
|
984
|
+
parseRetryAfter(response.headers.get('retry-after')) ?? 250 * 2 ** (attempt - 1),
|
|
985
|
+
signal,
|
|
986
|
+
);
|
|
987
|
+
continue;
|
|
988
|
+
}
|
|
989
|
+
if (response.status !== 200) {
|
|
990
|
+
await this.throwResponseError(response, true, 'Coordinator upload failed');
|
|
991
|
+
}
|
|
992
|
+
const record = parseTransferRecord(
|
|
993
|
+
await parseJsonResponse(response, this.options.maximumResponseBytes),
|
|
994
|
+
);
|
|
995
|
+
if (
|
|
996
|
+
record.name !== name || record.sha256 !== stableMetadata.sha256 ||
|
|
997
|
+
record.sizeBytes !== stableMetadata.sizeBytes ||
|
|
998
|
+
record.extractedSizeBytes !== stableMetadata.extractedSizeBytes ||
|
|
999
|
+
record.entryCount !== stableMetadata.entryCount
|
|
1000
|
+
) {
|
|
1001
|
+
throw new ProtocolError('Coordinator returned mismatched transfer metadata');
|
|
1002
|
+
}
|
|
1003
|
+
return record;
|
|
1004
|
+
}
|
|
1005
|
+
throw new CoordinatorError('Coordinator upload failed');
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
private async parseTransferDownload(
|
|
1009
|
+
response: Response,
|
|
1010
|
+
maxima: { sizeBytes: number; extractedSizeBytes: number; entryCount: number },
|
|
1011
|
+
): Promise<ITransferDownload> {
|
|
1012
|
+
try {
|
|
1013
|
+
if (response.headers.get('content-type')?.trim().toLowerCase() !== 'application/gzip') {
|
|
1014
|
+
throw new ProtocolError('Coordinator returned an invalid transfer content type');
|
|
1015
|
+
}
|
|
1016
|
+
const sha256 = responseHeader(response, 'x-content-sha256', 64);
|
|
1017
|
+
if (!sha256Pattern.test(sha256)) {
|
|
1018
|
+
throw new ProtocolError('Coordinator returned an invalid transfer SHA-256');
|
|
1019
|
+
}
|
|
1020
|
+
const sizeBytes = responseIntegerHeader(response, 'content-length', maxima.sizeBytes);
|
|
1021
|
+
const extractedSizeBytes = responseIntegerHeader(
|
|
1022
|
+
response,
|
|
1023
|
+
'x-extracted-bytes',
|
|
1024
|
+
maxima.extractedSizeBytes,
|
|
1025
|
+
);
|
|
1026
|
+
const entryCount = responseIntegerHeader(response, 'x-archive-entries', maxima.entryCount);
|
|
1027
|
+
if (!response.body) throw new ProtocolError('Coordinator returned an empty transfer body');
|
|
1028
|
+
return { sha256, sizeBytes, extractedSizeBytes, entryCount, body: response.body };
|
|
1029
|
+
} catch (error) {
|
|
1030
|
+
try {
|
|
1031
|
+
await response.body?.cancel(error);
|
|
1032
|
+
} catch (cleanupError) {
|
|
1033
|
+
throw new ResourceCleanupError('Coordinator transfer response cleanup failed', [
|
|
1034
|
+
error,
|
|
1035
|
+
cleanupError,
|
|
1036
|
+
]);
|
|
1037
|
+
}
|
|
1038
|
+
throw error;
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
private async throwResponseError(
|
|
1043
|
+
response: Response,
|
|
1044
|
+
fenced: boolean,
|
|
1045
|
+
operation: string,
|
|
1046
|
+
): Promise<never> {
|
|
1047
|
+
const body = await readBoundedBody(response, this.options.maximumResponseBytes);
|
|
1048
|
+
if (response.status === 401 || response.status === 403) throw new AuthenticationError();
|
|
1049
|
+
if (response.status === 409 && fenced) throw new LeaseLostError();
|
|
1050
|
+
if (response.status === 413) {
|
|
1051
|
+
throw new ProtocolError('Coordinator rejected a request above the protocol limit');
|
|
1052
|
+
}
|
|
1053
|
+
const detail = errorDetail(body);
|
|
1054
|
+
throw new CoordinatorError(
|
|
1055
|
+
`${operation} with HTTP ${response.status}${detail ? ` (${detail})` : ''}`,
|
|
1056
|
+
response.status,
|
|
1057
|
+
);
|
|
1058
|
+
}
|
|
1059
|
+
}
|