@elaraai/e3-cloud-files 1.1.20 → 1.1.22

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 (49) hide show
  1. package/README.md +99 -11
  2. package/dist/src/authoring.d.ts +88 -19
  3. package/dist/src/authoring.d.ts.map +1 -1
  4. package/dist/src/authoring.js +94 -25
  5. package/dist/src/authoring.js.map +1 -1
  6. package/dist/src/check/index.d.ts +1 -1
  7. package/dist/src/check/index.d.ts.map +1 -1
  8. package/dist/src/check/index.js +1 -1
  9. package/dist/src/check/index.js.map +1 -1
  10. package/dist/src/check.d.ts +7 -9
  11. package/dist/src/check.d.ts.map +1 -1
  12. package/dist/src/check.js +12 -11
  13. package/dist/src/check.js.map +1 -1
  14. package/dist/src/compat.d.ts +255 -3
  15. package/dist/src/compat.d.ts.map +1 -1
  16. package/dist/src/compat.js +60 -10
  17. package/dist/src/compat.js.map +1 -1
  18. package/dist/src/index.d.ts +2 -2
  19. package/dist/src/index.d.ts.map +1 -1
  20. package/dist/src/index.js +2 -2
  21. package/dist/src/index.js.map +1 -1
  22. package/dist/src/s3/index.d.ts.map +1 -1
  23. package/dist/src/s3/index.js +12 -0
  24. package/dist/src/s3/index.js.map +1 -1
  25. package/dist/src/sync/engine.d.ts +122 -10
  26. package/dist/src/sync/engine.d.ts.map +1 -1
  27. package/dist/src/sync/engine.js +337 -78
  28. package/dist/src/sync/engine.js.map +1 -1
  29. package/dist/src/sync/index.d.ts +3 -2
  30. package/dist/src/sync/index.d.ts.map +1 -1
  31. package/dist/src/sync/index.js +3 -2
  32. package/dist/src/sync/index.js.map +1 -1
  33. package/dist/src/sync/memory.d.ts +78 -0
  34. package/dist/src/sync/memory.d.ts.map +1 -1
  35. package/dist/src/sync/memory.js +206 -1
  36. package/dist/src/sync/memory.js.map +1 -1
  37. package/dist/src/sync/push.d.ts +15 -2
  38. package/dist/src/sync/push.d.ts.map +1 -1
  39. package/dist/src/sync/push.js +19 -6
  40. package/dist/src/sync/push.js.map +1 -1
  41. package/dist/src/sync/sealed.d.ts +251 -0
  42. package/dist/src/sync/sealed.d.ts.map +1 -0
  43. package/dist/src/sync/sealed.js +573 -0
  44. package/dist/src/sync/sealed.js.map +1 -0
  45. package/dist/test/orders.examples.d.ts +1 -1
  46. package/dist/test/orders.examples.d.ts.map +1 -1
  47. package/dist/test/typed.examples.d.ts +2 -2
  48. package/dist/test/typed.examples.d.ts.map +1 -1
  49. package/package.json +6 -6
@@ -59,10 +59,18 @@
59
59
  * Mappings that share a source and a prefix list it once a round; a glob that
60
60
  * matches only the prefix's own folder lists that folder alone.
61
61
  *
62
+ * A mapping of the repository's deliveries (`Files.deliveries()`) reads
63
+ * through the deliveries reader the sync is given ({@link SyncOptions}'s
64
+ * `deliveries`), never a binding: where the area is, the caller knows. A
65
+ * deliveries ledger is taken under the constant text `deliveries`, not the
66
+ * area's location, so a move from one area to another (an external bucket to
67
+ * the encrypted one) keeps what each target took trusted: every file is read
68
+ * once in the new place, and none is taken away.
69
+ *
62
70
  * @packageDocumentation
63
71
  */
64
72
  import { StringType, StructType, isTypeValueEqual, none, printFor, readBeast2HeaderType, some, variant } from '@elaraai/east';
65
- import { FILES_FILE_MAX_BYTES, FILES_FOLDER_ENTRY_MAX_BYTES, FILES_TYPED_VALUE_MAX_BYTES, FilesShapeType, filesProblemText, filesTargetText, sameFilesTarget, } from '@elaraai/e3-cloud-types';
73
+ import { FILES_FILE_MAX_BYTES, FILES_FOLDER_ENTRY_MAX_BYTES, FILES_SEALED_MAX_BYTES, FILES_TYPED_VALUE_MAX_BYTES, FilesShapeType, filesProblemText, filesTargetText, sameFilesTarget, } from '@elaraai/e3-cloud-types';
66
74
  import { FilesShapeTypeV1 } from '../compat.js';
67
75
  import { globMatcher, matchesTopFolderOnly } from '../paths.js';
68
76
  /**
@@ -164,25 +172,39 @@ function untypedShape(shape) {
164
172
  case 'listing': return variant('listing', shape.value);
165
173
  }
166
174
  }
175
+ /**
176
+ * Where a deliveries mapping's files are said to be taken from, in its
177
+ * ledger's `under`: a constant, never the area's location, so a move from
178
+ * one area to another leaves what each target took trusted.
179
+ */
180
+ export const DELIVERIES_UNDER = 'deliveries';
167
181
  /**
168
182
  * What a target's files are taken under: its mapping's shape and where its
169
- * source is bound, as one text. A ledger taken under another is not trusted:
170
- * its keys may name other files, and its paths another folder's. A shape
171
- * that names no type prints as the first version printed it, so a ledger it
172
- * wrote stays trusted.
183
+ * source is bound, as one text; a deliveries mapping's, the shape and
184
+ * {@link DELIVERIES_UNDER}, wherever the area is. A ledger taken under
185
+ * another is not trusted: its keys may name other files, and its paths
186
+ * another folder's. A shape that names no type prints as the first version
187
+ * printed it, so a ledger it wrote stays trusted.
173
188
  *
174
189
  * @param mapping - The mapping
175
- * @param binding - Its source's binding
190
+ * @param binding - Its source's binding; unused for a deliveries mapping
176
191
  * @returns The text
177
192
  */
178
193
  export function takenUnder(mapping, binding) {
194
+ const url = mapping.from.type === 'deliveries' ? DELIVERIES_UNDER : binding.url;
179
195
  const untyped = untypedShape(mapping.shape);
180
- return untyped === null ? printUnder({ url: binding.url, shape: mapping.shape }) : printUnderV1({ url: binding.url, shape: untyped });
196
+ return untyped === null ? printUnder({ url, shape: mapping.shape }) : printUnderV1({ url, shape: untyped });
197
+ }
198
+ /** What a mapping's files come from, as one text: a reader's and a listing's key. */
199
+ function fromKey(from) {
200
+ return from.type === 'source' ? `source\u0000${from.value}` : 'deliveries';
181
201
  }
182
202
  /** The most bytes of a folder's files a sync holds before it writes them, when not told: 256 MiB. */
183
203
  export const FOLDER_BATCH_BYTES = 256 * 1024 * 1024;
184
204
  /** The most files of a folder a sync writes at once. */
185
205
  const FOLDER_BATCH_FILES = 4096;
206
+ /** How many of a folder's sealed files are unsealed at once: each an object read and a private-key operation. */
207
+ const UNSEAL_IN_FLIGHT = 8;
186
208
  /** The head of a typed file read first for its type: 64 KiB, then wider, to at most 16 MiB. */
187
209
  const HEAD_PROBE_BYTES = 64 * 1024;
188
210
  const HEAD_MAX_BYTES = 16 * 1024 * 1024;
@@ -235,15 +257,20 @@ function same(a, b) {
235
257
  function entryOf(object, sha256) {
236
258
  return { etag: object.etag, size: object.size, modified: object.modified, ...(sha256 !== undefined && { sha256 }) };
237
259
  }
238
- /** A mapping's binding; checked to exist before a sync starts. */
260
+ /** A source mapping's binding, checked to exist before a sync starts; none for a deliveries mapping. */
239
261
  function bindingOf(mapping, options) {
240
- return options.bindings.find((b) => b.source === mapping.source);
262
+ const { from } = mapping;
263
+ return from.type === 'source' ? options.bindings.find((b) => b.source === from.value) : undefined;
241
264
  }
242
- /** A mapping's reader: one per bound source, for the sync. */
265
+ /** A mapping's reader: one per bound source, and one for the deliveries, for the sync. */
243
266
  function readerOf(sync, mapping) {
244
- let reader = sync.readers.get(mapping.source);
245
- if (reader === undefined)
246
- sync.readers.set(mapping.source, reader = sync.options.reader(bindingOf(mapping, sync.options)));
267
+ const key = fromKey(mapping.from);
268
+ let reader = sync.readers.get(key);
269
+ if (reader === undefined) {
270
+ // A deliveries mapping reaches here only when the sync was given its deliveries (checked before it starts)
271
+ reader = mapping.from.type === 'deliveries' ? sync.options.deliveries.reader() : sync.options.reader(bindingOf(mapping, sync.options));
272
+ sync.readers.set(key, reader);
273
+ }
247
274
  return reader;
248
275
  }
249
276
  /**
@@ -265,13 +292,13 @@ async function before(sync, mapping) {
265
292
  return { state, entries: state.entries, trusted: true, stale: false, current: null, under };
266
293
  return { state, entries: new Map(), trusted: false, stale: false, current: null, under };
267
294
  }
268
- /** A listing's key among a round's: its source, its prefix and its depth. */
269
- function listingKey(source, prefix, topFolderOnly) {
270
- return `${source}\u0000${prefix}\u0000${topFolderOnly ? 'top' : 'all'}`;
295
+ /** A listing's key among a round's: where its files come from, its prefix and its depth. */
296
+ function listingKey(from, prefix, topFolderOnly) {
297
+ return `${fromKey(from)}\u0000${prefix}\u0000${topFolderOnly ? 'top' : 'all'}`;
271
298
  }
272
299
  /** The files a mapping's prefix holds, as its source lists them: once a round, for every mapping that lists it. */
273
300
  async function listed(sync, mapping, prefix, topFolderOnly) {
274
- const key = listingKey(mapping.source, prefix, topFolderOnly);
301
+ const key = listingKey(mapping.from, prefix, topFolderOnly);
275
302
  const shared = sync.shared.get(key);
276
303
  const listing = () => readerOf(sync, mapping).list(prefix, { topFolderOnly });
277
304
  if (shared === undefined)
@@ -324,6 +351,28 @@ async function selection(sync, mapping, prefix, include) {
324
351
  function refusal(key, reason) {
325
352
  return { key, reason };
326
353
  }
354
+ /** Whether a reader unseals its files: its listed sizes are a sealed file's, not its plaintext's. */
355
+ function sealed(reader) {
356
+ return reader.unseal !== undefined;
357
+ }
358
+ /**
359
+ * A file as the sync reads it: itself from a reader of plaintext; from a
360
+ * sealed reader, its plaintext, once unsealed whole and within `maxBytes`,
361
+ * or the refusal, or a stop at the round's signal.
362
+ */
363
+ async function plainOf(sync, reader, file, maxBytes) {
364
+ if (reader.unseal === undefined)
365
+ return { object: file };
366
+ const { signal, roundMs } = sync.options;
367
+ const answer = await reader.unseal(file, { maxBytes, ...(signal !== undefined && { signal }), ...(roundMs !== undefined && { roundMs }) });
368
+ if ('refused' in answer)
369
+ return { refused: refusal(file.key, answer.refused) };
370
+ return answer;
371
+ }
372
+ /** The most bytes a typed value's file takes: a collection any size a sealed file may hold, else a value's limit. */
373
+ function typedMaxBytes(type) {
374
+ return isCollectionType(type) ? FILES_SEALED_MAX_BYTES : FILES_TYPED_VALUE_MAX_BYTES;
375
+ }
327
376
  /** The SHA-256 of bytes the sync holds, hex: a push finds a file it put unchanged by it. */
328
377
  async function sha256Of(bytes) {
329
378
  // A view over the bytes' own buffer, as the platform's digest takes one
@@ -459,25 +508,36 @@ async function syncOne(sync, mapping, input, chosen, missing) {
459
508
  report.unchanged = 1n;
460
509
  return reportOf(mapping, report);
461
510
  }
462
- if (chosen.size > FILES_FILE_MAX_BYTES) {
511
+ const reader = readerOf(sync, mapping);
512
+ if (!sealed(reader) && chosen.size > FILES_FILE_MAX_BYTES) {
463
513
  report.refused.push(refusal(chosen.key, variant('too_large', { size: BigInt(chosen.size), limit: BigInt(FILES_FILE_MAX_BYTES) })));
464
514
  return reportOf(mapping, report);
465
515
  }
466
- const taken = () => {
516
+ const taken = (size) => {
467
517
  if (!prior.trusted && !prior.stale)
468
518
  report.added = 1n;
469
519
  else
470
520
  report.changed = 1n;
471
- report.bytes = BigInt(chosen.size);
521
+ report.bytes = BigInt(size);
472
522
  report.updated = true;
473
523
  };
474
524
  if (options.dryRun === true) {
475
- taken();
525
+ taken(chosen.size);
526
+ return reportOf(mapping, report);
527
+ }
528
+ const plain = await plainOf(sync, reader, chosen, FILES_FILE_MAX_BYTES);
529
+ if ('refused' in plain) {
530
+ report.refused.push(plain.refused);
531
+ return reportOf(mapping, report);
532
+ }
533
+ if ('yielded' in plain) {
534
+ sync.progressed = true;
535
+ sync.yielded = true;
476
536
  return reportOf(mapping, report);
477
537
  }
478
538
  let bytes;
479
539
  try {
480
- bytes = await readerOf(sync, mapping).read(chosen);
540
+ bytes = await reader.read(plain.object);
481
541
  }
482
542
  catch (err) {
483
543
  if (!(err instanceof FilesUnreadableError))
@@ -486,9 +546,13 @@ async function syncOne(sync, mapping, input, chosen, missing) {
486
546
  report.refused.push(refusal(chosen.key, variant('unreadable', err.reason)));
487
547
  return reportOf(mapping, report);
488
548
  }
549
+ finally {
550
+ // The bytes are the sync's now: the reader holds them no longer
551
+ reader.release?.(plain.object);
552
+ }
489
553
  const value = await options.writer.setFile(input, bytes);
490
554
  await options.ledger.write(ledgerKeyOf(mapping.target), { ...NO_LEDGER, entries: new Map([[chosen.key, entryOf(chosen, await sha256Of(bytes))]]), value, under: prior.under });
491
- taken();
555
+ taken(bytes.length);
492
556
  sync.progressed = true;
493
557
  return reportOf(mapping, report);
494
558
  }
@@ -524,12 +588,13 @@ async function syncTyped(sync, mapping, input, type, chosen, missing) {
524
588
  await forget();
525
589
  return reportOf(mapping, report);
526
590
  }
591
+ let size = chosen.size;
527
592
  const counted = () => {
528
593
  if (!prior.trusted && !prior.stale)
529
594
  report.added = 1n;
530
595
  else
531
596
  report.changed = 1n;
532
- report.bytes = BigInt(chosen.size);
597
+ report.bytes = BigInt(size);
533
598
  };
534
599
  if (options.dryRun === true) {
535
600
  counted();
@@ -537,18 +602,38 @@ async function syncTyped(sync, mapping, input, type, chosen, missing) {
537
602
  return reportOf(mapping, report);
538
603
  }
539
604
  const reader = readerOf(sync, mapping);
540
- // The header first: a file of another type, or no beast2, costs no other byte
541
- const refused = await typedRefusal(reader, chosen, type);
542
- if (refused !== null) {
605
+ // A sealed file unsealed first, whole: its plaintext is what is typed
606
+ const plain = await plainOf(sync, reader, chosen, typedMaxBytes(type));
607
+ if ('yielded' in plain) {
608
+ sync.progressed = true;
609
+ sync.yielded = true;
610
+ return reportOf(mapping, report);
611
+ }
612
+ const forgetTaking = async (refused) => {
543
613
  report.refused.push(refused);
544
614
  if (taking !== null)
545
615
  await options.ledger.write(key, { ...prior.state, taking: null });
546
616
  return reportOf(mapping, report);
617
+ };
618
+ if ('refused' in plain)
619
+ return forgetTaking(plain.refused);
620
+ const file = plain.object;
621
+ let result;
622
+ try {
623
+ // The header first: a file of another type, or no beast2, costs no other byte
624
+ const refused = await typedRefusal(reader, file, type);
625
+ if (refused !== null)
626
+ return await forgetTaking(refused);
627
+ size = file.size;
628
+ result = await options.writer.takeTyped(input, file, type, reader, {
629
+ ...(resuming !== null && { resume: resuming }),
630
+ ...(options.signal !== undefined && { signal: options.signal }),
631
+ });
632
+ }
633
+ finally {
634
+ // Taken in, refused or stopped: the reader holds its plaintext no longer (a staged copy stays until the round ends)
635
+ reader.release?.(file);
547
636
  }
548
- const result = await options.writer.takeTyped(input, chosen, type, reader, {
549
- ...(resuming !== null && { resume: resuming }),
550
- ...(options.signal !== undefined && { signal: options.signal }),
551
- });
552
637
  switch (result.status) {
553
638
  case 'refused':
554
639
  report.refused.push(refusal(chosen.key, result.reason));
@@ -559,8 +644,10 @@ async function syncTyped(sync, mapping, input, type, chosen, missing) {
559
644
  case 'yielded':
560
645
  // Remembered where it stopped, under the ledger as it was, so the next
561
646
  // round resumes it; stopped before anything was kept, the next starts again
562
- if (result.taking !== null)
647
+ if (result.taking !== null) {
563
648
  await options.ledger.write(key, { ...prior.state, under: prior.state.under ?? prior.under, taking: result.taking });
649
+ sync.underWay.push(file);
650
+ }
564
651
  else if (taking !== null)
565
652
  await options.ledger.write(key, { ...prior.state, taking: null });
566
653
  sync.progressed = true;
@@ -629,12 +716,13 @@ async function syncSeed(sync, mapping, record, type, chosen, missing) {
629
716
  report.unchanged = 1n;
630
717
  return reportOf(mapping, report);
631
718
  }
719
+ let size = chosen.size;
632
720
  const counted = () => {
633
721
  if (previous === undefined)
634
722
  report.added = 1n;
635
723
  else
636
724
  report.changed = 1n;
637
- report.bytes = BigInt(chosen.size);
725
+ report.bytes = BigInt(size);
638
726
  };
639
727
  const { seed, seeds } = seedCommitOf(state.pending, prior.state);
640
728
  if (options.dryRun === true) {
@@ -645,21 +733,39 @@ async function syncSeed(sync, mapping, record, type, chosen, missing) {
645
733
  return reportOf(mapping, report);
646
734
  }
647
735
  const reader = readerOf(sync, mapping);
648
- const refused = await typedRefusal(reader, chosen, type);
649
- if (refused !== null) {
650
- report.refused.push(refused);
736
+ const plain = await plainOf(sync, reader, chosen, typedMaxBytes(type));
737
+ if ('yielded' in plain) {
738
+ sync.progressed = true;
739
+ sync.yielded = true;
651
740
  return reportOf(mapping, report);
652
741
  }
653
- const from = await originOf(reader, chosen);
654
- if ('refused' in from) {
655
- report.refused.push(from.refused);
742
+ if ('refused' in plain) {
743
+ report.refused.push(plain.refused);
656
744
  return reportOf(mapping, report);
657
745
  }
658
- const result = await writer.seed(record, chosen, type, reader, {
659
- genesis: state.pending,
660
- ...(from.origin !== null && { origin: from.origin }),
661
- ...(options.signal !== undefined && { signal: options.signal }),
662
- });
746
+ const file = plain.object;
747
+ let result;
748
+ try {
749
+ const refused = await typedRefusal(reader, file, type);
750
+ if (refused !== null) {
751
+ report.refused.push(refused);
752
+ return reportOf(mapping, report);
753
+ }
754
+ size = file.size;
755
+ const from = await originOf(reader, file);
756
+ if ('refused' in from) {
757
+ report.refused.push(from.refused);
758
+ return reportOf(mapping, report);
759
+ }
760
+ result = await writer.seed(record, file, type, reader, {
761
+ genesis: state.pending,
762
+ ...(from.origin !== null && { origin: from.origin }),
763
+ ...(options.signal !== undefined && { signal: options.signal }),
764
+ });
765
+ }
766
+ finally {
767
+ reader.release?.(file);
768
+ }
663
769
  if (result.status === 'refused') {
664
770
  report.refused.push(refusal(chosen.key, result.reason));
665
771
  return reportOf(mapping, report);
@@ -714,7 +820,8 @@ async function syncFeed(sync, mapping, record, mutation, type, files, missing) {
714
820
  report.kept = 'the mutation refused it earlier: not tried again until the file changes';
715
821
  return reportOf(mapping, report);
716
822
  }
717
- for (const file of fresh) {
823
+ const reader = readerOf(sync, mapping);
824
+ for (const file of sealed(reader) ? [] : fresh) {
718
825
  if (file.size > FILES_TYPED_VALUE_MAX_BYTES) {
719
826
  report.refused.push(refusal(file.key, variant('too_large', { size: BigInt(file.size), limit: BigInt(FILES_TYPED_VALUE_MAX_BYTES) })));
720
827
  break;
@@ -738,27 +845,43 @@ async function syncFeed(sync, mapping, record, mutation, type, files, missing) {
738
845
  report.waiting = 'the record has no state yet';
739
846
  return reportOf(mapping, report);
740
847
  }
741
- const reader = readerOf(sync, mapping);
742
848
  let first = true;
743
- for (const file of fresh) {
849
+ for (const listedFile of fresh) {
744
850
  if (!first && stopping(sync))
745
851
  break;
746
852
  first = false;
747
- const refused = await typedRefusal(reader, file, type);
748
- if (refused !== null) {
749
- report.refused.push(refused);
853
+ const plain = await plainOf(sync, reader, listedFile, FILES_TYPED_VALUE_MAX_BYTES);
854
+ if ('yielded' in plain) {
855
+ sync.progressed = true;
856
+ sync.yielded = true;
750
857
  break;
751
858
  }
752
- const from = await originOf(reader, file);
753
- if ('refused' in from) {
754
- report.refused.push(from.refused);
859
+ if ('refused' in plain) {
860
+ report.refused.push(plain.refused);
755
861
  break;
756
862
  }
757
- const result = await writer.feed(record, mutation, file, type, reader, {
758
- applied,
759
- ...(from.origin !== null && { origin: from.origin }),
760
- ...(options.signal !== undefined && { signal: options.signal }),
761
- });
863
+ const file = plain.object;
864
+ let result;
865
+ try {
866
+ const refused = await typedRefusal(reader, file, type);
867
+ if (refused !== null) {
868
+ report.refused.push(refused);
869
+ break;
870
+ }
871
+ const from = await originOf(reader, file);
872
+ if ('refused' in from) {
873
+ report.refused.push(from.refused);
874
+ break;
875
+ }
876
+ result = await writer.feed(record, mutation, file, type, reader, {
877
+ applied,
878
+ ...(from.origin !== null && { origin: from.origin }),
879
+ ...(options.signal !== undefined && { signal: options.signal }),
880
+ });
881
+ }
882
+ finally {
883
+ reader.release?.(file);
884
+ }
762
885
  if (result.status === 'waiting') {
763
886
  report.waiting = result.reason;
764
887
  break;
@@ -766,12 +889,12 @@ async function syncFeed(sync, mapping, record, mutation, type, files, missing) {
766
889
  if (result.status === 'refused') {
767
890
  // Remembered as tried: the next sync tries it again only once the file changes
768
891
  report.refused.push(refusal(file.key, result.reason));
769
- entries.set(file.key, entryOf(file, result.sha256));
892
+ entries.set(file.key, entryOf(listedFile, result.sha256));
770
893
  await options.ledger.write(key, { ...prior.state, entries: new Map(entries), under: prior.under, commit, tried: result.sha256 });
771
894
  sync.progressed = true;
772
895
  break;
773
896
  }
774
- entries.set(file.key, entryOf(file, result.sha256));
897
+ entries.set(file.key, entryOf(listedFile, result.sha256));
775
898
  applied.add(result.sha256);
776
899
  if (result.status === 'committed') {
777
900
  commit = result.commit;
@@ -806,9 +929,10 @@ async function syncFolder(sync, mapping, input, prefix, files) {
806
929
  const report = emptyTally();
807
930
  const prior = await before(sync, mapping);
808
931
  const binding = bindingOf(mapping, options);
932
+ const reader = readerOf(sync, mapping);
809
933
  // On a local repository, `latest` keeps only the greatest keys
810
934
  let kept = files;
811
- if (binding.latest.type === 'some') {
935
+ if (binding !== undefined && binding.latest.type === 'some') {
812
936
  const keys = [...files.keys()].sort();
813
937
  kept = new Map(keys.slice(Math.max(0, keys.length - Number(binding.latest.value))).map((path) => [path, files.get(path)]));
814
938
  }
@@ -822,7 +946,7 @@ async function syncFolder(sync, mapping, input, prefix, files) {
822
946
  staying.add(object.key);
823
947
  continue;
824
948
  }
825
- if (object.size > FILES_FOLDER_ENTRY_MAX_BYTES) {
949
+ if (!sealed(reader) && object.size > FILES_FOLDER_ENTRY_MAX_BYTES) {
826
950
  report.refused.push(refusal(object.key, variant('too_large', { size: BigInt(object.size), limit: BigInt(FILES_FOLDER_ENTRY_MAX_BYTES) })));
827
951
  // What the input held of it, if anything, stays
828
952
  if (previous !== undefined)
@@ -849,10 +973,11 @@ async function syncFolder(sync, mapping, input, prefix, files) {
849
973
  report.updated = true;
850
974
  return reportOf(mapping, report);
851
975
  }
852
- const reader = readerOf(sync, mapping);
853
976
  const entries = new Map(prior.entries);
854
- const batches = batched(toRead, options.batchBytes ?? FOLDER_BATCH_BYTES);
855
977
  const key = ledgerKeyOf(mapping.target);
978
+ if (sealed(reader))
979
+ return syncSealedFolder(sync, mapping, { input, prefix, reader, toRead, gone, fresh, entries, report, prior });
980
+ const batches = batched(toRead, options.batchBytes ?? FOLDER_BATCH_BYTES);
856
981
  let first = true;
857
982
  for (const batch of batches.length === 0 ? [[]] : batches) {
858
983
  if (!first && stopping(sync))
@@ -897,6 +1022,131 @@ async function syncFolder(sync, mapping, input, prefix, files) {
897
1022
  }
898
1023
  return reportOf(mapping, report);
899
1024
  }
1025
+ /**
1026
+ * Syncs a `folder` mapping from a sealed reader: its files unseal
1027
+ * {@link UNSEAL_IN_FLIGHT} at a time, in key order, and a batch closes by
1028
+ * plaintext bytes (the sync's batch bytes) or at {@link FOLDER_BATCH_FILES}
1029
+ * files, so what is held is bounded by the batch's plaintext and the files
1030
+ * in flight. A file whose plaintext is the one the ledger remembers (a file
1031
+ * delivered again, or the area moved) is remembered under its new ETag and
1032
+ * not written again. What is gone goes with the first batch, as with any
1033
+ * reader; the round may stop between batches, and a stop at its signal
1034
+ * writes the files already unsealed first.
1035
+ */
1036
+ async function syncSealedFolder(sync, mapping, plan) {
1037
+ const { options } = sync;
1038
+ const { input, prefix, reader, toRead, gone, fresh, entries, report, prior } = plan;
1039
+ const key = ledgerKeyOf(mapping.target);
1040
+ const maxBatchBytes = options.batchBytes ?? FOLDER_BATCH_BYTES;
1041
+ const open = async (object) => {
1042
+ const plain = await plainOf(sync, reader, object, FILES_FOLDER_ENTRY_MAX_BYTES);
1043
+ if (!('object' in plain))
1044
+ return plain;
1045
+ try {
1046
+ const bytes = await reader.read(plain.object);
1047
+ return { object, bytes, sha256: await sha256Of(bytes) };
1048
+ }
1049
+ catch (err) {
1050
+ if (!(err instanceof FilesUnreadableError))
1051
+ throw err;
1052
+ return { refused: refusal(object.key, variant('unreadable', err.reason)) };
1053
+ }
1054
+ finally {
1055
+ // The batch holds the bytes now, until it is written: the reader lets them go
1056
+ reader.release?.(plain.object);
1057
+ }
1058
+ };
1059
+ let first = true;
1060
+ let next = 0;
1061
+ const inFlight = [];
1062
+ const fill = () => {
1063
+ while (inFlight.length < UNSEAL_IN_FLIGHT && next < toRead.length) {
1064
+ const opening = open(toRead[next++]);
1065
+ // Awaited in its turn; a failure before then is not an unhandled rejection
1066
+ opening.catch(() => undefined);
1067
+ inFlight.push(opening);
1068
+ }
1069
+ };
1070
+ let stopped = false;
1071
+ try {
1072
+ while (first || next < toRead.length || inFlight.length > 0) {
1073
+ if (!first && stopping(sync))
1074
+ break;
1075
+ // One batch: files taken in key order until its plaintext bytes or its count is reached
1076
+ const set = new Map();
1077
+ const read = [];
1078
+ const same = [];
1079
+ let bytes = 0;
1080
+ fill();
1081
+ while (inFlight.length > 0 && bytes < maxBatchBytes && read.length + same.length < FOLDER_BATCH_FILES) {
1082
+ const opened = await inFlight.shift();
1083
+ fill();
1084
+ if ('yielded' in opened) {
1085
+ stopped = true;
1086
+ break;
1087
+ }
1088
+ if ('refused' in opened) {
1089
+ report.refused.push(opened.refused);
1090
+ continue;
1091
+ }
1092
+ // Every file read counts toward the batch, written or not: its plaintext was held
1093
+ if (prior.entries.get(opened.object.key)?.sha256 === opened.sha256) {
1094
+ same.push(opened);
1095
+ bytes += opened.bytes.length;
1096
+ continue;
1097
+ }
1098
+ set.set(relative(prefix, opened.object.key), opened.bytes);
1099
+ read.push({ object: opened.object, sha256: opened.sha256, bytes: opened.bytes.length });
1100
+ bytes += opened.bytes.length;
1101
+ }
1102
+ const remove = first ? new Set(gone.map((k) => relative(prefix, k))) : new Set();
1103
+ const makes = first && fresh;
1104
+ if (set.size > 0 || remove.size > 0 || makes) {
1105
+ const value = await options.writer.updateFolder(input, { set, remove, fresh: makes });
1106
+ if (first) {
1107
+ for (const k of gone)
1108
+ entries.delete(k);
1109
+ report.removed = BigInt(gone.length);
1110
+ }
1111
+ for (const file of read) {
1112
+ if (prior.entries.has(file.object.key))
1113
+ report.changed += 1n;
1114
+ else
1115
+ report.added += 1n;
1116
+ report.bytes += BigInt(file.bytes);
1117
+ entries.set(file.object.key, entryOf(file.object, file.sha256));
1118
+ }
1119
+ for (const file of same) {
1120
+ report.unchanged += 1n;
1121
+ entries.set(file.object.key, entryOf(file.object, file.sha256));
1122
+ }
1123
+ report.updated = true;
1124
+ await options.ledger.write(key, { ...NO_LEDGER, entries: new Map(entries), value, under: prior.under });
1125
+ sync.progressed = true;
1126
+ }
1127
+ else if (same.length > 0) {
1128
+ // The same plaintext under new ETags: remembered, the input as it is
1129
+ for (const file of same) {
1130
+ report.unchanged += 1n;
1131
+ entries.set(file.object.key, entryOf(file.object, file.sha256));
1132
+ }
1133
+ await options.ledger.write(key, { ...prior.state, entries: new Map(entries), under: prior.under });
1134
+ sync.progressed = true;
1135
+ }
1136
+ first = false;
1137
+ if (stopped) {
1138
+ sync.progressed = true;
1139
+ sync.yielded = true;
1140
+ break;
1141
+ }
1142
+ }
1143
+ }
1144
+ finally {
1145
+ // Files unsealed ahead of a stop are let go: the next round opens them again
1146
+ await Promise.allSettled(inFlight);
1147
+ }
1148
+ return reportOf(mapping, report);
1149
+ }
900
1150
  /** Syncs a `listing` mapping: written whole whenever any file is new, changed or gone. */
901
1151
  async function syncListing(sync, mapping, input, files) {
902
1152
  const { options } = sync;
@@ -978,8 +1228,9 @@ async function syncMapping(sync, mapping) {
978
1228
  *
979
1229
  * @param options - The declarations, the bindings, what reads, writes and remembers, and when to stop
980
1230
  * @returns What it did, per target it reached, and whether it stopped before the end
981
- * @throws {FilesSyncError} When a mapping's source is not bound, before
982
- * anything is read
1231
+ * @throws {FilesSyncError} When a mapping's source is not bound, or a
1232
+ * deliveries mapping has no deliveries to read (`deliveries_unavailable`),
1233
+ * before anything is read
983
1234
  * @throws {Error} When a target named is not one a declaration fills
984
1235
  */
985
1236
  export async function syncFilesRound(options) {
@@ -990,28 +1241,36 @@ export async function syncFilesRound(options) {
990
1241
  const order = (m) => (m.target.type === 'mutation' ? 1 : 0);
991
1242
  const mappings = wanted.map((m, i) => ({ m, i })).sort((a, b) => order(a.m) - order(b.m) || a.i - b.i).map(({ m }) => m);
992
1243
  const bound = new Set(options.bindings.map((b) => b.source));
993
- const problems = [...new Set(mappings.map((m) => m.source))]
1244
+ const problems = [...new Set(mappings.flatMap((m) => (m.from.type === 'source' ? [m.from.value] : [])))]
994
1245
  .filter((source) => !bound.has(source))
995
1246
  .map((source) => variant('source_unbound', { source }));
1247
+ if (options.deliveries === undefined && mappings.some((m) => m.from.type === 'deliveries'))
1248
+ problems.push(variant('deliveries_unavailable', null));
996
1249
  if (problems.length > 0)
997
1250
  throw new FilesSyncError(problems);
998
1251
  // The listings more than one mapping reads, each listed once
999
1252
  const listings = new Map();
1000
- for (const { source, shape } of mappings) {
1253
+ for (const { from, shape } of mappings) {
1001
1254
  if (shape.type === 'file')
1002
1255
  continue;
1003
- const key = listingKey(source, shape.value.prefix, matchesTopFolderOnly(shape.value.include.type === 'some' ? shape.value.include.value : null));
1256
+ const key = listingKey(from, shape.value.prefix, matchesTopFolderOnly(shape.value.include.type === 'some' ? shape.value.include.value : null));
1004
1257
  listings.set(key, (listings.get(key) ?? 0) + 1);
1005
1258
  }
1006
1259
  const shared = new Map([...listings].filter(([, uses]) => uses > 1).map(([key, uses]) => [key, { remaining: uses }]));
1007
- const sync = { options, readers: new Map(), shared, progressed: false, yielded: false };
1260
+ const sync = { options, readers: new Map(), shared, progressed: false, yielded: false, underWay: [] };
1008
1261
  const reports = [];
1009
- for (const mapping of mappings) {
1010
- if (stopping(sync))
1011
- break;
1012
- reports.push(await syncMapping(sync, mapping));
1013
- if (sync.yielded)
1014
- break;
1262
+ try {
1263
+ for (const mapping of mappings) {
1264
+ if (stopping(sync))
1265
+ break;
1266
+ reports.push(await syncMapping(sync, mapping));
1267
+ if (sync.yielded)
1268
+ break;
1269
+ }
1270
+ }
1271
+ finally {
1272
+ // Each reader lets go of what it holds: a sealed reader's staged plaintext
1273
+ await Promise.all([...sync.readers.values()].map((reader) => reader.close?.(sync.underWay)));
1015
1274
  }
1016
1275
  return { report: { started, finished: now(), dryRun: options.dryRun === true, mappings: reports }, yielded: sync.yielded };
1017
1276
  }
@@ -1021,8 +1280,8 @@ export async function syncFilesRound(options) {
1021
1280
  *
1022
1281
  * @param options - The declarations, the bindings, and what reads, writes and remembers
1023
1282
  * @returns What it did, per mapping
1024
- * @throws {FilesSyncError} When a mapping's source is not bound, before
1025
- * anything is read
1283
+ * @throws {FilesSyncError} When a mapping's source is not bound, or a
1284
+ * deliveries mapping has no deliveries to read, before anything is read
1026
1285
  * @throws {Error} When a target named is not one a declaration fills
1027
1286
  */
1028
1287
  export async function syncFiles(options) {