Repository navigation
Expand file tree
/
Copy pathupload-client.ts
More file actions
421 lines (390 loc) · 13.1 KB
/
Copy pathupload-client.ts
File metadata and controls
421 lines (390 loc) · 13.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
import { randomUUID } from 'node:crypto';
import { AppError } from '@agent-device/kernel/errors';
import {
buildDaemonHttpAuthHeaders,
buildDaemonHttpLeaseHeaders,
} from '@agent-device/contracts/daemon-http';
import { prepareUploadArtifact, type PreparedUploadArtifact } from './upload-client-artifact.ts';
import { isRetryableUploadStreamError, streamFileToHttpRequest } from './upload-stream.ts';
import type { UploadProgressSink } from './upload-progress.ts';
const UPLOAD_PREFLIGHT_TIMEOUT_MS = 30 * 1000;
const ARTIFACT_HASH_ALGORITHM = 'sha256';
type UploadArtifactOptions = {
localPath: string;
baseUrl: string;
token: string;
platform?: string;
/** The lease this upload is for; every request to the daemon names it in a header. */
leaseId?: string;
onProgress?: UploadProgressSink;
/**
* Ends the upload when the thing it is uploading for stops being worth finishing — today, a beat
* that found the device's lease gone. Aborted requests reject with the signal's own reason.
*/
signal?: AbortSignal;
};
type UploadResponse = {
ok: boolean;
uploadId: string;
};
type UploadPreflightResponse = {
ok: boolean;
cacheHit?: boolean;
uploadId?: string;
upload?: {
url?: string;
headers?: Record<string, string>;
};
};
type UploadPreflightResult =
| {
kind: 'cache-hit';
uploadId: string;
}
| {
kind: 'direct-upload';
uploadId: string;
url: string;
headers: Record<string, string>;
};
export async function uploadArtifact(options: UploadArtifactOptions): Promise<string> {
const prepared = await prepareUploadArtifact(options.localPath, options.platform);
const normalizedBase = options.baseUrl.endsWith('/') ? options.baseUrl : `${options.baseUrl}/`;
const uploadAttemptId = randomUUID();
try {
const preflight = await requestUploadPreflight({
normalizedBase,
token: options.token,
leaseId: options.leaseId,
artifact: prepared,
uploadAttemptId,
signal: options.signal,
});
if (preflight?.kind === 'cache-hit') {
return preflight.uploadId;
}
if (preflight?.kind === 'direct-upload') {
const directUpload = await tryDirectUploadWithResume({
normalizedBase,
token: options.token,
leaseId: options.leaseId,
artifact: prepared,
preflight,
uploadAttemptId,
onProgress: options.onProgress,
signal: options.signal,
});
if (directUpload) return directUpload;
options.onProgress?.({
type: 'fallback',
from: 'direct',
to: 'legacy',
fileName: prepared.fileName,
});
return await uploadLegacyArtifact({
normalizedBase,
token: options.token,
leaseId: options.leaseId,
artifact: prepared,
onProgress: options.onProgress,
signal: options.signal,
});
}
return await uploadLegacyArtifact({
normalizedBase,
token: options.token,
leaseId: options.leaseId,
artifact: prepared,
onProgress: options.onProgress,
signal: options.signal,
});
} finally {
prepared.cleanup();
}
}
async function tryDirectUploadWithResume(options: {
normalizedBase: string;
token: string;
leaseId?: string;
artifact: PreparedUploadArtifact;
preflight: Extract<UploadPreflightResult, { kind: 'direct-upload' }>;
uploadAttemptId: string;
onProgress?: UploadProgressSink;
signal?: AbortSignal;
}): Promise<string | undefined> {
const uploadOnce = async (
preflight: Extract<UploadPreflightResult, { kind: 'direct-upload' }>,
): Promise<string> => {
await uploadDirectArtifact(options, preflight);
return await finalizeDirectUpload({
normalizedBase: options.normalizedBase,
token: options.token,
leaseId: options.leaseId,
uploadId: preflight.uploadId,
signal: options.signal,
});
};
try {
return await uploadOnce(options.preflight);
} catch (error) {
// A canceled upload resumes for no reason: the thing it was uploaded for is already gone, and
// re-preflighting would ask the daemon for a fresh ticket to send bytes nobody is waiting on.
if (options.signal?.aborted) throw error;
if (!shouldRetryDirectUpload(error)) return undefined;
return await retryDirectUpload(options, uploadOnce);
}
}
/**
* One fresh attempt after a retryable stream failure, asked for under the same attempt id.
*
* Anything short of a usable ticket — a cache hit excepted, which is itself a finished upload —
* hands the caller back to the legacy path. A second failure is not retried again: a ticket that
* failed twice is a transport or ticket problem the legacy route may still survive.
*/
async function retryDirectUpload(
options: {
normalizedBase: string;
token: string;
leaseId?: string;
artifact: PreparedUploadArtifact;
uploadAttemptId: string;
onProgress?: UploadProgressSink;
signal?: AbortSignal;
},
uploadOnce: (
preflight: Extract<UploadPreflightResult, { kind: 'direct-upload' }>,
) => Promise<string>,
): Promise<string | undefined> {
const retryPreflight = await requestUploadPreflight({
normalizedBase: options.normalizedBase,
token: options.token,
leaseId: options.leaseId,
artifact: options.artifact,
uploadAttemptId: options.uploadAttemptId,
signal: options.signal,
});
if (retryPreflight?.kind === 'cache-hit') {
return retryPreflight.uploadId;
}
if (retryPreflight?.kind === 'direct-upload') {
try {
return await uploadOnce(retryPreflight);
} catch {
return undefined;
}
}
return undefined;
}
function shouldRetryDirectUpload(error: unknown): boolean {
if (!(error instanceof AppError)) return true;
return isRetryableUploadStreamError(error);
}
async function uploadLegacyArtifact(options: {
normalizedBase: string;
token: string;
leaseId?: string;
artifact: PreparedUploadArtifact;
onProgress?: UploadProgressSink;
signal?: AbortSignal;
}): Promise<string> {
const { normalizedBase, token, leaseId, artifact } = options;
const uploadUrl = new URL('upload', normalizedBase);
const headers: Record<string, string> = {
'content-type': artifact.contentType,
'x-artifact-type': artifact.artifactType,
'x-artifact-filename': artifact.fileName,
'x-artifact-hash': artifact.sha256,
'x-artifact-hash-algorithm': ARTIFACT_HASH_ALGORITHM,
'transfer-encoding': 'chunked',
};
Object.assign(headers, buildDaemonHttpAuthHeaders(token), buildDaemonHttpLeaseHeaders(leaseId));
const response = await streamFileToHttpRequest({
url: uploadUrl,
method: 'POST',
headers,
payloadPath: artifact.payloadPath,
timeoutMessage: 'Artifact upload timed out',
timeoutHint: 'The upload to the remote daemon exceeded the 5-minute timeout.',
errorMessage: 'Failed to upload artifact to remote daemon',
errorHint: 'Verify the remote daemon is reachable and supports artifact uploads.',
signal: options.signal,
progress: {
stage: 'legacy',
fileName: artifact.fileName,
onProgress: options.onProgress,
},
});
try {
const parsed = JSON.parse(response.body) as UploadResponse;
if (!parsed.ok || !parsed.uploadId) {
throw new AppError('COMMAND_FAILED', `Upload failed: ${response.body}`);
}
return parsed.uploadId;
} catch (error) {
if (error instanceof AppError) throw error;
throw new AppError('COMMAND_FAILED', `Invalid upload response: ${response.body}`);
}
}
async function requestUploadPreflight(options: {
normalizedBase: string;
token: string;
leaseId?: string;
artifact: PreparedUploadArtifact;
uploadAttemptId: string;
signal?: AbortSignal;
}): Promise<UploadPreflightResult | undefined> {
const preflightUrl = new URL('upload/preflight', options.normalizedBase);
const headers: Record<string, string> = {
'content-type': 'application/json',
};
Object.assign(
headers,
buildDaemonHttpAuthHeaders(options.token),
buildDaemonHttpLeaseHeaders(options.leaseId),
);
const response = await fetch(preflightUrl, {
method: 'POST',
headers,
signal: combineUploadSignals(options.signal, UPLOAD_PREFLIGHT_TIMEOUT_MS),
body: JSON.stringify({
uploadAttemptId: options.uploadAttemptId,
sha256: options.artifact.sha256,
fileName: options.artifact.fileName,
sizeBytes: options.artifact.sizeBytes,
artifactType: options.artifact.artifactType,
...(options.artifact.platform ? { platform: options.artifact.platform } : {}),
contentType: options.artifact.contentType,
}),
}).catch((error: unknown) => {
// A failed preflight is ordinary here — the caller falls back to the legacy upload. A canceled
// one is not: there is nothing to fall back to when the lease that paid for this upload is gone.
if (options.signal?.aborted) throw error;
return undefined;
});
if (!response?.ok) {
return undefined;
}
return parseUploadPreflightResult(await response.json().catch(() => undefined));
}
/**
* The signal one upload request runs under: the caller's cancellation and the request's own
* timeout, whichever fires first.
*/
function combineUploadSignals(signal: AbortSignal | undefined, timeoutMs: number): AbortSignal {
const timeout = AbortSignal.timeout(timeoutMs);
return signal ? AbortSignal.any([signal, timeout]) : timeout;
}
function parseUploadPreflightResult(value: unknown): UploadPreflightResult | undefined {
if (!value || typeof value !== 'object') {
return undefined;
}
const preflight = value as UploadPreflightResponse;
if (preflight.ok !== true || typeof preflight.uploadId !== 'string') {
return undefined;
}
if (preflight.cacheHit === true) {
return {
kind: 'cache-hit',
uploadId: preflight.uploadId,
};
}
const upload = preflight.upload;
if (!upload || typeof upload.url !== 'string') {
return undefined;
}
const headers = upload.headers ?? {};
if (!isStringRecord(headers)) {
return undefined;
}
return {
kind: 'direct-upload',
uploadId: preflight.uploadId,
url: upload.url,
headers,
};
}
function isStringRecord(value: unknown): value is Record<string, string> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
return false;
}
return Object.values(value).every((entry) => typeof entry === 'string');
}
async function uploadDirectArtifact(
options: {
normalizedBase: string;
leaseId?: string;
artifact: PreparedUploadArtifact;
onProgress?: UploadProgressSink;
signal?: AbortSignal;
},
ticket: Extract<UploadPreflightResult, { kind: 'direct-upload' }>,
): Promise<void> {
const { artifact, onProgress, signal } = options;
const url = new URL(ticket.url);
const response = await streamFileToHttpRequest({
url,
method: 'PUT',
// A ticket on the daemon's own origin is routed like any daemon request, so it names the lease
// too; a ticket elsewhere (a signed storage URL) gets only the headers the daemon handed out.
headers:
url.origin === new URL(options.normalizedBase).origin
? { ...ticket.headers, ...buildDaemonHttpLeaseHeaders(options.leaseId) }
: ticket.headers,
payloadPath: artifact.payloadPath,
timeoutMessage: 'Direct artifact upload timed out',
timeoutHint: 'The direct upload ticket did not accept the artifact within the timeout.',
errorMessage: 'Failed to upload artifact with direct upload ticket',
retryable: true,
signal,
progress: {
stage: 'direct',
fileName: artifact.fileName,
onProgress,
},
});
if (response.statusCode < 200 || response.statusCode >= 300) {
throw new AppError('COMMAND_FAILED', 'Direct artifact upload failed', {
statusCode: response.statusCode,
statusMessage: response.statusMessage,
});
}
}
async function finalizeDirectUpload(options: {
normalizedBase: string;
token: string;
leaseId?: string;
uploadId: string;
signal?: AbortSignal;
}): Promise<string> {
const finalizeUrl = new URL('upload/finalize', options.normalizedBase);
const headers: Record<string, string> = {
'content-type': 'application/json',
};
Object.assign(
headers,
buildDaemonHttpAuthHeaders(options.token),
buildDaemonHttpLeaseHeaders(options.leaseId),
);
const response = await fetch(finalizeUrl, {
method: 'POST',
headers,
signal: combineUploadSignals(options.signal, UPLOAD_PREFLIGHT_TIMEOUT_MS),
body: JSON.stringify({ uploadId: options.uploadId }),
}).catch((error) => {
// As with preflight: a canceled finalize is not a transport failure to report, it is the caller
// saying this upload is no longer worth finishing.
if (options.signal?.aborted) throw error;
throw new AppError('COMMAND_FAILED', 'Failed to finalize direct artifact upload', {}, error);
});
if (!response.ok) {
throw new AppError('COMMAND_FAILED', 'Direct artifact upload finalize failed', {
status: response.status,
statusText: response.statusText,
});
}
const parsed = (await response.json().catch(() => undefined)) as UploadResponse | undefined;
if (!parsed?.ok || !parsed.uploadId) {
throw new AppError('COMMAND_FAILED', 'Invalid upload finalize response');
}
return parsed.uploadId;
}