Skip to content

Commit 3de6fb7

Browse files
committed
Fix completion token handling for multiple Cloudflare asset batches
1 parent 4d9bc3d commit 3de6fb7

2 files changed

Lines changed: 46 additions & 22 deletions

File tree

‎packages/void/src/cli/cf-version-api.ts‎

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -257,10 +257,14 @@ async function uploadAssets(options: {
257257
{ manifest },
258258
options.verifyUploader,
259259
);
260-
let jwt = requiredString(session.jwt, 'asset upload token');
260+
const uploadJwt = requiredString(session.jwt, 'asset upload token');
261261
if (!Array.isArray(session.buckets)) {
262262
throw new Error('Cloudflare did not provide asset upload batches.');
263263
}
264+
if (session.buckets.length === 0) {
265+
return uploadJwt;
266+
}
267+
let completionJwt: string | undefined;
264268
for (const bucket of session.buckets) {
265269
if (!Array.isArray(bucket) || !bucket.every((hash) => typeof hash === 'string')) {
266270
throw new Error('Cloudflare returned an invalid asset upload batch.');
@@ -275,14 +279,16 @@ async function uploadAssets(options: {
275279
}
276280
const uploaded = await apiResult(
277281
`${options.accountUrl}/workers/assets/upload?base64=true`,
278-
jwt,
282+
uploadJwt,
279283
'POST',
280284
form,
281285
options.verifyUploader,
282286
);
283-
jwt = requiredString(uploaded.jwt, 'asset completion token');
287+
if (uploaded.jwt !== undefined) {
288+
completionJwt = requiredString(uploaded.jwt, 'asset completion token');
289+
}
284290
}
285-
return jwt;
291+
return requiredString(completionJwt, 'asset completion token');
286292
}
287293

288294
/** The Workers beta API is the only upload endpoint that accepts a version UUID as an inheritance source. */

‎packages/void/test/unit/cf-version-runner.test.ts‎

Lines changed: 36 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ it('treats a verified empty deployment list as missing but rejects malformed sta
200200
}
201201
});
202202

203-
async function output(config: Record<string, unknown> = {}) {
203+
async function output(config: Record<string, unknown> = {}, additionalAsset = false) {
204204
const root = mkdtempSync(join(tmpdir(), 'void-cf-runner-test-'));
205205
roots.push(root);
206206
const worker = join(root, 'dist', 'ssr');
@@ -211,6 +211,9 @@ async function output(config: Record<string, unknown> = {}) {
211211
const directory = join(worker, assets.directory);
212212
mkdirSync(directory, { recursive: true });
213213
writeFileSync(join(directory, 'index.html'), '<h1>Public</h1>');
214+
if (additionalAsset) {
215+
writeFileSync(join(directory, 'second.html'), '<h1>Second</h1>');
216+
}
214217
writeFileSync(join(directory, 'private.txt'), 'Never upload this');
215218
writeFileSync(join(directory, '.assetsignore'), 'private.txt\n');
216219
}
@@ -229,13 +232,16 @@ async function output(config: Record<string, unknown> = {}) {
229232
return prepared!;
230233
}
231234

232-
it('uploads live secrets through the version-aware API when the latest upload is inactive', async () => {
233-
const prepared = await output({
234-
secrets: { required: ['AUTH_SECRET'] },
235-
keep_secrets: true,
236-
keep_vars: true,
237-
assets: { directory: '../client', binding: 'ASSETS', not_found_handling: 'none' },
238-
});
235+
it('uploads live secrets and multiple asset batches when the latest upload is inactive', async () => {
236+
const prepared = await output(
237+
{
238+
secrets: { required: ['AUTH_SECRET'] },
239+
keep_secrets: true,
240+
keep_vars: true,
241+
assets: { directory: '../client', binding: 'ASSETS', not_found_handling: 'none' },
242+
},
243+
true,
244+
);
239245
try {
240246
const activeVersionId = '11111111-1111-4111-8111-111111111111';
241247
const pinActiveSecrets = createActiveSecretPinner({
@@ -259,27 +265,31 @@ it('uploads live secrets through the version-aware API when the latest upload is
259265
{ name: 'KEY', type: 'secret_key' },
260266
],
261267
});
262-
const requests: Array<{ url: string; body: string }> = [];
268+
const requests: Array<{ url: string; body: string; authorization: string | undefined }> = [];
269+
let uploadedBatches = 0;
263270
const server = createServer(async (request, response) => {
264271
const chunks: Array<Buffer> = [];
265272
for await (const chunk of request) {
266273
chunks.push(Buffer.from(chunk));
267274
}
268-
requests.push({ url: request.url ?? '', body: Buffer.concat(chunks).toString('utf8') });
275+
requests.push({
276+
url: request.url ?? '',
277+
body: Buffer.concat(chunks).toString('utf8'),
278+
authorization: request.headers.authorization,
279+
});
269280
response.writeHead(200, { 'Content-Type': 'application/json' });
270281
const path = request.url ?? '';
271282
const result = path.endsWith('/assets-upload-session')
272283
? {
273284
jwt: 'asset-token',
274-
buckets: [
275-
[
276-
(Object.values(JSON.parse(requests.at(-1)!.body).manifest)[0] as { hash: string })
277-
.hash,
278-
],
279-
],
285+
buckets: Object.values(JSON.parse(requests.at(-1)!.body).manifest).map((entry) => [
286+
(entry as { hash: string }).hash,
287+
]),
280288
}
281289
: path.includes('/assets/upload')
282-
? { jwt: 'completion-token' }
290+
? ++uploadedBatches === 2
291+
? { jwt: 'completion-token' }
292+
: {}
283293
: request.method === 'GET'
284294
? {
285295
id: activeVersionId,
@@ -327,7 +337,15 @@ it('uploads live secrets through the version-aware API when the latest upload is
327337
});
328338
expect(body.bindings).toContainEqual({ name: 'ASSETS', type: 'assets' });
329339
const session = requests.find(({ url }) => url.endsWith('/assets-upload-session'));
330-
expect(Object.keys(JSON.parse(session!.body).manifest)).toEqual(['/index.html']);
340+
expect(Object.keys(JSON.parse(session!.body).manifest)).toEqual([
341+
'/index.html',
342+
'/second.html',
343+
]);
344+
expect(
345+
requests
346+
.filter(({ url }) => url.includes('/assets/upload'))
347+
.map(({ authorization }) => authorization),
348+
).toEqual(['Bearer asset-token', 'Bearer asset-token']);
331349
} finally {
332350
await new Promise<void>((resolve, reject) =>
333351
server.close((error) => (error ? reject(error) : resolve())),

0 commit comments

Comments
 (0)