@cardinali-studio/adminkit 2.2.49 → 2.2.50

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.
Files changed (63) hide show
  1. package/dist/app/App.js +6 -6
  2. package/dist/app/app.css +67 -1
  3. package/dist/app/delivery.js +7 -7
  4. package/dist/app/guide/TransferGuide.js +1 -1
  5. package/dist/app/lib/deliveries.d.ts +6 -0
  6. package/dist/app/lib/delivery-capabilities.d.ts +31 -0
  7. package/dist/app/lib/delivery-capabilities.js +115 -0
  8. package/dist/app/lib/delivery-checkpoint-pipeline.d.ts +81 -0
  9. package/dist/app/lib/delivery-checkpoint-pipeline.js +195 -0
  10. package/dist/app/lib/delivery-finalize.d.ts +21 -0
  11. package/dist/app/lib/delivery-finalize.js +42 -0
  12. package/dist/app/lib/delivery-multipart-large.d.ts +18 -0
  13. package/dist/app/lib/delivery-multipart-large.js +28 -0
  14. package/dist/app/lib/delivery-network.d.ts +7 -1
  15. package/dist/app/lib/delivery-network.js +85 -18
  16. package/dist/app/lib/delivery-part-pipeline.d.ts +79 -0
  17. package/dist/app/lib/delivery-part-pipeline.js +270 -0
  18. package/dist/app/lib/delivery-upload-coordinator.d.ts +112 -0
  19. package/dist/app/lib/delivery-upload-coordinator.js +229 -0
  20. package/dist/app/lib/delivery-upload.d.ts +19 -3
  21. package/dist/app/lib/delivery-upload.js +226 -29
  22. package/dist/app/lib/upload-queue.d.ts +5 -0
  23. package/dist/app/lib/upload-queue.js +54 -29
  24. package/dist/app/routes/Deliveries.d.ts +9 -3
  25. package/dist/app/routes/Deliveries.js +299 -164
  26. package/dist/app/routes/DeliveryDashboard.js +1 -1
  27. package/dist/app/routes/DeliveryEmail.d.ts +8 -1
  28. package/dist/app/routes/DeliveryEmail.js +63 -23
  29. package/dist/app/routes/Overview.js +5 -5
  30. package/dist/app/routes/UploadDock.js +4 -3
  31. package/dist/form/media/MediaGrid.js +1 -1
  32. package/dist/functions/_shared/b2.js +98 -19
  33. package/dist/functions/_shared/delivery-activation.js +98 -0
  34. package/dist/functions/_shared/delivery-download-bundle.js +280 -0
  35. package/dist/functions/_shared/delivery-email.js +92 -13
  36. package/dist/functions/_shared/delivery-file-names.js +19 -0
  37. package/dist/functions/_shared/delivery-finalization-paid.js +31 -0
  38. package/dist/functions/_shared/delivery-finalization-storage.js +64 -0
  39. package/dist/functions/_shared/delivery-manifest-free.js +74 -0
  40. package/dist/functions/_shared/delivery-manifest.js +277 -20
  41. package/dist/functions/_shared/delivery-multipart-verification.js +68 -0
  42. package/dist/functions/_shared/delivery-request.js +74 -0
  43. package/dist/functions/_shared/delivery-storage-access.js +14 -0
  44. package/dist/functions/_shared/delivery-upload-admission.js +221 -0
  45. package/dist/functions/_shared/delivery-upload-contract.js +44 -0
  46. package/dist/functions/_shared/delivery-upload-free.js +80 -0
  47. package/dist/functions/_shared/delivery-upload-policy.js +64 -0
  48. package/dist/functions/_shared/delivery-upload-session.js +365 -0
  49. package/dist/functions/_shared/delivery-work-budget.js +49 -0
  50. package/dist/functions/api/deliveries.js +58 -17
  51. package/dist/functions/api/delivery/multipart.js +152 -15
  52. package/dist/functions/delivery-public/assets/client.js +59 -54
  53. package/dist/functions/delivery-public/assets/delivery.css +6 -2
  54. package/dist/functions/delivery-public/index.js +43 -15
  55. package/dist/functions/delivery-public/migrations/0015_delivery_activation_intents.sql +12 -0
  56. package/dist/functions/delivery-public/migrations/0016_delivery_multipart_verification.sql +16 -0
  57. package/dist/functions/delivery-public/migrations/0017_delivery_upload_admission.sql +38 -0
  58. package/dist/functions/delivery-public/migrations/0018_delivery_upload_sessions.sql +26 -0
  59. package/dist/functions/delivery-public/migrations/0019_delivery_manifest_fragments.sql +27 -0
  60. package/dist/functions/delivery-public/migrations/0020_delivery_email_reply_to.sql +1 -0
  61. package/dist/functions/index.js +3 -1
  62. package/dist/theme.css +2 -1
  63. package/package.json +1 -1
@@ -7,6 +7,8 @@
7
7
  * servire una singola foto con un GET Range senza duplicarla come oggetto.
8
8
  */
9
9
  import { deliveryJson, deliveryPut, deliveryGate, checkCancelled, UploadCancelled } from "./delivery-network.js";
10
+ import { DeliveryPartPipeline, PART_BATCH_ROLLOUT_ENABLED } from './delivery-part-pipeline.js';
11
+ import { ASYNC_CHECKPOINT_ROLLOUT_ENABLED, DeliveryCheckpointPipeline, DeliveryMetadataJournal } from './delivery-checkpoint-pipeline.js';
10
12
  import { DELIVERY_PART_BYTES, DELIVERY_MAX_ARCHIVE_BYTES, validateDeliverySourceBytes, DELIVERY_V1_MANIFEST_BYTES, DELIVERY_SKIP_REASON_CHARS } from "../../functions/_shared/delivery-limits.js";
11
13
  export { UploadCancelled } from "./delivery-network.js";
12
14
  const PART = DELIVERY_PART_BYTES;
@@ -17,6 +19,12 @@ const enc = new TextEncoder();
17
19
  const ZIP_FORMAT = "store-header-v1";
18
20
  const LEGACY_ZIP_FORMAT = "store-descriptor-v1";
19
21
  const droppedPaths = new WeakMap();
22
+ export function deliveryProgressPercent(progress) {
23
+ const originals = progress.phase === "originals" && progress.sourceBytes > 0;
24
+ const completed = originals ? progress.uploadedBytes : progress.doneFiles;
25
+ const total = originals ? progress.sourceBytes : progress.totalFiles;
26
+ return total > 0 ? Math.min(100, 100 * completed / total) : 0;
27
+ }
20
28
  /* Il cancello di pausa e annullamento.
21
29
  *
22
30
  * Chi carica lo passa da fuori (lib/upload-queue.ts) e questo file si limita a bussare: a
@@ -51,10 +59,12 @@ export async function uploadDeliveryPackage(deliveryId, packageId, selected, opt
51
59
  if (renewing || control.signal?.aborted)
52
60
  return;
53
61
  renewing = true;
54
- void fetch("/admin/api/deliveries", { method: "POST", credentials: "same-origin",
62
+ const claim = { action: 'manifestClaim', id: deliveryId, packageId, writerToken: token };
63
+ const renewal = control.json ? deliveryJson('/admin/api/deliveries', claim, { ...control, gate: async () => { } }, false) : fetch("/admin/api/deliveries", { method: "POST", credentials: "same-origin",
55
64
  headers: { "Content-Type": "application/json" }, signal: control.signal,
56
- body: JSON.stringify({ action: "manifestClaim", id: deliveryId, packageId, writerToken: token }),
57
- }).catch(() => { }).finally(() => { renewing = false; });
65
+ body: JSON.stringify(claim),
66
+ });
67
+ void renewal.catch(() => { }).finally(() => { renewing = false; });
58
68
  }, 5 * 60_000);
59
69
  try {
60
70
  return await performDeliveryPackage(deliveryId, packageId, selected, options, onProgress, control);
@@ -73,6 +83,7 @@ async function performDeliveryPackage(deliveryId, packageId, selected, options,
73
83
  abort();
74
84
  const local = {
75
85
  writerToken: control?.writerToken,
86
+ json: control?.json,
76
87
  signal: controller.signal,
77
88
  networkWaiting: (waiting) => control?.networkWaiting?.(waiting),
78
89
  gate: async () => { await deliveryGate({ ...control, signal: controller.signal, gate: () => control?.gate() || Promise.resolve() }); },
@@ -99,7 +110,7 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
99
110
  let checkpoint = null;
100
111
  if (options.manifestVersion === 2) {
101
112
  const status = await deliveryJson("/admin/api/deliveries", {
102
- action: "manifestStatus", id: deliveryId, packageId,
113
+ action: ASYNC_CHECKPOINT_ROLLOUT_ENABLED ? 'asyncCheckpointStatus' : "manifestStatus", id: deliveryId, packageId,
103
114
  }, control);
104
115
  if (status.state === "sealed" || status.state === "ready")
105
116
  return {
@@ -133,9 +144,18 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
133
144
  let metadataSize = 0;
134
145
  let phase = "originals";
135
146
  let sequence = checkpoint?.sequence || 0;
147
+ const persistenceControl = { ...control, gate: async () => { } };
148
+ const journal = ASYNC_CHECKPOINT_ROLLOUT_ENABLED && options.manifestVersion === 2
149
+ ? new DeliveryMetadataJournal(packageId, sequence, async (batch) => {
150
+ await deliveryJson('/admin/api/deliveries', { action: 'manifestReplayBatch', id: deliveryId, packageId, phase: 'originals', ...batch }, persistenceControl);
151
+ }, control) : null;
136
152
  for (let i = 0; i < entries.length; i++)
137
153
  entryByName.set(entries[i].name, i);
138
154
  async function flushMetadata() {
155
+ if (journal && phase === 'originals') {
156
+ await journal.flush();
157
+ return;
158
+ }
139
159
  if (!metadataBatch.length || options.manifestVersion !== 2)
140
160
  return;
141
161
  await deliveryJson("/admin/api/deliveries", { action: "manifestBatch", id: deliveryId, packageId,
@@ -146,6 +166,10 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
146
166
  async function saveMetadata(index, entry) {
147
167
  if (options.manifestVersion !== 2)
148
168
  return;
169
+ if (journal && phase === 'originals') {
170
+ await journal.append({ index, entry });
171
+ return;
172
+ }
149
173
  const row = { index, entry };
150
174
  const size = enc.encode(JSON.stringify(row)).length + 1;
151
175
  if (metadataBatch.length >= 200 || metadataSize + size > 250 * 1024)
@@ -158,7 +182,7 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
158
182
  sinks.push(originalsSink);
159
183
  // Confirmed multipart prefixes and derivative retries keep their original layout.
160
184
  const zipFormat = checkpoint ? (checkpoint.current?.zipFormat || LEGACY_ZIP_FORMAT) : ZIP_FORMAT;
161
- const originals = new ZipStream(originalsSink, options.manifestVersion === 2, zipFormat);
185
+ const originals = new ZipStream(originalsSink, options.manifestVersion === 2, zipFormat, !!journal);
162
186
  if (checkpoint) {
163
187
  if (checkpoint.complete) {
164
188
  originalsSink.totalBytes = checkpoint.offset;
@@ -166,11 +190,25 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
166
190
  }
167
191
  else {
168
192
  await originalsSink.restore(checkpoint.offset, checkpoint.partsHash);
169
- originals.restore(entries, files, checkpoint.offset);
193
+ originals.restore(entries, files, checkpoint.offset, checkpoint.current && 'stage' in checkpoint.current ? checkpoint.current : undefined);
170
194
  }
171
195
  }
172
196
  let lastCheckpoint = checkpoint?.offset || 0;
197
+ const checkpointPipeline = journal ? new DeliveryCheckpointPipeline(lastCheckpoint, async (snapshot) => {
198
+ await deliveryJson('/admin/api/deliveries', { action: 'asyncCheckpoint', id: deliveryId, packageId, checkpoint: snapshot }, persistenceControl);
199
+ }, control, offset => { lastCheckpoint = offset; }) : null;
200
+ originalsSink.checkpointWindow = checkpointPipeline;
201
+ // Resources are settled by the package finally, after aborting the shared signal.
202
+ originalsSink.checkpointResources = async () => { await Promise.allSettled([checkpointPipeline?.settle(), journal?.settle()]); };
173
203
  async function saveCheckpoint(current, offset) {
204
+ if (journal && checkpointPipeline) {
205
+ if (!checkpointPipeline.due(offset))
206
+ return;
207
+ const barrier = await journal.capture();
208
+ checkpointPipeline.offer({ version: 1, fileIndex: 'stage' in current ? files.length : processed, offset,
209
+ sequence: barrier.sequence, current: { ...current, metadataProtocol: 'original-replay-v1' } }, Promise.all([barrier.ready, originalsSink.waitThrough(offset / PART)]).then(() => { }));
210
+ return;
211
+ }
174
212
  if (options.manifestVersion !== 2 || offset - lastCheckpoint < PART * 4)
175
213
  return;
176
214
  await originalsSink.checkpointBoundary();
@@ -183,6 +221,7 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
183
221
  onProgress({
184
222
  phase: "originals", file: currentOriginal, doneFiles: processed, totalFiles: files.length,
185
223
  sourceBytes, uploadedBytes: originalsSink.uploadedBytes,
224
+ checkpointBytes: options.manifestVersion === 2 ? lastCheckpoint : undefined,
186
225
  transferredBytes: originalsSink.transferredBytes, startedAt,
187
226
  transferStartedAt: originalsSink.transferStartedAt || undefined,
188
227
  note: preparing ? "Verifico il file prima del caricamento…" : undefined,
@@ -193,7 +232,7 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
193
232
  await control.gate();
194
233
  const name = safePath(deliveryRelativeName(file));
195
234
  currentOriginal = name;
196
- const member = await originals.add(name, file, reportOriginals, new Date(file.lastModified), options.manifestVersion === 2 ? saveCheckpoint : undefined, checkpoint && !checkpoint.complete && processed === checkpoint.fileIndex ? checkpoint.current : undefined);
235
+ const member = await originals.add(name, file, reportOriginals, new Date(file.lastModified), options.manifestVersion === 2 ? saveCheckpoint : undefined, checkpoint && !checkpoint.complete && processed === checkpoint.fileIndex && !('stage' in (checkpoint.current || {})) ? checkpoint.current : undefined);
197
236
  entryByName.set(name, entries.length);
198
237
  entries.push({ name, type: file.type || mimeFromName(name), original: member });
199
238
  await saveMetadata(entries.length - 1, entries[entries.length - 1]);
@@ -201,11 +240,14 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
201
240
  reportOriginals();
202
241
  }
203
242
  if (!checkpoint?.complete)
204
- await originals.close();
243
+ await originals.close(journal ? saveCheckpoint : undefined);
205
244
  await flushMetadata();
206
245
  if (options.manifestVersion === 2 && !checkpoint?.complete) {
207
- await deliveryJson("/admin/api/deliveries", { action: "manifestCheckpoint", id: deliveryId, packageId,
208
- checkpoint: { version: 1, fileIndex: files.length, offset: originalsSink.totalBytes, sequence, complete: true, current: { zipFormat } } }, control);
246
+ await checkpointPipeline?.drain();
247
+ await deliveryJson("/admin/api/deliveries", { action: journal ? 'asyncCheckpoint' : "manifestCheckpoint", id: deliveryId, packageId,
248
+ checkpoint: { version: 1, fileIndex: files.length, offset: originalsSink.totalBytes, sequence: journal?.stats.sequence ?? sequence, complete: true,
249
+ current: { zipFormat, ...(journal ? { metadataProtocol: 'original-replay-v1' } : {}) } } }, control);
250
+ lastCheckpoint = originalsSink.totalBytes;
209
251
  }
210
252
  phase = "variants";
211
253
  sequence = 0;
@@ -265,6 +307,7 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
265
307
  imageDone++;
266
308
  onProgress({
267
309
  phase: "derivatives", file: sourceName, doneFiles: imageDone,
310
+ checkpointBytes: options.manifestVersion === 2 ? lastCheckpoint : undefined,
268
311
  totalFiles: imageFiles.length, sourceBytes,
269
312
  uploadedBytes: originalsSink.uploadedBytes + (webSink?.uploadedBytes || 0) +
270
313
  (thumbsSink?.uploadedBytes || 0),
@@ -282,6 +325,7 @@ async function buildDeliveryPackage(deliveryId, packageId, selected, options, on
282
325
  await flushMetadata();
283
326
  onProgress({
284
327
  phase: "finalizing", file: "", doneFiles: files.length, totalFiles: files.length,
328
+ checkpointBytes: options.manifestVersion === 2 ? lastCheckpoint : undefined,
285
329
  sourceBytes, uploadedBytes: originalsSink.uploadedBytes + (webSink?.uploadedBytes || 0) +
286
330
  (thumbsSink?.uploadedBytes || 0),
287
331
  transferredBytes: originalsSink.transferredBytes + (webSink?.transferredBytes || 0) +
@@ -312,6 +356,12 @@ class B2Sink {
312
356
  priorParts = new Map();
313
357
  inFlight = new Set();
314
358
  failure = null;
359
+ pipeline = null;
360
+ checkpointWindow = null;
361
+ checkpointResources;
362
+ pendingParts = new Map();
363
+ registeredThrough = 0;
364
+ registeredAhead = new Set();
315
365
  onTransfer;
316
366
  control;
317
367
  constructor(deliveryId, packageId, variant, onTransfer, control, forceMultipart = false) {
@@ -325,6 +375,8 @@ class B2Sink {
325
375
  async write(input) {
326
376
  if (!input.byteLength)
327
377
  return;
378
+ if (this.checkpointWindow)
379
+ await this.checkpointWindow.beforeWrite(this.totalBytes + input.byteLength);
328
380
  if (this.totalBytes + input.byteLength > DELIVERY_MAX_ARCHIVE_BYTES) {
329
381
  throw new Error("L’archivio supera il limite tecnico: dividi i file in più invii.");
330
382
  }
@@ -358,6 +410,7 @@ class B2Sink {
358
410
  if (this.buffered)
359
411
  await this.queuePart(this.take(this.buffered));
360
412
  await this.drain();
413
+ await this.checkpointWindow?.drain();
361
414
  await this.control?.gate();
362
415
  if (this.session.state === "completed") {
363
416
  if (this.session.bytes !== this.totalBytes || this.priorParts.size !== this.partNumber) {
@@ -383,6 +436,18 @@ class B2Sink {
383
436
  this.session.bytes = reconciled.bytes;
384
437
  }
385
438
  this.priorParts = new Map(reconciled.parts.map((part) => [part.partNumber, part]));
439
+ // This code path cannot be selected by client options or an env flag.
440
+ // Capability negotiation/certification must land before rollout is enabled.
441
+ if (PART_BATCH_ROLLOUT_ENABLED && this.forceMultipart && this.variant === 'originals' && this.session.state !== 'completed') {
442
+ this.pipeline = new DeliveryPartPipeline(this.session.id, {
443
+ presign: (partNumbers, control) => postJson({ action: 'presignBatch', uploadId: out.upload.id, partNumbers }, control),
444
+ put: (sign, body, control) => {
445
+ this.startTransfer();
446
+ return deliveryPut(sign, body.buffer, 'application/octet-stream', control);
447
+ },
448
+ record: (parts, batchId, control) => postJson({ action: 'recordBatch', uploadId: out.upload.id, parts, batchId }, control),
449
+ }, this.control || { gate: async () => { } }, this.priorParts, bytes => { this.transferredBytes += bytes; this.onTransfer?.(); }, bytes => this.markUploaded(bytes, false));
450
+ }
386
451
  return out.upload;
387
452
  }
388
453
  async queuePart(body) {
@@ -393,6 +458,10 @@ class B2Sink {
393
458
  const session = await this.ensureSession();
394
459
  const partNumber = ++this.partNumber;
395
460
  await this.failIfNeeded();
461
+ if (this.pipeline) {
462
+ await this.pipeline.enqueue(partNumber, body);
463
+ return;
464
+ }
396
465
  let task;
397
466
  task = this.uploadPart(body, partNumber, session)
398
467
  .catch((error) => {
@@ -401,6 +470,8 @@ class B2Sink {
401
470
  })
402
471
  .finally(() => this.inFlight.delete(task));
403
472
  this.inFlight.add(task);
473
+ this.pendingParts.set(partNumber, task);
474
+ void task.finally(() => this.pendingParts.delete(partNumber));
404
475
  if (this.inFlight.size >= UPLOAD_CONCURRENCY) {
405
476
  await Promise.race(this.inFlight);
406
477
  await this.failIfNeeded();
@@ -411,6 +482,7 @@ class B2Sink {
411
482
  const prior = this.priorParts.get(partNumber);
412
483
  if (prior?.size === body.byteLength && prior.digest === digest) {
413
484
  this.markUploaded(body.byteLength, false);
485
+ this.markRegistered(partNumber);
414
486
  return;
415
487
  }
416
488
  if (session.state === "completed") {
@@ -428,6 +500,7 @@ class B2Sink {
428
500
  await postJson({ action: "record", uploadId: session.id, partNumber, etag,
429
501
  digest, size: body.byteLength }, this.control);
430
502
  this.markUploaded(body.byteLength, true);
503
+ this.markRegistered(partNumber);
431
504
  }
432
505
  async restore(offset, partsHash) {
433
506
  await this.ensureSession();
@@ -439,6 +512,25 @@ class B2Sink {
439
512
  this.partNumber = count;
440
513
  this.totalBytes = offset;
441
514
  this.uploadedBytes = offset;
515
+ this.registeredThrough = count;
516
+ this.pipeline?.restorePrefix(count);
517
+ }
518
+ markRegistered(number) {
519
+ this.registeredAhead.add(number);
520
+ while (this.registeredAhead.delete(this.registeredThrough + 1))
521
+ this.registeredThrough++;
522
+ }
523
+ async waitThrough(through) {
524
+ if (this.pipeline)
525
+ return this.pipeline.waitThrough(through);
526
+ while (this.registeredThrough < through) {
527
+ await this.failIfNeeded();
528
+ const pending = [...this.pendingParts].filter(([n]) => n <= through).map(([, p]) => p);
529
+ if (!pending.length)
530
+ throw new Error('Prefisso checkpoint non confermato');
531
+ await Promise.race(pending);
532
+ }
533
+ await this.failIfNeeded();
442
534
  }
443
535
  async gate() { await this.control?.gate(); }
444
536
  async checkpointBoundary() {
@@ -446,8 +538,12 @@ class B2Sink {
446
538
  if (this.buffered)
447
539
  throw new Error("Checkpoint fuori dal confine di una parte.");
448
540
  }
449
- async settle() { await Promise.allSettled([...this.inFlight]); }
541
+ async settle() {
542
+ await Promise.allSettled([...this.inFlight, ...(this.pipeline ? [this.pipeline.settle()] : []), ...(this.checkpointResources ? [this.checkpointResources()] : [])]);
543
+ }
450
544
  async drain() {
545
+ if (this.pipeline)
546
+ await this.pipeline.flush();
451
547
  while (this.inFlight.size) {
452
548
  await Promise.race(this.inFlight);
453
549
  await this.failIfNeeded();
@@ -495,19 +591,25 @@ function firstStartedAt(...sinks) {
495
591
  return values.length ? Math.min(...values) : undefined;
496
592
  }
497
593
  export class ZipStream {
594
+ extendedCheckpoints;
498
595
  utc;
499
596
  sink;
500
597
  offset = 0;
501
598
  entries = [];
502
599
  format;
503
- constructor(sink, utc = false, format = ZIP_FORMAT) {
600
+ directoryResume;
601
+ constructor(sink, utc = false, format = ZIP_FORMAT, extendedCheckpoints = false) {
602
+ this.extendedCheckpoints = extendedCheckpoints;
504
603
  if (![ZIP_FORMAT, LEGACY_ZIP_FORMAT].includes(format))
505
604
  throw new Error("Formato del checkpoint ZIP non supportato.");
506
605
  this.utc = utc;
507
606
  this.sink = sink;
508
607
  this.format = format;
509
608
  }
510
- restore(entries, files, offset) {
609
+ restore(entries, files, offset, directory) {
610
+ if (directory && (!this.extendedCheckpoints || directory.directoryOffset + directory.directoryRead !== offset || directory.zipFormat !== this.format))
611
+ throw new Error('Ripresa directory non valida');
612
+ this.directoryResume = directory;
511
613
  this.offset = offset;
512
614
  this.entries = entries.map((entry, i) => {
513
615
  const name = enc.encode(entry.name);
@@ -528,6 +630,9 @@ export class ZipStream {
528
630
  throw new Error("Formato del checkpoint ZIP diverso dal caricamento.");
529
631
  // STORE has a known size, but needs a CRC before its local header can
530
632
  // be self-contained. Two bounded reads avoid buffering whole photos.
633
+ // Keep at most one read buffer. Small members can write the exact snapshot
634
+ // we checksummed, including when a part boundary divides it into two slices.
635
+ let snapshot;
531
636
  let headerCrc = 0;
532
637
  if (!legacy) {
533
638
  let value = 0xffffffff;
@@ -538,6 +643,8 @@ export class ZipStream {
538
643
  const chunk = new Uint8Array(await blob.slice(offset, offset + length).arrayBuffer());
539
644
  if (chunk.length !== length)
540
645
  throw new Error("Lettura sorgente incompleta durante la verifica.");
646
+ if (size <= READ && !resume)
647
+ snapshot = chunk;
541
648
  value = crc32Update(value, chunk);
542
649
  progress?.(offset + length, true);
543
650
  }
@@ -562,14 +669,32 @@ export class ZipStream {
562
669
  v.setUint16(28, extra.length, true);
563
670
  local.set(name, 30);
564
671
  local.set(extra, 30 + name.length);
565
- if (!resume)
566
- await this.push(local);
672
+ const headerRead = resume?.headerRead || 0;
673
+ if (headerRead && (!this.extendedCheckpoints || resume.read !== 0 || resume.localOffset + headerRead !== this.offset ||
674
+ resume.dataOffset !== localOffset + local.length || headerRead > local.length))
675
+ throw new Error('Header del checkpoint non valido');
676
+ if (!resume || headerRead) {
677
+ if (this.extendedCheckpoints && checkpoint) {
678
+ let done = headerRead;
679
+ while (done < local.length) {
680
+ const length = Math.min(local.length - done, PART - this.offset % PART);
681
+ await this.push(local.subarray(done, done + length));
682
+ done += length;
683
+ if (this.offset % PART === 0)
684
+ await checkpoint({ name: nameValue, size, read: 0, crc: 0xffffffff, chain: '',
685
+ localOffset, dataOffset: localOffset + local.length, time, date, zipFormat: this.format,
686
+ ...(!legacy ? { headerCrc } : {}), headerRead: done }, this.offset);
687
+ }
688
+ }
689
+ else
690
+ await this.push(local);
691
+ }
567
692
  const dataOffset = resume?.dataOffset ?? this.offset;
568
693
  let crc = 0xffffffff;
569
694
  let read = 0;
570
695
  let chain = "";
571
696
  if (resume && (resume.name !== nameValue || resume.size !== size || resume.time !== time || resume.date !== date ||
572
- resume.read > size || resume.read < 0 || dataOffset + resume.read !== this.offset))
697
+ resume.read > size || resume.read < 0 || dataOffset + resume.read + (resume.descriptorRead || 0) !== this.offset))
573
698
  throw new Error("File diverso da quello del checkpoint.");
574
699
  // Verifica il prefisso del solo file interrotto; gli originali già conclusi sono
575
700
  // la copia remota autorevole. Non mescolare un nuovo suffisso a un vecchio prefisso.
@@ -588,10 +713,10 @@ export class ZipStream {
588
713
  throw new Error("Il file interrotto è cambiato: impossibile riprenderlo senza alterare i dati.");
589
714
  while (read < size) {
590
715
  const length = Math.min(READ, size - read, checkpoint ? PART - (this.offset % PART) : READ);
591
- const chunk = new Uint8Array(await blob.slice(read, read + length).arrayBuffer());
716
+ const chunk = snapshot ? snapshot.subarray(read, read + length) : new Uint8Array(await blob.slice(read, read + length).arrayBuffer());
592
717
  if (chunk.length !== length)
593
718
  throw new Error("Lettura sorgente incompleta.");
594
- crc = crc32Update(crc, chunk);
719
+ crc = snapshot && length === size ? (headerCrc ^ 0xffffffff) >>> 0 : crc32Update(crc, chunk);
595
720
  if (checkpoint)
596
721
  chain = await digestHex(enc.encode(chain + ":" + await digestHex(chunk)));
597
722
  read += chunk.byteLength;
@@ -601,6 +726,7 @@ export class ZipStream {
601
726
  zipFormat: this.format, ...(!legacy ? { headerCrc } : {}) }, this.offset);
602
727
  progress?.(read);
603
728
  }
729
+ const runningCrc = crc;
604
730
  crc = (crc ^ 0xffffffff) >>> 0;
605
731
  if (!legacy && crc !== headerCrc)
606
732
  throw new Error("Il file è cambiato durante il caricamento. Riseleziona i file e riprova.");
@@ -617,13 +743,70 @@ export class ZipStream {
617
743
  d.setUint32(8, size, true);
618
744
  d.setUint32(12, size, true);
619
745
  }
620
- await this.push(descriptor);
746
+ let done = resume?.descriptorRead || 0;
747
+ if (done && (!this.extendedCheckpoints || done > descriptor.length))
748
+ throw new Error('Descrittore del checkpoint non valido');
749
+ if (this.extendedCheckpoints && checkpoint) {
750
+ while (done < descriptor.length) {
751
+ const length = Math.min(descriptor.length - done, PART - this.offset % PART);
752
+ await this.push(descriptor.subarray(done, done + length));
753
+ done += length;
754
+ if (this.offset % PART === 0)
755
+ await checkpoint({ name: nameValue, size, read, crc: runningCrc, chain,
756
+ localOffset, dataOffset, time, date, zipFormat: this.format, descriptorRead: done }, this.offset);
757
+ }
758
+ }
759
+ else
760
+ await this.push(descriptor);
621
761
  }
622
762
  this.entries.push({ name, size, crc, localOffset, time, date });
623
763
  return { offset: dataOffset, length: size, crc32: crc };
624
764
  }
625
- async close() {
626
- const centralOffset = this.offset;
765
+ async close(checkpoint) {
766
+ const centralOffset = this.directoryResume?.directoryOffset ?? this.offset;
767
+ let logicalOffset = centralOffset, skip = this.directoryResume?.directoryRead || 0, chain = '';
768
+ let proofChunks = [], proofBytes = 0;
769
+ const pushDirectory = async (data) => {
770
+ if (!this.extendedCheckpoints) {
771
+ await this.push(data);
772
+ logicalOffset += data.length;
773
+ return;
774
+ }
775
+ let read = 0;
776
+ while (read < data.length) {
777
+ const length = Math.min(data.length - read, PART - logicalOffset % PART, READ - proofBytes);
778
+ const chunk = data.subarray(read, read + length);
779
+ proofChunks.push(chunk);
780
+ proofBytes += length;
781
+ read += length;
782
+ logicalOffset += length;
783
+ // Fixed byte segments, independent of entry boundaries: avoid
784
+ // two crypto calls for every tiny central-directory record.
785
+ if (proofBytes === READ || logicalOffset % PART === 0) {
786
+ const block = new Uint8Array(proofBytes);
787
+ let at = 0;
788
+ for (const piece of proofChunks) {
789
+ block.set(piece, at);
790
+ at += piece.length;
791
+ }
792
+ chain = await digestHex(enc.encode(chain + ':' + await digestHex(block)));
793
+ proofChunks = [];
794
+ proofBytes = 0;
795
+ }
796
+ if (skip) {
797
+ if (length > skip)
798
+ throw new Error('Prefisso directory non allineato');
799
+ skip -= length;
800
+ if (!skip && chain !== this.directoryResume.directoryChain)
801
+ throw new Error('Directory diversa dal checkpoint');
802
+ continue;
803
+ }
804
+ await this.push(chunk);
805
+ if (checkpoint && this.offset % PART === 0)
806
+ await checkpoint({ stage: 'directory', zipFormat: this.format,
807
+ directoryOffset: centralOffset, directoryRead: logicalOffset - centralOffset, directoryChain: chain }, this.offset);
808
+ }
809
+ };
627
810
  for (const entry of this.entries) {
628
811
  const legacy = this.format === LEGACY_ZIP_FORMAT;
629
812
  const largeSize = entry.size >= 0xffffffff;
@@ -649,12 +832,12 @@ export class ZipStream {
649
832
  v.setUint32(42, largeOffset || (legacy && large) ? 0xffffffff : entry.localOffset, true);
650
833
  central.set(entry.name, 46);
651
834
  central.set(extra, 46 + entry.name.length);
652
- await this.push(central);
835
+ await pushDirectory(central);
653
836
  }
654
- const centralSize = this.offset - centralOffset;
837
+ const centralSize = logicalOffset - centralOffset;
655
838
  const needs64 = this.entries.length >= 0xffff || centralOffset >= 0xffffffff || centralSize >= 0xffffffff;
656
839
  if (needs64) {
657
- const zip64Offset = this.offset;
840
+ const zip64Offset = logicalOffset;
658
841
  const end64 = bytes(56);
659
842
  const e = view(end64);
660
843
  e.setUint32(0, 0x06064b50, true);
@@ -665,13 +848,13 @@ export class ZipStream {
665
848
  setU64(e, 32, this.entries.length);
666
849
  setU64(e, 40, centralSize);
667
850
  setU64(e, 48, centralOffset);
668
- await this.push(end64);
851
+ await pushDirectory(end64);
669
852
  const locator = bytes(20);
670
853
  const l = view(locator);
671
854
  l.setUint32(0, 0x07064b50, true);
672
855
  setU64(l, 8, zip64Offset);
673
856
  l.setUint32(16, 1, true);
674
- await this.push(locator);
857
+ await pushDirectory(locator);
675
858
  }
676
859
  const end = bytes(22);
677
860
  const e = view(end);
@@ -680,7 +863,9 @@ export class ZipStream {
680
863
  e.setUint16(10, Math.min(this.entries.length, 0xffff), true);
681
864
  e.setUint32(12, Math.min(centralSize, 0xffffffff), true);
682
865
  e.setUint32(16, Math.min(centralOffset, 0xffffffff), true);
683
- await this.push(end);
866
+ await pushDirectory(end);
867
+ if (skip)
868
+ throw new Error('Checkpoint oltre la directory ZIP');
684
869
  await this.sink.close();
685
870
  }
686
871
  async sinkGate() { await this.sink.gate?.(); }
@@ -892,14 +1077,26 @@ const CRC_TABLE = (() => {
892
1077
  }
893
1078
  return table;
894
1079
  })();
1080
+ // Slicing-by-4 CRC32. Each table advances a contribution by one zero byte.
1081
+ function advanceCrcTable(previous) {
1082
+ return previous.map(crc => CRC_TABLE[crc & 255] ^ (crc >>> 8));
1083
+ }
1084
+ const CRC_1 = advanceCrcTable(CRC_TABLE);
1085
+ const CRC_2 = advanceCrcTable(CRC_1);
1086
+ const CRC_3 = advanceCrcTable(CRC_2);
895
1087
  function crc32Update(crc, data) {
896
1088
  let c = crc;
897
- for (let i = 0; i < data.length; i++)
1089
+ let i = 0;
1090
+ for (; i + 3 < data.length; i += 4) {
1091
+ c = CRC_3[(c ^ data[i]) & 255] ^ CRC_2[((c >>> 8) ^ data[i + 1]) & 255] ^
1092
+ CRC_1[((c >>> 16) ^ data[i + 2]) & 255] ^ CRC_TABLE[(c >>> 24) ^ data[i + 3]];
1093
+ }
1094
+ for (; i < data.length; i++)
898
1095
  c = CRC_TABLE[(c ^ data[i]) & 0xff] ^ (c >>> 8);
899
1096
  return c >>> 0;
900
1097
  }
901
1098
  async function digestHex(data) {
902
- const digest = await crypto.subtle.digest("SHA-256", data.buffer);
1099
+ const digest = await crypto.subtle.digest("SHA-256", data);
903
1100
  return [...new Uint8Array(digest)]
904
1101
  .map((byte) => byte.toString(16).padStart(2, "0")).join("");
905
1102
  }
@@ -1,4 +1,5 @@
1
1
  import { type DeliveryUploadProgress, type UploadControl } from "./delivery-upload.js";
2
+ import { type UploadSessionReference } from './delivery-upload-coordinator.js';
2
3
  export type UploadState = "running" | "paused" | "cancelling" | "done" | "failed";
3
4
  export interface UploadJob {
4
5
  /** L'id del pacchetto: uno per caricamento. */
@@ -15,6 +16,8 @@ export interface UploadJob {
15
16
  retryable?: boolean;
16
17
  }
17
18
  interface StartInput {
19
+ uploadSession?: UploadSessionReference;
20
+ sourceFingerprint?: string;
18
21
  deliveryId: string;
19
22
  packageId: string;
20
23
  title: string;
@@ -32,6 +35,8 @@ export declare function uploadFor(deliveryId: string, list: UploadJob[]): Upload
32
35
  export declare function isBusy(job: UploadJob | undefined): boolean;
33
36
  export declare class Gate implements UploadControl {
34
37
  private id;
38
+ writerToken?: string;
39
+ json?: UploadControl['json'];
35
40
  readonly controller: AbortController;
36
41
  readonly signal: AbortSignal;
37
42
  private waitingRequests;