@phnx-labs/artifacts-cli 0.8.2 → 0.9.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/CHANGELOG.md +45 -0
- package/README.md +35 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +201 -196
- package/dist/cli.js.map +1 -1
- package/dist/commands/share.d.ts +6 -0
- package/dist/commands/share.js +100 -5
- package/dist/commands/share.js.map +1 -1
- package/dist/lib/share/media-core.d.ts +64 -0
- package/dist/lib/share/media-core.js +376 -0
- package/dist/lib/share/media-core.js.map +1 -0
- package/dist/lib/share/media.d.ts +48 -0
- package/dist/lib/share/media.js +76 -0
- package/dist/lib/share/media.js.map +1 -0
- package/dist/lib/share/provision.d.ts +14 -0
- package/dist/lib/share/provision.js +27 -4
- package/dist/lib/share/provision.js.map +1 -1
- package/dist/lib/share/publish.d.ts +9 -8
- package/dist/lib/share/publish.js +633 -28
- package/dist/lib/share/publish.js.map +1 -1
- package/dist/lib/share/worker-media-template.d.ts +1 -0
- package/dist/lib/share/worker-media-template.js +873 -0
- package/dist/lib/share/worker-media-template.js.map +1 -0
- package/dist/lib/share/worker-publish-template.d.ts +1 -0
- package/dist/lib/share/worker-publish-template.js +866 -0
- package/dist/lib/share/worker-publish-template.js.map +1 -0
- package/dist/lib/share/worker-template.js +330 -266
- package/dist/lib/share/worker-template.js.map +1 -1
- package/package.json +7 -2
|
@@ -0,0 +1,866 @@
|
|
|
1
|
+
// Publish and multipart helper source injected into the generated Cloudflare Worker.
|
|
2
|
+
// Keep this as source text: renderWorkerSource bundles it with the main Worker template.
|
|
3
|
+
export const SHARE_PUBLISH_WORKER_SOURCE = `
|
|
4
|
+
// Validate the publish principal/path and build the one canonical R2 metadata
|
|
5
|
+
// record used by both a normal PUT and multipart create. Keeping this shared is
|
|
6
|
+
// important: a large video must not silently lose expiry, provenance, --meta,
|
|
7
|
+
// owner, or org visibility stamps just because its bytes arrive in parts.
|
|
8
|
+
async function preparePublish(request, env, path, auth) {
|
|
9
|
+
const vis = normalizeVisibility(request.headers.get('x-share-visibility'));
|
|
10
|
+
if (vis.error) return { error: vis.error };
|
|
11
|
+
const visibility = vis.value;
|
|
12
|
+
if (visibility === 'me' || visibility === 'org') {
|
|
13
|
+
const phoenixBase = typeof env.PHOENIX_ID_BASE === 'string' ? env.PHOENIX_ID_BASE.replace(/\\/+$/, '') : '';
|
|
14
|
+
if (auth.kind !== 'phoenix' || !phoenixBase) {
|
|
15
|
+
return { error: json({ error: 'visibility me/org requires Phoenix identity' }, 400) };
|
|
16
|
+
}
|
|
17
|
+
if (visibility === 'org') {
|
|
18
|
+
const domain = emailDomain(auth.email);
|
|
19
|
+
if (!domain) return { error: json({ error: 'org visibility requires a verified email domain' }, 400) };
|
|
20
|
+
if (PUBLIC_INBOX_DOMAINS.indexOf(domain) !== -1) {
|
|
21
|
+
return { error: json({ error: 'org visibility cannot use a public email domain', domain: domain }, 400) };
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let viewerTokenHash = '';
|
|
27
|
+
if (visibility === 'private') {
|
|
28
|
+
const rawToken = request.headers.get('x-share-viewer-token') || '';
|
|
29
|
+
if (!rawToken) return { error: json({ error: 'visibility private requires a viewer token' }, 400) };
|
|
30
|
+
viewerTokenHash = await sha256Hex(rawToken);
|
|
31
|
+
}
|
|
32
|
+
const commentsHeader = request.headers.get('x-share-comments');
|
|
33
|
+
if (commentsHeader !== null && !isCommentPolicy(commentsHeader)) {
|
|
34
|
+
return { error: json({ error: 'comments must be off, audience, or signed_in' }, 400) };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
const segments = path.split('/').filter(Boolean);
|
|
38
|
+
if (auth.kind === 'phoenix') {
|
|
39
|
+
const requestedRaw = request.headers.get('x-share-handle') || '';
|
|
40
|
+
const requested = sanitizeNamespace(requestedRaw);
|
|
41
|
+
if (requestedRaw && (!requested || requested.length > 63)) {
|
|
42
|
+
return { error: json({ error: 'invalid handle', handle: requestedRaw }, 400) };
|
|
43
|
+
}
|
|
44
|
+
const expected = requested || phoenixHandle(auth);
|
|
45
|
+
if (!expected || segments[0] !== expected) {
|
|
46
|
+
return { error: json({ error: 'namespace mismatch', owner: expected }, 403) };
|
|
47
|
+
}
|
|
48
|
+
const claimed = await claimHandle(env.BUCKET, expected, auth.owner, auth.email || '');
|
|
49
|
+
if (claimed.error) return claimed;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const expiresAt = request.headers.get('x-share-expires-at') || '';
|
|
53
|
+
const contentType = request.headers.get('content-type') || 'text/html; charset=utf-8';
|
|
54
|
+
const usePercent = (request.headers.get('x-share-encoding') || '') === 'percent';
|
|
55
|
+
const readText = function (name) {
|
|
56
|
+
const folded = request.headers.get('x-share-' + name) || '';
|
|
57
|
+
if (usePercent) {
|
|
58
|
+
const encoded = request.headers.get('x-share-' + name + '-u');
|
|
59
|
+
if (encoded) {
|
|
60
|
+
try { return decodeURIComponent(encoded); } catch (e) { return folded; }
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
return folded;
|
|
64
|
+
};
|
|
65
|
+
const fields = {
|
|
66
|
+
agent: readText('agent'), session: readText('session'), host: readText('host'),
|
|
67
|
+
repo: readText('repo'), date: readText('date'), avatar: readText('avatar'),
|
|
68
|
+
label: readText('label'), ogTitle: readText('og-title'), ogDescription: readText('og-description'),
|
|
69
|
+
};
|
|
70
|
+
const labelSource = request.headers.get('x-share-label-source') || '';
|
|
71
|
+
let extraMeta = {};
|
|
72
|
+
const metaEncoded = usePercent ? request.headers.get('x-share-meta-u') : null;
|
|
73
|
+
if (metaEncoded) {
|
|
74
|
+
try {
|
|
75
|
+
const parsed = JSON.parse(decodeURIComponent(metaEncoded));
|
|
76
|
+
if (parsed && typeof parsed === 'object') extraMeta = parsed;
|
|
77
|
+
} catch (e) {
|
|
78
|
+
// Malformed Unicode metadata falls back to the latin1-safe header.
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (!Object.keys(extraMeta).length) {
|
|
82
|
+
const metaHeader = request.headers.get('x-share-meta');
|
|
83
|
+
if (metaHeader) {
|
|
84
|
+
try {
|
|
85
|
+
const parsed = JSON.parse(metaHeader);
|
|
86
|
+
if (parsed && typeof parsed === 'object') extraMeta = parsed;
|
|
87
|
+
} catch (e) {
|
|
88
|
+
// Malformed --meta is ignored, matching the normal publish contract.
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
const customMetadata = { ...extraMeta };
|
|
93
|
+
for (const reservedKey of RESERVED_METADATA_KEYS) delete customMetadata[reservedKey];
|
|
94
|
+
if (expiresAt) customMetadata['expires-at'] = expiresAt;
|
|
95
|
+
customMetadata.visibility = visibility;
|
|
96
|
+
if (viewerTokenHash) customMetadata['viewer-token-hash'] = viewerTokenHash;
|
|
97
|
+
const owner = auth.kind === 'phoenix' ? auth.owner : (env.SHARE_NAMESPACE || segments[0] || 'byo');
|
|
98
|
+
if (owner) customMetadata.owner = owner;
|
|
99
|
+
if (visibility === 'org') customMetadata.org_domain = emailDomain(auth.email);
|
|
100
|
+
if (fields.agent) customMetadata.agent = fields.agent;
|
|
101
|
+
if (fields.session) customMetadata.session = fields.session;
|
|
102
|
+
if (fields.host) customMetadata.host = fields.host;
|
|
103
|
+
if (fields.repo) customMetadata.repo = fields.repo;
|
|
104
|
+
if (fields.date) customMetadata.date = fields.date;
|
|
105
|
+
if (fields.avatar) customMetadata.avatar = fields.avatar;
|
|
106
|
+
if (fields.label) customMetadata.label = fields.label;
|
|
107
|
+
if (labelSource) customMetadata['label-source'] = labelSource;
|
|
108
|
+
if (fields.ogTitle) customMetadata['og-title'] = fields.ogTitle;
|
|
109
|
+
if (fields.ogDescription) customMetadata['og-description'] = fields.ogDescription;
|
|
110
|
+
if (commentsHeader !== null) customMetadata['comment-policy'] = commentsHeader;
|
|
111
|
+
return { visibility, commentsHeader, segments, expiresAt, contentType, customMetadata };
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
var MIN_MULTIPART_PART_BYTES = 5 * 1024 * 1024;
|
|
115
|
+
var MAX_MULTIPART_PART_BYTES = 50 * 1024 * 1024;
|
|
116
|
+
var MULTIPART_PART_LEASE_MS = 15 * 60 * 1000;
|
|
117
|
+
var PATH_MUTATION_LEASE_MS = 5 * 60 * 1000;
|
|
118
|
+
|
|
119
|
+
async function multipartCreateFingerprint(path, auth, publish, noRevision, createKey, totalSize) {
|
|
120
|
+
const metadata = {};
|
|
121
|
+
const keys = Object.keys(publish.customMetadata || {}).sort();
|
|
122
|
+
for (const key of keys) {
|
|
123
|
+
// These are intentionally different on a replay: published-at is stamped at
|
|
124
|
+
// request time and multipart-token is minted per R2 upload. A validated
|
|
125
|
+
// client key carries the raw expiry intent, so ignore its newly-resolved
|
|
126
|
+
// absolute expires-at while still hashing every other effective field.
|
|
127
|
+
if (key === 'published-at' || key === 'multipart-token') continue;
|
|
128
|
+
if (createKey && key === 'expires-at') continue;
|
|
129
|
+
metadata[key] = publish.customMetadata[key];
|
|
130
|
+
}
|
|
131
|
+
return sha256Hex(JSON.stringify({
|
|
132
|
+
createKey: createKey,
|
|
133
|
+
owner: auth.owner,
|
|
134
|
+
path: path,
|
|
135
|
+
contentType: publish.contentType,
|
|
136
|
+
visibility: publish.visibility,
|
|
137
|
+
noRevision: noRevision,
|
|
138
|
+
totalSize: totalSize,
|
|
139
|
+
metadata: metadata,
|
|
140
|
+
}));
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function multipartStateKey(uploadId) {
|
|
144
|
+
return '__multipart/' + encodeURIComponent(uploadId);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function multipartPathLockKey(path) {
|
|
148
|
+
return '__multipart-path/' + encodeURIComponent(path);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
async function readPathMutationLock(bucket, path) {
|
|
152
|
+
const object = await bucket.get(multipartPathLockKey(path));
|
|
153
|
+
if (!object) return null;
|
|
154
|
+
const lock = JSON.parse(await object.text());
|
|
155
|
+
if (!lock || typeof lock !== 'object') throw new Error('invalid path mutation lock');
|
|
156
|
+
return { object: object, lock: lock };
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async function acquirePathMutationLock(bucket, path, holder, kind) {
|
|
160
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
161
|
+
const current = await readPathMutationLock(bucket, path);
|
|
162
|
+
const now = Date.now();
|
|
163
|
+
if (current && current.lock.holder === holder) return current.object;
|
|
164
|
+
// Multipart owns the path for the whole resumable upload and therefore has
|
|
165
|
+
// no expiry. Short PUT/PATCH/DELETE/expiry mutations use a bounded lease so
|
|
166
|
+
// a terminated Worker cannot strand the path forever; reclamation below is
|
|
167
|
+
// still a CAS against the stale lock's etag.
|
|
168
|
+
const occupied = current && current.lock.holder && (
|
|
169
|
+
current.lock.kind === 'multipart' ||
|
|
170
|
+
typeof current.lock.expiresAt !== 'number' ||
|
|
171
|
+
current.lock.expiresAt > now
|
|
172
|
+
);
|
|
173
|
+
if (occupied) return null;
|
|
174
|
+
const next = {
|
|
175
|
+
holder: holder,
|
|
176
|
+
kind: kind,
|
|
177
|
+
acquiredAt: now,
|
|
178
|
+
expiresAt: kind === 'mutation' ? now + PATH_MUTATION_LEASE_MS : 0,
|
|
179
|
+
};
|
|
180
|
+
const opts = {
|
|
181
|
+
httpMetadata: { contentType: 'application/json' },
|
|
182
|
+
customMetadata: { visibility: 'unlisted', path: path },
|
|
183
|
+
onlyIf: current ? { etagMatches: current.object.etag } : { etagDoesNotMatch: '*' },
|
|
184
|
+
};
|
|
185
|
+
const written = await bucket.put(multipartPathLockKey(path), JSON.stringify(next), opts);
|
|
186
|
+
if (written !== null) return written;
|
|
187
|
+
}
|
|
188
|
+
return null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async function pathMutationLockOwned(bucket, path, holder) {
|
|
192
|
+
const current = await readPathMutationLock(bucket, path);
|
|
193
|
+
return !!current && current.lock.holder === holder && (
|
|
194
|
+
current.lock.kind === 'multipart' ||
|
|
195
|
+
(typeof current.lock.expiresAt === 'number' && current.lock.expiresAt > Date.now())
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
async function releasePathMutationLock(bucket, path, holder) {
|
|
200
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
201
|
+
const current = await readPathMutationLock(bucket, path);
|
|
202
|
+
if (!current || current.lock.holder !== holder) return;
|
|
203
|
+
const released = {
|
|
204
|
+
holder: '',
|
|
205
|
+
kind: 'released',
|
|
206
|
+
acquiredAt: current.lock.acquiredAt || 0,
|
|
207
|
+
expiresAt: 0,
|
|
208
|
+
releasedAt: Date.now(),
|
|
209
|
+
};
|
|
210
|
+
const written = await bucket.put(multipartPathLockKey(path), JSON.stringify(released), {
|
|
211
|
+
httpMetadata: { contentType: 'application/json' },
|
|
212
|
+
customMetadata: { visibility: 'unlisted', path: path },
|
|
213
|
+
onlyIf: { etagMatches: current.object.etag },
|
|
214
|
+
});
|
|
215
|
+
if (written !== null) return;
|
|
216
|
+
}
|
|
217
|
+
throw new Error('path mutation lock contended during release');
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async function acquireMultipartPathLock(bucket, path, uploadId) {
|
|
221
|
+
return acquirePathMutationLock(bucket, path, uploadId, 'multipart');
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function releaseMultipartPathLock(bucket, path, uploadId) {
|
|
225
|
+
return releasePathMutationLock(bucket, path, uploadId);
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function validUploadId(uploadId) {
|
|
229
|
+
return typeof uploadId === 'string' && uploadId.length > 0 && uploadId.length <= 1024;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
async function readMultipartState(bucket, uploadId) {
|
|
233
|
+
const object = await bucket.get(multipartStateKey(uploadId));
|
|
234
|
+
if (!object) return null;
|
|
235
|
+
try {
|
|
236
|
+
const state = JSON.parse(await object.text());
|
|
237
|
+
if (!state || typeof state !== 'object') return null;
|
|
238
|
+
return { object: object, state: state };
|
|
239
|
+
} catch (e) {
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
async function writeMultipartState(bucket, uploadId, state, previousEtag) {
|
|
245
|
+
const opts = {
|
|
246
|
+
httpMetadata: { contentType: 'application/json' },
|
|
247
|
+
customMetadata: { visibility: 'unlisted', owner: state.owner || '', path: state.path || '' },
|
|
248
|
+
};
|
|
249
|
+
if (previousEtag) opts.onlyIf = { etagMatches: previousEtag };
|
|
250
|
+
return bucket.put(multipartStateKey(uploadId), JSON.stringify(state), opts);
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function multipartError(error, fallback, status) {
|
|
254
|
+
const message = error && typeof error.message === 'string' ? error.message : fallback;
|
|
255
|
+
return json({ error: message || fallback }, status || 400);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
async function ownedMultipartState(env, auth, path, uploadId) {
|
|
259
|
+
if (!validUploadId(uploadId)) return { error: json({ error: 'uploadId is required' }, 400) };
|
|
260
|
+
const record = await readMultipartState(env.BUCKET, uploadId);
|
|
261
|
+
if (!record) {
|
|
262
|
+
return { error: json({ error: 'multipart upload not found', status: 'missing', restart: true }, 404) };
|
|
263
|
+
}
|
|
264
|
+
if (record.state.owner !== auth.owner || record.state.path !== path) {
|
|
265
|
+
// Do not tell a caller using the wrong identity/path that its saved handle is
|
|
266
|
+
// terminal. The real owner's durable state and reservation are still live.
|
|
267
|
+
return { error: json({ error: 'multipart upload not found' }, 404) };
|
|
268
|
+
}
|
|
269
|
+
return record;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
async function restoreMultipartReplacement(env, path, replacement, completionToken) {
|
|
273
|
+
const current = await env.BUCKET.head(path);
|
|
274
|
+
const landed = !!current && current.customMetadata && current.customMetadata['multipart-token'] === completionToken;
|
|
275
|
+
// Under the non-expiring multipart reservation, a non-token canonical (or a
|
|
276
|
+
// missing first publish) means an earlier retry already finished rollback.
|
|
277
|
+
if (!landed) {
|
|
278
|
+
if ((replacement.hadExisting && current) || (!replacement.hadExisting && !current)) return;
|
|
279
|
+
throw new Error('completed object changed before rollback');
|
|
280
|
+
}
|
|
281
|
+
if (!replacement.hadExisting) {
|
|
282
|
+
await env.BUCKET.delete(path);
|
|
283
|
+
return;
|
|
284
|
+
}
|
|
285
|
+
const backup = await env.BUCKET.get(replacement.backupKey);
|
|
286
|
+
if (!backup) throw new Error('multipart replacement backup missing');
|
|
287
|
+
const headers = new Headers();
|
|
288
|
+
backup.writeHttpMetadata(headers);
|
|
289
|
+
await env.BUCKET.put(path, backup.body, {
|
|
290
|
+
httpMetadata: headers.get('content-type') ? { contentType: headers.get('content-type') } : undefined,
|
|
291
|
+
customMetadata: backup.customMetadata || {},
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
function multipartCleanupPending(error) {
|
|
296
|
+
const detail = error && typeof error.message === 'string' ? error.message : 'multipart cleanup did not complete';
|
|
297
|
+
return json({ error: detail, status: 'cleanup_pending', retry: true }, 503);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
async function releaseTerminalMultipartLock(env, path, uploadId) {
|
|
301
|
+
try {
|
|
302
|
+
await releaseMultipartPathLock(env.BUCKET, path, uploadId);
|
|
303
|
+
return null;
|
|
304
|
+
} catch (error) {
|
|
305
|
+
return multipartCleanupPending(error);
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
async function finishMultipartRejection(env, path, uploadId, record) {
|
|
310
|
+
let state = record.state;
|
|
311
|
+
let stateEtag = record.object.etag;
|
|
312
|
+
try {
|
|
313
|
+
if (state.status === 'rejecting') {
|
|
314
|
+
if (!(await pathMutationLockOwned(env.BUCKET, path, uploadId))) {
|
|
315
|
+
throw new Error('multipart path reservation was lost during rollback');
|
|
316
|
+
}
|
|
317
|
+
await restoreMultipartReplacement(env, path, state.replacement, state.completionToken);
|
|
318
|
+
if (state.replacement.backupKey) await env.BUCKET.delete(state.replacement.backupKey);
|
|
319
|
+
state = { ...state, status: 'rejected' };
|
|
320
|
+
const rejectedWrite = await writeMultipartState(env.BUCKET, uploadId, state, stateEtag);
|
|
321
|
+
if (rejectedWrite === null) throw new Error('multipart rejection receipt conflicted');
|
|
322
|
+
stateEtag = rejectedWrite.etag;
|
|
323
|
+
}
|
|
324
|
+
const cleanupError = await releaseTerminalMultipartLock(env, path, uploadId);
|
|
325
|
+
if (cleanupError) return cleanupError;
|
|
326
|
+
return multipartRejectedResponse(state);
|
|
327
|
+
} catch (error) {
|
|
328
|
+
return multipartCleanupPending(error);
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function guardMultipartPartLock(env, path, uploadId, record, upload) {
|
|
333
|
+
const locks = record.state.partLocks || {};
|
|
334
|
+
const keys = Object.keys(locks);
|
|
335
|
+
if (!keys.length) return null;
|
|
336
|
+
const lock = locks[keys[0]];
|
|
337
|
+
const expiresAt = lock && typeof lock === 'object' && typeof lock.expiresAt === 'number' ? lock.expiresAt : 0;
|
|
338
|
+
if (expiresAt > Date.now()) {
|
|
339
|
+
return json({ error: 'a multipart part is still uploading; retry after it finishes' }, 409);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Never reuse a multipart upload after an in-flight part lease is lost. R2
|
|
343
|
+
// offers no conditional uploadPart, so clearing/taking over a stale lock could
|
|
344
|
+
// let the old request overwrite the new part after its etag was recorded.
|
|
345
|
+
// Poisoning and aborting the whole upload makes that ordering harmless: no
|
|
346
|
+
// request can subsequently complete it, even if the old uploadPart resolves.
|
|
347
|
+
const aborted = {
|
|
348
|
+
...record.state,
|
|
349
|
+
status: 'aborted',
|
|
350
|
+
abortReason: 'part upload lease expired; create a new multipart upload',
|
|
351
|
+
};
|
|
352
|
+
const written = await writeMultipartState(env.BUCKET, uploadId, aborted, record.object.etag);
|
|
353
|
+
if (written === null) return json({ error: 'multipart state changed; retry' }, 409);
|
|
354
|
+
try { await upload.abort(); } catch (e) { /* tombstone still prevents completion */ }
|
|
355
|
+
const cleanupError = await releaseTerminalMultipartLock(env, path, uploadId);
|
|
356
|
+
if (cleanupError) return cleanupError;
|
|
357
|
+
return json({ error: aborted.abortReason, status: 'aborted', restart: true }, 409);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function multipartRejectedResponse(state) {
|
|
361
|
+
let body = { error: 'multipart upload was rejected' };
|
|
362
|
+
try {
|
|
363
|
+
const parsed = JSON.parse(state.rejection.body);
|
|
364
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) body = parsed;
|
|
365
|
+
} catch (e) { /* preserve a machine-readable terminal response */ }
|
|
366
|
+
return json({ ...body, status: 'rejected', restart: true }, state.rejection.status);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
async function handleMultipartUpload(request, env, url, path, action) {
|
|
370
|
+
const methods = { create: 'POST', resume: 'POST', part: 'PUT', complete: 'POST', abort: 'DELETE' };
|
|
371
|
+
if (!Object.prototype.hasOwnProperty.call(methods, action)) return json({ error: 'unknown multipart action' }, 400);
|
|
372
|
+
if (request.method !== methods[action]) return json({ error: 'method not allowed' }, 405);
|
|
373
|
+
const auth = await authorizeWrite(request, env);
|
|
374
|
+
if (auth.error) return auth.error;
|
|
375
|
+
if (auth.kind !== 'phoenix') return json({ error: 'multipart upload requires Phoenix identity' }, 403);
|
|
376
|
+
if (typeof env.BUCKET.resumeMultipartUpload !== 'function' || typeof env.BUCKET.createMultipartUpload !== 'function') {
|
|
377
|
+
return json({ error: 'multipart upload is not configured' }, 501);
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
if (action === 'create') {
|
|
381
|
+
const publish = await preparePublish(request, env, path, auth);
|
|
382
|
+
if (publish.error) return publish.error;
|
|
383
|
+
if (publish.visibility !== 'me' && publish.visibility !== 'org') {
|
|
384
|
+
return json({ error: 'multipart media requires me or org visibility' }, 400);
|
|
385
|
+
}
|
|
386
|
+
if (String(publish.contentType).toLowerCase().indexOf('video/') !== 0) {
|
|
387
|
+
return json({ error: 'multipart media requires video content-type' }, 415);
|
|
388
|
+
}
|
|
389
|
+
const createKey = (request.headers.get('x-share-multipart-key') || '').trim();
|
|
390
|
+
if (createKey && !/^[0-9a-f]{64}$/.test(createKey)) {
|
|
391
|
+
return json({ error: 'x-share-multipart-key must be 64 lowercase hex characters' }, 400);
|
|
392
|
+
}
|
|
393
|
+
const totalSizeHeader = request.headers.get('x-share-total-size') || '';
|
|
394
|
+
const totalSize = Number(totalSizeHeader);
|
|
395
|
+
if (!/^[1-9][0-9]*$/.test(totalSizeHeader) || !Number.isSafeInteger(totalSize)) {
|
|
396
|
+
return json({ error: 'x-share-total-size must be a positive safe integer' }, 400);
|
|
397
|
+
}
|
|
398
|
+
if (!hasUnlimitedStorage(env.SHARE_UNLIMITED_STORAGE, auth)) {
|
|
399
|
+
let usageState;
|
|
400
|
+
try {
|
|
401
|
+
usageState = await readUsage(env, auth.owner);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
return multipartError(error, 'could not read storage limits', 503);
|
|
404
|
+
}
|
|
405
|
+
const limits = planLimits(usageState.usage.plan);
|
|
406
|
+
if (totalSize > limits.maxFileBytes) {
|
|
407
|
+
return json({ error: 'file too large', maxBytes: limits.maxFileBytes, gotBytes: totalSize }, 413);
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
const noRevision = !!request.headers.get('x-share-no-revision');
|
|
411
|
+
const createFingerprint = await multipartCreateFingerprint(path, auth, publish, noRevision, createKey, totalSize);
|
|
412
|
+
let upload;
|
|
413
|
+
try {
|
|
414
|
+
const completionToken = crypto.randomUUID();
|
|
415
|
+
publish.customMetadata['multipart-token'] = completionToken;
|
|
416
|
+
upload = await env.BUCKET.createMultipartUpload(path, {
|
|
417
|
+
httpMetadata: { contentType: publish.contentType },
|
|
418
|
+
customMetadata: publish.customMetadata,
|
|
419
|
+
});
|
|
420
|
+
const state = {
|
|
421
|
+
path: path,
|
|
422
|
+
owner: auth.owner,
|
|
423
|
+
completionToken: completionToken,
|
|
424
|
+
status: 'active',
|
|
425
|
+
visibility: publish.visibility,
|
|
426
|
+
contentType: publish.contentType,
|
|
427
|
+
expiresAt: publish.expiresAt || null,
|
|
428
|
+
totalSize: totalSize,
|
|
429
|
+
noRevision: noRevision,
|
|
430
|
+
createKey: createKey,
|
|
431
|
+
createFingerprint: createFingerprint,
|
|
432
|
+
partBytes: null,
|
|
433
|
+
parts: {},
|
|
434
|
+
};
|
|
435
|
+
// Persist recovery state before taking the non-expiring path reservation.
|
|
436
|
+
// A state-write failure can then abort without ever stranding the path;
|
|
437
|
+
// a lost create response can be recovered by a later create/resume.
|
|
438
|
+
await writeMultipartState(env.BUCKET, upload.uploadId, state, null);
|
|
439
|
+
const lock = await acquireMultipartPathLock(env.BUCKET, path, upload.uploadId);
|
|
440
|
+
if (lock === null) {
|
|
441
|
+
await upload.abort();
|
|
442
|
+
await env.BUCKET.delete(multipartStateKey(upload.uploadId));
|
|
443
|
+
const existingLock = await readPathMutationLock(env.BUCKET, path);
|
|
444
|
+
if (existingLock && existingLock.lock.kind === 'multipart') {
|
|
445
|
+
const existingState = await readMultipartState(env.BUCKET, existingLock.lock.holder);
|
|
446
|
+
if (
|
|
447
|
+
createKey &&
|
|
448
|
+
existingState &&
|
|
449
|
+
existingState.state.owner === auth.owner &&
|
|
450
|
+
existingState.state.path === path &&
|
|
451
|
+
existingState.state.createKey === createKey &&
|
|
452
|
+
existingState.state.createFingerprint === createFingerprint
|
|
453
|
+
) {
|
|
454
|
+
return json({
|
|
455
|
+
uploadId: existingLock.lock.holder,
|
|
456
|
+
path: path,
|
|
457
|
+
resumed: true,
|
|
458
|
+
expiresAt: existingState.state.expiresAt || null,
|
|
459
|
+
totalSize: existingState.state.totalSize,
|
|
460
|
+
}, 200);
|
|
461
|
+
}
|
|
462
|
+
}
|
|
463
|
+
return json({ error: 'another multipart upload is active for this path' }, 409);
|
|
464
|
+
}
|
|
465
|
+
} catch (error) {
|
|
466
|
+
// A thrown lock PUT may have committed before the transport failed. Never
|
|
467
|
+
// discard its state or abort it until the lock is known not to be ours;
|
|
468
|
+
// the next create can recover the upload id from the durable reservation.
|
|
469
|
+
try {
|
|
470
|
+
const currentLock = upload ? await readPathMutationLock(env.BUCKET, path) : null;
|
|
471
|
+
if (upload && currentLock && currentLock.lock.holder === upload.uploadId) {
|
|
472
|
+
return multipartCleanupPending(error);
|
|
473
|
+
}
|
|
474
|
+
if (upload) await upload.abort();
|
|
475
|
+
if (upload) await env.BUCKET.delete(multipartStateKey(upload.uploadId));
|
|
476
|
+
} catch (cleanupError) {
|
|
477
|
+
return multipartCleanupPending(cleanupError);
|
|
478
|
+
}
|
|
479
|
+
return multipartError(error, 'could not create multipart upload', 500);
|
|
480
|
+
}
|
|
481
|
+
return json({ uploadId: upload.uploadId, path: path, expiresAt: publish.expiresAt || null, totalSize: totalSize }, 200);
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
const uploadId = url.searchParams.get('uploadId') || '';
|
|
485
|
+
const record = await ownedMultipartState(env, auth, path, uploadId);
|
|
486
|
+
if (record.error) return record.error;
|
|
487
|
+
|
|
488
|
+
if (record.state.status === 'complete') {
|
|
489
|
+
try {
|
|
490
|
+
if (record.state.noRevision && record.state.replacement && record.state.replacement.backupKey) {
|
|
491
|
+
await env.BUCKET.delete(record.state.replacement.backupKey);
|
|
492
|
+
}
|
|
493
|
+
} catch (error) {
|
|
494
|
+
return multipartCleanupPending(error);
|
|
495
|
+
}
|
|
496
|
+
const cleanupError = await releaseTerminalMultipartLock(env, path, uploadId);
|
|
497
|
+
if (cleanupError) return cleanupError;
|
|
498
|
+
if (action === 'resume' || action === 'complete') {
|
|
499
|
+
if (action === 'resume') {
|
|
500
|
+
return json({
|
|
501
|
+
uploadId: uploadId,
|
|
502
|
+
path: path,
|
|
503
|
+
status: 'complete',
|
|
504
|
+
parts: Object.values(record.state.parts || {}),
|
|
505
|
+
result: record.state.result,
|
|
506
|
+
expiresAt: record.state.expiresAt || (record.state.result && record.state.result.expiresAt) || null,
|
|
507
|
+
totalSize: record.state.totalSize,
|
|
508
|
+
}, 200);
|
|
509
|
+
}
|
|
510
|
+
return json(record.state.result, 200);
|
|
511
|
+
}
|
|
512
|
+
return json({ error: 'multipart upload is already complete', status: 'complete', result: record.state.result }, 409);
|
|
513
|
+
}
|
|
514
|
+
if (record.state.status === 'rejecting') {
|
|
515
|
+
if (action === 'resume' || action === 'complete') {
|
|
516
|
+
return finishMultipartRejection(env, path, uploadId, record);
|
|
517
|
+
}
|
|
518
|
+
return json({ error: 'multipart rejection cleanup is pending', status: 'cleanup_pending', retry: true }, 503);
|
|
519
|
+
}
|
|
520
|
+
if (record.state.status === 'rejected') {
|
|
521
|
+
const cleanupError = await releaseTerminalMultipartLock(env, path, uploadId);
|
|
522
|
+
if (cleanupError) return cleanupError;
|
|
523
|
+
if (action === 'resume' || action === 'complete') {
|
|
524
|
+
return multipartRejectedResponse(record.state);
|
|
525
|
+
}
|
|
526
|
+
return json({ error: 'multipart upload was rejected', status: 'rejected', restart: true }, 409);
|
|
527
|
+
}
|
|
528
|
+
if (record.state.status === 'aborted') {
|
|
529
|
+
const cleanupError = await releaseTerminalMultipartLock(env, path, uploadId);
|
|
530
|
+
if (cleanupError) return cleanupError;
|
|
531
|
+
return json({ error: record.state.abortReason || 'multipart upload was aborted', status: 'aborted', restart: true }, 409);
|
|
532
|
+
}
|
|
533
|
+
const upload = env.BUCKET.resumeMultipartUpload(path, uploadId);
|
|
534
|
+
|
|
535
|
+
if (action === 'resume') {
|
|
536
|
+
const locked = await guardMultipartPartLock(env, path, uploadId, record, upload);
|
|
537
|
+
if (locked) return locked;
|
|
538
|
+
// Stored is an internal phase: R2 completion landed but quota/final receipt
|
|
539
|
+
// cleanup still needs the client's normal complete retry under this upload id.
|
|
540
|
+
const resumeStatus = record.state.status === 'stored' ? 'completing' : record.state.status;
|
|
541
|
+
return json({
|
|
542
|
+
uploadId: uploadId,
|
|
543
|
+
path: path,
|
|
544
|
+
status: resumeStatus,
|
|
545
|
+
parts: Object.values(record.state.parts || {}),
|
|
546
|
+
expiresAt: record.state.expiresAt || null,
|
|
547
|
+
totalSize: record.state.totalSize,
|
|
548
|
+
}, 200);
|
|
549
|
+
}
|
|
550
|
+
|
|
551
|
+
if (action === 'abort') {
|
|
552
|
+
if (record.state.status !== 'active') return json({ error: 'multipart upload is completing' }, 409);
|
|
553
|
+
const locked = await guardMultipartPartLock(env, path, uploadId, record, upload);
|
|
554
|
+
if (locked) return locked;
|
|
555
|
+
try {
|
|
556
|
+
const aborted = { ...record.state, status: 'aborted', abortReason: 'multipart upload was aborted' };
|
|
557
|
+
const written = await writeMultipartState(env.BUCKET, uploadId, aborted, record.object.etag);
|
|
558
|
+
if (written === null) return json({ error: 'multipart state changed; retry abort' }, 409);
|
|
559
|
+
try { await upload.abort(); } catch (e) { /* tombstone prevents any later completion */ }
|
|
560
|
+
const cleanupError = await releaseTerminalMultipartLock(env, path, uploadId);
|
|
561
|
+
if (cleanupError) return cleanupError;
|
|
562
|
+
return json({ ok: true, uploadId: uploadId, status: 'aborted' }, 200);
|
|
563
|
+
} catch (error) {
|
|
564
|
+
return multipartCleanupPending(error);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
if (action === 'part') {
|
|
569
|
+
if (record.state.status !== 'active') return json({ error: 'multipart upload is completing' }, 409);
|
|
570
|
+
const locked = await guardMultipartPartLock(env, path, uploadId, record, upload);
|
|
571
|
+
if (locked) return locked;
|
|
572
|
+
const partNumber = Number(url.searchParams.get('partNumber'));
|
|
573
|
+
const contentLength = request.headers.get('content-length') || '';
|
|
574
|
+
const declaredBytes = Number(contentLength);
|
|
575
|
+
const finalPart = request.headers.get('x-share-final-part') === '1';
|
|
576
|
+
if (!Number.isInteger(partNumber) || partNumber < 1 || partNumber > 10000) {
|
|
577
|
+
return json({ error: 'partNumber must be an integer from 1 to 10000' }, 400);
|
|
578
|
+
}
|
|
579
|
+
if (!/^[0-9]+$/.test(contentLength) || !Number.isSafeInteger(declaredBytes) || declaredBytes <= 0) {
|
|
580
|
+
return json({ error: 'content-length is required for multipart parts' }, 411);
|
|
581
|
+
}
|
|
582
|
+
if (declaredBytes > MAX_MULTIPART_PART_BYTES) {
|
|
583
|
+
return json({ error: 'multipart part too large', maxBytes: MAX_MULTIPART_PART_BYTES, gotBytes: declaredBytes }, 413);
|
|
584
|
+
}
|
|
585
|
+
if (!finalPart && declaredBytes < MIN_MULTIPART_PART_BYTES) {
|
|
586
|
+
return json({ error: 'non-final multipart parts must be at least 5 MiB', minBytes: MIN_MULTIPART_PART_BYTES }, 400);
|
|
587
|
+
}
|
|
588
|
+
if (!finalPart && record.state.partBytes !== null && record.state.partBytes !== declaredBytes) {
|
|
589
|
+
return json({ error: 'non-final multipart parts must have equal size', expectedBytes: record.state.partBytes, gotBytes: declaredBytes }, 400);
|
|
590
|
+
}
|
|
591
|
+
if (!request.body) return json({ error: 'multipart part body is required' }, 400);
|
|
592
|
+
const completedPart = record.state.parts && record.state.parts[String(partNumber)];
|
|
593
|
+
if (completedPart && completedPart.size === declaredBytes && completedPart.final === finalPart) {
|
|
594
|
+
return json({ partNumber: completedPart.partNumber, etag: completedPart.etag }, 200);
|
|
595
|
+
}
|
|
596
|
+
const recordedParts = record.state.parts || {};
|
|
597
|
+
let otherPartBytes = 0;
|
|
598
|
+
for (const key of Object.keys(recordedParts)) {
|
|
599
|
+
if (key !== String(partNumber)) otherPartBytes += recordedParts[key].size;
|
|
600
|
+
}
|
|
601
|
+
if (otherPartBytes + declaredBytes > record.state.totalSize) {
|
|
602
|
+
return json({
|
|
603
|
+
error: 'multipart parts exceed declared total size',
|
|
604
|
+
totalSize: record.state.totalSize,
|
|
605
|
+
gotBytes: otherPartBytes + declaredBytes,
|
|
606
|
+
}, 413);
|
|
607
|
+
}
|
|
608
|
+
const partLockToken = crypto.randomUUID();
|
|
609
|
+
const lockedState = {
|
|
610
|
+
...record.state,
|
|
611
|
+
partLocks: {
|
|
612
|
+
[String(partNumber)]: {
|
|
613
|
+
token: partLockToken,
|
|
614
|
+
partNumber: partNumber,
|
|
615
|
+
startedAt: Date.now(),
|
|
616
|
+
expiresAt: Date.now() + MULTIPART_PART_LEASE_MS,
|
|
617
|
+
},
|
|
618
|
+
},
|
|
619
|
+
};
|
|
620
|
+
const lock = await writeMultipartState(env.BUCKET, uploadId, lockedState, record.object.etag);
|
|
621
|
+
if (lock === null) return json({ error: 'multipart state changed; resume and retry the part' }, 409);
|
|
622
|
+
try {
|
|
623
|
+
// Deliberately hand the request stream straight to R2. Large media must
|
|
624
|
+
// never pass through readBodyBounded or an ArrayBuffer in this Worker.
|
|
625
|
+
const part = await upload.uploadPart(partNumber, request.body);
|
|
626
|
+
const state = { ...lockedState, partLocks: {}, parts: { ...(record.state.parts || {}) } };
|
|
627
|
+
if (!finalPart && state.partBytes === null) state.partBytes = declaredBytes;
|
|
628
|
+
state.parts[String(partNumber)] = { partNumber: part.partNumber, etag: part.etag, size: declaredBytes, final: finalPart };
|
|
629
|
+
const stored = await writeMultipartState(env.BUCKET, uploadId, state, lock.etag);
|
|
630
|
+
if (stored === null) return json({ error: 'multipart state changed; resume and retry the part' }, 409);
|
|
631
|
+
return json({ partNumber: part.partNumber, etag: part.etag }, 200);
|
|
632
|
+
} catch (error) {
|
|
633
|
+
try {
|
|
634
|
+
const current = await readMultipartState(env.BUCKET, uploadId);
|
|
635
|
+
const currentLock = current && current.state.partLocks && current.state.partLocks[String(partNumber)];
|
|
636
|
+
if (currentLock && currentLock.token === partLockToken) {
|
|
637
|
+
await writeMultipartState(env.BUCKET, uploadId, { ...current.state, partLocks: {} }, current.object.etag);
|
|
638
|
+
}
|
|
639
|
+
} catch (e) { /* the lease/tombstone path recovers a stranded lock */ }
|
|
640
|
+
return multipartError(error, 'could not upload multipart part', 502);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
const locked = await guardMultipartPartLock(env, path, uploadId, record, upload);
|
|
645
|
+
if (locked) return locked;
|
|
646
|
+
if (!(await pathMutationLockOwned(env.BUCKET, path, uploadId))) {
|
|
647
|
+
return json({ error: 'multipart path reservation was lost; abort and create a new upload' }, 409);
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const completeBody = await readBodyBounded(request, 4 * 1024 * 1024);
|
|
651
|
+
if (completeBody.oversize) return json({ error: 'complete parts body is too large' }, 413);
|
|
652
|
+
let body;
|
|
653
|
+
try { body = JSON.parse(new TextDecoder().decode(completeBody.bytes)); } catch (e) { return json({ error: 'complete requires a JSON parts body' }, 400); }
|
|
654
|
+
const parts = body && Array.isArray(body.parts) ? body.parts : [];
|
|
655
|
+
if (!parts.length || parts.length > 10000) return json({ error: 'complete requires 1 to 10000 parts' }, 400);
|
|
656
|
+
const recorded = record.state.parts || {};
|
|
657
|
+
const seen = new Set();
|
|
658
|
+
let completedPartBytes = 0;
|
|
659
|
+
for (let i = 0; i < parts.length; i++) {
|
|
660
|
+
const part = parts[i];
|
|
661
|
+
if (!part || !Number.isInteger(part.partNumber) || part.partNumber !== i + 1 || typeof part.etag !== 'string' || !part.etag || part.etag.length > 256 || seen.has(part.partNumber)) {
|
|
662
|
+
return json({ error: 'complete parts must be unique, consecutive, and ordered from 1' }, 400);
|
|
663
|
+
}
|
|
664
|
+
seen.add(part.partNumber);
|
|
665
|
+
const saved = recorded[String(part.partNumber)];
|
|
666
|
+
if (!saved || saved.etag !== part.etag) return json({ error: 'complete contains an unknown multipart part' }, 400);
|
|
667
|
+
completedPartBytes += saved.size;
|
|
668
|
+
if (i < parts.length - 1 && (saved.final || saved.size < MIN_MULTIPART_PART_BYTES || saved.size !== record.state.partBytes)) {
|
|
669
|
+
return json({ error: 'non-final multipart parts must be at least 5 MiB and equal size' }, 400);
|
|
670
|
+
}
|
|
671
|
+
if (i === parts.length - 1 && !saved.final) return json({ error: 'last multipart part was not marked final' }, 400);
|
|
672
|
+
}
|
|
673
|
+
if (completedPartBytes !== record.state.totalSize) {
|
|
674
|
+
return json({
|
|
675
|
+
error: 'multipart parts do not match declared total size',
|
|
676
|
+
totalSize: record.state.totalSize,
|
|
677
|
+
gotBytes: completedPartBytes,
|
|
678
|
+
}, 400);
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
let state = record.state;
|
|
682
|
+
let stateEtag = record.object.etag;
|
|
683
|
+
let replacement = state.replacement || null;
|
|
684
|
+
if (state.status === 'active') {
|
|
685
|
+
const existing = await env.BUCKET.get(path);
|
|
686
|
+
const backupKey = existing
|
|
687
|
+
? (state.noRevision ? '__multipart-backups/' + encodeURIComponent(uploadId) : path + '/rev-' + Date.now() + '-' + Math.random().toString(36).slice(2, 8))
|
|
688
|
+
: '';
|
|
689
|
+
try {
|
|
690
|
+
if (existing) {
|
|
691
|
+
const headers = new Headers();
|
|
692
|
+
existing.writeHttpMetadata(headers);
|
|
693
|
+
await env.BUCKET.put(backupKey, existing.body, {
|
|
694
|
+
httpMetadata: headers.get('content-type') ? { contentType: headers.get('content-type') } : undefined,
|
|
695
|
+
customMetadata: existing.customMetadata || {},
|
|
696
|
+
});
|
|
697
|
+
}
|
|
698
|
+
const current = await env.BUCKET.head(path);
|
|
699
|
+
if ((existing && (!current || current.etag !== existing.etag)) || (!existing && current)) {
|
|
700
|
+
if (backupKey) await env.BUCKET.delete(backupKey);
|
|
701
|
+
return json({ error: 'publish conflict: object changed before multipart completion' }, 409);
|
|
702
|
+
}
|
|
703
|
+
replacement = {
|
|
704
|
+
hadExisting: !!existing,
|
|
705
|
+
existingEtag: existing ? existing.etag : '',
|
|
706
|
+
existingSize: existing && typeof existing.size === 'number' ? existing.size : 0,
|
|
707
|
+
backupKey: backupKey,
|
|
708
|
+
};
|
|
709
|
+
state = { ...state, status: 'completing', replacement: replacement, completionParts: parts };
|
|
710
|
+
const phase = await writeMultipartState(env.BUCKET, uploadId, state, stateEtag);
|
|
711
|
+
if (phase === null) {
|
|
712
|
+
if (backupKey) await env.BUCKET.delete(backupKey);
|
|
713
|
+
return json({ error: 'multipart state changed; resume and retry complete' }, 409);
|
|
714
|
+
}
|
|
715
|
+
stateEtag = phase.etag;
|
|
716
|
+
} catch (error) {
|
|
717
|
+
if (backupKey) try { await env.BUCKET.delete(backupKey); } catch (e) { /* cleanup best-effort */ }
|
|
718
|
+
return multipartError(error, 'could not prepare multipart completion', 500);
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
// A retry after a lost response consults the unique token stamped when the
|
|
723
|
+
// upload was created. If it is already canonical, do not call R2 complete a
|
|
724
|
+
// second time (R2 rejects that with 10024); proceed idempotently to charging.
|
|
725
|
+
let completed = await env.BUCKET.head(path);
|
|
726
|
+
const landed = !!completed && completed.customMetadata && completed.customMetadata['multipart-token'] === state.completionToken;
|
|
727
|
+
if (!landed) {
|
|
728
|
+
const stillOriginal = replacement.hadExisting
|
|
729
|
+
? !!completed && completed.etag === replacement.existingEtag
|
|
730
|
+
: !completed;
|
|
731
|
+
if (!stillOriginal) return json({ error: 'publish conflict: object changed before multipart completion' }, 409);
|
|
732
|
+
try {
|
|
733
|
+
// upload.complete cannot take an R2 precondition. The reservation is held
|
|
734
|
+
// from create through this exact call, while PUT/PATCH/DELETE must acquire
|
|
735
|
+
// the same key, closing the final check-to-complete race.
|
|
736
|
+
if (!(await pathMutationLockOwned(env.BUCKET, path, uploadId))) {
|
|
737
|
+
return json({ error: 'multipart path reservation was lost; abort and create a new upload' }, 409);
|
|
738
|
+
}
|
|
739
|
+
await upload.complete(state.completionParts || parts);
|
|
740
|
+
} catch (error) {
|
|
741
|
+
return multipartError(error, 'could not complete multipart upload', 502);
|
|
742
|
+
}
|
|
743
|
+
completed = await env.BUCKET.head(path);
|
|
744
|
+
}
|
|
745
|
+
if (!completed || typeof completed.size !== 'number' || !completed.customMetadata || completed.customMetadata['multipart-token'] !== state.completionToken) {
|
|
746
|
+
return json({ error: 'completed multipart object is missing or changed' }, 500);
|
|
747
|
+
}
|
|
748
|
+
const realBytes = completed.size;
|
|
749
|
+
if (realBytes !== state.totalSize) {
|
|
750
|
+
try {
|
|
751
|
+
const rejectionBody = JSON.stringify({
|
|
752
|
+
error: 'completed object does not match declared total size',
|
|
753
|
+
totalSize: state.totalSize,
|
|
754
|
+
gotBytes: realBytes,
|
|
755
|
+
});
|
|
756
|
+
const rejecting = { ...state, status: 'rejecting', rejection: { status: 400, body: rejectionBody } };
|
|
757
|
+
const rejectingWrite = await writeMultipartState(env.BUCKET, uploadId, rejecting, stateEtag);
|
|
758
|
+
if (rejectingWrite === null) throw new Error('multipart size rejection phase conflicted');
|
|
759
|
+
return finishMultipartRejection(env, path, uploadId, { object: rejectingWrite, state: rejecting });
|
|
760
|
+
} catch (error) {
|
|
761
|
+
return multipartCleanupPending(error);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
if (state.status !== 'stored') {
|
|
765
|
+
state = { ...state, status: 'stored', completedSize: realBytes };
|
|
766
|
+
try {
|
|
767
|
+
const storedPhase = await writeMultipartState(env.BUCKET, uploadId, state, stateEtag);
|
|
768
|
+
if (storedPhase !== null) stateEtag = storedPhase.etag;
|
|
769
|
+
} catch (e) {
|
|
770
|
+
// The completion token above still makes the next retry recoverable.
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
|
|
774
|
+
let charged;
|
|
775
|
+
try {
|
|
776
|
+
const charge = replacement.hadExisting && !state.noRevision ? realBytes : realBytes - replacement.existingSize;
|
|
777
|
+
charged = await chargeShareWrite(env, auth, {
|
|
778
|
+
charge: charge,
|
|
779
|
+
newCanonical: !replacement.hadExisting,
|
|
780
|
+
fileBytes: realBytes,
|
|
781
|
+
countRate: true,
|
|
782
|
+
unlimitedVideoMultipart: true,
|
|
783
|
+
idempotencyKey: uploadId,
|
|
784
|
+
});
|
|
785
|
+
} catch (error) {
|
|
786
|
+
// A transport failure can happen after the ledger CAS committed. Re-read
|
|
787
|
+
// the receipt only to turn a known committed charge into success. A missing
|
|
788
|
+
// or unreadable receipt is indeterminate, never a quota rejection: preserve
|
|
789
|
+
// the landed object, completing state, and path reservation so the same
|
|
790
|
+
// upload id can safely retry the idempotent ledger mutation.
|
|
791
|
+
try {
|
|
792
|
+
const usageAfterError = (await readUsage(env, auth.owner)).usage;
|
|
793
|
+
if (usageAfterError.multipartCharges.indexOf(uploadId) !== -1) charged = {};
|
|
794
|
+
} catch (e) { /* the next complete retry re-reads through chargeShareWrite */ }
|
|
795
|
+
if (!charged) return multipartCleanupPending(error);
|
|
796
|
+
}
|
|
797
|
+
if (charged.error) {
|
|
798
|
+
const rejectionBody = await charged.error.clone().text();
|
|
799
|
+
const rejecting = { ...state, status: 'rejecting', rejection: { status: charged.error.status, body: rejectionBody } };
|
|
800
|
+
try {
|
|
801
|
+
const rejectingWrite = await writeMultipartState(env.BUCKET, uploadId, rejecting, stateEtag);
|
|
802
|
+
if (rejectingWrite === null) throw new Error('multipart rejection phase conflicted');
|
|
803
|
+
return finishMultipartRejection(env, path, uploadId, { object: rejectingWrite, state: rejecting });
|
|
804
|
+
} catch (error) {
|
|
805
|
+
return multipartCleanupPending(error);
|
|
806
|
+
}
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
const authoritativeExpiresAt = state.expiresAt || null;
|
|
810
|
+
const result = {
|
|
811
|
+
ok: true,
|
|
812
|
+
uploadId: uploadId,
|
|
813
|
+
path: path,
|
|
814
|
+
url: url.origin + '/' + path,
|
|
815
|
+
size: realBytes,
|
|
816
|
+
visibility: state.visibility,
|
|
817
|
+
expiresAt: authoritativeExpiresAt,
|
|
818
|
+
totalSize: state.totalSize,
|
|
819
|
+
};
|
|
820
|
+
try {
|
|
821
|
+
const finished = { ...state, status: 'complete', result: result };
|
|
822
|
+
const finishedWrite = await writeMultipartState(env.BUCKET, uploadId, finished, stateEtag);
|
|
823
|
+
if (finishedWrite === null) throw new Error('multipart completion receipt conflicted');
|
|
824
|
+
if (state.noRevision && replacement.backupKey) await env.BUCKET.delete(replacement.backupKey);
|
|
825
|
+
await releaseMultipartPathLock(env.BUCKET, path, uploadId);
|
|
826
|
+
} catch (error) {
|
|
827
|
+
// The stored phase + CAS-protected charge receipt make a retry safe even if
|
|
828
|
+
// writing the final receipt or cleanup failed after the object landed.
|
|
829
|
+
return multipartCleanupPending(error);
|
|
830
|
+
}
|
|
831
|
+
return json(result, 200);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
function json(body, status) {
|
|
835
|
+
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
// Length-independent constant-time-ish compare (Workers has no timingSafeEqual).
|
|
839
|
+
function safeEqual(a, b) {
|
|
840
|
+
if (typeof a !== 'string' || typeof b !== 'string') return false;
|
|
841
|
+
const la = a.length, lb = b.length;
|
|
842
|
+
let out = la ^ lb;
|
|
843
|
+
for (let i = 0; i < la; i++) out |= a.charCodeAt(i) ^ b.charCodeAt(i % lb || 0);
|
|
844
|
+
return out === 0 && la === lb;
|
|
845
|
+
}
|
|
846
|
+
|
|
847
|
+
// URL-safety, not collision-resistance. Two values that differ only in
|
|
848
|
+
// case/punctuation share a prefix.
|
|
849
|
+
function sanitizeNamespace(s) {
|
|
850
|
+
return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
// Public handle: email local-part, plus-tag stripped. Must match CLI handleFromEmail.
|
|
854
|
+
function handleFromEmail(email) {
|
|
855
|
+
if (!email) return '';
|
|
856
|
+
const local = String(email).split('@')[0] || '';
|
|
857
|
+
const beforePlus = local.split('+')[0] || local;
|
|
858
|
+
return sanitizeNamespace(beforePlus);
|
|
859
|
+
}
|
|
860
|
+
|
|
861
|
+
function phoenixHandle(auth) {
|
|
862
|
+
return handleFromEmail(auth.email) || sanitizeNamespace(auth.owner);
|
|
863
|
+
}
|
|
864
|
+
|
|
865
|
+
`;
|
|
866
|
+
//# sourceMappingURL=worker-publish-template.js.map
|