@cardinali-studio/adminkit 2.2.49 → 2.2.51
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/dist/app/App.js +6 -6
- package/dist/app/app.css +110 -1
- package/dist/app/delivery.js +7 -7
- package/dist/app/guide/TransferGuide.js +1 -1
- package/dist/app/lib/deliveries.d.ts +6 -0
- package/dist/app/lib/delivery-capabilities.d.ts +31 -0
- package/dist/app/lib/delivery-capabilities.js +115 -0
- package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
- package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
- package/dist/app/lib/delivery-finalize.d.ts +21 -0
- package/dist/app/lib/delivery-finalize.js +42 -0
- package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
- package/dist/app/lib/delivery-multipart-large.js +28 -0
- package/dist/app/lib/delivery-network.d.ts +7 -1
- package/dist/app/lib/delivery-network.js +85 -18
- package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
- package/dist/app/lib/delivery-part-pipeline.js +270 -0
- package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
- package/dist/app/lib/delivery-upload-coordinator.js +229 -0
- package/dist/app/lib/delivery-upload.d.ts +19 -3
- package/dist/app/lib/delivery-upload.js +226 -29
- package/dist/app/lib/upload-queue.d.ts +5 -0
- package/dist/app/lib/upload-queue.js +54 -29
- package/dist/app/routes/Deliveries.d.ts +9 -3
- package/dist/app/routes/Deliveries.js +318 -189
- package/dist/app/routes/DeliveryDashboard.js +1 -1
- package/dist/app/routes/DeliveryEmail.d.ts +8 -1
- package/dist/app/routes/DeliveryEmail.js +63 -23
- package/dist/app/routes/DeliveryRecipientPreview.d.ts +14 -0
- package/dist/app/routes/DeliveryRecipientPreview.js +49 -0
- package/dist/app/routes/Overview.js +5 -5
- package/dist/app/routes/UploadDock.js +4 -3
- package/dist/form/media/MediaGrid.js +1 -1
- package/dist/functions/_shared/b2.js +98 -19
- package/dist/functions/_shared/delivery-activation.js +98 -0
- package/dist/functions/_shared/delivery-download-bundle.js +280 -0
- package/dist/functions/_shared/delivery-email.js +92 -13
- package/dist/functions/_shared/delivery-file-names.js +19 -0
- package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
- package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
- package/dist/functions/_shared/delivery-manifest-free.js +74 -0
- package/dist/functions/_shared/delivery-manifest.js +277 -20
- package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
- package/dist/functions/_shared/delivery-request.js +74 -0
- package/dist/functions/_shared/delivery-storage-access.js +14 -0
- package/dist/functions/_shared/delivery-upload-admission.js +221 -0
- package/dist/functions/_shared/delivery-upload-contract.js +44 -0
- package/dist/functions/_shared/delivery-upload-free.js +80 -0
- package/dist/functions/_shared/delivery-upload-policy.js +64 -0
- package/dist/functions/_shared/delivery-upload-session.js +365 -0
- package/dist/functions/_shared/delivery-work-budget.js +49 -0
- package/dist/functions/api/deliveries.js +58 -17
- package/dist/functions/api/delivery/multipart.js +152 -15
- package/dist/functions/delivery-public/assets/client.js +59 -54
- package/dist/functions/delivery-public/assets/delivery.css +6 -2
- package/dist/functions/delivery-public/index.js +43 -15
- package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
- package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
- package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
- package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
- package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
- package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
- package/dist/functions/index.js +3 -1
- package/dist/theme.css +2 -1
- package/package.json +1 -1
|
@@ -5,6 +5,10 @@
|
|
|
5
5
|
import { b2ObjectKey, b2PutSmall, b2Head } from './b2.js';
|
|
6
6
|
import { sha256 } from './delivery-crypto.js';
|
|
7
7
|
import { DELIVERY_MAX_ARCHIVE_BYTES, validateDeliverySourceBytes } from './delivery-limits.js';
|
|
8
|
+
import { ensureManifestObject, verifyArchiveHeads, measureFinalization } from './delivery-finalization-storage.js';
|
|
9
|
+
import { assertUploadSessionInvocation, uploadSessionMarker } from './delivery-upload-contract.js';
|
|
10
|
+
import { freeWork, needsPaid, assertFreeEntryRead, assertFreeCheckpointRead, readFreeManifestDraft } from './delivery-upload-free.js';
|
|
11
|
+
import { prepareFreeManifestPage } from './delivery-manifest-free.js';
|
|
8
12
|
export const MANIFEST_BATCH_ENTRIES = 200;
|
|
9
13
|
export const MANIFEST_BATCH_BYTES = 256 * 1024;
|
|
10
14
|
export const MANIFEST_MAX_ENTRIES = 100_000;
|
|
@@ -45,6 +49,7 @@ async function activePackage(env, body, write = false) {
|
|
|
45
49
|
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`)
|
|
46
50
|
.bind(String(body.packageId || ''), String(body.id || '')).first();
|
|
47
51
|
if (!pkg || manifestVersion(pkg) !== 2) throw fail('Pacchetto v2 non disponibile', 409);
|
|
52
|
+
assertUploadSessionInvocation(env, pkg);
|
|
48
53
|
if (write) await assertManifestWriter(env, pkg.id, body.writerToken);
|
|
49
54
|
return pkg;
|
|
50
55
|
}
|
|
@@ -92,8 +97,9 @@ export async function ingestManifest(env, body) {
|
|
|
92
97
|
if (receipt.digest !== digest) throw fail('Il batch esiste con contenuti diversi', 409);
|
|
93
98
|
return { accepted: true };
|
|
94
99
|
}
|
|
95
|
-
const state = await env.DB.prepare('SELECT
|
|
100
|
+
const state = await env.DB.prepare('SELECT state,metadata_bytes FROM delivery_manifest_state WHERE package_id=?').bind(pkg.id).first();
|
|
96
101
|
if (pkg.state !== 'uploading' || state?.state !== 'uploading') throw fail('Il manifest è già congelato', 409);
|
|
102
|
+
await assertFreeEntryRead(env,pkg.id,"AND entry_id IN (SELECT json_extract(value,'$.index') FROM json_each(?))",[payload]);
|
|
97
103
|
const prior = await env.DB.prepare(`SELECT entry_id,entry_json FROM delivery_manifest_entries WHERE package_id=?
|
|
98
104
|
AND entry_id IN (SELECT json_extract(value,'$.index') FROM json_each(?))`).bind(pkg.id, payload).all();
|
|
99
105
|
const previous = new Map((prior.results || []).map(row => [row.entry_id, JSON.parse(row.entry_json)]));
|
|
@@ -137,8 +143,69 @@ export async function ingestManifest(env, body) {
|
|
|
137
143
|
return { accepted: true };
|
|
138
144
|
}
|
|
139
145
|
|
|
146
|
+
// New, opt-in originals protocol. Existing original claims are the durable
|
|
147
|
+
// receipts, so regrouping after a checkpoint never overwrites an original or
|
|
148
|
+
// depends on the legacy originals-N batch boundaries. No new schema is needed.
|
|
149
|
+
export async function ingestReplayManifest(env, body) {
|
|
150
|
+
const pkg = await activePackage(env, body, true);
|
|
151
|
+
if (body.phase !== 'originals' || !Array.isArray(body.entries) || !body.entries.length ||
|
|
152
|
+
body.entries.length > MANIFEST_BATCH_ENTRIES || bytes(JSON.stringify(body.entries)) > MANIFEST_BATCH_BYTES) throw fail('Batch replay non valido', 413);
|
|
153
|
+
const seen = new Set();
|
|
154
|
+
const rows = body.entries.map(row => {
|
|
155
|
+
if (!Number.isSafeInteger(row?.index) || row.index < 0 || row.index >= pkg.file_count || seen.has(row.index)) throw fail('Indice file non valido');
|
|
156
|
+
seen.add(row.index);
|
|
157
|
+
const clean = entry(row.entry);
|
|
158
|
+
if (clean.web || clean.thumb || clean.skipped != null || clean.width != null || clean.height != null) throw fail('Il replay accetta soltanto metadati originali');
|
|
159
|
+
return { index: row.index, entry: clean };
|
|
160
|
+
}).sort((a,b) => a.index-b.index);
|
|
161
|
+
const digest = await sha256(JSON.stringify([pkg.id, rows]));
|
|
162
|
+
if (body.batchId !== 'm3_' + digest) throw fail('Identità replay non valida', 409);
|
|
163
|
+
const payload = JSON.stringify(rows);
|
|
164
|
+
const original = e => ({ name: e.name, type: e.type, original: member(e.original) });
|
|
165
|
+
const read = async () => (await env.DB.prepare(`SELECT e.entry_id,e.entry_json,
|
|
166
|
+
EXISTS(SELECT 1 FROM delivery_manifest_claims c WHERE c.package_id=e.package_id AND c.phase='originals' AND c.entry_id=e.entry_id) claimed
|
|
167
|
+
FROM delivery_manifest_entries e WHERE e.package_id=? AND e.entry_id IN
|
|
168
|
+
(SELECT json_extract(value,'$.index') FROM json_each(?))`).bind(pkg.id, payload).all()).results || [];
|
|
169
|
+
await assertFreeEntryRead(env,pkg.id,"AND entry_id IN (SELECT json_extract(value,'$.index') FROM json_each(?))",[payload],2);
|
|
170
|
+
const previous = new Map((await read()).map(r => [r.entry_id, r]));
|
|
171
|
+
const matches = (saved, row) => saved?.claimed && JSON.stringify(original(JSON.parse(saved.entry_json))) === JSON.stringify(row.entry);
|
|
172
|
+
if (rows.some(r => previous.has(r.index) && !matches(previous.get(r.index), r))) throw fail('Metadati originali diversi da quelli confermati', 409);
|
|
173
|
+
const missing = rows.filter(r => !previous.has(r.index));
|
|
174
|
+
if (!missing.length) return { accepted: true, batchId: body.batchId };
|
|
175
|
+
const state = await env.DB.prepare('SELECT state,metadata_bytes FROM delivery_manifest_state WHERE package_id=?').bind(pkg.id).first();
|
|
176
|
+
const delta = missing.reduce((n, r) => n + bytes(JSON.stringify(r.entry)), 0);
|
|
177
|
+
if (pkg.state !== 'uploading' || state?.state !== 'uploading') throw fail('Il manifest è già congelato', 409);
|
|
178
|
+
if (state.metadata_bytes + delta > MANIFEST_MAX_BYTES) throw fail('Troppi metadati per questo invio', 413);
|
|
179
|
+
const guard = `EXISTS(SELECT 1 FROM delivery_manifest_state s JOIN delivery_packages p ON p.id=s.package_id
|
|
180
|
+
JOIN deliveries d ON d.id=p.delivery_id WHERE s.package_id=? AND s.state='uploading' AND p.state='uploading'
|
|
181
|
+
AND s.writer_token=? AND s.metadata_bytes=? AND d.status!='deleted'
|
|
182
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))`;
|
|
183
|
+
const args = [pkg.id, body.writerToken, state.metadata_bytes];
|
|
184
|
+
const fresh = JSON.stringify(missing.map(r => ({ ...r, requiresVariant: Number(!!(pkg.web_enabled || pkg.gallery_enabled) && /\.(jpe?g|png|webp)$/i.test(r.entry.name)) })));
|
|
185
|
+
try { await env.DB.batch([
|
|
186
|
+
env.DB.prepare(`INSERT INTO delivery_manifest_claims(package_id,phase,entry_id)
|
|
187
|
+
SELECT ?,'originals',json_extract(value,'$.index') FROM json_each(?) WHERE ${guard}`).bind(pkg.id, fresh, ...args),
|
|
188
|
+
env.DB.prepare(`INSERT INTO delivery_manifest_entries(package_id,entry_id,name,has_preview,requires_variant,source_bytes,entry_json)
|
|
189
|
+
SELECT ?,json_extract(value,'$.index'),json_extract(value,'$.entry.name'),0,json_extract(value,'$.requiresVariant'),
|
|
190
|
+
json_extract(value,'$.entry.original.length'),json_extract(value,'$.entry') FROM json_each(?) WHERE ${guard}`)
|
|
191
|
+
.bind(pkg.id, fresh, ...args),
|
|
192
|
+
env.DB.prepare(`UPDATE delivery_manifest_state SET metadata_bytes=metadata_bytes+? WHERE package_id=? AND ${guard}`).bind(delta, pkg.id, ...args),
|
|
193
|
+
]); } catch (error) {
|
|
194
|
+
if (/UNIQUE constraint failed|SQLITE_CONSTRAINT/i.test(String(error?.message))) throw fail('Metadati originali in conflitto', 409);
|
|
195
|
+
throw error;
|
|
196
|
+
}
|
|
197
|
+
await activePackage(env, body, true);
|
|
198
|
+
const saved = new Map((await read()).map(r => [r.entry_id, r]));
|
|
199
|
+
if (!rows.every(r => matches(saved.get(r.index), r))) throw fail('Replay cambiato o annullato', 409);
|
|
200
|
+
return { accepted: true, batchId: body.batchId };
|
|
201
|
+
}
|
|
202
|
+
|
|
140
203
|
export async function finalizeManifestStep(env, body) {
|
|
141
204
|
const pkg = await activePackage(env, body, true);
|
|
205
|
+
if (parseManifest(pkg.manifest_json).finalizationProtocol === 'common-v1') throw fail('Il pacchetto richiede la finalizzazione comune', 409);
|
|
206
|
+
// Fence in-flight legacy requests too: a common reader can take ownership
|
|
207
|
+
// while an earlier request is awaiting storage, before the root exists.
|
|
208
|
+
const legacyOwner = "COALESCE(json_extract(manifest_json,'$.finalizationProtocol'),'')!='common-v1'";
|
|
142
209
|
if (pkg.state === 'ready') return { done: true };
|
|
143
210
|
validateDeliverySourceBytes(pkg.source_bytes);
|
|
144
211
|
const uploads = (await env.DB.prepare('SELECT * FROM delivery_uploads WHERE package_id=?').bind(pkg.id).all()).results || [];
|
|
@@ -152,7 +219,7 @@ export async function finalizeManifestStep(env, body) {
|
|
|
152
219
|
MIN(entry_id) lo,MAX(entry_id) hi,SUM(CASE WHEN requires_variant=1 AND variant_done=0 THEN 1 ELSE 0 END) pending FROM delivery_manifest_entries WHERE package_id=?`).bind(pkg.id).first();
|
|
153
220
|
if (totals.pending || totals.n !== pkg.file_count || totals.bytes !== pkg.source_bytes || totals.lo !== 0 || totals.hi !== pkg.file_count - 1) throw fail('Elenco dei file incompleto', 409);
|
|
154
221
|
await env.DB.prepare(`UPDATE delivery_manifest_state SET state='sealed' WHERE package_id=? AND state='uploading'
|
|
155
|
-
AND EXISTS (SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading')`).bind(pkg.id, pkg.id).run();
|
|
222
|
+
AND EXISTS (SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading' AND ${legacyOwner})`).bind(pkg.id, pkg.id).run();
|
|
156
223
|
state = await env.DB.prepare('SELECT * FROM delivery_manifest_state WHERE package_id=?').bind(pkg.id).first();
|
|
157
224
|
}
|
|
158
225
|
if (!state || !['sealed','ready'].includes(state.state)) throw fail('Finalizzazione non disponibile', 409);
|
|
@@ -175,16 +242,24 @@ export async function finalizeManifestStep(env, body) {
|
|
|
175
242
|
const end = rows.at(-1).index + 1;
|
|
176
243
|
await env.DB.prepare(`INSERT OR IGNORE INTO delivery_manifest_objects
|
|
177
244
|
(package_id,page_number,object_key,digest,end_cursor,entry_count)
|
|
178
|
-
SELECT ?,?,?,?,?,? WHERE EXISTS (SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading')`)
|
|
245
|
+
SELECT ?,?,?,?,?,? WHERE EXISTS (SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading' AND ${legacyOwner})`)
|
|
179
246
|
.bind(pkg.id, state.page_count, key, digest, end, rows.length, pkg.id).run();
|
|
180
|
-
const reserved = await env.DB.prepare(
|
|
247
|
+
const reserved = await env.DB.prepare(`SELECT * FROM delivery_manifest_objects WHERE package_id=? AND page_number=?
|
|
248
|
+
AND EXISTS(SELECT 1 FROM delivery_packages WHERE id=? AND ${legacyOwner})`).bind(pkg.id, state.page_count, pkg.id).first();
|
|
181
249
|
if (reserved?.object_key !== key) throw fail('Generazione modificata o annullata', 409);
|
|
182
250
|
await b2PutSmall(env, key, json, 'application/json');
|
|
183
|
-
await env.DB.batch([
|
|
184
|
-
env.DB.prepare(
|
|
251
|
+
const committed = await env.DB.batch([
|
|
252
|
+
env.DB.prepare(`UPDATE delivery_manifest_objects SET verified=1 WHERE package_id=? AND page_number=? AND digest=?
|
|
253
|
+
AND EXISTS(SELECT 1 FROM delivery_packages WHERE id=? AND ${legacyOwner})`).bind(pkg.id, state.page_count, digest, pkg.id),
|
|
185
254
|
env.DB.prepare(`UPDATE delivery_manifest_state SET cursor=?,page_count=page_count+1 WHERE package_id=? AND cursor=? AND state='sealed'
|
|
186
|
-
AND EXISTS (SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading')`).bind(end, pkg.id, state.cursor, pkg.id),
|
|
255
|
+
AND EXISTS (SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading' AND ${legacyOwner})`).bind(end, pkg.id, state.cursor, pkg.id),
|
|
187
256
|
]);
|
|
257
|
+
if (!committed[1].meta.changes) {
|
|
258
|
+
// Cancellation already makes the following legacy step unavailable; keep
|
|
259
|
+
// that existing contract. A protocol handover must reject this stale ack.
|
|
260
|
+
const current = await env.DB.prepare('SELECT manifest_json FROM delivery_packages WHERE id=?').bind(pkg.id).first();
|
|
261
|
+
if (parseManifest(current?.manifest_json).finalizationProtocol === 'common-v1') throw fail('Il pacchetto richiede la finalizzazione comune', 409);
|
|
262
|
+
}
|
|
188
263
|
return { done: false, cursor: end, total: pkg.file_count };
|
|
189
264
|
}
|
|
190
265
|
const pages = (await env.DB.prepare('SELECT page_number,object_key,digest,entry_count FROM delivery_manifest_objects WHERE package_id=? AND page_number>=0 AND verified=1 ORDER BY page_number').bind(pkg.id).all()).results || [];
|
|
@@ -201,15 +276,16 @@ export async function finalizeManifestStep(env, body) {
|
|
|
201
276
|
const digest = await sha256(json);
|
|
202
277
|
const key = b2ObjectKey(pkg.storage_prefix, `manifest-v2/root-${digest}.json`);
|
|
203
278
|
await env.DB.prepare(`INSERT OR IGNORE INTO delivery_manifest_objects(package_id,page_number,object_key,digest,end_cursor,entry_count)
|
|
204
|
-
SELECT ?,-1,?,?,?,0 WHERE EXISTS(SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading')`)
|
|
279
|
+
SELECT ?,-1,?,?,?,0 WHERE EXISTS(SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading' AND ${legacyOwner})`)
|
|
205
280
|
.bind(pkg.id, key, digest, pkg.file_count, pkg.id).run();
|
|
206
|
-
const reserved = await env.DB.prepare(
|
|
281
|
+
const reserved = await env.DB.prepare(`SELECT object_key FROM delivery_manifest_objects WHERE package_id=? AND page_number=-1
|
|
282
|
+
AND EXISTS(SELECT 1 FROM delivery_packages WHERE id=? AND ${legacyOwner})`).bind(pkg.id, pkg.id).first();
|
|
207
283
|
if (reserved?.object_key !== key) throw fail('Descrittore finale in conflitto', 409);
|
|
208
284
|
await b2PutSmall(env, key, json, 'application/json');
|
|
209
285
|
const marker = JSON.stringify({ version: 2, generation: pkg.id, root: key, digest });
|
|
210
286
|
await env.DB.batch([
|
|
211
287
|
env.DB.prepare(`UPDATE delivery_packages SET state='ready',manifest_json=?,manifest_key=?,originals_key=?,web_key=?,thumbs_key=?,stored_bytes=?,updated_at=?
|
|
212
|
-
WHERE id=? AND state='uploading' AND EXISTS(SELECT 1 FROM delivery_manifest_state WHERE package_id=? AND state='sealed' AND cursor=?)`)
|
|
288
|
+
WHERE id=? AND state='uploading' AND ${legacyOwner} AND EXISTS(SELECT 1 FROM delivery_manifest_state WHERE package_id=? AND state='sealed' AND cursor=?)`)
|
|
213
289
|
.bind(marker, key, byVariant.originals.object_key, byVariant.web?.object_key || null, byVariant.thumbs?.object_key || null,
|
|
214
290
|
uploads.reduce((n,u) => n + u.bytes,0), new Date().toISOString(), pkg.id, pkg.id, pkg.file_count),
|
|
215
291
|
env.DB.prepare(`UPDATE delivery_manifest_state SET state='ready',root_json=? WHERE package_id=?
|
|
@@ -220,11 +296,164 @@ export async function finalizeManifestStep(env, body) {
|
|
|
220
296
|
return { done: true };
|
|
221
297
|
}
|
|
222
298
|
|
|
223
|
-
|
|
299
|
+
// Common, one-step finalizer. The HTTP capability gate remains disabled.
|
|
300
|
+
export async function finalizeManifestStepCommon(env, body, trace, work) {
|
|
301
|
+
work ??= freeWork(env);
|
|
302
|
+
const time = (stage, operation) => measureFinalization(trace, stage, operation);
|
|
303
|
+
const pkg = await activePackage(env, body, true);
|
|
304
|
+
validateDeliverySourceBytes(pkg.source_bytes);
|
|
305
|
+
if (pkg.state === 'ready') {
|
|
306
|
+
const marker = parseManifest(pkg.manifest_json);
|
|
307
|
+
const root = await env.DB.prepare('SELECT object_key,digest,verified FROM delivery_manifest_objects WHERE package_id=? AND page_number=-1').bind(pkg.id).first();
|
|
308
|
+
if (!root || marker.generation !== pkg.id || root.object_key !== marker.root || root.digest !== marker.digest || pkg.manifest_key !== marker.root) throw fail('Prova del manifest pronto non valida', 409);
|
|
309
|
+
if (!root.verified) {
|
|
310
|
+
if(freeWork(env)) {
|
|
311
|
+
const bound=await env.DB.prepare("SELECT length(CAST(root_json AS BLOB))*2 bytes FROM delivery_manifest_state WHERE package_id=? AND state='ready'").bind(pkg.id).first();
|
|
312
|
+
if(!bound||!work.canRead(bound.bytes))throw needsPaid();
|
|
313
|
+
}
|
|
314
|
+
const saved = await env.DB.prepare("SELECT root_json FROM delivery_manifest_state WHERE package_id=? AND state='ready'").bind(pkg.id).first();
|
|
315
|
+
if (!saved?.root_json || await sha256(saved.root_json) !== root.digest) throw fail('Descrittore pronto non verificabile', 409);
|
|
316
|
+
await time('rootRecovery', () => ensureManifestObject(env, root.object_key, saved.root_json, false));
|
|
317
|
+
await activePackage(env, body, true);
|
|
318
|
+
const changed = await env.DB.prepare(`UPDATE delivery_manifest_objects SET verified=1 WHERE package_id=? AND page_number=-1 AND digest=?
|
|
319
|
+
AND EXISTS(SELECT 1 FROM delivery_packages p JOIN deliveries d ON d.id=p.delivery_id JOIN delivery_manifest_state s ON s.package_id=p.id
|
|
320
|
+
WHERE p.id=? AND p.state='ready' AND s.writer_token=? AND d.status!='deleted'
|
|
321
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))`)
|
|
322
|
+
.bind(pkg.id, root.digest, pkg.id, body.writerToken).run();
|
|
323
|
+
if (!changed.meta.changes) throw fail('Verifica pronta cambiata o annullata', 409);
|
|
324
|
+
}
|
|
325
|
+
return { done: true, phase: 'ready', cursor: pkg.file_count, total: pkg.file_count };
|
|
326
|
+
}
|
|
327
|
+
const uploads = (await env.DB.prepare('SELECT * FROM delivery_uploads WHERE package_id=? LIMIT 4').bind(pkg.id).all()).results || [];
|
|
328
|
+
if(uploads.length>3)throw fail('Troppi archivi nella generazione',409);
|
|
329
|
+
if (uploads.some(u => u.state !== 'completed' || !['originals','web','thumbs'].includes(u.variant))) throw fail('Archivi della generazione non validi', 409);
|
|
330
|
+
const byVariant = Object.fromEntries(uploads.map(u => [u.variant, u]));
|
|
331
|
+
for (const kind of ['originals', ...(pkg.web_enabled || pkg.gallery_enabled ? ['web'] : []), ...(pkg.gallery_enabled ? ['thumbs'] : [])]) {
|
|
332
|
+
if (byVariant[kind]?.state !== 'completed') throw fail('Gli archivi non sono ancora completi', 409);
|
|
333
|
+
}
|
|
334
|
+
const fence = `EXISTS(SELECT 1 FROM delivery_packages p JOIN delivery_manifest_state s ON s.package_id=p.id
|
|
335
|
+
JOIN deliveries d ON d.id=p.delivery_id WHERE p.id=? AND p.state='uploading' AND s.writer_token=? AND d.status!='deleted'
|
|
336
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))`;
|
|
337
|
+
const args = [pkg.id, body.writerToken];
|
|
338
|
+
const state = await env.DB.prepare('SELECT state,cursor,page_count,created_at FROM delivery_manifest_state WHERE package_id=?').bind(pkg.id).first();
|
|
339
|
+
if (['uploading','sealed'].includes(state?.state) && parseManifest(pkg.manifest_json).finalizationProtocol !== 'common-v1') {
|
|
340
|
+
await env.DB.prepare(`UPDATE delivery_packages SET manifest_json=json_set(manifest_json,'$.finalizationProtocol','common-v1')
|
|
341
|
+
WHERE id=? AND manifest_json=? AND ${fence}`).bind(pkg.id, pkg.manifest_json, ...args).run();
|
|
342
|
+
const owned = await activePackage(env, body, true);
|
|
343
|
+
if (owned.state !== 'uploading' || parseManifest(owned.manifest_json).finalizationProtocol !== 'common-v1') throw fail('Protocollo di finalizzazione cambiato', 409);
|
|
344
|
+
}
|
|
345
|
+
if (state?.state === 'ready') {
|
|
346
|
+
const marker = parseManifest(pkg.manifest_json);
|
|
347
|
+
const proof = await env.DB.prepare('SELECT object_key,digest,verified FROM delivery_manifest_objects WHERE package_id=? AND page_number=-1').bind(pkg.id).first();
|
|
348
|
+
if (!proof?.verified || marker.finalizationProtocol !== 'common-v1' || proof.object_key !== marker.root || proof.digest !== marker.digest) throw fail('Manifest verificato non disponibile', 409);
|
|
349
|
+
return { done: true, phase: 'verified', cursor: pkg.file_count, total: pkg.file_count };
|
|
350
|
+
}
|
|
351
|
+
if (state?.state === 'uploading') {
|
|
352
|
+
await time('seal', async () => {
|
|
353
|
+
const totals = await env.DB.prepare(`SELECT COUNT(*) n,COALESCE(SUM(source_bytes),0) bytes,MIN(entry_id) lo,MAX(entry_id) hi,
|
|
354
|
+
SUM(CASE WHEN requires_variant=1 AND variant_done=0 THEN 1 ELSE 0 END) pending FROM
|
|
355
|
+
(SELECT entry_id,source_bytes,requires_variant,variant_done FROM delivery_manifest_entries WHERE package_id=? ${freeWork(env)?'LIMIT 33':''})`).bind(pkg.id).first();
|
|
356
|
+
if(freeWork(env)&&totals.n>32)throw needsPaid();
|
|
357
|
+
if (totals.pending || totals.n !== pkg.file_count || totals.bytes !== pkg.source_bytes || totals.lo !== 0 || totals.hi !== pkg.file_count - 1) throw fail('Elenco dei file incompleto', 409);
|
|
358
|
+
const changed = await env.DB.prepare(`UPDATE delivery_manifest_state SET state='sealed' WHERE package_id=? AND state='uploading' AND ${fence}`).bind(pkg.id, ...args).run();
|
|
359
|
+
if (!changed.meta.changes) throw fail('Sigillatura cambiata o annullata', 409);
|
|
360
|
+
});
|
|
361
|
+
return { done: false, phase: 'sealed', cursor: 0, total: pkg.file_count };
|
|
362
|
+
}
|
|
363
|
+
if (state?.state !== 'sealed') throw fail('Finalizzazione non disponibile', 409);
|
|
364
|
+
if (state.cursor < pkg.file_count) {
|
|
365
|
+
const prior = await env.DB.prepare('SELECT object_key,digest,end_cursor,entry_count,verified FROM delivery_manifest_objects WHERE package_id=? AND page_number=?').bind(pkg.id, state.page_count).first();
|
|
366
|
+
const preparation=await prepareFreeManifestPage(env,pkg,state,prior,byVariant,body);
|
|
367
|
+
if(preparation)return preparation;
|
|
368
|
+
const sizes = await time('pageSizes', async () => (await env.DB.prepare(`SELECT entry_id,length(CAST(entry_json AS BLOB)) bytes FROM delivery_manifest_entries
|
|
369
|
+
WHERE package_id=? AND entry_id>=? ORDER BY entry_id LIMIT 200`).bind(pkg.id, state.cursor).all()).results || []);
|
|
370
|
+
const selected = [];
|
|
371
|
+
let size = 128; // Preserve the existing logical page packing rule.
|
|
372
|
+
for (const r of sizes) {
|
|
373
|
+
if (prior && r.entry_id >= prior.end_cursor) break;
|
|
374
|
+
const n = r.bytes + bytes('{"index":' + r.entry_id + ',"entry":}') + 1;
|
|
375
|
+
if (!prior && size + n > MANIFEST_BATCH_BYTES) break;
|
|
376
|
+
if (r.entry_id !== state.cursor + selected.length || size + n > MANIFEST_BATCH_BYTES) throw fail('Pagina del manifest non valida', 409);
|
|
377
|
+
selected.push(r.entry_id); size += n;
|
|
378
|
+
}
|
|
379
|
+
if (!selected.length || prior && (selected.length !== prior.entry_count || selected.at(-1) + 1 !== prior.end_cursor)) throw fail('Prenotazione pagina non valida', 409);
|
|
380
|
+
const end = selected.at(-1) + 1;
|
|
381
|
+
if (work) {
|
|
382
|
+
// Size the serialized application rows, including escaped entry_json,
|
|
383
|
+
// before transferring them to JS. D1 wire metadata is not included.
|
|
384
|
+
const bound = await env.DB.prepare(`SELECT COALESCE(SUM(length(CAST(json_object('entry_id',entry_id,'entry_json',entry_json) AS BLOB))+1),0)+2 bytes
|
|
385
|
+
FROM delivery_manifest_entries WHERE package_id=? AND entry_id>=? AND entry_id<?`).bind(pkg.id, state.cursor, end).first();
|
|
386
|
+
if (!work.canRead(bound.bytes)) {
|
|
387
|
+
if(freeWork(env))throw needsPaid();
|
|
388
|
+
if (!work.used.units) throw Object.assign(fail('Pagina oltre il budget operativo della richiesta', 413), { code: 'upload_budget_exceeded', retryable: false });
|
|
389
|
+
return { done: false, phase: 'pages', cursor: state.cursor, total: pkg.file_count, budgetStopped: true };
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
const rows = await time('pageRead', async () => ((await env.DB.prepare(`SELECT entry_id,entry_json FROM delivery_manifest_entries
|
|
393
|
+
WHERE package_id=? AND entry_id>=? AND entry_id<? ORDER BY entry_id`).bind(pkg.id, state.cursor, end).all()).results || [])
|
|
394
|
+
.map(r => ({ index: r.entry_id, entry: JSON.parse(r.entry_json) })));
|
|
395
|
+
if (rows.length !== selected.length) throw fail('Pagina del manifest cambiata', 409);
|
|
396
|
+
for (const r of rows) for (const [kind, field] of [['originals','original'],['web','web'],['thumbs','thumb']]) {
|
|
397
|
+
const m = r.entry[field];
|
|
398
|
+
if (m && (!byVariant[kind] || m.offset + m.length > byVariant[kind].bytes)) throw fail('Il manifest supera i byte dell’archivio', 409);
|
|
399
|
+
}
|
|
400
|
+
const json = JSON.stringify({ version: 2, generation: pkg.id, entries: rows });
|
|
401
|
+
if (bytes(json) > MANIFEST_BATCH_BYTES) throw fail('Pagina troppo grande', 413);
|
|
402
|
+
const digest = await sha256(json), key = b2ObjectKey(pkg.storage_prefix, `manifest-v2/${state.page_count}-${digest}.json`);
|
|
403
|
+
const inserted = await env.DB.prepare(`INSERT OR IGNORE INTO delivery_manifest_objects(package_id,page_number,object_key,digest,end_cursor,entry_count)
|
|
404
|
+
SELECT ?,?,?,?,?,? WHERE ${fence}`).bind(pkg.id, state.page_count, key, digest, end, rows.length, ...args).run();
|
|
405
|
+
const reserved = await env.DB.prepare('SELECT object_key,digest FROM delivery_manifest_objects WHERE package_id=? AND page_number=?').bind(pkg.id, state.page_count).first();
|
|
406
|
+
if (reserved?.object_key !== key || reserved.digest !== digest) throw fail('Generazione pagina cambiata', 409);
|
|
407
|
+
await time('pageObject', () => ensureManifestObject(env, key, json, inserted.meta.changes === 1));
|
|
408
|
+
await env.DB.batch([
|
|
409
|
+
env.DB.prepare(`UPDATE delivery_manifest_objects SET verified=1 WHERE package_id=? AND page_number=? AND digest=? AND ${fence}`).bind(pkg.id, state.page_count, digest, ...args),
|
|
410
|
+
env.DB.prepare(`UPDATE delivery_manifest_state SET cursor=?,page_count=page_count+1 WHERE package_id=? AND cursor=? AND state='sealed' AND ${fence}`).bind(end, pkg.id, state.cursor, ...args),
|
|
411
|
+
]);
|
|
412
|
+
await activePackage(env, body, true);
|
|
413
|
+
const saved = await env.DB.prepare('SELECT cursor FROM delivery_manifest_state WHERE package_id=?').bind(pkg.id).first();
|
|
414
|
+
if (saved.cursor < end) throw fail('Avanzamento pagina non persistito', 409);
|
|
415
|
+
return { done: false, phase: 'pages', cursor: saved.cursor, total: pkg.file_count };
|
|
416
|
+
}
|
|
417
|
+
if(freeWork(env)&&state.page_count>32)throw needsPaid();
|
|
418
|
+
const bound = await env.DB.prepare(`SELECT COUNT(*) n,COALESCE(SUM(length(CAST(json_object('page_number',page_number,
|
|
419
|
+
'object_key',object_key,'digest',digest,'entry_count',entry_count) AS BLOB))+1),0) bytes FROM
|
|
420
|
+
(SELECT page_number,object_key,digest,entry_count FROM delivery_manifest_objects
|
|
421
|
+
WHERE package_id=? AND page_number>=0 AND verified=1 ${freeWork(env)?'LIMIT 33':''})`).bind(pkg.id).first();
|
|
422
|
+
if (bound.n !== state.page_count || bound.bytes > MANIFEST_BATCH_BYTES) throw fail('Descrittore del manifest troppo grande o incompleto', 413);
|
|
423
|
+
if(work&&!work.canRead(bound.bytes+4096))throw freeWork(env)?needsPaid():Object.assign(fail('Radice oltre il budget operativo',413),{code:'upload_budget_exceeded',retryable:false});
|
|
424
|
+
const pages = (await env.DB.prepare('SELECT page_number,object_key,digest,entry_count FROM delivery_manifest_objects WHERE package_id=? AND page_number>=0 AND verified=1 ORDER BY page_number').bind(pkg.id).all()).results || [];
|
|
425
|
+
if (pages.some((p,i) => p.page_number !== i) || pages.reduce((n,p) => n + p.entry_count, 0) !== pkg.file_count) throw fail('Pagine del manifest incomplete', 409);
|
|
426
|
+
const archives = await time('archiveHeads', () => verifyArchiveHeads(env, uploads));
|
|
427
|
+
const json = JSON.stringify({ version: 2, generation: pkg.id, createdAt: state.created_at, fileCount: pkg.file_count, sourceBytes: pkg.source_bytes, archives, pages });
|
|
428
|
+
if (bytes(json) > MANIFEST_BATCH_BYTES) throw fail('Descrittore del manifest troppo grande', 413);
|
|
429
|
+
const digest = await sha256(json), key = b2ObjectKey(pkg.storage_prefix, `manifest-v2/root-${digest}.json`);
|
|
430
|
+
const inserted = await env.DB.prepare(`INSERT OR IGNORE INTO delivery_manifest_objects(package_id,page_number,object_key,digest,end_cursor,entry_count)
|
|
431
|
+
SELECT ?,-1,?,?,?,0 WHERE ${fence}`).bind(pkg.id, key, digest, pkg.file_count, ...args).run();
|
|
432
|
+
const root = await env.DB.prepare('SELECT object_key,digest FROM delivery_manifest_objects WHERE package_id=? AND page_number=-1').bind(pkg.id).first();
|
|
433
|
+
if (root?.object_key !== key || root.digest !== digest) throw fail('Descrittore finale in conflitto', 409);
|
|
434
|
+
await time('rootObject', () => ensureManifestObject(env, key, json, inserted.meta.changes === 1));
|
|
435
|
+
const sessionMarker = uploadSessionMarker(pkg);
|
|
436
|
+
const marker = JSON.stringify({ version: 2, generation: pkg.id, root: key, digest, finalizationProtocol: 'common-v1',
|
|
437
|
+
...(sessionMarker ? { uploadSession: sessionMarker } : {}) });
|
|
438
|
+
await env.DB.batch([
|
|
439
|
+
env.DB.prepare(`UPDATE delivery_manifest_objects SET verified=1 WHERE package_id=? AND page_number=-1 AND digest=? AND ${fence}`).bind(pkg.id, digest, ...args),
|
|
440
|
+
env.DB.prepare(`UPDATE delivery_packages SET manifest_json=?,manifest_key=?,originals_key=?,web_key=?,thumbs_key=?,stored_bytes=?,updated_at=? WHERE id=? AND ${fence}`)
|
|
441
|
+
.bind(marker, key, byVariant.originals.object_key, byVariant.web?.object_key || null, byVariant.thumbs?.object_key || null, uploads.reduce((n,u) => n+u.bytes,0), new Date().toISOString(), pkg.id, ...args),
|
|
442
|
+
env.DB.prepare(`UPDATE delivery_manifest_state SET state='ready',root_json=? WHERE package_id=? AND EXISTS
|
|
443
|
+
(SELECT 1 FROM delivery_packages WHERE id=? AND state='uploading' AND manifest_json=?)`).bind(json, pkg.id, pkg.id, marker),
|
|
444
|
+
]);
|
|
445
|
+
const ready = await activePackage(env, body, true);
|
|
446
|
+
if (ready.manifest_json !== marker) throw fail('Completamento annullato o in conflitto', 409);
|
|
447
|
+
return { done: true, phase: 'verified', cursor: pkg.file_count, total: pkg.file_count };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
export async function manifestStatus(env, body, allowAsync = false) {
|
|
224
451
|
const pkg = await activePackage(env, body);
|
|
452
|
+
await assertFreeCheckpointRead(env,pkg.id);
|
|
225
453
|
const state = await env.DB.prepare('SELECT state FROM delivery_manifest_state WHERE package_id=?').bind(pkg.id).first();
|
|
226
454
|
const row = await env.DB.prepare('SELECT checkpoint_json FROM delivery_checkpoints WHERE package_id=?').bind(pkg.id).first();
|
|
227
455
|
const cp = row ? JSON.parse(row.checkpoint_json) : null;
|
|
456
|
+
if (cp?.current?.metadataProtocol === 'original-replay-v1' && !allowAsync) throw fail('Il checkpoint richiede il client con protocollo asincrono', 409);
|
|
228
457
|
if (cp?.validation && !cp.complete) {
|
|
229
458
|
const upload = await env.DB.prepare("SELECT * FROM delivery_uploads WHERE package_id=? AND variant='originals'").bind(pkg.id).first();
|
|
230
459
|
if (!upload) throw fail('Archivio del checkpoint non disponibile', 409);
|
|
@@ -238,7 +467,8 @@ export async function manifestStatus(env, body) {
|
|
|
238
467
|
return { state: state.state, checkpoint: cp };
|
|
239
468
|
}
|
|
240
469
|
export async function manifestDraftPage(env, body) {
|
|
241
|
-
|
|
470
|
+
const pkg=await activePackage(env,body);
|
|
471
|
+
return freeWork(env)||uploadSessionMarker(pkg)?readFreeManifestDraft(env,{...body,packageId:pkg.id}):readManifestPage(env,pkg,body.after??-1,200,false);
|
|
242
472
|
}
|
|
243
473
|
const CHECKPOINT_PART_BYTES = 16 * 1024 * 1024;
|
|
244
474
|
// A bounded tail fits with the interrupted member in the existing 32 KiB row.
|
|
@@ -261,6 +491,7 @@ async function extendProof(proof, parts) {
|
|
|
261
491
|
return next;
|
|
262
492
|
}
|
|
263
493
|
async function checkpointParts(env, uploadId, after, through) {
|
|
494
|
+
if(freeWork(env)&&(through-after>32||!Number.isSafeInteger(through-after)||through<after))throw needsPaid();
|
|
264
495
|
return (await env.DB.prepare(`SELECT part_number,size,digest FROM delivery_upload_parts
|
|
265
496
|
WHERE upload_id=? AND part_number>? AND part_number<=? ORDER BY part_number`)
|
|
266
497
|
.bind(uploadId, after, through).all()).results || [];
|
|
@@ -284,6 +515,7 @@ async function verifyCheckpointProof(cp, upload, parts) {
|
|
|
284
515
|
// Called before accepting the remote completion, including lost-response recovery.
|
|
285
516
|
export async function assertCheckpointParts(env, upload, parts) {
|
|
286
517
|
if (upload.variant !== 'originals' || manifestVersion(upload) !== 2) return;
|
|
518
|
+
await assertFreeCheckpointRead(env,upload.package_id);
|
|
287
519
|
const row = await env.DB.prepare('SELECT checkpoint_json FROM delivery_checkpoints WHERE package_id=?').bind(upload.package_id).first();
|
|
288
520
|
const cp = row ? JSON.parse(row.checkpoint_json) : null;
|
|
289
521
|
if (!cp || cp.complete) return;
|
|
@@ -295,9 +527,12 @@ function checkpointPayload(cp) {
|
|
|
295
527
|
return { version: 1, fileIndex: cp.fileIndex, offset: cp.offset, sequence: cp.sequence,
|
|
296
528
|
complete: cp.complete === true, current: cp.current ?? null };
|
|
297
529
|
}
|
|
298
|
-
export async function saveManifestCheckpoint(env, body) {
|
|
530
|
+
export async function saveManifestCheckpoint(env, body, allowAsync = false) {
|
|
299
531
|
const pkg = await activePackage(env, body, true);
|
|
532
|
+
await assertFreeCheckpointRead(env,pkg.id);
|
|
300
533
|
const cp = body.checkpoint;
|
|
534
|
+
if(freeWork(env)&&bytes(JSON.stringify(cp))*2>12288)throw needsPaid();
|
|
535
|
+
if (cp?.current?.metadataProtocol != null && (!allowAsync || cp.current.metadataProtocol !== 'original-replay-v1')) throw fail('Protocollo checkpoint non disponibile', 409);
|
|
301
536
|
const partBytes = CHECKPOINT_PART_BYTES;
|
|
302
537
|
if (!cp || cp.version !== 1 || (cp.complete !== undefined && typeof cp.complete !== 'boolean') || !Number.isSafeInteger(cp.fileIndex) || cp.fileIndex < 0 || cp.fileIndex > pkg.file_count ||
|
|
303
538
|
!Number.isSafeInteger(cp.offset) || cp.offset < 0 || cp.offset > DELIVERY_MAX_ARCHIVE_BYTES ||
|
|
@@ -306,10 +541,14 @@ export async function saveManifestCheckpoint(env, body) {
|
|
|
306
541
|
if (!upload) throw fail('Archivio del checkpoint non disponibile', 409);
|
|
307
542
|
const previousRow = await env.DB.prepare('SELECT checkpoint_json FROM delivery_checkpoints WHERE package_id=?').bind(pkg.id).first();
|
|
308
543
|
const previous = previousRow ? JSON.parse(previousRow.checkpoint_json) : null;
|
|
544
|
+
if (previous?.current?.metadataProtocol === 'original-replay-v1' && (!allowAsync || cp?.current?.metadataProtocol !== 'original-replay-v1')) throw fail('Il checkpoint richiede il client con protocollo asincrono', 409);
|
|
309
545
|
if (previous && (cp.offset < previous.offset || cp.fileIndex < previous.fileIndex || cp.sequence < previous.sequence)) {
|
|
310
546
|
throw fail('Checkpoint precedente a quello confermato', 409);
|
|
311
547
|
}
|
|
312
|
-
|
|
548
|
+
const sameOffsetCompletion = allowAsync && cp.complete === true && previous && !previous.complete &&
|
|
549
|
+
previous.current?.metadataProtocol === 'original-replay-v1' && previous.current.stage === 'directory' &&
|
|
550
|
+
previous.fileIndex === pkg.file_count && cp.offset === previous.offset;
|
|
551
|
+
if (previous && cp.offset === previous.offset && !sameOffsetCompletion) {
|
|
313
552
|
if (JSON.stringify(checkpointPayload(cp)) !== JSON.stringify(checkpointPayload(previous))) throw fail('Checkpoint diverso allo stesso offset', 409);
|
|
314
553
|
return { accepted: true };
|
|
315
554
|
}
|
|
@@ -325,6 +564,7 @@ export async function saveManifestCheckpoint(env, body) {
|
|
|
325
564
|
}
|
|
326
565
|
// Original entries are insert-only. Variant updates preserve their original
|
|
327
566
|
// identity; PK + the interval count prove continuity of just the new suffix.
|
|
567
|
+
if(freeWork(env)&&cp.fileIndex-firstFile>32)throw needsPaid();
|
|
328
568
|
const count = await env.DB.prepare(`SELECT COUNT(*) n FROM delivery_manifest_entries
|
|
329
569
|
WHERE package_id=? AND entry_id>=? AND entry_id<?`).bind(pkg.id, firstFile, cp.fileIndex).first();
|
|
330
570
|
if (count.n !== cp.fileIndex - firstFile) throw fail('Metadati precedenti al checkpoint incompleti', 409);
|
|
@@ -332,9 +572,22 @@ export async function saveManifestCheckpoint(env, body) {
|
|
|
332
572
|
if (cp.fileIndex !== pkg.file_count || upload.state !== 'completed' || cp.offset !== upload.bytes) throw fail('Archivio del checkpoint incompleto', 409);
|
|
333
573
|
if (previous) await verifyCheckpointProof(previous, upload, await checkpointParts(env, upload.id, 0, previous.offset / partBytes));
|
|
334
574
|
} else {
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
575
|
+
const c = cp.current;
|
|
576
|
+
const extended = allowAsync && c?.metadataProtocol === 'original-replay-v1';
|
|
577
|
+
const boundaryMode = extended && (c.stage != null || c.headerRead != null || c.descriptorRead != null);
|
|
578
|
+
if (extended && Number(c.stage != null) + Number(c.headerRead != null) + Number(c.descriptorRead != null) > 1) throw fail('Stati checkpoint incompatibili');
|
|
579
|
+
const directory = extended && c.stage === 'directory' && cp.fileIndex === pkg.file_count &&
|
|
580
|
+
Number.isSafeInteger(c.directoryOffset) && c.directoryOffset >= 0 && Number.isSafeInteger(c.directoryRead) && c.directoryRead > 0 &&
|
|
581
|
+
c.directoryOffset + c.directoryRead === cp.offset && /^[a-f0-9]{64}$/.test(c.directoryChain || '');
|
|
582
|
+
const header = extended && cp.fileIndex < pkg.file_count && Number.isSafeInteger(c.headerRead) && c.headerRead > 0 &&
|
|
583
|
+
c.headerRead <= c.dataOffset - c.localOffset && c.localOffset + c.headerRead === cp.offset && c.read === 0 && c.crc === 0xffffffff && c.chain === '';
|
|
584
|
+
const descriptor = extended && cp.fileIndex < pkg.file_count && c.zipFormat === 'store-descriptor-v1' &&
|
|
585
|
+
Number.isSafeInteger(c.descriptorRead) && c.descriptorRead > 0 && c.descriptorRead <= (c.size >= 0xffffffff ? 24 : 16) &&
|
|
586
|
+
c.read === c.size && c.dataOffset + c.read + c.descriptorRead === cp.offset && /^[a-f0-9]{64}$/.test(c.chain || '');
|
|
587
|
+
const member = !boundaryMode && cp.fileIndex < pkg.file_count && c &&
|
|
588
|
+
Number.isSafeInteger(c.read) && c.read >= 1 && c.dataOffset + c.read === cp.offset && /^[a-f0-9]{64}$/.test(c.chain || '');
|
|
589
|
+
if (!cp.offset || cp.offset % partBytes || !c || !(directory || header || descriptor || member) ||
|
|
590
|
+
(extended && !['store-header-v1','store-descriptor-v1'].includes(c.zipFormat))) throw fail('Checkpoint non allineato');
|
|
338
591
|
const n = cp.offset / partBytes;
|
|
339
592
|
const parts = await checkpointParts(env, upload.id, proof.partCount, n);
|
|
340
593
|
checkParts(parts, proof.partCount, n);
|
|
@@ -349,15 +602,19 @@ export async function saveManifestCheckpoint(env, body) {
|
|
|
349
602
|
if (bytes(json) > 32768) throw fail('Checkpoint troppo grande', 413);
|
|
350
603
|
await env.DB.prepare(`INSERT INTO delivery_checkpoints(package_id,offset,checkpoint_json)
|
|
351
604
|
SELECT ?,?,? WHERE EXISTS(SELECT 1 FROM delivery_packages p JOIN delivery_manifest_state s ON s.package_id=p.id
|
|
352
|
-
WHERE p.id=? AND p.state='uploading' AND s.writer_token=?
|
|
605
|
+
JOIN deliveries d ON d.id=p.delivery_id WHERE p.id=? AND p.state='uploading' AND s.writer_token=? AND d.status!='deleted'
|
|
606
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))
|
|
353
607
|
ON CONFLICT(package_id) DO UPDATE SET offset=excluded.offset,checkpoint_json=excluded.checkpoint_json
|
|
354
|
-
WHERE delivery_checkpoints.checkpoint_json=? AND excluded.offset>delivery_checkpoints.offset`)
|
|
355
|
-
.bind(pkg.id, cp.offset, json, pkg.id, body.writerToken, previousRow?.checkpoint_json ?? null).run();
|
|
608
|
+
WHERE delivery_checkpoints.checkpoint_json=? AND (excluded.offset>delivery_checkpoints.offset OR (? AND excluded.offset=delivery_checkpoints.offset))`)
|
|
609
|
+
.bind(pkg.id, cp.offset, json, pkg.id, body.writerToken, previousRow?.checkpoint_json ?? null, Number(!!sameOffsetCompletion)).run();
|
|
356
610
|
const saved = await env.DB.prepare('SELECT checkpoint_json FROM delivery_checkpoints WHERE package_id=?').bind(pkg.id).first();
|
|
357
611
|
if (!saved || saved.checkpoint_json !== json) throw fail('Checkpoint cambiato o annullato', 409);
|
|
358
612
|
return { accepted: true };
|
|
359
613
|
}
|
|
360
614
|
|
|
615
|
+
export const asyncManifestStatus = (env, body) => manifestStatus(env, body, true);
|
|
616
|
+
export const saveAsyncManifestCheckpoint = (env, body) => saveManifestCheckpoint(env, body, true);
|
|
617
|
+
|
|
361
618
|
// La lease supera la durata massima delle URL PUT (15 min) e dei PUT in volo
|
|
362
619
|
// (30 min). La stessa identità locale recupera subito; un altro dispositivo deve
|
|
363
620
|
// attendere un'ora senza attività, evitando un takeover con scritture ancora vive.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { b2ListPartsPage } from './b2.js';
|
|
2
|
+
import { assertManifestWriter, manifestVersion } from './delivery-manifest.js';
|
|
3
|
+
import { sha256 } from './delivery-crypto.js';
|
|
4
|
+
import { DELIVERY_MAX_ARCHIVE_BYTES, DELIVERY_PART_BYTES, validateDeliverySourceBytes } from './delivery-limits.js';
|
|
5
|
+
import { policyError } from './delivery-work-budget.js';
|
|
6
|
+
import { assertUploadSessionInvocation } from './delivery-upload-contract.js';
|
|
7
|
+
import { freeWork,needsPaid,assertFreePartRead } from './delivery-upload-free.js';
|
|
8
|
+
|
|
9
|
+
const invalid = message => policyError('delivery_parts_conflict', message);
|
|
10
|
+
// A preparation proof only: no receipt is deleted, created or weakened. This
|
|
11
|
+
// can run as separate requests on either profile; it does not certify Free CPU.
|
|
12
|
+
export async function verifyMultipartStep(env, body) {
|
|
13
|
+
const count = body.partCount, bytes = body.bytes;
|
|
14
|
+
if (!Number.isSafeInteger(count) || count < 1 || count > 10_000 || !Number.isSafeInteger(bytes) || bytes < 1 || bytes > DELIVERY_MAX_ARCHIVE_BYTES || Math.ceil(bytes / DELIVERY_PART_BYTES) !== count) throw invalid('Dimensione o conteggio multipart non valido');
|
|
15
|
+
if (!await env.DB.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='delivery_multipart_verification'").first()) throw policyError('upload_capability_changed', 'Migrazione della verifica multipart non disponibile', 503);
|
|
16
|
+
const upload = await env.DB.prepare(`SELECT u.*,p.manifest_json,p.source_bytes FROM delivery_uploads u
|
|
17
|
+
JOIN delivery_packages p ON p.id=u.package_id JOIN deliveries d ON d.id=u.delivery_id
|
|
18
|
+
WHERE u.id=? AND u.state='uploading' AND p.state='uploading' AND d.status!='deleted'
|
|
19
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now'))`).bind(String(body.uploadId || '')).first();
|
|
20
|
+
if (!upload || upload.variant !== 'originals' || manifestVersion(upload) !== 2) throw invalid('La verifica richiede originali v2 in caricamento');
|
|
21
|
+
assertUploadSessionInvocation(env, upload);
|
|
22
|
+
validateDeliverySourceBytes(upload.source_bytes);
|
|
23
|
+
await assertManifestWriter(env, upload.package_id, body.writerToken);
|
|
24
|
+
if(freeWork(env)) {
|
|
25
|
+
if(count>32)throw needsPaid();
|
|
26
|
+
await assertFreePartRead(env,upload.id);
|
|
27
|
+
}
|
|
28
|
+
const fence = `EXISTS(SELECT 1 FROM delivery_uploads u JOIN delivery_packages p ON p.id=u.package_id
|
|
29
|
+
JOIN deliveries d ON d.id=u.delivery_id JOIN delivery_manifest_state s ON s.package_id=p.id
|
|
30
|
+
WHERE u.id=? AND u.b2_upload_id=? AND u.object_key=? AND u.state='uploading' AND p.state='uploading'
|
|
31
|
+
AND s.writer_token=? AND d.status!='deleted'
|
|
32
|
+
AND (d.files_expires_at IS NULL OR d.files_expires_at>strftime('%Y-%m-%dT%H:%M:%fZ','now')))
|
|
33
|
+
AND (SELECT COUNT(*) FROM delivery_upload_parts WHERE upload_id=?)=?
|
|
34
|
+
AND (SELECT COALESCE(SUM(size),0) FROM delivery_upload_parts WHERE upload_id=?)=?`;
|
|
35
|
+
const args = [upload.id, upload.b2_upload_id, upload.object_key, body.writerToken, upload.id, count, upload.id, bytes];
|
|
36
|
+
const totals = await env.DB.prepare(`SELECT COUNT(*) n,MIN(part_number) lo,MAX(part_number) hi,COALESCE(SUM(size),0) bytes,
|
|
37
|
+
SUM(CASE WHEN digest IS NULL OR length(digest)!=64 OR digest GLOB '*[^a-f0-9]*' THEN 1 ELSE 0 END) pending
|
|
38
|
+
FROM delivery_upload_parts WHERE upload_id=?`).bind(upload.id).first();
|
|
39
|
+
if (totals.n !== count || totals.lo !== 1 || totals.hi !== count || totals.bytes !== bytes || totals.pending) throw invalid('Ricevute originali incomplete o non confermate');
|
|
40
|
+
const seed = await sha256(JSON.stringify(['multipart-verify-v1', upload.id, upload.b2_upload_id, upload.object_key, count, bytes]));
|
|
41
|
+
await env.DB.prepare(`INSERT OR IGNORE INTO delivery_multipart_verification(upload_id,remote_upload_id,object_key,expected_count,expected_bytes,chain)
|
|
42
|
+
SELECT ?,?,?,?,?,? WHERE ${fence}`).bind(upload.id, upload.b2_upload_id, upload.object_key, count, bytes, seed, ...args).run();
|
|
43
|
+
const job = await env.DB.prepare('SELECT * FROM delivery_multipart_verification WHERE upload_id=? AND remote_upload_id=?').bind(upload.id,upload.b2_upload_id).first();
|
|
44
|
+
if (!job || job.object_key !== upload.object_key || job.expected_count !== count || job.expected_bytes !== bytes) throw invalid('Generazione o dichiarazione multipart cambiata');
|
|
45
|
+
const reply = saved => ({ done: saved.state === 'verified', phase: 'parts', cursor: saved.cursor, total: count, bytes: saved.verified_bytes, proof: saved.chain });
|
|
46
|
+
if (job.state === 'verified') return reply(job);
|
|
47
|
+
let remote;
|
|
48
|
+
try { remote = await b2ListPartsPage(env, upload.object_key, upload.b2_upload_id, job.cursor); }
|
|
49
|
+
catch (error) {
|
|
50
|
+
if (error.status === 404) throw policyError('upload_completion_recovery_required', 'Sessione remota non disponibile: verificare il completamento esistente con il percorso compatibile.');
|
|
51
|
+
throw error;
|
|
52
|
+
}
|
|
53
|
+
if (!remote.parts.length) throw invalid('Pagina multipart remota vuota');
|
|
54
|
+
const saved = (await env.DB.prepare(`SELECT part_number,etag,size,digest FROM delivery_upload_parts WHERE upload_id=? AND part_number>? AND part_number<=? ORDER BY part_number LIMIT 32`).bind(upload.id, job.cursor, remote.parts.at(-1).partNumber).all()).results || [];
|
|
55
|
+
if (!remote.parts.length || remote.parts.length !== saved.length || remote.parts.some((p,i) => {
|
|
56
|
+
const s = saved[i]; return p.partNumber !== s.part_number || p.etag !== s.etag || p.size !== s.size || !/^[a-f0-9]{64}$/.test(s.digest) || p.size > DELIVERY_PART_BYTES || p.partNumber < count && p.size !== DELIVERY_PART_BYTES;
|
|
57
|
+
})) throw invalid('Le parti remote non corrispondono alle ricevute originali');
|
|
58
|
+
let chain = job.chain, verifiedBytes = job.verified_bytes;
|
|
59
|
+
for (const p of saved) { chain = await sha256(JSON.stringify([chain,p.part_number,p.etag,p.size,p.digest])); verifiedBytes += p.size; }
|
|
60
|
+
const cursor = saved.at(-1).part_number, done = cursor === count;
|
|
61
|
+
if (cursor > count || remote.truncated === done || done && verifiedBytes !== bytes) throw invalid('Confine finale multipart non valido');
|
|
62
|
+
const updated = await env.DB.prepare(`UPDATE delivery_multipart_verification SET cursor=?,verified_bytes=?,chain=?,state=?
|
|
63
|
+
WHERE upload_id=? AND remote_upload_id=? AND cursor=? AND chain=? AND ${fence}`)
|
|
64
|
+
.bind(cursor, verifiedBytes, chain, done ? 'verified' : 'scanning', upload.id, upload.b2_upload_id, job.cursor, job.chain, ...args).run();
|
|
65
|
+
await assertManifestWriter(env, upload.package_id, body.writerToken);
|
|
66
|
+
if (!updated.meta.changes) throw invalid('Verifica concorrente, annullata o generazione cambiata; rileggi il cursore');
|
|
67
|
+
return reply({ state: done ? 'verified' : 'scanning', cursor, verified_bytes: verifiedBytes, chain });
|
|
68
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
// The legacy envelope is deliberately independent of the candidate Free/Paid
|
|
2
|
+
// micro-budgets. It accommodates the 1.8 MB v1 manifest and the 256 KiB v2
|
|
3
|
+
// entries array, with wrapper/escaping headroom. It is not a CPU certification.
|
|
4
|
+
export const DELIVERY_LEGACY_REQUEST_BYTES = 8 * 1024 * 1024;
|
|
5
|
+
export const DELIVERY_UPLOAD_REQUEST_BYTES = Object.freeze({free:40960,paid:278528});
|
|
6
|
+
|
|
7
|
+
// Reserved protocol entry point for a future rollout. Call only after the
|
|
8
|
+
// current namespace gate; the profile is server authority, never a header/body.
|
|
9
|
+
// Keep the legacy 8 MiB reader independent so old consumers remain compatible.
|
|
10
|
+
export function readUploadSessionJson(request,env) {
|
|
11
|
+
const max=DELIVERY_UPLOAD_REQUEST_BYTES[env.DELIVERY_UPLOAD_PROFILE];
|
|
12
|
+
if(!max)throw new DeliveryBodyError('Budget di upload non verificato',409,'upload_budget_unknown');
|
|
13
|
+
return readDeliveryJson(request,max);
|
|
14
|
+
}
|
|
15
|
+
export function readDeliveryUploadBody(request,env) {
|
|
16
|
+
return request.headers.has('X-Delivery-Upload-Protocol')?readUploadSessionJson(request,env):readDeliveryJson(request);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export class DeliveryBodyError extends Error {
|
|
20
|
+
constructor(message, status, code) {
|
|
21
|
+
super(message);
|
|
22
|
+
this.status = status;
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.retryable = false;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Count the actual wire bytes, including whitespace and the whole JSON wrapper.
|
|
29
|
+
// Content-Length is only an early rejection; a small/missing value never grants
|
|
30
|
+
// permission to read an unbounded body. Do not clone/tee a request for parsing.
|
|
31
|
+
export async function readDeliveryJson(request, maxBytes = DELIVERY_LEGACY_REQUEST_BYTES) {
|
|
32
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 1 || maxBytes > DELIVERY_LEGACY_REQUEST_BYTES) {
|
|
33
|
+
throw new TypeError('Invalid server request budget');
|
|
34
|
+
}
|
|
35
|
+
const exceeded = () => new DeliveryBodyError('Il corpo della richiesta supera il budget di upload', 413, 'upload_budget_exceeded');
|
|
36
|
+
const declared = request.headers.get('content-length');
|
|
37
|
+
if (declared !== null && /^\d+$/.test(declared) && Number(declared) > maxBytes) {
|
|
38
|
+
void request.body?.cancel().catch(() => {});
|
|
39
|
+
throw exceeded();
|
|
40
|
+
}
|
|
41
|
+
if (!request.body) throw new DeliveryBodyError('Corpo JSON non valido', 400);
|
|
42
|
+
const reader = request.body.getReader();
|
|
43
|
+
let bytes = 0;
|
|
44
|
+
const decoder = new TextDecoder(), chunks = [];
|
|
45
|
+
try {
|
|
46
|
+
for (;;) {
|
|
47
|
+
const { value, done } = await reader.read();
|
|
48
|
+
if (done) break;
|
|
49
|
+
bytes += value.byteLength;
|
|
50
|
+
if (bytes > maxBytes) {
|
|
51
|
+
// Do not wait for a potentially stalled upstream producer to cancel.
|
|
52
|
+
void reader.cancel().catch(() => {});
|
|
53
|
+
throw exceeded();
|
|
54
|
+
}
|
|
55
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
56
|
+
}
|
|
57
|
+
chunks.push(decoder.decode());
|
|
58
|
+
return JSON.parse(chunks.join(''));
|
|
59
|
+
} catch (error) {
|
|
60
|
+
if (error instanceof DeliveryBodyError) throw error;
|
|
61
|
+
throw new DeliveryBodyError('Corpo JSON non valido', 400);
|
|
62
|
+
} finally {
|
|
63
|
+
reader.releaseLock();
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function deliveryBodyErrorResponse(error) {
|
|
68
|
+
if (!(error instanceof DeliveryBodyError)) throw error;
|
|
69
|
+
return new Response(JSON.stringify({ ok: false, error: error.message,
|
|
70
|
+
...(error.code ? { code: error.code, retryable: false } : {}) }), {
|
|
71
|
+
status: error.status,
|
|
72
|
+
headers: { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' },
|
|
73
|
+
});
|
|
74
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// Server-signed requests already have a fresh signature. A denied HEAD may
|
|
2
|
+
// still be answered by the existing one-byte GET fallback.
|
|
3
|
+
export function storageControlRequest(signedRequest) {
|
|
4
|
+
return async (env, method, key, options) => {
|
|
5
|
+
const response = await signedRequest(env, method, key, options);
|
|
6
|
+
if (response.status === 401 || (response.status === 403 && method !== "HEAD")) {
|
|
7
|
+
await response.body?.cancel();
|
|
8
|
+
throw Object.assign(new Error("Il servizio non può accedere ai file. Avvisa chi gestisce il sito, poi riprendi il caricamento."), {
|
|
9
|
+
code: "upload_storage_access_denied", status: 502, retryable: false, providerStatus: response.status,
|
|
10
|
+
});
|
|
11
|
+
}
|
|
12
|
+
return response;
|
|
13
|
+
};
|
|
14
|
+
}
|