@elaraai/e3-api-server 1.0.97 → 1.0.98

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 (58) hide show
  1. package/README.md +57 -4
  2. package/dist/src/handlers/dataflow.d.ts +9 -1
  3. package/dist/src/handlers/dataflow.d.ts.map +1 -1
  4. package/dist/src/handlers/dataflow.js +19 -4
  5. package/dist/src/handlers/dataflow.js.map +1 -1
  6. package/dist/src/handlers/dataset-batches.d.ts +203 -0
  7. package/dist/src/handlers/dataset-batches.d.ts.map +1 -0
  8. package/dist/src/handlers/dataset-batches.js +442 -0
  9. package/dist/src/handlers/dataset-batches.js.map +1 -0
  10. package/dist/src/handlers/dataset-place.d.ts +104 -0
  11. package/dist/src/handlers/dataset-place.d.ts.map +1 -0
  12. package/dist/src/handlers/dataset-place.js +282 -0
  13. package/dist/src/handlers/dataset-place.js.map +1 -0
  14. package/dist/src/handlers/dataset-reads.d.ts +205 -0
  15. package/dist/src/handlers/dataset-reads.d.ts.map +1 -0
  16. package/dist/src/handlers/dataset-reads.js +350 -0
  17. package/dist/src/handlers/dataset-reads.js.map +1 -0
  18. package/dist/src/handlers/datasets.d.ts +19 -30
  19. package/dist/src/handlers/datasets.d.ts.map +1 -1
  20. package/dist/src/handlers/datasets.js +84 -549
  21. package/dist/src/handlers/datasets.js.map +1 -1
  22. package/dist/src/handlers/datasets.spec.js +968 -14
  23. package/dist/src/handlers/datasets.spec.js.map +1 -1
  24. package/dist/src/handlers/index.d.ts +5 -1
  25. package/dist/src/handlers/index.d.ts.map +1 -1
  26. package/dist/src/handlers/index.js +4 -1
  27. package/dist/src/handlers/index.js.map +1 -1
  28. package/dist/src/handlers/key-search.d.ts +102 -0
  29. package/dist/src/handlers/key-search.d.ts.map +1 -0
  30. package/dist/src/handlers/key-search.js +351 -0
  31. package/dist/src/handlers/key-search.js.map +1 -0
  32. package/dist/src/handlers/segments.d.ts +124 -0
  33. package/dist/src/handlers/segments.d.ts.map +1 -0
  34. package/dist/src/handlers/segments.js +278 -0
  35. package/dist/src/handlers/segments.js.map +1 -0
  36. package/dist/src/handlers/workspaces.spec.js +1 -0
  37. package/dist/src/handlers/workspaces.spec.js.map +1 -1
  38. package/dist/src/portable.spec.js +3 -2
  39. package/dist/src/portable.spec.js.map +1 -1
  40. package/dist/src/routes/dataset-path.d.ts +16 -0
  41. package/dist/src/routes/dataset-path.d.ts.map +1 -1
  42. package/dist/src/routes/dataset-path.js +18 -0
  43. package/dist/src/routes/dataset-path.js.map +1 -1
  44. package/dist/src/routes/datasets.d.ts.map +1 -1
  45. package/dist/src/routes/datasets.js +228 -2
  46. package/dist/src/routes/datasets.js.map +1 -1
  47. package/dist/src/routes/executions.js +1 -1
  48. package/dist/src/routes/executions.js.map +1 -1
  49. package/dist/src/routes/transfer.d.ts.map +1 -1
  50. package/dist/src/routes/transfer.js +11 -5
  51. package/dist/src/routes/transfer.js.map +1 -1
  52. package/dist/src/stopping-run.d.ts +24 -3
  53. package/dist/src/stopping-run.d.ts.map +1 -1
  54. package/dist/src/stopping-run.js +29 -7
  55. package/dist/src/stopping-run.js.map +1 -1
  56. package/dist/src/stopping-run.spec.js +30 -1
  57. package/dist/src/stopping-run.spec.js.map +1 -1
  58. package/package.json +5 -5
@@ -4,16 +4,17 @@
4
4
  */
5
5
  import { describe, it } from 'node:test';
6
6
  import assert from 'node:assert/strict';
7
- import { ArrayType, DictType, IntegerType, NullType, RUN_MAX_BYTES, SetType, SortedMap, StringType, StructType, compareFor, decodeBeast2For, encodeBeast2For, encodeBeast2PagedFor, equalFor, none, some, toEastTypeValue, variant, } from '@elaraai/east';
8
- import { computeHash, datasetWrite, InMemoryTransferBackend, writeRecordState } from '@elaraai/e3-core';
7
+ import { ArrayType, DictType, IntegerType, NullType, OptionType, RUN_MAX_BYTES, SetType, SortedMap, StringType, StructType, compareFor, decodeBeast2For, encodeBeast2For, encodeBeast2PagedFor, equalFor, none, printFor, some, toEastTypeValue, variant, } from '@elaraai/east';
8
+ import { computeHash, datasetWrite, InMemoryTransferBackend, readRecordState, writeRecordState } from '@elaraai/e3-core';
9
9
  import { InMemoryStorage, encodeInSegmentsOf, storeSegmentsOf } from '@elaraai/e3-core/test';
10
- import { BEAST2_CONTENT_TYPE, PackageObjectType, RecordIndexObjectType, WorkspaceRecordType, decodeCollectionManifest, indexCollectionType, indexWindowType, } from '@elaraai/e3-types';
10
+ import { BEAST2_CONTENT_TYPE, E3_RELEASE, PackageObjectType, RecordIndexObjectType, TRANSFER_PROTOCOL_VERSION, WorkspaceRecordType, datasetRowsType, decodeCollectionManifest, encodeCollectionManifest, indexCollectionType, indexWindowType, } from '@elaraai/e3-types';
11
11
  import { Hono } from 'hono';
12
- import { ResponseType } from '../types.js';
12
+ import { ResponseType, TransferUploadRequestType, TransferUploadResponseType } from '../types.js';
13
13
  import { createDatasetRoutes } from '../routes/datasets.js';
14
+ import { createTransferRoutes } from '../routes/transfer.js';
14
15
  import { findDatasetKey, getDataset, setDataset } from './datasets.js';
15
- // The page handlers through the handlers entry, as a host reaches them.
16
- import { getDatasetPage, getValuePage } from './index.js';
16
+ // The page and batch handlers through the handlers entry, as a host reaches them.
17
+ import { DATASET_BATCH_BODY_MAX, decodedSegmentStats, findDatasetKeys, getDatasetPage, getDatasetRows, getDatasetRuns, getValuePage, placeDatasetRuns, withinDatasetRuns, } from './index.js';
17
18
  /**
18
19
  * ~`byteLength` bytes of high-entropy ASCII, deterministic across runs.
19
20
  *
@@ -511,19 +512,23 @@ describe('findDatasetKey', () => {
511
512
  assert.deepEqual(await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { prefix: 'k9' })), { found: false, row: 2500, count: 0 });
512
513
  assert.deepEqual(await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { prefix: '' })), { found: true, row: 0, count: 2500 });
513
514
  });
514
- it('decodes at most the touched segments: one for exact, two for a spanning prefix', async () => {
515
+ it('decodes at most the touched segments — one for exact, two for a spanning prefix — and keeps them', async () => {
515
516
  const storage = new InMemoryStorage();
516
517
  const blob = encodeInSegmentsOf(LookupType, 97)(lookupOf(2500));
517
518
  const hash = await seedDataset(storage, blob, 'lookup', LookupType);
518
- // Warm the cache of opened datasets, then count reads: the fences come
519
- // with the manifest, and each segment decode is one read of its object.
520
- await findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k0150"' });
521
- await findDatasetKey(storage, REPO, WS, lookupPath, { prefix: 'k01' });
519
+ // The fences come with the manifest, so a bisect reads nothing, and each
520
+ // segment decode is one read of its object.
522
521
  const spy = spyObjectReads(storage, await segmentsOf(storage, hash));
523
522
  assert.deepEqual(await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k0150"' })), { found: true, row: 150, count: 1 });
524
- assert.equal(spy.wholeReads(), 1, 'an exact find decodes exactly one segment');
523
+ assert.equal(spy.wholeReads(), 1, 'an exact find decodes exactly one segment: rows 97..193');
524
+ // k01__ is rows 100..199: its lower bound is in the segment the key was,
525
+ // which is kept, and its upper bound in the next, rows 194..290.
525
526
  assert.deepEqual(await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { prefix: 'k01' })), { found: true, row: 100, count: 100 });
526
- assert.equal(spy.wholeReads(), 3, 'a boundary-spanning prefix decodes exactly the two edge segments');
527
+ assert.equal(spy.wholeReads(), 2, 'a boundary-spanning prefix decodes the edge segment not yet kept');
528
+ // Asked again, both answer from the kept segments.
529
+ await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k0150"' }));
530
+ await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { prefix: 'k01' }));
531
+ assert.equal(spy.wholeReads(), 2, 'a segment decoded once is never read again while it is kept');
527
532
  });
528
533
  it('scalar keys parse as .east literals; bad literals are key_parse_error', async () => {
529
534
  const storage = new InMemoryStorage();
@@ -686,6 +691,7 @@ async function seedIndexedRecord(storage, n) {
686
691
  keyIr: '0'.repeat(64), multi: false, valueIr: some('0'.repeat(64)),
687
692
  keyType: toEastTypeValue(IntegerType), valueType: toEastTypeValue(StringType),
688
693
  buildIr: '0'.repeat(64), runner: variant('east_node', { platforms: [], decode: variant('lazy', null) }),
694
+ form: variant('entries', null),
689
695
  }));
690
696
  const StatusEntryType = StructType({ ik: PlanStatusKeyType, k: StringType });
691
697
  const statusEntries = new SortedMap([...rows].map(([k, row]) => [
@@ -696,6 +702,7 @@ async function seedIndexedRecord(storage, n) {
696
702
  keyIr: '0'.repeat(64), multi: false, valueIr: some('0'.repeat(64)),
697
703
  keyType: toEastTypeValue(PlanStatusKeyType), valueType: toEastTypeValue(StringType),
698
704
  buildIr: '0'.repeat(64), runner: variant('east_node', { platforms: [], decode: variant('lazy', null) }),
705
+ form: variant('entries', null),
699
706
  }));
700
707
  const state = await writeRecordState(storage, REPO, {
701
708
  primary, indexes: new Map([
@@ -719,7 +726,13 @@ async function seedIndexedRecord(storage, n) {
719
726
  })));
720
727
  await storage.datasets.write(REPO, WS, 'records/plans', variant('value', { hash: state, versions: new Map() }));
721
728
  const manifest = decodeCollectionManifest(await storage.objects.read(REPO, primary));
722
- return { rows, primarySegments: manifest.entries.map((entry) => entry.hash), statusSegments: await segmentsOf(storage, statusIndex) };
729
+ return {
730
+ rows,
731
+ primary,
732
+ primarySegments: manifest.entries.map((entry) => entry.hash),
733
+ statusSegments: await segmentsOf(storage, statusIndex),
734
+ dueSegments: await segmentsOf(storage, index),
735
+ };
723
736
  }
724
737
  describe('getDatasetPage (index reads)', () => {
725
738
  it('a joined page reads each primary segment it needs once, and serves the window whole', async () => {
@@ -773,6 +786,124 @@ describe('getDatasetPage (index reads)', () => {
773
786
  assert.deepEqual(touched, [], 'a covering read is the index alone');
774
787
  });
775
788
  });
789
+ /** A summary index's key (#1039): a week, then a press. */
790
+ const PressWeekType = StructType({ __tile: IntegerType, press: StringType });
791
+ /** Its entries' keys: each stands for every row of its key, so names none. */
792
+ const PressWeekEntryType = StructType({ ik: PressWeekType, k: NullType });
793
+ /** Its totals. */
794
+ const TotalsType = StructType({ count: IntegerType, ms: IntegerType });
795
+ describe('a summary index (#1039)', () => {
796
+ /**
797
+ * The `plans` record of `seedIndexedRecord`, with a summary beside its
798
+ * indexes: `presses` presses by `weeks` weeks, each total its own count and
799
+ * milliseconds. Its entries are `{ik, k: Null}`: one stands for many rows.
800
+ */
801
+ async function seedSummary(storage, presses, weeks) {
802
+ await seedIndexedRecord(storage, 300);
803
+ const ref = await storage.datasets.read(REPO, WS, 'records/plans');
804
+ assert.ok(ref?.type === 'value');
805
+ const totals = new SortedMap(undefined, compareFor(PressWeekEntryType));
806
+ for (let week = 0; week < weeks; week++) {
807
+ for (let p = 0; p < presses; p++) {
808
+ totals.set({ ik: { __tile: BigInt(week), press: `P-${String(p).padStart(4, '0')}` }, k: null }, { count: BigInt(week + p + 1), ms: BigInt((week + p) * 1000) });
809
+ }
810
+ }
811
+ const manifest = await datasetWrite(storage, REPO, totals, indexCollectionType(NullType, PressWeekType, TotalsType));
812
+ const summary = await storage.objects.write(REPO, encodeBeast2For(RecordIndexObjectType)({
813
+ keyIr: '0'.repeat(64), multi: true, valueIr: none,
814
+ keyType: toEastTypeValue(PressWeekType), valueType: toEastTypeValue(TotalsType),
815
+ buildIr: '0'.repeat(64), runner: variant('east_node', { platforms: [], decode: variant('lazy', null) }),
816
+ form: variant('summary', { mergeIr: '1'.repeat(64) }),
817
+ }));
818
+ const held = await readRecordState(storage, REPO, ref.value.hash);
819
+ const state = await writeRecordState(storage, REPO, {
820
+ primary: held.primary, indexes: new Map([...held.indexes, ['by_press_week', { manifest, index: summary }]]),
821
+ });
822
+ await storage.datasets.write(REPO, WS, 'records/plans', variant('value', { hash: state, versions: new Map() }));
823
+ return totals;
824
+ }
825
+ /** A summary's window, as e3 answers it: `indexWindowType` with a Null `key`. */
826
+ const SummaryWindowType = ArrayType(StructType({ ik: PressWeekType, key: NullType, value: TotalsType, row: OptionType(PlanRowType) }));
827
+ const decodeSummaryWindow = decodeBeast2For(SummaryWindowType);
828
+ it('pages its totals as an index page, each entry naming no row, and answers a block\'s search and its runs', async () => {
829
+ const storage = new InMemoryStorage();
830
+ const totals = await seedSummary(storage, 50, 12);
831
+ const state = await stateOf(storage);
832
+ const page = await getDatasetPage(storage, REPO, WS, plansPath, { offset: 0, limit: 600, index: 'by_press_week' });
833
+ assert.equal(page.status, 200, await page.clone().text());
834
+ const window = decodeSummaryWindow(new Uint8Array(await page.arrayBuffer()));
835
+ assert.equal(window.length, 600);
836
+ const unjoined = equalFor(OptionType(PlanRowType));
837
+ for (const [i, [entry, value]] of [...totals].entries()) {
838
+ const read = window[i];
839
+ assert.ok(equalFor(PressWeekType)(read.ik, entry.ik) && equalFor(TotalsType)(read.value, value), `total ${i}`);
840
+ assert.ok(equalFor(NullType)(read.key, null), 'a summary\'s entry names no row');
841
+ assert.ok(unjoined(read.row, none));
842
+ }
843
+ // A block: week 3's presses P-0010 to P-0019, one contiguous run of the summary.
844
+ const { results } = await batchJson(await findDatasetKeys(storage, REPO, WS, plansPath, {
845
+ queries: [{ from: ['3', '"P-0010"'], to: ['3', '"P-0020"'] }], index: 'by_press_week', hash: state,
846
+ }));
847
+ assert.deepEqual(results, [{ found: true, row: 3 * 50 + 10, count: 10 }]);
848
+ const runs = await getDatasetRuns(storage, REPO, WS, plansPath, { runs: [[results[0].row, results[0].count]], hash: state, index: 'by_press_week' });
849
+ assert.equal(runs.status, 200, await runs.clone().text());
850
+ const block = decodeSummaryWindow(new Uint8Array(await runs.arrayBuffer()));
851
+ assert.deepEqual(block.map((entry) => entry.ik.press), Array.from({ length: 10 }, (_, i) => `P-${String(10 + i).padStart(4, '0')}`));
852
+ assert.ok(block.every((entry) => equalFor(IntegerType)(entry.ik.__tile, 3n)), 'all in week 3');
853
+ });
854
+ it('refuses a joined read of it, a page or runs, naming it: its entries name no row to join', async () => {
855
+ const storage = new InMemoryStorage();
856
+ await seedSummary(storage, 10, 4);
857
+ const state = await stateOf(storage);
858
+ for (const response of [
859
+ await getDatasetPage(storage, REPO, WS, plansPath, { offset: 0, limit: 10, index: 'by_press_week', join: true }),
860
+ await getDatasetRuns(storage, REPO, WS, plansPath, { runs: [[0, 5]], hash: state, index: 'by_press_week', join: true }),
861
+ ]) {
862
+ const refused = await refusalOf(response);
863
+ assert.deepEqual([refused.status, refused.type], [400, 'bad_request']);
864
+ assert.match(refused.message, /^index 'by_press_week' of 'records\/plans' is a summary: each entry stands for every row of its key and names none to join — read it without join$/);
865
+ }
866
+ // The record's other indexes still join.
867
+ assert.equal((await getDatasetPage(storage, REPO, WS, plansPath, { offset: 0, limit: 10, index: 'by_due', join: true })).status, 200);
868
+ });
869
+ it('refuses a read of a Dict\'s rows by its runs, naming it: its entries name no key to read the rows of', async () => {
870
+ const storage = new InMemoryStorage();
871
+ await seedSummary(storage, 10, 4);
872
+ const state = await stateOf(storage);
873
+ const refused = await refusalOf(await getDatasetRows(storage, REPO, WS, plansPath, { keysOf: { path: plansPath, index: 'by_press_week', runs: [[0, 5]], hash: state } }));
874
+ assert.deepEqual([refused.status, refused.type], [400, 'bad_request']);
875
+ assert.match(refused.message, /^index 'by_press_week' of 'records\/plans' is a summary: each entry stands for every row of its key and names none to read the rows of$/);
876
+ });
877
+ it('refuses a placement of runs of it, naming it: its entries name no row to place in a record segment', async () => {
878
+ // `placeDatasetRuns` places each entry's `k` by the record's fences; a
879
+ // summary's `k` is Null, so a placement of it places nothing of a row.
880
+ const storage = new InMemoryStorage();
881
+ await seedSummary(storage, 10, 4);
882
+ const state = await stateOf(storage);
883
+ const response = await placeDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_press_week', runs: [[0, 5]], hash: state });
884
+ const body = await response.clone().text();
885
+ assert.equal(response.status, 400, `a placement of a summary's entries is refused, never answered: got ${response.status} ${body}`);
886
+ const refused = await refusalOf(response);
887
+ assert.equal(refused.type, 'bad_request');
888
+ assert.match(refused.message, /^index 'by_press_week' of 'records\/plans' is a summary: each entry stands for every row of its key and names none to place in a record segment$/);
889
+ });
890
+ it('refuses a membership read of its runs, naming it: its entries name no row whose membership to answer', async () => {
891
+ // A membership read answers which of a record's rows a narrowing holds; a
892
+ // summary's entry stands for many rows and names none, so an answer of it
893
+ // says nothing of a row.
894
+ const storage = new InMemoryStorage();
895
+ await seedSummary(storage, 10, 4);
896
+ const state = await stateOf(storage);
897
+ const response = await withinDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_press_week', runs: [[0, 5]], keys: ['(ik=(__tile=0, press="P-0002"), k=null)'], hash: state });
898
+ const body = await response.clone().text();
899
+ assert.equal(response.status, 400, `a membership read of a summary's entries is refused, never answered: got ${response.status} ${body}`);
900
+ const refused = await refusalOf(response);
901
+ assert.equal(refused.type, 'bad_request');
902
+ assert.match(refused.message, /^index 'by_press_week' of 'records\/plans' is a summary: each entry stands for every row of its key and names none to answer whether a narrowing holds it$/);
903
+ // The record's other indexes still answer both.
904
+ assert.equal((await placeDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_due', runs: [[0, 5]], hash: state })).status, 200);
905
+ });
906
+ });
776
907
  describe('findDatasetKey (through an index)', () => {
777
908
  it('takes the index key: an exact key is every entry under it, and a prefix or leading fields a run of them', async () => {
778
909
  const storage = new InMemoryStorage();
@@ -852,4 +983,827 @@ describe('who may keep an answer pinned to a hash', () => {
852
983
  }
853
984
  });
854
985
  });
986
+ /** Counts whole-object reads of each watched object, by its hash. */
987
+ function spyReadsByObject(storage, watched) {
988
+ const objects = storage.objects;
989
+ const hashes = new Set(watched);
990
+ const reads = new Map();
991
+ const read = objects.read.bind(objects);
992
+ objects.read = (repo, hash) => {
993
+ if (hashes.has(hash))
994
+ reads.set(hash, (reads.get(hash) ?? 0) + 1);
995
+ return read(repo, hash);
996
+ };
997
+ return {
998
+ reads,
999
+ total: () => [...reads.values()].reduce((sum, n) => sum + n, 0),
1000
+ restore: () => { objects.read = read; },
1001
+ };
1002
+ }
1003
+ /** A batch's JSON answer, asserting it is a 200. */
1004
+ async function batchJson(response) {
1005
+ assert.equal(response.status, 200, `batch failed: ${await response.clone().text()}`);
1006
+ return await response.json();
1007
+ }
1008
+ /** A refusal's status, its JSON error and the content hash it names. */
1009
+ async function refusalOf(response) {
1010
+ const { error } = await response.json();
1011
+ return { status: response.status, type: error.type, message: error.message, sha: response.headers.get('X-Content-SHA256') };
1012
+ }
1013
+ /** The `by_status` index window, as e3 answers it. */
1014
+ const decodeStatusWindow = decodeBeast2For(indexWindowType(StringType, PlanStatusKeyType, StringType, PlanRowType));
1015
+ const StatusWindowType = indexWindowType(StringType, PlanStatusKeyType, StringType, PlanRowType);
1016
+ /** The state hash an indexed record's dataset holds. */
1017
+ async function stateOf(storage) {
1018
+ const state = await storage.datasets.read(REPO, WS, 'records/plans');
1019
+ assert.ok(state?.type === 'value');
1020
+ return state.value.hash;
1021
+ }
1022
+ describe('findDatasetKeys (several key searches in one request)', () => {
1023
+ it('answers each query as findDatasetKey does, in the order asked, at one hash', async () => {
1024
+ const storage = new InMemoryStorage();
1025
+ await seedIndexedRecord(storage, 12_000);
1026
+ const state = await stateOf(storage);
1027
+ const byStatus = [
1028
+ { key: '(status="late", week=3)' },
1029
+ { key: '(status="late", week=12)' },
1030
+ { fields: ['"late"'] },
1031
+ { fields: ['"late"', '3'] },
1032
+ { prefix: 'l' },
1033
+ { prefix: 'z' },
1034
+ { from: ['"late"', '3'], to: ['"late"', '5'] },
1035
+ { from: ['"open"'] },
1036
+ { to: ['"done"', '2'] },
1037
+ { key: '(status="late", week=3)' },
1038
+ ];
1039
+ const answer = await batchJson(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: byStatus, index: 'by_status', hash: state }));
1040
+ const expected = [];
1041
+ for (const query of byStatus)
1042
+ expected.push(await findJson(await findDatasetKey(storage, REPO, WS, plansPath, { ...query, index: 'by_status' })));
1043
+ assert.deepEqual(answer.results, expected);
1044
+ assert.deepEqual(answer.results[0], { found: true, row: 5200, count: 400 }, 'a key through an index is every entry under it');
1045
+ // The record's own keys: a key, a miss between keys, a prefix and a range.
1046
+ const byKey = [{ key: '"p-000042"' }, { key: '"p-000042x"' }, { prefix: 'p-0001' }, { from: ['"p-000100"'], to: ['"p-000110"'] }];
1047
+ const own = await findDatasetKeys(storage, REPO, WS, plansPath, { queries: byKey });
1048
+ assert.equal(own.headers.get('X-Content-SHA256'), state);
1049
+ assert.equal(own.headers.get('Cache-Control'), 'no-store', 'a POST is no cache\'s to keep');
1050
+ const ownExpected = [];
1051
+ for (const query of byKey)
1052
+ ownExpected.push(await findJson(await findDatasetKey(storage, REPO, WS, plansPath, query)));
1053
+ assert.deepEqual((await batchJson(own)).results, ownExpected);
1054
+ assert.deepEqual(ownExpected[1], { found: false, row: 43, count: 0 }, 'a miss answers its insertion row');
1055
+ });
1056
+ it('reads each segment its searches land in once, however many land in it', async () => {
1057
+ const storage = new InMemoryStorage();
1058
+ const { statusSegments } = await seedIndexedRecord(storage, 12_000);
1059
+ const spy = spyReadsByObject(storage, statusSegments);
1060
+ // Fifty searches, two bounds each, inside `late`'s weeks 3 and 4.
1061
+ const queries = Array.from({ length: 50 }, (_, i) => ({ from: ['"late"', '3', `"p-${String(i * 7).padStart(6, '0')}"`], to: ['"late"', '4'] }));
1062
+ try {
1063
+ const { results } = await batchJson(await findDatasetKeys(storage, REPO, WS, plansPath, { queries, index: 'by_status' }));
1064
+ assert.equal(results.length, 50);
1065
+ assert.ok(results.every((result) => result.found), 'every search names a run of `late` week 3');
1066
+ assert.deepEqual([...spy.reads.values()].filter((n) => n !== 1), [], 'every segment touched is read exactly once');
1067
+ assert.ok(spy.total() > 0 && spy.total() <= 3, `a hundred bounds in two weeks' entries read the few segments they lie in, read ${spy.total()}`);
1068
+ const before = spy.total();
1069
+ await batchJson(await findDatasetKeys(storage, REPO, WS, plansPath, { queries, index: 'by_status' }));
1070
+ assert.equal(spy.total(), before, 'asked again, the batch reads nothing: its segments are kept');
1071
+ }
1072
+ finally {
1073
+ spy.restore();
1074
+ }
1075
+ });
1076
+ it('refuses more than 10,000 queries, a query a single search refuses — naming its place — and a stale pin', async () => {
1077
+ const storage = new InMemoryStorage();
1078
+ await seedIndexedRecord(storage, 300);
1079
+ const state = await stateOf(storage);
1080
+ const many = await refusalOf(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: Array.from({ length: 10_001 }, () => ({ key: '"p-000001"' })) }));
1081
+ assert.deepEqual([many.status, many.type], [400, 'bad_request']);
1082
+ assert.match(many.message, /at most 10000 queries; this one has 10001/);
1083
+ const intPrefix = await refusalOf(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: [{ key: '(status="late", week=3)' }, { fields: ['"late"'], prefix: '3' }], index: 'by_status' }));
1084
+ assert.deepEqual([intPrefix.status, intPrefix.type], [400, 'bad_request']);
1085
+ assert.match(intPrefix.message, /^query 1: prefix continues key field 'week', which is Integer, not String/);
1086
+ const badLiteral = await refusalOf(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: [{ key: 'p-1' }] }));
1087
+ assert.deepEqual([badLiteral.status, badLiteral.type], [400, 'key_parse_error']);
1088
+ assert.match(badLiteral.message, /^query 0: /);
1089
+ const stale = await refusalOf(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: [{ key: '"p-000001"' }], hash: '0'.repeat(64) }));
1090
+ assert.deepEqual([stale.status, stale.type, stale.sha], [409, 'dataset_hash_mismatch', state]);
1091
+ const missing = await refusalOf(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: [], index: 'nope' }));
1092
+ assert.deepEqual([missing.status, missing.type], [404, 'index_not_found']);
1093
+ assert.deepEqual(await batchJson(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: [] })), { results: [] });
1094
+ });
1095
+ });
1096
+ const decodeRows = decodeBeast2For(datasetRowsType(StringType, PlanRowType));
1097
+ const OptionRowType = OptionType(PlanRowType);
1098
+ describe('getDatasetRows (the rows of several keys in one request)', () => {
1099
+ it('answers each key\'s row, or its absence, and its position as a search and a one-row page give them', async () => {
1100
+ const storage = new InMemoryStorage();
1101
+ const { rows } = await seedIndexedRecord(storage, 3000);
1102
+ const state = await stateOf(storage);
1103
+ const keys = ['p-002999', 'p-000000', 'p-001500x', 'p-001234', 'a', 'z', 'p-001234', 'p-000097'];
1104
+ const response = await getDatasetRows(storage, REPO, WS, plansPath, { keys: keys.map((key) => printKey(key)), hash: state });
1105
+ assert.equal(response.status, 200, await response.clone().text());
1106
+ assert.equal(response.headers.get('X-Content-SHA256'), state);
1107
+ assert.equal(response.headers.get('X-Page-Count'), String(keys.length));
1108
+ assert.equal(response.headers.get('X-Total-Elements'), '3000');
1109
+ const answers = decodeRows(new Uint8Array(await response.arrayBuffer()));
1110
+ assert.equal(answers.length, keys.length);
1111
+ for (const [i, key] of keys.entries()) {
1112
+ const found = await findJson(await findDatasetKey(storage, REPO, WS, plansPath, { key: printKey(key) }));
1113
+ const answer = answers[i];
1114
+ assert.equal(answer.key, key, `key ${i} answers the key asked`);
1115
+ assert.equal(answer.position, BigInt(found.row), `key ${i}'s position is a search's row`);
1116
+ if (!found.found) {
1117
+ assert.ok(equalFor(OptionRowType)(answer.row, none), `key ${i} is absent`);
1118
+ continue;
1119
+ }
1120
+ const page = await getDatasetPage(storage, REPO, WS, plansPath, { offset: found.row, limit: 1 });
1121
+ const held = [...decodeBeast2For(PlansType)(new Uint8Array(await page.arrayBuffer()))];
1122
+ assert.ok(equalFor(OptionRowType)(answer.row, some(held[0][1])), `key ${i}'s row is a one-row page's`);
1123
+ assert.ok(equalFor(OptionRowType)(answer.row, some(rows.get(key))));
1124
+ }
1125
+ });
1126
+ it('reads each segment its keys lie in once', async () => {
1127
+ const storage = new InMemoryStorage();
1128
+ const { primary, primarySegments } = await seedIndexedRecord(storage, 12_000);
1129
+ const keys = Array.from({ length: 400 }, (_, i) => `p-${String((i * 6007) % 12_000).padStart(6, '0')}`);
1130
+ const cumulative = [];
1131
+ let sum = 0;
1132
+ for (const entry of decodeCollectionManifest(await storage.objects.read(REPO, primary)).entries) {
1133
+ sum += Number(entry.count);
1134
+ cumulative.push(sum);
1135
+ }
1136
+ const spy = spyReadsByObject(storage, primarySegments);
1137
+ try {
1138
+ const response = await getDatasetRows(storage, REPO, WS, plansPath, { keys: keys.map((key) => printKey(key)) });
1139
+ const answers = decodeRows(new Uint8Array(await response.arrayBuffer()));
1140
+ assert.ok(answers.every((answer) => answer.row.type === 'some'), 'every key is held');
1141
+ const holding = new Set();
1142
+ for (const answer of answers)
1143
+ holding.add(cumulative.findIndex((end) => Number(answer.position) < end));
1144
+ assert.deepEqual([...spy.reads.values()].filter((n) => n !== 1), [], 'every segment touched is read exactly once');
1145
+ assert.equal(spy.total(), holding.size, 'the keys read exactly the segments holding them');
1146
+ }
1147
+ finally {
1148
+ spy.restore();
1149
+ }
1150
+ });
1151
+ it('holds the answer to the byte budget, answering the keys it reached in order', async () => {
1152
+ const storage = new InMemoryStorage();
1153
+ await seedIndexedRecord(storage, 300);
1154
+ const response = await getDatasetRows(storage, REPO, WS, plansPath, { keys: ['"p-000010"', '"p-000020"', '"p-000030"'] }, { byteBudget: 1 });
1155
+ assert.equal(response.status, 200, await response.clone().text());
1156
+ assert.equal(response.headers.get('X-Page-Count'), '1');
1157
+ const answers = decodeRows(new Uint8Array(await response.arrayBuffer()));
1158
+ assert.deepEqual(answers.map((answer) => answer.key), ['p-000010'], 'the first key, the one the budget reached');
1159
+ });
1160
+ it('refuses more than 10,000 keys, a key that is no literal of the key type — naming its place — another kind of dataset, and a stale pin', async () => {
1161
+ const storage = new InMemoryStorage();
1162
+ await seedIndexedRecord(storage, 300);
1163
+ const state = await stateOf(storage);
1164
+ const many = await refusalOf(await getDatasetRows(storage, REPO, WS, plansPath, { keys: Array.from({ length: 10_001 }, () => '"p"') }));
1165
+ assert.deepEqual([many.status, many.type], [400, 'bad_request']);
1166
+ const bad = await refusalOf(await getDatasetRows(storage, REPO, WS, plansPath, { keys: ['"p-000001"', 'p-000002'] }));
1167
+ assert.deepEqual([bad.status, bad.type], [400, 'key_parse_error']);
1168
+ assert.match(bad.message, /^key 1: /);
1169
+ const stale = await refusalOf(await getDatasetRows(storage, REPO, WS, plansPath, { keys: ['"p-000001"'], hash: '0'.repeat(64) }));
1170
+ assert.deepEqual([stale.status, stale.type, stale.sha], [409, 'dataset_hash_mismatch', state]);
1171
+ const arrays = new InMemoryStorage();
1172
+ await seedDataset(arrays, encodeInSegmentsOf(RowsType, 100)(makeRows(50)), 'rows', RowsType);
1173
+ const notDict = await refusalOf(await getDatasetRows(arrays, REPO, WS, rowsPath, { keys: ['1'] }));
1174
+ assert.deepEqual([notDict.status, notDict.type], [400, 'dataset_not_searchable']);
1175
+ });
1176
+ });
1177
+ const NoteRowType = StructType({ note: StringType });
1178
+ const NotesType = DictType(StringType, NoteRowType);
1179
+ const notesPath = [variant('field', 'inputs'), variant('field', 'notes')];
1180
+ const ranksPath = [variant('field', 'inputs'), variant('field', 'ranks')];
1181
+ const NoteRowsType = datasetRowsType(StringType, NoteRowType);
1182
+ const decodeNoteRows = decodeBeast2For(NoteRowsType);
1183
+ /**
1184
+ * Seeds the plans of {@link seedIndexedRecord} and, beside them in the same
1185
+ * workspace, `inputs.notes` — a note on every third plan, keyed as the plans
1186
+ * are, and a key no plan has — and `inputs.ranks`, a Dict keyed by Integer:
1187
+ * the Dicts a read by the plans' runs reads.
1188
+ */
1189
+ async function seedPlanNotes(storage, n) {
1190
+ const seeded = await seedIndexedRecord(storage, n);
1191
+ const notes = new SortedMap([
1192
+ ...[...seeded.rows.keys()].filter((_, i) => i % 3 === 0).map((key) => [key, { note: `Note on ${key}` }]),
1193
+ ['q-000001', { note: 'on no plan' }],
1194
+ ], compareFor(StringType));
1195
+ const notesHash = await datasetWrite(storage, REPO, notes, NotesType);
1196
+ const ranksHash = await datasetWrite(storage, REPO, new Map([[1n, 'one'], [2n, 'two']]), IntLookupType);
1197
+ const state = await stateOf(storage);
1198
+ const structure = variant('struct', new Map([
1199
+ ['inputs', variant('struct', new Map([
1200
+ ['notes', variant('value', { type: toEastTypeValue(NotesType), writable: true })],
1201
+ ['ranks', variant('value', { type: toEastTypeValue(IntLookupType), writable: true })],
1202
+ ]))],
1203
+ ['records', variant('struct', new Map([
1204
+ ['plans', variant('value', { type: toEastTypeValue(PlansType), writable: false })],
1205
+ ]))],
1206
+ ]));
1207
+ const refs = new Map([
1208
+ ['inputs/notes', variant('value', { hash: notesHash, versions: new Map() })],
1209
+ ['inputs/ranks', variant('value', { hash: ranksHash, versions: new Map() })],
1210
+ ['records/plans', variant('value', { hash: state, versions: new Map() })],
1211
+ ]);
1212
+ const pkgHash = await storage.objects.write(REPO, encodeBeast2For(PackageObjectType)({
1213
+ tasks: new Map(), data: { structure, refs }, functions: new Map(), records: new Map(), sources: new Map(),
1214
+ }));
1215
+ await storage.refs.workspaceWrite(REPO, WS, encodeBeast2For(WorkspaceRecordType)(some({
1216
+ packageName: 'plans', packageVersion: '1.0.0', packageHash: pkgHash, deployedAt: new Date(0), currentRunId: none,
1217
+ })));
1218
+ for (const [path, ref] of refs)
1219
+ await storage.datasets.write(REPO, WS, path, ref);
1220
+ return { ...seeded, notes, notesHash, noteSegments: await segmentsOf(storage, notesHash) };
1221
+ }
1222
+ describe('getDatasetRows by runs (the rows of the keys some runs of a record\'s index name, #1393)', () => {
1223
+ it('answers each entry\'s key, its row or none, and its position, as a read by the keys the runs\' entries name', async () => {
1224
+ const storage = new InMemoryStorage();
1225
+ const { notesHash } = await seedPlanNotes(storage, 12_000);
1226
+ const state = await stateOf(storage);
1227
+ const runs = [[100, 50], [4000, 30], [5199, 2], [11_990, 10]];
1228
+ const response = await getDatasetRows(storage, REPO, WS, notesPath, { keysOf: { path: plansPath, index: 'by_status', runs, hash: state }, hash: notesHash });
1229
+ assert.equal(response.status, 200, await response.clone().text());
1230
+ assert.equal(response.headers.get('X-Content-SHA256'), notesHash, 'the answer is of the Dict pinned');
1231
+ assert.equal(response.headers.get('X-Page-Count'), '92');
1232
+ assert.equal(response.headers.get('X-Run-Entries'), '92');
1233
+ assert.equal(response.headers.get('X-Total-Elements'), '4001', 'the Dict\'s rows');
1234
+ assert.equal(response.headers.get('Cache-Control'), 'no-store', 'a POST is no cache\'s to keep');
1235
+ const read = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_status' });
1236
+ const keys = decodeStatusWindow(new Uint8Array(await read.arrayBuffer())).map((entry) => printKey(entry.key));
1237
+ const byKeys = await getDatasetRows(storage, REPO, WS, notesPath, { keys, hash: notesHash });
1238
+ const answers = decodeNoteRows(new Uint8Array(await response.arrayBuffer()));
1239
+ assert.ok(equalFor(NoteRowsType)(answers, decodeNoteRows(new Uint8Array(await byKeys.arrayBuffer()))), 'as a read by the keys does, in the runs\' order');
1240
+ assert.ok(answers.some((answer) => answer.row.type === 'some') && answers.some((answer) => answer.row.type === 'none'), 'noted plans and plans with none');
1241
+ });
1242
+ it('reads the record itself by its own index\'s runs as a joined read of the runs does', async () => {
1243
+ const storage = new InMemoryStorage();
1244
+ await seedIndexedRecord(storage, 3000);
1245
+ const state = await stateOf(storage);
1246
+ const runs = [[0, 7], [1000, 40], [2990, 10]];
1247
+ const response = await getDatasetRows(storage, REPO, WS, plansPath, { keysOf: { path: plansPath, index: 'by_due', runs, hash: state }, hash: state });
1248
+ assert.equal(response.status, 200, await response.clone().text());
1249
+ const joined = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_due', join: true });
1250
+ const window = decodeBeast2For(DueWindowType)(new Uint8Array(await joined.arrayBuffer()));
1251
+ const answers = decodeRows(new Uint8Array(await response.arrayBuffer()));
1252
+ assert.equal(answers.length, window.length);
1253
+ assert.ok(answers.every((answer, i) => equalFor(OptionRowType)(answer.row, window[i].row)), 'each entry\'s row, as a join fills it');
1254
+ });
1255
+ it('reads each index segment the runs touch once and each segment of the Dict their keys lie in once, and none of the record\'s', async () => {
1256
+ const storage = new InMemoryStorage();
1257
+ const { notesHash, noteSegments, primarySegments, dueSegments } = await seedPlanNotes(storage, 12_000);
1258
+ const state = await stateOf(storage);
1259
+ assert.ok(noteSegments.length > 1, `the notes span segments, got ${noteSegments.length}`);
1260
+ // `by_due` scatters the record: a run's keys land all over the notes.
1261
+ const runs = [[0, 400], [3000, 300], [9000, 600]];
1262
+ const spy = spyReadsByObject(storage, [...primarySegments, ...dueSegments, ...noteSegments]);
1263
+ try {
1264
+ const response = await getDatasetRows(storage, REPO, WS, notesPath, { keysOf: { path: plansPath, index: 'by_due', runs, hash: state }, hash: notesHash });
1265
+ assert.equal(response.status, 200, await response.clone().text());
1266
+ assert.equal(response.headers.get('X-Page-Count'), '1300');
1267
+ assert.deepEqual([...spy.reads.values()].filter((n) => n !== 1), [], 'every segment touched is read exactly once');
1268
+ assert.deepEqual([...spy.reads.keys()].filter((hash) => primarySegments.includes(hash)), [], 'the index names the keys: no record segment is read');
1269
+ assert.ok([...spy.reads.keys()].some((hash) => dueSegments.includes(hash)), 'the runs read the index');
1270
+ assert.ok([...spy.reads.keys()].filter((hash) => noteSegments.includes(hash)).length > 1, 'the keys read the notes they lie in');
1271
+ }
1272
+ finally {
1273
+ spy.restore();
1274
+ }
1275
+ });
1276
+ it('cuts an answer at a page\'s bounds and the byte budget, saying how many it holds of how many, and the rest reads on', async () => {
1277
+ const storage = new InMemoryStorage();
1278
+ const { notesHash } = await seedPlanNotes(storage, 12_000);
1279
+ const state = await stateOf(storage);
1280
+ const keysOf = (runs) => ({ path: plansPath, index: 'by_status', runs, hash: state });
1281
+ const first = await getDatasetRows(storage, REPO, WS, notesPath, { keysOf: keysOf([[0, 6000], [6000, 6000]]), hash: notesHash });
1282
+ assert.equal(first.status, 200, await first.clone().text());
1283
+ assert.equal(first.headers.get('X-Page-Count'), '10000', 'an answer holds a page\'s 10,000 entries at most');
1284
+ assert.equal(first.headers.get('X-Run-Entries'), '12000');
1285
+ const rest = await getDatasetRows(storage, REPO, WS, notesPath, { keysOf: keysOf([[10_000, 2000]]), hash: notesHash });
1286
+ assert.equal(rest.headers.get('X-Page-Count'), '2000', 'and the rest reads on from there');
1287
+ const answers = [...decodeNoteRows(new Uint8Array(await first.arrayBuffer())), ...decodeNoteRows(new Uint8Array(await rest.arrayBuffer()))];
1288
+ assert.equal(answers.filter((answer) => answer.row.type === 'some').length, 4000, 'every plan\'s note, once');
1289
+ const budget = await getDatasetRows(storage, REPO, WS, notesPath, { keysOf: keysOf([[0, 10], [20, 10]]), hash: notesHash }, { byteBudget: 1 });
1290
+ assert.equal(budget.headers.get('X-Page-Count'), '1', 'the byte budget clamps the entries too');
1291
+ assert.equal(budget.headers.get('X-Run-Entries'), '20');
1292
+ });
1293
+ it('refuses more than 10,000 runs, runs not of the index, either pin when stale — each in its own words — an index the record lacks, keys of another type and a dataset that is no Dict', async () => {
1294
+ const storage = new InMemoryStorage();
1295
+ const { notesHash } = await seedPlanNotes(storage, 300);
1296
+ const state = await stateOf(storage);
1297
+ /** A read of a Dict, the notes pinned unless another is named, by the plans' `by_status` runs, as `of` alters them. */
1298
+ const refused = async (of, dict = { path: notesPath, hash: notesHash }) => refusalOf(await getDatasetRows(storage, REPO, WS, dict.path, {
1299
+ keysOf: { path: plansPath, index: 'by_status', runs: [[0, 10]], hash: state, ...of },
1300
+ ...(dict.hash !== undefined && { hash: dict.hash }),
1301
+ }));
1302
+ const many = await refused({ runs: Array.from({ length: 10_001 }, (_, i) => [i, 1]) });
1303
+ assert.deepEqual([many.status, many.type], [400, 'bad_request']);
1304
+ assert.match(many.message, /at most 10000 runs; this one has 10001/);
1305
+ assert.match((await refused({ runs: [[290, 20]] })).message, /run 0 ends at row 310, past the collection's 300 rows/);
1306
+ assert.match((await refused({ runs: [[10, 5], [12, 3]] })).message, /run 1 starts at row 12, before the run before it ends \(15\)/);
1307
+ const staleDict = await refused({}, { path: notesPath, hash: '0'.repeat(64) });
1308
+ assert.deepEqual([staleDict.status, staleDict.type, staleDict.sha], [409, 'dataset_hash_mismatch', notesHash], 'the Dict\'s pin names the Dict\'s content');
1309
+ const staleRuns = await refused({ hash: '0'.repeat(64) });
1310
+ assert.deepEqual([staleRuns.status, staleRuns.type, staleRuns.sha], [409, 'runs_hash_mismatch', state], 'the runs\' pin names the record\'s');
1311
+ assert.match(staleRuns.message, /^Dataset 'records\/plans' content is [0-9a-f]{64}, not 0{64}: the runs are positions at content it no longer holds/);
1312
+ const missing = await refused({ index: 'nope' });
1313
+ assert.deepEqual([missing.status, missing.type], [404, 'index_not_found']);
1314
+ const otherKeys = await refused({}, { path: ranksPath });
1315
+ assert.deepEqual([otherKeys.status, otherKeys.type], [400, 'bad_request']);
1316
+ assert.match(otherKeys.message, /^index 'by_status' of 'records\/plans' names keys of \.String, and this Dict's keys are \.Integer$/, 'each type as East prints it');
1317
+ const arrays = new InMemoryStorage();
1318
+ await seedDataset(arrays, encodeInSegmentsOf(RowsType, 100)(makeRows(50)), 'rows', RowsType);
1319
+ const notDict = await refusalOf(await getDatasetRows(arrays, REPO, WS, rowsPath, { keysOf: { path: plansPath, index: 'by_status', runs: [[0, 1]], hash: state } }));
1320
+ assert.deepEqual([notDict.status, notDict.type], [400, 'dataset_not_searchable']);
1321
+ });
1322
+ });
1323
+ /** A String key's `.east` literal. */
1324
+ function printKey(key) {
1325
+ return JSON.stringify(key);
1326
+ }
1327
+ describe('getDatasetRuns (the entries of several runs in one request)', () => {
1328
+ it('answers each run\'s entries through an index as by-offset index pages give them, joined or not', async () => {
1329
+ const storage = new InMemoryStorage();
1330
+ await seedIndexedRecord(storage, 12_000);
1331
+ const state = await stateOf(storage);
1332
+ const runs = [[100, 50], [4000, 30], [5199, 2], [11_990, 10]];
1333
+ for (const join of [false, true]) {
1334
+ const response = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_status', join });
1335
+ assert.equal(response.status, 200, await response.clone().text());
1336
+ assert.equal(response.headers.get('X-Page-Count'), '92');
1337
+ assert.equal(response.headers.get('X-Run-Entries'), '92');
1338
+ assert.equal(response.headers.get('X-Window-Index'), 'by_status');
1339
+ assert.equal(response.headers.get('X-Window-Joined'), join ? 'true' : null);
1340
+ const window = decodeStatusWindow(new Uint8Array(await response.arrayBuffer()));
1341
+ const expected = [];
1342
+ for (const [offset, limit] of runs) {
1343
+ const page = await getDatasetPage(storage, REPO, WS, plansPath, { offset, limit, index: 'by_status', join });
1344
+ expected.push(...decodeStatusWindow(new Uint8Array(await page.arrayBuffer())));
1345
+ }
1346
+ assert.ok(equalFor(StatusWindowType)(window, expected), `the runs' entries, in order (join ${join})`);
1347
+ }
1348
+ });
1349
+ it('reads each segment the runs touch once, and each record segment a join needs once', async () => {
1350
+ const storage = new InMemoryStorage();
1351
+ const { primarySegments, dueSegments } = await seedIndexedRecord(storage, 12_000);
1352
+ const state = await stateOf(storage);
1353
+ // `by_due` scatters the record: a run's keys land all over it.
1354
+ const runs = [[0, 400], [3000, 300], [9000, 600]];
1355
+ const spy = spyReadsByObject(storage, [...primarySegments, ...dueSegments]);
1356
+ try {
1357
+ const response = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_due', join: true });
1358
+ assert.equal(response.status, 200, await response.clone().text());
1359
+ assert.equal(response.headers.get('X-Page-Count'), '1300');
1360
+ assert.deepEqual([...spy.reads.values()].filter((n) => n !== 1), [], 'every segment touched is read exactly once');
1361
+ assert.ok([...spy.reads.keys()].some((hash) => primarySegments.includes(hash)), 'the join reads the record');
1362
+ assert.ok([...spy.reads.keys()].some((hash) => dueSegments.includes(hash)), 'the runs read the index');
1363
+ }
1364
+ finally {
1365
+ spy.restore();
1366
+ }
1367
+ });
1368
+ it('answers runs of the dataset\'s own rows as a value of its type, holding exactly those rows', async () => {
1369
+ const storage = new InMemoryStorage();
1370
+ const { rows } = await seedIndexedRecord(storage, 3000);
1371
+ const state = await stateOf(storage);
1372
+ const runs = [[0, 3], [96, 4], [2990, 10]];
1373
+ const response = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state });
1374
+ assert.equal(response.status, 200, await response.clone().text());
1375
+ assert.equal(response.headers.get('X-Window-Index'), null);
1376
+ const value = decodeBeast2For(PlansType)(new Uint8Array(await response.arrayBuffer()));
1377
+ const all = [...rows];
1378
+ const expected = new SortedMap(runs.flatMap(([row, count]) => all.slice(row, row + count)), compareFor(StringType));
1379
+ assert.ok(equalFor(PlansType)(value, expected), 'the union of the runs, in the record\'s order');
1380
+ });
1381
+ it('cuts an answer at a page\'s bounds, saying how many it holds of how many, and the rest reads on', async () => {
1382
+ const storage = new InMemoryStorage();
1383
+ await seedIndexedRecord(storage, 12_000);
1384
+ const state = await stateOf(storage);
1385
+ const runs = [[0, 6000], [6000, 6000]];
1386
+ const first = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_status' });
1387
+ assert.equal(first.status, 200, await first.clone().text());
1388
+ assert.equal(first.headers.get('X-Page-Count'), '10000', 'a page holds at most 10,000 entries');
1389
+ assert.equal(first.headers.get('X-Run-Entries'), '12000');
1390
+ const head = decodeStatusWindow(new Uint8Array(await first.arrayBuffer()));
1391
+ // The rest: the runs named, less the 10,000 entries in hand.
1392
+ const rest = await getDatasetRuns(storage, REPO, WS, plansPath, { runs: [[10_000, 2000]], hash: state, index: 'by_status' });
1393
+ const tail = decodeStatusWindow(new Uint8Array(await rest.arrayBuffer()));
1394
+ const whole = await getDatasetPage(storage, REPO, WS, plansPath, { offset: 10_000, limit: 2000, index: 'by_status' });
1395
+ assert.ok(equalFor(StatusWindowType)(tail, decodeStatusWindow(new Uint8Array(await whole.arrayBuffer()))));
1396
+ assert.equal(head.length + tail.length, 12_000);
1397
+ const budget = await getDatasetRuns(storage, REPO, WS, plansPath, { runs: [[0, 10], [20, 10]], hash: state, index: 'by_status' }, { byteBudget: 1 });
1398
+ assert.equal(budget.headers.get('X-Page-Count'), '1', 'the byte budget clamps the entries too');
1399
+ assert.equal(budget.headers.get('X-Run-Entries'), '20');
1400
+ });
1401
+ it('refuses runs that are not ascending, disjoint and inside, more than 10,000 of them, a join with no index, and a stale pin', async () => {
1402
+ const storage = new InMemoryStorage();
1403
+ await seedIndexedRecord(storage, 300);
1404
+ const state = await stateOf(storage);
1405
+ const refused = async (runs, extra = {}) => refusalOf(await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, ...extra }));
1406
+ assert.match((await refused([[10, 5], [12, 3]])).message, /run 1 starts at row 12, before the run before it ends \(15\)/);
1407
+ assert.match((await refused([[290, 20]])).message, /run 0 ends at row 310, past the collection's 300 rows/);
1408
+ assert.match((await refused([[3, 0]])).message, /run 0 is \[3, 0\]/);
1409
+ assert.match((await refused([[-1, 2]])).message, /run 0 is \[-1, 2\]/);
1410
+ assert.equal((await refused(Array.from({ length: 10_001 }, (_, i) => [i, 1]))).type, 'bad_request');
1411
+ assert.match((await refused([[0, 1]], { join: true })).message, /name the index/);
1412
+ assert.deepEqual(await refused([[0, 1]], { index: 'nope' }).then((r) => [r.status, r.type]), [404, 'index_not_found']);
1413
+ const stale = await refusalOf(await getDatasetRuns(storage, REPO, WS, plansPath, { runs: [[0, 1]], hash: '0'.repeat(64) }));
1414
+ assert.deepEqual([stale.status, stale.type, stale.sha], [409, 'dataset_hash_mismatch', state]);
1415
+ });
1416
+ });
1417
+ /** The `by_due` index window, as e3 answers it. */
1418
+ const DueWindowType = indexWindowType(StringType, IntegerType, StringType, PlanRowType);
1419
+ const decodeDueWindow = decodeBeast2For(DueWindowType);
1420
+ /** An entry key of the `by_status` index: its index key beside the row's key. */
1421
+ const StatusEntryKeyType = StructType({ ik: PlanStatusKeyType, k: StringType });
1422
+ const printStatusEntryKey = printFor(StatusEntryKeyType);
1423
+ /** The rows each of a stored collection's segments ends before, by its manifest. */
1424
+ async function cumulativeOf(storage, manifest) {
1425
+ const out = [];
1426
+ let sum = 0;
1427
+ for (const entry of decodeCollectionManifest(await storage.objects.read(REPO, manifest)).entries) {
1428
+ sum += Number(entry.count);
1429
+ out.push(sum);
1430
+ }
1431
+ return out;
1432
+ }
1433
+ /** Where some index entries' rows sit, worked out from the record's rows: each segment holding some, with how many. */
1434
+ function placementOf(keys, rows, cumulative) {
1435
+ const positions = new Map([...rows.keys()].map((key, i) => [key, i]));
1436
+ const held = new Map();
1437
+ for (const key of keys) {
1438
+ const segment = cumulative.findIndex((end) => positions.get(key) < end);
1439
+ held.set(segment, (held.get(segment) ?? 0) + 1);
1440
+ }
1441
+ return [...held].sort((a, b) => a[0] - b[0]).map(([segment, count]) => ({
1442
+ segment, offset: segment === 0 ? 0 : cumulative[segment - 1], count: cumulative[segment] - (segment === 0 ? 0 : cumulative[segment - 1]), rows: count,
1443
+ }));
1444
+ }
1445
+ /** Adds windows' placements up, segment by segment. */
1446
+ function sumPlacements(placements) {
1447
+ const held = new Map();
1448
+ for (const segment of placements.flat()) {
1449
+ const known = held.get(segment.segment);
1450
+ held.set(segment.segment, known === undefined ? { ...segment } : { ...known, rows: known.rows + segment.rows });
1451
+ }
1452
+ return [...held.values()].sort((a, b) => a.segment - b.segment);
1453
+ }
1454
+ describe('placeDatasetRuns (where a narrowing\'s runs of an index sit in its record)', () => {
1455
+ it('places each entry of the runs in the record segment that holds its row, reading each index segment once and no record segment', async () => {
1456
+ const storage = new InMemoryStorage();
1457
+ const { rows, primary, primarySegments, dueSegments } = await seedIndexedRecord(storage, 12_000);
1458
+ const state = await stateOf(storage);
1459
+ // `by_due` scatters the record: a run's rows land all over it.
1460
+ const runs = [[0, 400], [3000, 300], [9000, 600]];
1461
+ const spy = spyReadsByObject(storage, [...primarySegments, ...dueSegments]);
1462
+ let answer;
1463
+ try {
1464
+ const response = await placeDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_due', runs, hash: state });
1465
+ assert.equal(response.headers.get('X-Content-SHA256'), state);
1466
+ assert.equal(response.headers.get('Cache-Control'), 'no-store', 'a POST is no cache\'s to keep');
1467
+ assert.equal(response.headers.get('X-Run-Entries'), '1300');
1468
+ assert.equal(response.headers.get('X-Total-Elements'), '12000', 'the record\'s rows');
1469
+ answer = await batchJson(response);
1470
+ assert.deepEqual([...spy.reads.keys()].filter((hash) => primarySegments.includes(hash)), [], 'the record\'s fences place each row: no record segment is read');
1471
+ assert.ok(spy.total() > 0, 'the index\'s segments are read');
1472
+ assert.deepEqual([...spy.reads.values()].filter((n) => n !== 1), [], 'each index segment touched is read once');
1473
+ }
1474
+ finally {
1475
+ spy.restore();
1476
+ }
1477
+ assert.equal(answer.placed, 1300);
1478
+ const read = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_due' });
1479
+ const keys = decodeDueWindow(new Uint8Array(await read.arrayBuffer())).map((entry) => entry.key);
1480
+ assert.deepEqual(answer.segments, placementOf(keys, rows, await cumulativeOf(storage, primary)));
1481
+ assert.ok(answer.segments.length > 3, `the runs' rows scatter across the record, in ${answer.segments.length} segments`);
1482
+ });
1483
+ it('places a window of the runs at a time, within a page\'s bounds, the windows adding up to the whole', async () => {
1484
+ const storage = new InMemoryStorage();
1485
+ const { rows, primary } = await seedIndexedRecord(storage, 12_000);
1486
+ const state = await stateOf(storage);
1487
+ const place = async (runs, window = {}, byteBudget) => batchJson(await placeDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_status', runs, hash: state, ...window }, byteBudget === undefined ? {} : { byteBudget }));
1488
+ // `late` is rows 4000..7999 of `by_status`, and `open`'s week 0 is 8000..8399.
1489
+ const runs = [[4000, 4000], [8000, 400]];
1490
+ const whole = await place(runs);
1491
+ assert.equal(whole.placed, 4400);
1492
+ const read = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_status' });
1493
+ assert.deepEqual(whole.segments, placementOf(decodeStatusWindow(new Uint8Array(await read.arrayBuffer())).map((entry) => entry.key), rows, await cumulativeOf(storage, primary)));
1494
+ const windows = [];
1495
+ for (let offset = 0; offset < 4400;) {
1496
+ const window = await place(runs, { offset, limit: 777 });
1497
+ assert.ok(window.placed > 0 && window.placed <= 777, `a window places at most its limit, placed ${window.placed}`);
1498
+ windows.push(window.segments);
1499
+ offset += window.placed;
1500
+ }
1501
+ assert.equal(windows.length, 6);
1502
+ assert.deepEqual(sumPlacements(windows), whole.segments, 'the windows add up to the whole, segment by segment');
1503
+ assert.deepEqual(await place(runs, { offset: 4400 }), { segments: [], placed: 0 }, 'past the runs\' end, nothing');
1504
+ assert.equal((await place(runs, {}, 1)).placed, 1, 'the byte budget clamps a window');
1505
+ const capped = await place([[0, 12_000]]);
1506
+ assert.equal(capped.placed, 10_000, 'a window places a page\'s 10,000 entries at most');
1507
+ const rest = await place([[0, 12_000]], { offset: capped.placed });
1508
+ assert.equal(rest.placed, 2000, 'and the rest places on from there');
1509
+ assert.equal(sumPlacements([capped.segments, rest.segments]).reduce((sum, segment) => sum + segment.rows, 0), 12_000);
1510
+ assert.deepEqual(sumPlacements([capped.segments, rest.segments]).map((segment) => segment.rows), sumPlacements([capped.segments, rest.segments]).map((segment) => segment.count), 'the whole index places every row of every segment');
1511
+ });
1512
+ it('refuses runs that are not ascending, disjoint and inside the index, more than 10,000 of them, a bad window, an index the record lacks, and a stale pin', async () => {
1513
+ const storage = new InMemoryStorage();
1514
+ await seedIndexedRecord(storage, 300);
1515
+ const state = await stateOf(storage);
1516
+ const refused = async (request) => refusalOf(await placeDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_status', runs: [[0, 1]], hash: state, ...request }));
1517
+ assert.match((await refused({ runs: [[10, 5], [12, 3]] })).message, /run 1 starts at row 12, before the run before it ends \(15\)/);
1518
+ assert.match((await refused({ runs: [[290, 20]] })).message, /run 0 ends at row 310, past the collection's 300 rows/);
1519
+ assert.match((await refused({ runs: [[3, 0]] })).message, /run 0 is \[3, 0\]/);
1520
+ const many = await refused({ runs: Array.from({ length: 10_001 }, (_, i) => [i, 1]) });
1521
+ assert.deepEqual([many.status, many.type], [400, 'bad_request']);
1522
+ assert.match(many.message, /at most 10000 runs; this one has 10001/);
1523
+ assert.match((await refused({ offset: -1 })).message, /offset -1 is not a row at least 0/);
1524
+ assert.match((await refused({ limit: 1.5 })).message, /limit 1.5 is not a count at least 0/);
1525
+ const missing = await refused({ index: 'nope' });
1526
+ assert.deepEqual([missing.status, missing.type], [404, 'index_not_found']);
1527
+ const stale = await refused({ hash: '0'.repeat(64) });
1528
+ assert.deepEqual([stale.status, stale.type, stale.sha], [409, 'dataset_hash_mismatch', state]);
1529
+ // Ten thousand runs, the most a placement takes, place as one.
1530
+ const big = new InMemoryStorage();
1531
+ await seedIndexedRecord(big, 12_000);
1532
+ const most = await batchJson(await placeDatasetRuns(big, REPO, WS, plansPath, { index: 'by_due', runs: Array.from({ length: 10_000 }, (_, i) => [i, 1]), hash: await stateOf(big) }));
1533
+ assert.equal(most.placed, 10_000);
1534
+ });
1535
+ });
1536
+ describe('withinDatasetRuns (which entries a narrowing\'s runs of an index hold)', () => {
1537
+ it('answers whether each entry lies in one of the runs, reading at most two index segments a run and no record segment', async () => {
1538
+ const storage = new InMemoryStorage();
1539
+ const { rows, primarySegments, statusSegments } = await seedIndexedRecord(storage, 12_000);
1540
+ const state = await stateOf(storage);
1541
+ // One `late` row's entry, `late`'s week 3, and every `open` entry.
1542
+ const runs = [[4000, 1], [5200, 400], [8000, 4000]];
1543
+ const held = new Set();
1544
+ const read = await getDatasetRuns(storage, REPO, WS, plansPath, { runs, hash: state, index: 'by_status' });
1545
+ for (const entry of decodeStatusWindow(new Uint8Array(await read.arrayBuffer())))
1546
+ held.add(printStatusEntryKey({ ik: entry.ik, k: entry.key }));
1547
+ // A row's entry key, as the index files it: its status and week, then its key.
1548
+ const sampled = [...rows].filter((_, i) => i % 37 === 0).map(([k, row]) => printStatusEntryKey({ ik: { status: ['done', 'late', 'open'][Number(row.due % 3n)], week: row.due % 10n }, k }));
1549
+ assert.ok(sampled.some((key) => held.has(key)) && sampled.some((key) => !held.has(key)), 'the keys are in and out of the runs');
1550
+ // Each run's first and last entries, and those just outside it: where a slip at a run's edge shows.
1551
+ const edges = [...new Set(runs.flatMap(([row, count]) => [row - 1, row, row + count - 1, row + count]))]
1552
+ .filter((row) => row >= 0 && row < 12_000).sort((a, b) => a - b);
1553
+ const edgeRead = await getDatasetRuns(storage, REPO, WS, plansPath, { runs: edges.map((row) => [row, 1]), hash: state, index: 'by_status' });
1554
+ const edgeKeys = decodeStatusWindow(new Uint8Array(await edgeRead.arrayBuffer())).map((entry) => printStatusEntryKey({ ik: entry.ik, k: entry.key }));
1555
+ assert.equal(edgeKeys.length, edges.length);
1556
+ const keys = [...sampled, ...edgeKeys];
1557
+ const fresh = new InMemoryStorage();
1558
+ await seedIndexedRecord(fresh, 12_000);
1559
+ const spy = spyReadsByObject(fresh, [...primarySegments, ...statusSegments]);
1560
+ try {
1561
+ const response = await withinDatasetRuns(fresh, REPO, WS, plansPath, { index: 'by_status', runs, keys, hash: await stateOf(fresh) });
1562
+ assert.equal(response.headers.get('Cache-Control'), 'no-store');
1563
+ const { within } = await batchJson(response);
1564
+ assert.deepEqual(within, keys.map((key) => held.has(key)), 'each key is in the runs exactly when a read of them holds it');
1565
+ assert.deepEqual(within.slice(sampled.length), edges.map((row) => runs.some(([start, count]) => row >= start && row < start + count)), 'each run holds its first and last entries, and not those beside it');
1566
+ assert.deepEqual([...spy.reads.keys()].filter((hash) => primarySegments.includes(hash)), [], 'no record segment is read');
1567
+ assert.ok(spy.total() > 0 && spy.total() <= 2 * runs.length, `the runs' first and last entries lie in at most two segments a run, read ${spy.total()}`);
1568
+ assert.deepEqual([...spy.reads.values()].filter((n) => n !== 1), [], 'each read once');
1569
+ }
1570
+ finally {
1571
+ spy.restore();
1572
+ }
1573
+ });
1574
+ it('refuses more than 10,000 keys or runs, runs not of the index, a key that is no entry key — naming its place — an index the record lacks, and a stale pin', async () => {
1575
+ const storage = new InMemoryStorage();
1576
+ await seedIndexedRecord(storage, 300);
1577
+ const state = await stateOf(storage);
1578
+ const refused = async (request) => refusalOf(await withinDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_status', runs: [[0, 10]], keys: [], hash: state, ...request }));
1579
+ const manyKeys = await refused({ keys: Array.from({ length: 10_001 }, () => '(ik=(status="late", week=1), k="p-000001")') });
1580
+ assert.match(manyKeys.message, /at most 10000 keys; this one has 10001/);
1581
+ assert.match((await refused({ runs: Array.from({ length: 10_001 }, (_, i) => [i, 1]) })).message, /at most 10000 runs/);
1582
+ assert.match((await refused({ runs: [[5, 5], [8, 2]] })).message, /run 1 starts at row 8/);
1583
+ const bad = await refused({ keys: ['(ik=(status="late", week=1), k="p-000001")', '(status="late", week=1)'] });
1584
+ assert.deepEqual([bad.status, bad.type], [400, 'key_parse_error']);
1585
+ assert.match(bad.message, /^key 1: /, 'an index key alone is no entry key');
1586
+ const missing = await refused({ index: 'nope' });
1587
+ assert.deepEqual([missing.status, missing.type], [404, 'index_not_found']);
1588
+ const stale = await refused({ hash: '0'.repeat(64) });
1589
+ assert.deepEqual([stale.status, stale.type, stale.sha], [409, 'dataset_hash_mismatch', state]);
1590
+ assert.deepEqual(await batchJson(await withinDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_status', runs: [], keys: ['(ik=(status="late", week=1), k="p-000001")'], hash: state })), { within: [false] }, 'no run holds anything');
1591
+ });
1592
+ });
1593
+ describe('the batch routes', () => {
1594
+ /** An app mounting the dataset routes behind the transfer routes, as every server does. */
1595
+ function serverOf(storage, options = {}) {
1596
+ const app = new Hono();
1597
+ const prefix = '/api/repos/:repo/workspaces/:ws/datasets';
1598
+ app.route(prefix, createTransferRoutes(storage, () => REPO, new InMemoryTransferBackend({ baseUrl: '' })).api);
1599
+ app.route(prefix, createDatasetRoutes(storage, () => REPO, undefined, options));
1600
+ return app;
1601
+ }
1602
+ const post = (app, query, body) => app.request(`/api/repos/${REPO}/workspaces/${WS}/datasets/records/plans?${query}`, {
1603
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: typeof body === 'string' ? body : JSON.stringify(body),
1604
+ });
1605
+ it('answer a POST naming its batch, past the transfer routes, as their handlers do', async () => {
1606
+ const storage = new InMemoryStorage();
1607
+ await seedIndexedRecord(storage, 300);
1608
+ const state = await stateOf(storage);
1609
+ const app = serverOf(storage);
1610
+ const found = await batchJson(await post(app, `findKeys=true&index=by_status&hash=${state}`, { queries: [{ fields: ['"late"'] }, { key: '(status="late", week=3)' }] }));
1611
+ assert.deepEqual(found.results, (await batchJson(await findDatasetKeys(storage, REPO, WS, plansPath, { queries: [{ fields: ['"late"'] }, { key: '(status="late", week=3)' }], index: 'by_status', hash: state }))).results);
1612
+ const rows = await post(app, `rows=true&hash=${state}`, { keys: ['"p-000007"', '"nope"'] });
1613
+ assert.equal(rows.status, 200, await rows.clone().text());
1614
+ assert.deepEqual(decodeRows(new Uint8Array(await rows.arrayBuffer())).map((answer) => [answer.key, answer.row.type]), [['p-000007', 'some'], ['nope', 'none']]);
1615
+ const runs = await post(app, `runs=true&index=by_status&join=true&hash=${state}`, { runs: [[0, 5], [100, 5]] });
1616
+ assert.equal(runs.status, 200, await runs.clone().text());
1617
+ assert.equal(runs.headers.get('X-Page-Count'), '10');
1618
+ assert.equal(runs.headers.get('X-Window-Joined'), 'true');
1619
+ // A page's byte budget holds a batch's answer too.
1620
+ const tight = serverOf(storage, { pageByteBudget: 1 });
1621
+ assert.equal((await post(tight, `rows=true&hash=${state}`, { keys: ['"p-000007"', '"p-000008"'] })).headers.get('X-Page-Count'), '1');
1622
+ });
1623
+ it('answer a batch read of a dataset named upload, whose own path ends as an upload\'s init does, and leave its upload to the transfer routes', async () => {
1624
+ // A batch read is a POST to the dataset's own path, and the transfer
1625
+ // routes, mounted first, took every POST whose path ends in `/upload` as an
1626
+ // upload's init — so `inputs.upload` could never be read in a batch,
1627
+ // though its GET reads worked.
1628
+ const storage = new InMemoryStorage();
1629
+ await seedDataset(storage, encodeBeast2PagedFor(LookupType)(lookupOf(10)), 'upload', LookupType);
1630
+ const app = serverOf(storage);
1631
+ const response = await app.request(`/api/repos/${REPO}/workspaces/${WS}/datasets/inputs/upload?findKeys=true`, {
1632
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ queries: [{ key: '"k0003"' }] }),
1633
+ });
1634
+ const body = await response.clone().text();
1635
+ assert.equal(response.headers.get('Content-Type'), 'application/json', `a batch read's JSON answer, not an upload's: got ${response.status} ${body.slice(0, 200)}`);
1636
+ assert.deepEqual((await response.json()).results, [{ found: true, row: 3, count: 1 }]);
1637
+ // Its upload's init, to its own `/upload`, names no batch: the transfer routes plan it.
1638
+ const init = await app.request(`/api/repos/${REPO}/workspaces/${WS}/datasets/inputs/upload/upload?protocol=${TRANSFER_PROTOCOL_VERSION}&release=${E3_RELEASE}`, {
1639
+ method: 'POST', headers: { 'Content-Type': BEAST2_CONTENT_TYPE },
1640
+ body: encodeBeast2For(TransferUploadRequestType)({ hash: '0'.repeat(64), size: 10n }),
1641
+ });
1642
+ const planned = decodeBeast2For(ResponseType(TransferUploadResponseType))(new Uint8Array(await init.arrayBuffer()));
1643
+ assert.ok(planned.type === 'success' && planned.value.type === 'upload_parts', `the init is planned as an upload's: ${JSON.stringify(planned.type)}`);
1644
+ });
1645
+ it('refuse a body past 16 MiB, 413, as its length says so or as its bytes pass it, never reading the rest', async () => {
1646
+ // A batch names at most 10,000 queries, keys or runs, and its body was
1647
+ // read whole, however large, before anything looked at it.
1648
+ const storage = new InMemoryStorage();
1649
+ await seedIndexedRecord(storage, 300);
1650
+ const state = await stateOf(storage);
1651
+ const app = serverOf(storage);
1652
+ const at = `/api/repos/${REPO}/workspaces/${WS}/datasets/records/plans?findKeys=true&hash=${state}`;
1653
+ const cap = DATASET_BATCH_BODY_MAX;
1654
+ assert.equal(cap, 16 * 1024 * 1024);
1655
+ // Declared: one query whose key literal alone is the cap's bytes.
1656
+ const huge = JSON.stringify({ queries: [{ key: JSON.stringify('k'.repeat(cap)) }] });
1657
+ const declared = await app.request(at, {
1658
+ method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': String(huge.length) }, body: huge,
1659
+ });
1660
+ assert.equal(declared.status, 413, `a body its length says is past the cap is refused: got ${declared.status} ${(await declared.clone().text()).slice(0, 200)}`);
1661
+ const byLength = await refusalOf(declared);
1662
+ assert.equal(byLength.type, 'payload_too_large');
1663
+ assert.equal(byLength.message, `A batch read's body is ${huge.length} bytes, past the ${cap} a batch's body holds at most: split it into smaller batches`);
1664
+ // Undeclared, sent as it is made: whitespace to four times the cap, then a batch.
1665
+ let made = 0;
1666
+ const chunk = new Uint8Array(64 * 1024).fill(0x20);
1667
+ const streamed = new ReadableStream({
1668
+ pull(controller) {
1669
+ if (made > 4 * cap) {
1670
+ controller.enqueue(new TextEncoder().encode('{"queries":[]}'));
1671
+ controller.close();
1672
+ return;
1673
+ }
1674
+ made += chunk.byteLength;
1675
+ controller.enqueue(chunk);
1676
+ },
1677
+ });
1678
+ const undeclared = await app.request(at, {
1679
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: streamed, duplex: 'half',
1680
+ });
1681
+ assert.equal(undeclared.status, 413, `a body whose bytes pass the cap is refused: got ${undeclared.status} ${(await undeclared.clone().text()).slice(0, 200)}`);
1682
+ const byBytes = await refusalOf(undeclared);
1683
+ assert.equal(byBytes.type, 'payload_too_large');
1684
+ assert.equal(byBytes.message, `A batch read's body is past the ${cap} bytes a batch's body holds at most: split it into smaller batches`);
1685
+ assert.ok(made <= cap + 4 * chunk.byteLength, `the body is read no further than just past the cap: ${made} bytes made`);
1686
+ // A body within it is answered, as every other batch here is.
1687
+ const small = await app.request(at, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: ' {"queries":[{"key":"\\"p-000007\\""}]}' });
1688
+ assert.deepEqual((await batchJson(small)).results, [{ found: true, row: 7, count: 1 }]);
1689
+ });
1690
+ it('refuse a body not of the batch\'s form, a read of runs pinned to nothing, and two batches at once, and leave every other POST to no route', async () => {
1691
+ const storage = new InMemoryStorage();
1692
+ await seedIndexedRecord(storage, 300);
1693
+ const app = serverOf(storage);
1694
+ const refused = async (query, body) => refusalOf(await post(app, query, body));
1695
+ assert.match((await refused('findKeys=true', 'not json')).message, /^The body is not JSON/);
1696
+ assert.match((await refused('findKeys=true', { keys: [] })).message, /is \{ "queries": \[ … \] \}/);
1697
+ assert.match((await refused('findKeys=true', { queries: [{ key: 7 }] })).message, /query 0's key is not a string/);
1698
+ assert.match((await refused('findKeys=true', { queries: [{ index: 'x' }] })).message, /query 0 names index/);
1699
+ assert.match((await refused('rows=true', { keys: [1] })).message, /is \{ "keys": \[/);
1700
+ assert.match((await refused('runs=true&hash=x', { runs: [[1]] })).message, /run 0 is not \[row, count\]/);
1701
+ assert.match((await refused('runs=true', { runs: [] })).message, /names the content hash its runs are positions at/);
1702
+ assert.match((await refused('rows=true&findKeys=true', { keys: [] })).message, /Ask for one batch/);
1703
+ const other = await post(app, '', {});
1704
+ assert.equal(other.status, 404, 'a POST naming no batch is no route');
1705
+ });
1706
+ it('answer a placement and a membership read as their handlers do, and refuse their bodies\' wrong forms', async () => {
1707
+ const storage = new InMemoryStorage();
1708
+ await seedIndexedRecord(storage, 3000);
1709
+ const state = await stateOf(storage);
1710
+ const app = serverOf(storage);
1711
+ const placed = await batchJson(await post(app, `place=true&hash=${state}`, { index: 'by_status', runs: [[0, 100], [1000, 50]], offset: 20, limit: 70 }));
1712
+ assert.deepEqual(placed, await batchJson(await placeDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_status', runs: [[0, 100], [1000, 50]], offset: 20, limit: 70, hash: state })));
1713
+ assert.equal(placed.placed, 70);
1714
+ const key = '(ik=(status="done", week=0), k="p-000000")';
1715
+ const within = await batchJson(await post(app, `within=true&hash=${state}`, { index: 'by_status', runs: [[0, 100]], keys: [key] }));
1716
+ assert.deepEqual(within, await batchJson(await withinDatasetRuns(storage, REPO, WS, plansPath, { index: 'by_status', runs: [[0, 100]], keys: [key], hash: state })));
1717
+ const refused = async (query, body) => refusalOf(await post(app, query, body));
1718
+ assert.match((await refused('place=true', { index: 'by_status', runs: [] })).message, /A placement names the content hash its runs are positions at/);
1719
+ assert.match((await refused('within=true', { index: 'by_status', runs: [], keys: [] })).message, /A membership read names the content hash/);
1720
+ assert.match((await refused(`place=true&hash=${state}`, { runs: [] })).message, /A placement names the index its runs are rows of/);
1721
+ assert.match((await refused(`within=true&hash=${state}`, { index: '', runs: [], keys: [] })).message, /A membership read names the index/);
1722
+ assert.match((await refused(`place=true&hash=${state}`, { index: 'by_status', runs: [[1]] })).message, /run 0 is not \[row, count\]/);
1723
+ assert.match((await refused(`place=true&hash=${state}`, { index: 'by_status', runs: [], offset: '1' })).message, /offset is a number/);
1724
+ assert.match((await refused(`within=true&hash=${state}`, { index: 'by_status', runs: [] })).message, /A membership read is \{ "index"/);
1725
+ assert.match((await refused(`place=true&within=true&hash=${state}`, {})).message, /Ask for one batch/);
1726
+ });
1727
+ it('answer a read of rows by runs as its handler does, the record named by its keypath, and refuse its body\'s wrong forms', async () => {
1728
+ const storage = new InMemoryStorage();
1729
+ const { notesHash } = await seedPlanNotes(storage, 3000);
1730
+ const state = await stateOf(storage);
1731
+ const app = serverOf(storage);
1732
+ const notes = (query, body) => app.request(`/api/repos/${REPO}/workspaces/${WS}/datasets/inputs/notes?${query}`, {
1733
+ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
1734
+ });
1735
+ const runs = [[0, 30], [1000, 20]];
1736
+ const routed = await notes(`rows=true&hash=${notesHash}`, { keysOf: { path: '.records.plans', index: 'by_status', hash: state, runs } });
1737
+ assert.equal(routed.status, 200, await routed.clone().text());
1738
+ assert.equal(routed.headers.get('X-Run-Entries'), '50');
1739
+ const handled = await getDatasetRows(storage, REPO, WS, notesPath, { keysOf: { path: plansPath, index: 'by_status', runs, hash: state }, hash: notesHash });
1740
+ assert.deepEqual(new Uint8Array(await routed.arrayBuffer()), new Uint8Array(await handled.arrayBuffer()), 'the bytes its handler answers');
1741
+ const refused = async (body) => refusalOf(await notes(`rows=true&hash=${notesHash}`, body));
1742
+ const of = { path: '.records.plans', index: 'by_status', hash: state, runs };
1743
+ assert.match((await refused({ keys: [], keysOf: of })).message, /names its keys or the runs that name them, not both/);
1744
+ assert.match((await refused({ keysOf: 'records/plans' })).message, /^A read of rows by runs is \{ "keysOf": \{ "path"/);
1745
+ assert.match((await refused({ keysOf: { ...of, hash: '' } })).message, /^A read of rows by runs is/);
1746
+ assert.match((await refused({ keysOf: { ...of, index: 7 } })).message, /^A read of rows by runs is/);
1747
+ assert.match((await refused({ keysOf: { ...of, path: 'records/plans' } })).message, /^keysOf's path must be a dataset's path, as a status names it/);
1748
+ assert.match((await refused({ keysOf: { ...of, path: '' } })).message, /names the record its runs are of/);
1749
+ assert.match((await refused({ keysOf: { ...of, runs: [[1]] } })).message, /run 0 is not \[row, count\]/);
1750
+ });
1751
+ });
1752
+ describe('the decoded segments the API process keeps', () => {
1753
+ it('serve a window read again, and a search in a segment a window decoded, with nothing read', async () => {
1754
+ const storage = new InMemoryStorage();
1755
+ const blob = encodeInSegmentsOf(LookupType, 97)(lookupOf(2500));
1756
+ const hash = await seedDataset(storage, blob, 'lookup', LookupType);
1757
+ const spy = spyReadsByObject(storage, await segmentsOf(storage, hash));
1758
+ const decodes = decodedSegmentStats().decodes;
1759
+ try {
1760
+ const window = await getDatasetPage(storage, REPO, WS, lookupPath, { offset: 150, limit: 100 });
1761
+ assert.equal(window.status, 200);
1762
+ assert.equal(spy.total(), 2, 'rows 150..249 lie in two segments');
1763
+ assert.equal(decodedSegmentStats().decodes - decodes, 2, 'each decoded once');
1764
+ const again = await getDatasetPage(storage, REPO, WS, lookupPath, { offset: 150, limit: 100 });
1765
+ assert.deepEqual(new Uint8Array(await again.arrayBuffer()), new Uint8Array(await window.arrayBuffer()), 'the same bytes');
1766
+ await findJson(await findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k0200"' }));
1767
+ assert.equal(spy.total(), 2, 'the window again and the search in its segments read nothing');
1768
+ }
1769
+ finally {
1770
+ spy.restore();
1771
+ }
1772
+ });
1773
+ it('read a segment two requests ask for at once once, for both', async () => {
1774
+ const storage = new InMemoryStorage();
1775
+ const blob = encodeInSegmentsOf(LookupType, 97)(lookupOf(2500));
1776
+ const hash = await seedDataset(storage, blob, 'lookup', LookupType);
1777
+ const spy = spyReadsByObject(storage, await segmentsOf(storage, hash));
1778
+ try {
1779
+ const [a, b] = await Promise.all([
1780
+ findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k1000"' }),
1781
+ findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k1001"' }),
1782
+ ]);
1783
+ assert.deepEqual([await findJson(a), await findJson(b)], [{ found: true, row: 1000, count: 1 }, { found: true, row: 1001, count: 1 }]);
1784
+ assert.equal(spy.total(), 1, 'one segment holds both keys, and it is read once');
1785
+ }
1786
+ finally {
1787
+ spy.restore();
1788
+ }
1789
+ });
1790
+ it('refuse a collection whose manifest names its segments out of order, naming them, for a window, a segment and a search', async () => {
1791
+ const storage = new InMemoryStorage();
1792
+ const blob = encodeInSegmentsOf(LookupType, 97)(lookupOf(500));
1793
+ const hash = await seedDataset(storage, blob, 'lookup', LookupType);
1794
+ // The manifest's fences stay; segments 1 and 2 are named in each other's place.
1795
+ const manifest = decodeCollectionManifest(await storage.objects.read(REPO, hash));
1796
+ const entries = [...manifest.entries];
1797
+ [entries[1], entries[2]] = [{ ...entries[1], hash: entries[2].hash }, { ...entries[2], hash: entries[1].hash }];
1798
+ const swapped = await storage.objects.write(REPO, encodeCollectionManifest({ ...manifest, entries }));
1799
+ await storage.datasets.write(REPO, WS, 'inputs/lookup', variant('value', { hash: swapped, versions: new Map() }));
1800
+ const window = await refusalOf(await getDatasetPage(storage, REPO, WS, lookupPath, { offset: 90, limit: 20 }));
1801
+ assert.deepEqual([window.status, window.type], [400, 'dataset_not_canonical']);
1802
+ assert.match(window.message, /segment 1's first key is not its fence/);
1803
+ const segment = await refusalOf(await getDatasetPage(storage, REPO, WS, lookupPath, { segment: 2 }));
1804
+ assert.deepEqual([segment.status, segment.type], [400, 'dataset_not_segmented']);
1805
+ const search = await refusalOf(await findDatasetKey(storage, REPO, WS, lookupPath, { key: '"k0100"' }));
1806
+ assert.deepEqual([search.status, search.type], [400, 'dataset_not_canonical']);
1807
+ });
1808
+ });
855
1809
  //# sourceMappingURL=datasets.spec.js.map