Skip to content

Commit 2ddef1b

Browse files
committed
WC-2683 Provide documentation for asset upload
1 parent b50b5a0 commit 2ddef1b

File tree

1 file changed

+373
-0
lines changed

1 file changed

+373
-0
lines changed
Lines changed: 373 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,373 @@
1+
---
2+
pcx_content_type: concept
3+
title: Direct Uploads
4+
sidebar:
5+
order: 11
6+
head: []
7+
description: Upload assets through the Workers API.
8+
---
9+
10+
import {
11+
Badge,
12+
Description,
13+
FileTree,
14+
InlineBadge,
15+
Render,
16+
TabItem,
17+
Tabs,
18+
} from "~/components";
19+
20+
:::note
21+
22+
Directly uploading assets via APIs is an advanced approach that most users will not need. Instead, we encourage users to deploy your Worker with [Wrangler](/workers/static-assets/get-started/#1-create-a-new-worker-project-using-the-cli).
23+
24+
:::
25+
26+
Our API empowers users to upload and include static assets as part of a Worker. These static assets can be served for free, and additionally, users can also fetch assets through an optional [assets binding](/workers/static-assets/binding/) to power more advanced applications. This guide will describe the process for attaching assets to your Worker directly with the API.
27+
28+
```mermaid
29+
sequenceDiagram
30+
participant User
31+
participant Workers API
32+
User<<->>Workers API: Submit manifest<br/>POST /client/v4/accounts/:accountId/workers/scripts/:scriptName/assets-upload-session
33+
User<<->>Workers API: Upload files<br/>POST /client/v4/accounts/:accountId/workers/assets/upload?base64=true
34+
User<<->>Workers API: Upload script version<br/>PUT /client/v4/accounts/:accountId/workers/scripts/:scriptName
35+
```
36+
37+
The asset upload flow can be distilled into three distinct phases:
38+
39+
1. Registration of a manifest
40+
2. Upload of the assets
41+
3. Deployment of the Worker
42+
43+
## Upload manifest
44+
45+
The asset manifest is a ledger which keeps track of files we want to use in our Worker. This manifest is used to track assets associated with each Worker version, and eliminate the need to upload unchanged files prior to a new upload.
46+
47+
The [manifest upload request](/api/operations/worker-script-update-create-assets-upload-session) describes each file which we intend to upload. Each file is its own key representing the file path and name, and is an object which contains metadata about the file.
48+
49+
`hash` represents a 32 hexadecimal character hash of the file, while `size` is the size (in bytes) of the file.
50+
51+
```bash title="Example manifest upload request"
52+
curl -X POST https://api.cloudflare.com/client/v4/accounts/{account_id}/workers/scripts/{script_name}/assets-upload-session \
53+
--header 'content-type: application/json' \
54+
--header 'Authorization: Bearer <API_TOKEN>' \
55+
--data '{ "manifest": { "/filea.html": { "hash": "08f1dfda4574284ab3c21666d1", "size": 12 }, "/fileb.html": { "hash": "4f1c1af44620d531446ceef93f", "size": 23 }, "/filec.html": { "hash": "54995e302614e0523757a04ec1", "size": 23 } } }'
56+
```
57+
58+
The resulting response will contain a JWT, which provides authentication during file upload. The JWT is valid for one hour.
59+
60+
In addition to the JWT, the response instructs users how to optimally batch upload their files. These instructions are encoded in the `buckets` field. Each array in `buckets` contains a list of file hashes which should be uploaded together. Hashes of files that have been recently uploaded may not be returned in the API response; they do not need to be re-uploaded.
61+
62+
```curl title="Example manifest upload response"
63+
{
64+
"result": {
65+
"jwt": "<UPLOAD_TOKEN>",
66+
"buckets": [
67+
[
68+
"08f1dfda4574284ab3c21666d1",
69+
"4f1c1af44620d531446ceef93f"
70+
],
71+
[
72+
"54995e302614e0523757a04ec1"
73+
]
74+
]
75+
},
76+
"success": true,
77+
"errors": null,
78+
"messages": null
79+
}
80+
```
81+
82+
:::note
83+
84+
If all assets have been previously uploaded, `buckets` will be empty, and `jwt` will contain a completion token. Uploading files is not necessary, and you can skip directly to [uploading a new script or version](/workers/static-assets/direct-upload/#createdeploy-new-version).
85+
86+
:::
87+
88+
### Limitations
89+
90+
- Each file must be under 25 MiB
91+
- The overall manifest must not contain more than 20,000 file entries
92+
93+
## Upload Static Assets
94+
95+
The [file upload API](/api/operations/worker-assets-upload) requires files be uploaded using `multipart/form-data`. The contents of each file must be base64 encoded, and the `base64` query parameter in the URL must be set to `true`.
96+
97+
The `Authorization` header must be provided as a bearer token, using the JWT (upload token) from the aforementioned manifest upload call.
98+
99+
Once every file in the manifest has been uploaded, a status code of 201 will be returned, with the `jwt` field present. This JWT is a final "completion" token which can be used to create a deployment of a Worker with this set of assets. This completion token is valid for 1 hour.
100+
101+
## Create/Deploy New Version
102+
103+
[Script](/api/operations/worker-script-upload-worker-module) and [version](/api/operations/worker-versions-upload-version) upload endpoints require specifying a metadata part in the form data. Here, we can provide the completion token from the previous (upload assets) step.
104+
105+
```bash title="Example Worker Metadata Specifying Completion Token"
106+
{
107+
"main_module": "main.js",
108+
"assets": {
109+
"jwt": "<completion_token>"
110+
},
111+
"compatibility_date": "2021-09-14"
112+
}
113+
```
114+
115+
If this is a Worker which already has assets, and you wish to just re-use the existing set of assets, we do not have to specify the completion token again. Instead, we can pass the boolean `keep_assets` option.
116+
117+
```bash title="Example Worker Metadata Specifying keep_assets"
118+
{
119+
"main_module": "main.js",
120+
"keep_assets": true,
121+
"compatibility_date": "2021-09-14"
122+
}
123+
```
124+
125+
Asset [routing configuration](/workers/static-assets/routing/#routing-configuration) can be provided in the `assets` object, such as `html_handling` and `not_found_handling`.
126+
127+
```bash title="Example Worker Metadata Specifying Asset Configuration"
128+
{
129+
"main_module": "main.js",
130+
"assets": {
131+
"jwt": "<completion_token>",
132+
"config" {
133+
"html_handling": "auto-trailing-slash"
134+
}
135+
},
136+
"compatibility_date": "2021-09-14"
137+
}
138+
```
139+
140+
Optionally, an assets binding can be provided if you wish to fetch and serve assets from within your Worker code.
141+
142+
```bash title="Example Worker Metadata Specifying Asset Binding"
143+
{
144+
"main_module": "main.js",
145+
"assets": {
146+
...
147+
},
148+
"bindings": [
149+
...
150+
{
151+
"name": "ASSETS",
152+
"type": "assets"
153+
}
154+
...
155+
]
156+
"compatibility_date": "2021-09-14"
157+
}
158+
```
159+
160+
## Programmatic Example
161+
162+
<Tabs> <TabItem label="TypeScript" icon="seti:typescript">
163+
164+
```ts
165+
import * as fs from "fs";
166+
import * as path from "path";
167+
import * as crypto from "crypto";
168+
import { FormData, fetch } from "undici";
169+
import "node:process";
170+
171+
const accountId: string = ""; // Replace with your actual account ID
172+
const filesDirectory: string = "assets"; // Adjust to your assets directory
173+
const scriptName: string = "my-new-script"; // Replace with desired script name
174+
175+
interface FileMetadata {
176+
hash: string;
177+
size: number;
178+
}
179+
180+
interface UploadSessionData {
181+
uploadToken: string;
182+
buckets: string[][];
183+
fileMetadata: Record<string, FileMetadata>;
184+
}
185+
186+
interface UploadResponse {
187+
result: {
188+
jwt: string;
189+
buckets: string[][];
190+
};
191+
success: boolean;
192+
errors: any;
193+
messages: any;
194+
}
195+
196+
// Function to calculate the SHA-256 hash of a file and truncate to 32 characters
197+
function calculateFileHash(filePath: string): {
198+
fileHash: string;
199+
fileSize: number;
200+
} {
201+
const hash = crypto.createHash("sha256");
202+
const fileBuffer = fs.readFileSync(filePath);
203+
hash.update(fileBuffer);
204+
const fileHash = hash.digest("hex").slice(0, 32); // Grab the first 32 characters
205+
const fileSize = fileBuffer.length;
206+
return { fileHash, fileSize };
207+
}
208+
209+
// Function to gather file metadata for all files in the directory
210+
function gatherFileMetadata(directory: string): Record<string, FileMetadata> {
211+
const files = fs.readdirSync(directory);
212+
const fileMetadata: Record<string, FileMetadata> = {};
213+
214+
files.forEach((file) => {
215+
const filePath = path.join(directory, file);
216+
const { fileHash, fileSize } = calculateFileHash(filePath);
217+
fileMetadata["/" + file] = {
218+
hash: fileHash,
219+
size: fileSize,
220+
};
221+
});
222+
223+
return fileMetadata;
224+
}
225+
226+
function findMatch(
227+
fileHash: string,
228+
fileMetadata: Record<string, FileMetadata>,
229+
): string {
230+
for (let prop in fileMetadata) {
231+
const file = fileMetadata[prop] as FileMetadata;
232+
if (file.hash === fileHash) {
233+
return prop;
234+
}
235+
}
236+
throw new Error("unknown fileHash");
237+
}
238+
239+
// Function to upload a batch of files using the JWT from the first response
240+
async function uploadFilesBatch(
241+
jwt: string,
242+
fileHashes: string[][],
243+
fileMetadata: Record<string, FileMetadata>,
244+
): Promise<string> {
245+
const form = new FormData();
246+
247+
fileHashes.forEach(async (bucket) => {
248+
bucket.forEach((fileHash) => {
249+
const fullPath = findMatch(fileHash, fileMetadata);
250+
const relPath = filesDirectory + "/" + path.basename(fullPath);
251+
const fileBuffer = fs.readFileSync(relPath);
252+
const base64Data = fileBuffer.toString("base64"); // Convert file to Base64
253+
254+
form.append(
255+
fileHash,
256+
new File([base64Data], fileHash, {
257+
type: "text/html", // Modify Content-Type header based on type of file
258+
}),
259+
fileHash,
260+
);
261+
});
262+
263+
const response = await fetch(
264+
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/assets/upload?base64=true`,
265+
{
266+
method: "POST",
267+
headers: {
268+
Authorization: `Bearer ${jwt}`,
269+
},
270+
body: form,
271+
},
272+
);
273+
274+
const data = (await response.json()) as UploadResponse;
275+
if (data && data.result.jwt) {
276+
return { completionToken: data.result.jwt };
277+
}
278+
});
279+
280+
throw new Error("Should have received completion token");
281+
}
282+
283+
async function scriptUpload(completionToken: string): Promise<void> {
284+
const form = new FormData();
285+
286+
// Configure metadata
287+
form.append(
288+
"metadata",
289+
JSON.stringify({
290+
main_module: "index.mjs",
291+
compatibility_date: "2022-03-11",
292+
assets: {
293+
jwt: completionToken, // Provide the completion token from file uploads
294+
},
295+
bindings: [{ name: "ASSETS", type: "assets" }], // Optional assets binding to fetch from user worker
296+
}),
297+
);
298+
299+
// Configure (optional) user worker
300+
form.append(
301+
"index.js",
302+
new File(
303+
[
304+
"export default {async fetch(request, env) { return new Response('Hello world from user worker!'); }}",
305+
],
306+
"index.mjs",
307+
{
308+
type: "application/javascript+module",
309+
},
310+
),
311+
);
312+
313+
const response = await fetch(
314+
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}`,
315+
{
316+
method: "PUT",
317+
headers: {
318+
Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
319+
},
320+
body: form,
321+
},
322+
);
323+
324+
if (response.status != 200) {
325+
throw new Error("unexpected status code");
326+
}
327+
}
328+
329+
// Function to make the POST request to start the assets upload session
330+
async function startUploadSession(): Promise<UploadSessionData> {
331+
const fileMetadata = gatherFileMetadata(filesDirectory);
332+
333+
const requestBody = JSON.stringify({
334+
manifest: fileMetadata,
335+
});
336+
337+
const response = await fetch(
338+
`https://api.cloudflare.com/client/v4/accounts/${accountId}/workers/scripts/${scriptName}/assets-upload-session`,
339+
{
340+
method: "POST",
341+
headers: {
342+
Authorization: `Bearer ${process.env.CLOUDFLARE_API_TOKEN}`,
343+
"Content-Type": "application/json",
344+
},
345+
body: requestBody,
346+
},
347+
);
348+
349+
const data = (await response.json()) as UploadResponse;
350+
const jwt = data.result.jwt;
351+
352+
return {
353+
uploadToken: jwt,
354+
buckets: data.result.buckets,
355+
fileMetadata,
356+
};
357+
}
358+
359+
// Begin the upload session by uploading a new manifest
360+
const { uploadToken, buckets, fileMetadata } = await startUploadSession();
361+
362+
// If all files are already uploaded, a completion token will be immediately returned. Otherwise,
363+
// we should upload the missing files
364+
let completionToken = uploadToken;
365+
if (buckets.length > 0) {
366+
completionToken = await uploadFilesBatch(uploadToken, buckets, fileMetadata);
367+
}
368+
369+
// Once we have uploaded all of our files, we can upload a new script, and assets, with completion token
370+
await scriptUpload(completionToken);
371+
```
372+
373+
</TabItem> </Tabs>

0 commit comments

Comments
 (0)