effect-dynamodb 1.37.0 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +1 -1
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +312 -338
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts.map +1 -1
  6. package/dist/Batch.js +72 -191
  7. package/dist/Batch.js.map +1 -1
  8. package/dist/Collection.d.ts.map +1 -1
  9. package/dist/Collection.js +15 -16
  10. package/dist/Collection.js.map +1 -1
  11. package/dist/DynamoClient.d.ts +28 -13
  12. package/dist/DynamoClient.d.ts.map +1 -1
  13. package/dist/DynamoClient.js +64 -86
  14. package/dist/DynamoClient.js.map +1 -1
  15. package/dist/Entity.d.ts +9 -84
  16. package/dist/Entity.d.ts.map +1 -1
  17. package/dist/Entity.js +1094 -2682
  18. package/dist/Entity.js.map +1 -1
  19. package/dist/EventStore.d.ts +10 -10
  20. package/dist/EventStore.d.ts.map +1 -1
  21. package/dist/EventStore.js +181 -291
  22. package/dist/EventStore.js.map +1 -1
  23. package/dist/Query.d.ts +70 -32
  24. package/dist/Query.d.ts.map +1 -1
  25. package/dist/Query.js +501 -80
  26. package/dist/Query.js.map +1 -1
  27. package/dist/Table.d.ts +8 -2
  28. package/dist/Table.d.ts.map +1 -1
  29. package/dist/Table.js +7 -0
  30. package/dist/Table.js.map +1 -1
  31. package/dist/Transaction.d.ts +2 -18
  32. package/dist/Transaction.d.ts.map +1 -1
  33. package/dist/Transaction.js +1 -58
  34. package/dist/Transaction.js.map +1 -1
  35. package/dist/index.d.ts +1 -1
  36. package/dist/index.d.ts.map +1 -1
  37. package/dist/index.js +1 -1
  38. package/dist/index.js.map +1 -1
  39. package/dist/internal/BoundQuery.d.ts +11 -8
  40. package/dist/internal/BoundQuery.d.ts.map +1 -1
  41. package/dist/internal/BoundQuery.js +6 -2
  42. package/dist/internal/BoundQuery.js.map +1 -1
  43. package/dist/internal/Cursor.d.ts +9 -4
  44. package/dist/internal/Cursor.d.ts.map +1 -1
  45. package/dist/internal/Cursor.js +12 -2
  46. package/dist/internal/Cursor.js.map +1 -1
  47. package/dist/internal/ProjectionEngine.d.ts +2 -16
  48. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  49. package/dist/internal/ProjectionEngine.js +44 -229
  50. package/dist/internal/ProjectionEngine.js.map +1 -1
  51. package/dist/internal/RangePlanner.d.ts +0 -76
  52. package/dist/internal/RangePlanner.d.ts.map +1 -1
  53. package/dist/internal/RangePlanner.js +2 -206
  54. package/dist/internal/RangePlanner.js.map +1 -1
  55. package/dist/internal/Rekey.d.ts +28 -6
  56. package/dist/internal/Rekey.d.ts.map +1 -1
  57. package/dist/internal/Rekey.js +46 -10
  58. package/dist/internal/Rekey.js.map +1 -1
  59. package/dist/internal/ShardMerge.d.ts +83 -0
  60. package/dist/internal/ShardMerge.d.ts.map +1 -0
  61. package/dist/internal/ShardMerge.js +182 -0
  62. package/dist/internal/ShardMerge.js.map +1 -0
  63. package/dist/internal/TransactPlan.d.ts +1 -8
  64. package/dist/internal/TransactPlan.d.ts.map +1 -1
  65. package/dist/internal/TransactPlan.js +2 -9
  66. package/dist/internal/TransactPlan.js.map +1 -1
  67. package/dist/internal/TransactWriteOps.d.ts +6 -9
  68. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  69. package/dist/internal/TransactWriteOps.js +3 -79
  70. package/dist/internal/TransactWriteOps.js.map +1 -1
  71. package/dist/internal/TransactableOps.d.ts +10 -8
  72. package/dist/internal/TransactableOps.d.ts.map +1 -1
  73. package/dist/internal/TransactableOps.js +18 -14
  74. package/dist/internal/TransactableOps.js.map +1 -1
  75. package/package.json +7 -5
package/dist/Query.js CHANGED
@@ -17,7 +17,8 @@ import { compileExpr, ExprTag, emptyPartProblem, isEmptyExpr } from "./internal/
17
17
  import { batchGetRaw } from "./internal/Hydrate.js";
18
18
  import { packedExprRefusal, packedProjectionRefusal, } from "./internal/Packed.js";
19
19
  import { compilePath } from "./internal/PathBuilder.js";
20
- import { compositePlanner, cursorRefusal, DEFAULT_MAX_SKIPS, displayKeyCondition, JUMP_INITIAL, JUMP_MAX_LIMIT, keyPassesPlanner, readFrom, toKeyCondition, } from "./internal/RangePlanner.js";
20
+ import { canonicalJson, compositePlanner, cursorRefusal, DEFAULT_MAX_SKIPS, displayKeyCondition, fnv1a32, JUMP_INITIAL, JUMP_MAX_LIMIT, keyConditionHolds, readFrom, toKeyCondition, } from "./internal/RangePlanner.js";
21
+ import * as ShardMerge from "./internal/ShardMerge.js";
21
22
  import { diagnoseFailure, explainDiagnosis, withCause } from "./internal/WriteDiagnosis.js";
22
23
  import { fromAttributeMap, toAttributeValue } from "./Marshaller.js";
23
24
  /**
@@ -75,6 +76,9 @@ export const make = (config) => new QueryImpl({
75
76
  hydration: config.hydration,
76
77
  keyConditionDiagnosis: config.keyConditionDiagnosis,
77
78
  operationTarget: config.operationTarget,
79
+ fanOut: undefined,
80
+ fanOutStart: undefined,
81
+ concurrencyValue: undefined,
78
82
  tableName: config.tableName,
79
83
  indexName: config.indexName,
80
84
  pkField: config.pkField,
@@ -95,7 +99,6 @@ export const make = (config) => new QueryImpl({
95
99
  cursorText: undefined,
96
100
  planner: undefined,
97
101
  maxSkips: undefined,
98
- key136: undefined,
99
102
  zorderOptions: undefined,
100
103
  plan: undefined,
101
104
  rowCheck: undefined,
@@ -120,6 +123,9 @@ export const makeScan = (config) => new QueryImpl({
120
123
  hydration: undefined,
121
124
  keyConditionDiagnosis: undefined,
122
125
  operationTarget: undefined,
126
+ fanOut: undefined,
127
+ fanOutStart: undefined,
128
+ concurrencyValue: undefined,
123
129
  tableName: config.tableName,
124
130
  indexName: config.indexName,
125
131
  pkField: "",
@@ -140,7 +146,6 @@ export const makeScan = (config) => new QueryImpl({
140
146
  cursorText: undefined,
141
147
  planner: undefined,
142
148
  maxSkips: undefined,
143
- key136: undefined,
144
149
  zorderOptions: undefined,
145
150
  plan: undefined,
146
151
  rowCheck: undefined,
@@ -158,54 +163,82 @@ const encodeCursor = (key) => Cursor.encodeKeyCursor(key);
158
163
  // ---------------------------------------------------------------------------
159
164
  // Combinators (all dual for data-first and data-last)
160
165
  // ---------------------------------------------------------------------------
166
+ /** @internal Install `condition` as the query's one sort key condition. */
167
+ const withSortKeyCondition = (state, condition) => new QueryImpl({
168
+ ...state,
169
+ skConditions: state.skField === undefined ? [] : [{ field: state.skField, condition }],
170
+ keepRow: undefined,
171
+ });
172
+ /**
173
+ * @internal A pruned fan-out (#183) as it reads with no pins: one shard was chosen
174
+ * for values a replaced condition no longer selects.
175
+ */
176
+ const withoutPruning = (state) => {
177
+ const spec = state.fanOut;
178
+ if (spec?.everyPartition === undefined)
179
+ return state;
180
+ return {
181
+ ...state,
182
+ pkValue: spec.everyPartition[0],
183
+ fanOut: { ...spec, partitions: spec.everyPartition, pruned: false, everyPartition: undefined },
184
+ };
185
+ };
161
186
  /**
162
187
  * Add a sort key condition to the query.
163
188
  * Only one SK condition is supported (last one wins if multiple are added).
189
+ *
190
+ * The condition replaces what the query's accessor pinned, so on a sharded index
191
+ * (#183) the query reads every shard again: a row the new condition selects can
192
+ * be in any of them.
164
193
  */
165
194
  export const where = Function.dual(2, (self, condition) => {
166
195
  const state = self._state;
167
196
  if (!state.skField)
168
197
  return self;
169
- return new QueryImpl({
170
- ...state,
171
- skConditions: [{ field: state.skField, condition }],
172
- // A new condition is not the pins the 1.36 key was composed for (#171):
173
- // the caller that composed it installs the 1.36 key again.
174
- key136: undefined,
175
- });
198
+ return withSortKeyCondition(withoutPruning(state), condition);
176
199
  });
177
- /** @internal Do two sort key conditions select the same keys, operand for operand? */
178
- const sameCondition = (a, b) => JSON.stringify(a) === JSON.stringify(b);
179
- /**
180
- * @internal Also read the key 1.36 composed for this query's pins (#171,
181
- * DESIGN.md §7 "Rows written by 1.36"): its partition key and its `eq` /
182
- * `beginsWith` sort key condition (or none). A row 1.36 wrote whose key text
183
- * changed in 1.37 sits there until it is written again or `rekey` moves it.
184
- * A terminal reads both keys as two passes of one plan
185
- * (`RangePlanner.keyPassesPlanner`): the 1.36 key first, or last under
186
- * {@link reverse}. A key equal to the query's own adds nothing — unless its
187
- * rows are split by form (`KeyPass.rows.split`) — so a query whose key text
188
- * did not change sends exactly what it always sent. Installed after the
189
- * pins' {@link where}, which clears it.
190
- */
191
- export const alsoRead136 = (self, key) => {
200
+ /**
201
+ * @internal {@link where} for a condition composed from the query's own pins, or
202
+ * bounded under them (an accessor's, `.where()` on a bound query): it selects only
203
+ * rows those pins select, so the shard chosen for them (#183) still holds them all.
204
+ */
205
+ export const whereUnderPins = (self, condition) => {
192
206
  const state = self._state;
193
- if (key === undefined || state.isScan)
194
- return self;
195
- const own = state.skConditions[0]?.condition;
196
- const same = key.pkValue === state.pkValue && sameCondition(key.condition, own);
197
- if (same && key.rows?.split !== true)
207
+ if (!state.skField)
198
208
  return self;
199
- return new QueryImpl({ ...state, key136: key });
209
+ return withSortKeyCondition(state, condition);
200
210
  };
201
211
  /**
202
- * @internal {@link alsoRead136} for a query whose 1.36 key differs in its
203
- * partition key alone (a collection, a partition's tombstones): the 1.36
204
- * partition under the query's own sort key condition.
212
+ * @internal Read a sharded index's partitions and merge them (#183): what
213
+ * {@link KeyComposer.composeReadPartitions} returned for the query's pins. An
214
+ * unsharded index's query is unchanged.
205
215
  */
206
- export const alsoReadPartition136 = (self, pkValue) => pkValue === undefined
216
+ export const fanOut = (self, read) => read.fanOut === undefined
207
217
  ? self
208
- : alsoRead136(self, { pkValue, condition: self._state.skConditions[0]?.condition });
218
+ : new QueryImpl({
219
+ ...self._state,
220
+ pkValue: read.partitions[0],
221
+ fanOut: { ...read.fanOut, partitions: read.partitions },
222
+ });
223
+ /** @internal Does this query read a sharded index's partitions (#183)? */
224
+ export const isFanOut = (self) => self._state.fanOut !== undefined;
225
+ /**
226
+ * How many requests a query of a sharded index sends at once, per round of its
227
+ * fan-out (#183). The default is one per partition. A query with no fan-out sends
228
+ * one request at a time whatever this says. Anything but a positive integer
229
+ * throws `[EDD-9105]`.
230
+ *
231
+ * ```ts
232
+ * query.pipe(Query.concurrency(4), Query.collect)
233
+ * ```
234
+ */
235
+ export const concurrency = Function.dual(2, (self, n) => {
236
+ if (!Number.isInteger(n) || n < 1) {
237
+ throw new Error(`[EDD-9105] concurrency(${JSON.stringify(n)}) is not a number of requests: pass a ` +
238
+ `positive integer.`);
239
+ }
240
+ return new QueryImpl({ ...self._state, concurrencyValue: n });
241
+ });
209
242
  /**
210
243
  * Return **at most `n` items** — a contract on results, not on round trips.
211
244
  *
@@ -334,16 +367,34 @@ export const startFrom = Function.dual(2, (self, cursor) => cursor === ""
334
367
  * combinators that follow (`reverse`, `startFrom`, …) still apply. Not a
335
368
  * combinator: Z-order and skip-scan are reached through `BoundQuery`.
336
369
  */
337
- export const plan = (self, install) => new QueryImpl("zorder" in install
338
- ? { ...self._state, zorderOptions: { ...self._state.zorderOptions, ...install.zorder } }
339
- : { ...self._state, planner: install.planner, maxSkips: install.maxSkips });
370
+ export const plan = (self, install) => {
371
+ if (self._state.fanOut !== undefined)
372
+ throw shardedPlanRefusal(self._state);
373
+ return new QueryImpl("zorder" in install
374
+ ? { ...self._state, zorderOptions: { ...self._state.zorderOptions, ...install.zorder } }
375
+ : { ...self._state, planner: install.planner, maxSkips: install.maxSkips });
376
+ };
377
+ /**
378
+ * @internal `[EDD-9104]`: `.within()`, skip-scan and `.zorder()` plan one
379
+ * partition's reads, so a sharded index would need a plan per shard. A follow-up.
380
+ */
381
+ const shardedPlanRefusal = (state) => new Error(`[EDD-9104] Index "${state.indexName}" of ${state.entityTypes.join(", ") || "this query"} is ` +
382
+ `sharded: .within(), skip-scan and .zorder() aren't supported on a sharded index. Use the ` +
383
+ `accessor's sort key composites or .where(), or .filter() for the rest.`);
384
+ /** @internal {@link shardedPlanRefusal}, for an accessor to raise before it plans. */
385
+ export const refuseShardedPlan = (self) => {
386
+ if (self._state.fanOut !== undefined)
387
+ throw shardedPlanRefusal(self._state);
388
+ };
340
389
  /**
341
390
  * @internal A query no stored row satisfies (#171) — a `.history()` bound with
342
391
  * no key text below it (`lt("")` on a string orderBy) — planned `empty`, as a
343
392
  * `.within()` whose bounds admit no value is: nothing is sent, the terminals
344
393
  * return no items, and `explain()` reports the `empty` plan.
345
394
  */
346
- export const planEmpty = (self) => plan(self, {
395
+ export const planEmpty = (self) =>
396
+ // Nothing is read, so no partition is: a fan-out has nothing left to merge.
397
+ plan(new QueryImpl({ ...self._state, fanOut: undefined }), {
347
398
  planner: compositePlanner({
348
399
  entityType: self._state.entityTypes.join(", ") || "unknown",
349
400
  index: self._state.indexName ?? "primary",
@@ -784,13 +835,17 @@ const sizingMode = (state) => {
784
835
  return "natural";
785
836
  if (state.limitValue === undefined)
786
837
  return "none";
787
- // Planned queries (`.within()`) are new, so they adapt under `maxPages` too.
788
- if (state.maxPagesValue !== undefined && state.planner === undefined)
838
+ // Planned queries (`.within()`) and fan-outs are new, so they adapt under
839
+ // `maxPages` too: there is no 1.36 sizing to keep.
840
+ if (state.maxPagesValue !== undefined && state.planner === undefined && !isFanOutState(state)) {
789
841
  return "natural";
842
+ }
790
843
  if (filtered(state) || dropsRows(state))
791
844
  return "adaptive";
792
845
  return "budget";
793
846
  };
847
+ /** @internal Does this state read a sharded index's partitions? */
848
+ const isFanOutState = (state) => state.fanOut !== undefined;
794
849
  /**
795
850
  * @internal Whether rows are filtered — server-side (the caller's filter or a
796
851
  * plan's own, #171), with a client predicate or by a plan's row check — so a
@@ -1010,11 +1065,10 @@ const prepared = (state, tableName) => {
1010
1065
  const filterRefusal = refuseEmptyFilterParts(state);
1011
1066
  if (filterRefusal !== undefined)
1012
1067
  return Effect.fail(filterRefusal);
1013
- // A query that also reads its 1.36 key (#171) plans both passes from the
1014
- // prepared state: the prepare step may swap its own condition.
1015
- if (state.key136 !== undefined && state.planner === undefined) {
1068
+ // A sharded index's query reads its partitions (#183), resumed from its cursor.
1069
+ if (state.fanOut !== undefined) {
1016
1070
  return Effect.flatMap(applyPrepare(state, tableName), (ready) => {
1017
- const resumed = resume(ready);
1071
+ const resumed = resumeFanOut(ready, ready.fanOut);
1018
1072
  return resumed instanceof ValidationError ? Effect.fail(resumed) : Effect.succeed(resumed);
1019
1073
  });
1020
1074
  }
@@ -1031,7 +1085,6 @@ const applyPrepare = (state, tableName) => state.prepare === undefined
1031
1085
  return {
1032
1086
  ...state,
1033
1087
  prepare: undefined,
1034
- pkValue: prep.pkValue ?? state.pkValue,
1035
1088
  keepRow: prep.keep,
1036
1089
  skConditions: swap === undefined
1037
1090
  ? state.skConditions
@@ -1040,20 +1093,6 @@ const applyPrepare = (state, tableName) => state.prepare === undefined
1040
1093
  : c),
1041
1094
  };
1042
1095
  });
1043
- /**
1044
- * @internal The plan of a query that also reads its 1.36 key (#171): its own
1045
- * key and the 1.36 key, as two passes. `undefined` without one.
1046
- */
1047
- const keyPasses = (state) => state.key136 === undefined || state.isScan
1048
- ? undefined
1049
- : keyPassesPlanner({
1050
- entityType: state.entityTypes.join(", ") || "unknown",
1051
- index: state.indexName ?? "primary",
1052
- pkField: state.pkField,
1053
- skField: state.skField,
1054
- current: { pkValue: state.pkValue, condition: state.skConditions[0]?.condition },
1055
- legacy: state.key136,
1056
- });
1057
1096
  /** @internal The planner a `.within()` installed, resolved against the final state. */
1058
1097
  const resolvePlanner = (state, factory) => factory({
1059
1098
  reverse: !state.scanForward,
@@ -1073,20 +1112,13 @@ const resume = (state) => {
1073
1112
  if (state.cursorText !== undefined && cursor === undefined) {
1074
1113
  return cursorRefusal(entityType, "it is not a cursor a query returned");
1075
1114
  }
1076
- const factory = state.planner ?? keyPasses(state);
1115
+ if (cursor?.z !== undefined) {
1116
+ return cursorRefusal(entityType, "it comes from a query of a sharded index, and this isn't one");
1117
+ }
1118
+ const factory = state.planner;
1077
1119
  if (factory === undefined) {
1078
1120
  if (cursor === undefined)
1079
1121
  return state;
1080
- if (cursor.p !== undefined) {
1081
- // From the same query while it also read its 1.36 key (#171) — the
1082
- // fallback since turned off: a position under the current key resumes.
1083
- if (cursor.p === 1) {
1084
- return cursorRefusal(entityType, "it reads rows under their 1.36 key, and this query no longer does");
1085
- }
1086
- return cursor.k === undefined
1087
- ? state
1088
- : { ...state, exclusiveStartKey: Cursor.keyFromWire(cursor.k) };
1089
- }
1090
1122
  if (cursor.k === undefined ||
1091
1123
  cursor.f !== undefined ||
1092
1124
  cursor.s !== undefined ||
@@ -1109,7 +1141,6 @@ const plannedConditions = (state, range) => {
1109
1141
  /** @internal The state one planned read is sent with: its range and its row check. */
1110
1142
  const readState = (state, step) => ({
1111
1143
  ...state,
1112
- pkValue: step.pkValue ?? state.pkValue,
1113
1144
  skConditions: plannedConditions(state, step.range),
1114
1145
  rowCheck: step.rowCheck,
1115
1146
  });
@@ -1276,7 +1307,11 @@ forCursor) => {
1276
1307
  ]);
1277
1308
  if (projected.size === 0)
1278
1309
  return [];
1279
- const borrowed = new Set(!forCursor || state.limitValue === undefined || !state.keyFields ? [] : state.keyFields);
1310
+ // A fan-out always reads them: the merge compares each row's sort key, and a
1311
+ // cursor resumes each partition after its last row (#183).
1312
+ const borrowed = new Set((!isFanOutState(state) && (!forCursor || state.limitValue === undefined)) || !state.keyFields
1313
+ ? []
1314
+ : state.keyFields);
1280
1315
  // A query that drops rows reads what it judges them by (#133, #171).
1281
1316
  for (const attr of judgedAttributes(state))
1282
1317
  borrowed.add(attr);
@@ -1322,7 +1357,7 @@ const examinePage = (client, tableName, state, returned, budget, borrowedFields)
1322
1357
  // (`end` stays at `next`) — or, under a predicate, accepts one row past
1323
1358
  // the budget. No terminal asks; a guard all the same (#171).
1324
1359
  if (budget === 0)
1325
- return { items: [], stoppedAt: -1, accepted: 0 };
1360
+ return { items: [], stoppedAt: -1, accepted: 0, rows: [] };
1326
1361
  const hasPredicate = state.predicates.length > 0 || dropsRows(state);
1327
1362
  // Borrowed attributes the raw-row hook reads are stripped after it ran:
1328
1363
  // borrowed into the request's projection, or — on a `BatchGet`-hydrated
@@ -1343,6 +1378,7 @@ const examinePage = (client, tableName, state, returned, budget, borrowedFields)
1343
1378
  }
1344
1379
  }
1345
1380
  const items = [];
1381
+ const rows = [];
1346
1382
  let next = 0;
1347
1383
  while (next < returned.length) {
1348
1384
  const end = budget === undefined || hasPredicate
@@ -1369,13 +1405,14 @@ const examinePage = (client, tableName, state, returned, budget, borrowedFields)
1369
1405
  if (hasPredicate && !accepts(state, item))
1370
1406
  continue;
1371
1407
  items.push(item);
1408
+ rows.push(positions[k]);
1372
1409
  if (budget !== undefined && items.length >= budget) {
1373
- return { items, stoppedAt: positions[k], accepted: items.length };
1410
+ return { items, stoppedAt: positions[k], accepted: items.length, rows };
1374
1411
  }
1375
1412
  }
1376
1413
  next = end;
1377
1414
  }
1378
- return { items, stoppedAt: -1, accepted: items.length };
1415
+ return { items, stoppedAt: -1, accepted: items.length, rows };
1379
1416
  });
1380
1417
  /**
1381
1418
  * @internal The subject of a query for consumed-capacity reports: its
@@ -1496,6 +1533,9 @@ const executeCore = (self) => Effect.gen(function* () {
1496
1533
  if (limitValue !== undefined && limitValue <= 0) {
1497
1534
  return { items: [], cursor: Option.none() };
1498
1535
  }
1536
+ if (state.fanOutStart !== undefined) {
1537
+ return yield* executeFanOut(client, tableName, state, state.fanOutStart);
1538
+ }
1499
1539
  if (state.plan !== undefined)
1500
1540
  return yield* executePlanned(client, tableName, state, state.plan);
1501
1541
  // Key attributes borrowed into an active projection so an over-reading
@@ -1730,6 +1770,9 @@ const pageStream = (client, tableName, state) => {
1730
1770
  if (limitValue !== undefined && limitValue <= 0) {
1731
1771
  return Stream.empty;
1732
1772
  }
1773
+ if (state.fanOutStart !== undefined) {
1774
+ return fanOutPageStream(client, tableName, state, state.fanOutStart);
1775
+ }
1733
1776
  if (state.plan !== undefined)
1734
1777
  return plannedPageStream(client, tableName, state, state.plan);
1735
1778
  return Stream.paginate({
@@ -1941,6 +1984,9 @@ const countCore = (self) => Effect.gen(function* () {
1941
1984
  const items = yield* collect(self);
1942
1985
  return items.length;
1943
1986
  }
1987
+ if (state.fanOutStart !== undefined) {
1988
+ return yield* countFanOut(client, tableName, state, state.fanOutStart);
1989
+ }
1944
1990
  if (state.plan !== undefined)
1945
1991
  return yield* countPlanned(client, tableName, state, state.plan);
1946
1992
  // Rows that may be history are judged by a few attributes, so only those
@@ -2112,7 +2158,9 @@ const countPlanned = (client, tableName, state, plan) => Effect.gen(function* ()
2112
2158
  */
2113
2159
  export const explain = (self) => Effect.sync(() => {
2114
2160
  const state = self._state;
2115
- const factory = state.planner ?? keyPasses(state);
2161
+ if (state.fanOut !== undefined)
2162
+ return explainFanOut(state, state.fanOut);
2163
+ const factory = state.planner;
2116
2164
  if (factory === undefined) {
2117
2165
  const [lower, upper] = displayKeyCondition(state.skConditions[0]?.condition);
2118
2166
  return {
@@ -2164,11 +2212,384 @@ export const asParams = (self) => Effect.gen(function* () {
2164
2212
  }
2165
2213
  }
2166
2214
  // A `BatchGet`-hydrated query shows its index query; the `BatchGetItem`
2167
- // that follows each page is not part of these parameters. Nor is the
2168
- // read of a 1.36 key (#171): these are the query's own key's.
2215
+ // that follows each page is not part of these parameters.
2169
2216
  return buildDynamoCommand(indexQueryState(state), tableName);
2170
2217
  });
2171
2218
  // ---------------------------------------------------------------------------
2219
+ // Sharded indexes (#183, docs/designs/gsi-write-sharding.md §6)
2220
+ // ---------------------------------------------------------------------------
2221
+ /** @internal The partitions a fan-out reads, in merge order: its layouts'. */
2222
+ const fanOutPartitions = (state, spec) => {
2223
+ const condition = state.skConditions[0]?.condition;
2224
+ return spec.partitions.map((pkValue) => ({ pkValue, condition }));
2225
+ };
2226
+ /** @internal What a sharded query's cursor must have come from. */
2227
+ const fanOutFingerprint = (state, spec, partitions) => fnv1a32(canonicalJson({
2228
+ index: state.indexName,
2229
+ entityTypes: state.entityTypes,
2230
+ count: spec.count,
2231
+ source: spec.source,
2232
+ previous: spec.previous,
2233
+ partitions: partitions.map(({ pkValue, condition }) => ({ pkValue, condition })),
2234
+ reverse: !state.scanForward,
2235
+ }));
2236
+ /** @internal The checksum of a cursor's positions. */
2237
+ const positionsChecksum = (positions) => fnv1a32(canonicalJson(positions));
2238
+ /**
2239
+ * @internal A fan-out's partitions, resumed from its {@link startFrom} cursor: a
2240
+ * cursor from another layout or query, a position it can't hold or an altered one
2241
+ * is `[EDD-9094]`.
2242
+ */
2243
+ const resumeFanOut = (state, spec) => {
2244
+ const partitions = fanOutPartitions(state, spec);
2245
+ const fingerprint = fanOutFingerprint(state, spec, partitions);
2246
+ const started = (merge) => ({
2247
+ ...state,
2248
+ fanOutStart: { partitions, fingerprint, merge },
2249
+ });
2250
+ if (state.cursorText === undefined)
2251
+ return started(ShardMerge.fromStart(partitions.length));
2252
+ const entityType = state.entityTypes.join(", ") || "unknown";
2253
+ const refuse = (why) => cursorRefusal(entityType, why);
2254
+ const cursor = Cursor.decode(state.cursorText);
2255
+ if (cursor === undefined)
2256
+ return refuse("it is not a cursor a query returned");
2257
+ if (cursor.z === undefined) {
2258
+ return refuse("this index is sharded, and it comes from a query that wasn't");
2259
+ }
2260
+ if (cursor.f !== fingerprint) {
2261
+ return refuse("its shard layout or its query differs from this one's");
2262
+ }
2263
+ if (cursor.c !== positionsChecksum(cursor.z))
2264
+ return refuse("its positions were altered");
2265
+ if (cursor.z.length !== partitions.length) {
2266
+ return refuse("it doesn't hold one position per partition");
2267
+ }
2268
+ const keyNames = new Set((state.keyFields ?? []).filter((name) => name !== state.pkField));
2269
+ const boundaries = [];
2270
+ for (let i = 0; i < partitions.length; i++) {
2271
+ const at = cursor.z[i];
2272
+ if (at === 0) {
2273
+ boundaries.push({ _tag: "Start" });
2274
+ continue;
2275
+ }
2276
+ if (at === 1) {
2277
+ boundaries.push({ _tag: "Done" });
2278
+ continue;
2279
+ }
2280
+ const names = Object.keys(at);
2281
+ if (names.length !== keyNames.size || !names.every((name) => keyNames.has(name))) {
2282
+ return refuse("a position isn't a key of this index");
2283
+ }
2284
+ const partition = partitions[i];
2285
+ const sort = state.skField === undefined ? undefined : at[state.skField];
2286
+ const value = sort === undefined ? undefined : Cursor.wireToKeyValue(sort);
2287
+ if (partition.condition !== undefined &&
2288
+ (value === undefined || !keyConditionHolds(partition.condition, value))) {
2289
+ return refuse("a position is outside the query's key condition");
2290
+ }
2291
+ boundaries.push({
2292
+ _tag: "At",
2293
+ key: Cursor.keyFromWire({ ...at, [state.pkField]: { S: partition.pkValue } }),
2294
+ });
2295
+ }
2296
+ return started(ShardMerge.initial(boundaries));
2297
+ };
2298
+ /** @internal A boundary as a cursor records it. */
2299
+ const positionOf = (state, boundary) => {
2300
+ if (boundary._tag === "Start")
2301
+ return Effect.succeed(0);
2302
+ if (boundary._tag === "Done")
2303
+ return Effect.succeed(1);
2304
+ const key = boundary._tag === "At" ? boundary.key : keyOfItem(boundary.row, state.keyFields);
2305
+ const wire = key === undefined ? undefined : Cursor.keyToWire(key);
2306
+ if (wire === undefined) {
2307
+ return Effect.die(new Error(`[internal] A row read from sharded index "${state.indexName}" lacks a key attribute ` +
2308
+ `of ${JSON.stringify(state.keyFields)}, which the cursor resumes after.`));
2309
+ }
2310
+ const { [state.pkField]: _partition, ...position } = wire;
2311
+ return Effect.succeed(position);
2312
+ };
2313
+ /** @internal The cursor of a fan-out at `merge`: v2, or `None` once every partition is done. */
2314
+ const fanOutCursor = (state, start, merge) => ShardMerge.isFinished(merge)
2315
+ ? Effect.succeed(Option.none())
2316
+ : Effect.map(Effect.forEach(merge, (partition) => positionOf(state, partition.boundary)), (z) => Option.some(Cursor.encodeV2({
2317
+ v: 2,
2318
+ f: start.fingerprint,
2319
+ s: "key",
2320
+ z,
2321
+ c: positionsChecksum(z),
2322
+ })));
2323
+ /** @internal One partition's request, as `state` sends it. */
2324
+ const partitionState = (state, partition) => ({
2325
+ ...state,
2326
+ pkValue: partition.pkValue,
2327
+ skConditions: partition.condition === undefined || state.skField === undefined
2328
+ ? []
2329
+ : [{ field: state.skField, condition: partition.condition }],
2330
+ rowCheck: undefined,
2331
+ });
2332
+ /** @internal The `ExclusiveStartKey` a boundary resumes from. */
2333
+ const fanOutStartKey = (state, boundary) => boundary._tag === "At"
2334
+ ? boundary.key
2335
+ : boundary._tag === "After"
2336
+ ? keyOfItem(boundary.row, state.keyFields)
2337
+ : undefined;
2338
+ /**
2339
+ * @internal The `Limit` of a partition's next request (design §6.5), `remaining`
2340
+ * items still owed and `active` partitions unfinished: the partition's share of
2341
+ * what is owed, growing where it keeps running dry.
2342
+ */
2343
+ const fanOutLimit = (sent, remaining, active, est) => {
2344
+ const mode = sizingMode(sent);
2345
+ if (remaining === undefined || mode === "none")
2346
+ return legacyRequestLimit(sent, remaining);
2347
+ const share = Math.ceil(remaining / Math.max(active, 1));
2348
+ if (mode === "adaptive")
2349
+ return nextLimit(est, share, filtered(sent));
2350
+ if (mode === "budget") {
2351
+ return Math.min(remaining, Math.max(Math.ceil(share * SAFETY), est.lastLimit * GROWTH));
2352
+ }
2353
+ return legacyRequestLimit(sent, remaining, est.requests + 1);
2354
+ };
2355
+ const startFanOut = (start) => ({
2356
+ merge: start.merge,
2357
+ estimators: start.partitions.map(() => emptyEstimator),
2358
+ pages: start.partitions.map(() => undefined),
2359
+ requests: 0,
2360
+ rounds: 0,
2361
+ emitted: 0,
2362
+ });
2363
+ /** @internal How many requests a fan-out's round sends at once. */
2364
+ const fanOutConcurrency = (state, partitions) => state.concurrencyValue ?? Math.max(partitions, 1);
2365
+ /** @internal Are `maxPages` rounds used up? */
2366
+ const roundsUsed = (state, run) => state.maxPagesValue != null && run.rounds >= state.maxPagesValue;
2367
+ /**
2368
+ * @internal One round of a fan-out: read every partition with nothing buffered
2369
+ * and more to read (at most one page each), unless `read` is false, then emit
2370
+ * what is proven in order, up to the `limit`. Any request's failure fails the
2371
+ * round, with the others interrupted. A page is reported to the observers when
2372
+ * its rows are consumed, so `accepted` is exact.
2373
+ */
2374
+ const fanOutRound = (client, tableName, state, start, run) => Effect.gen(function* () {
2375
+ const limitValue = state.limitValue;
2376
+ const remainingBefore = limitValue === undefined ? undefined : limitValue - run.emitted;
2377
+ const needing = ShardMerge.needingRead(run.merge);
2378
+ const active = ShardMerge.unfinished(run.merge);
2379
+ let merge = run.merge;
2380
+ const estimators = [...run.estimators];
2381
+ const pages = [...run.pages];
2382
+ // The same attributes for every partition: a row check on one borrows what it
2383
+ // judges, and `examinePage` strips the lot.
2384
+ const borrowed = [
2385
+ ...new Set(start.partitions.flatMap((partition) => cursorProjectionFields(indexQueryState(partitionState(state, partition)), true))),
2386
+ ];
2387
+ const report = (i) => {
2388
+ const page = pages[i];
2389
+ if (page === undefined)
2390
+ return Effect.void;
2391
+ pages[i] = undefined;
2392
+ estimators[i] = observeEstimator(estimators[i], {
2393
+ scanned: page.counts.scannedCount,
2394
+ accepted: page.accepted,
2395
+ limitSent: page.limitSent,
2396
+ });
2397
+ return notify(page.sent, {
2398
+ kind: "read",
2399
+ request: page.request,
2400
+ limit: page.limitSent,
2401
+ ...page.counts,
2402
+ accepted: page.accepted,
2403
+ });
2404
+ };
2405
+ const responses = yield* Effect.forEach(needing, (i, n) => Effect.gen(function* () {
2406
+ const sent = partitionState(state, start.partitions[i]);
2407
+ const limitSent = fanOutLimit(sent, remainingBefore, active, estimators[i]);
2408
+ const cmd = buildDynamoCommand(indexQueryState(sent), tableName, { ExclusiveStartKey: fanOutStartKey(state, run.merge[i].boundary), Limit: limitSent }, borrowed);
2409
+ const result = yield* send(client, sent, cmd);
2410
+ return {
2411
+ i,
2412
+ request: run.requests + n + 1,
2413
+ sent,
2414
+ limitSent,
2415
+ result,
2416
+ };
2417
+ }), { concurrency: fanOutConcurrency(state, needing.length) });
2418
+ for (const { i, request, sent, limitSent, result } of responses) {
2419
+ const returned = (result.Items ?? []);
2420
+ const kept = returned.filter((row) => !isExcludedRow(sent, row));
2421
+ merge = ShardMerge.absorb(merge, i, kept, result.LastEvaluatedKey);
2422
+ pages[i] = { sent, request, limitSent, counts: responseCounts(result), accepted: 0 };
2423
+ // Nothing left in the page: nothing will ever be consumed from it.
2424
+ if (kept.length === 0)
2425
+ yield* report(i);
2426
+ }
2427
+ const budget = limitValue === undefined ? Number.POSITIVE_INFINITY : limitValue - run.emitted;
2428
+ const selection = yield* Effect.try({
2429
+ try: () => ShardMerge.select(merge, budget, {
2430
+ skField: state.skField ?? "",
2431
+ reverse: !state.scanForward,
2432
+ }),
2433
+ catch: (error) => error,
2434
+ }).pipe(Effect.orDie);
2435
+ merge = selection.state;
2436
+ // Rows dropped at the read aren't examined again; the rest are decoded
2437
+ // together, which is what lets a `BatchGet`-hydrated query fetch them at once.
2438
+ const page = yield* examinePage(client, tableName, { ...state, rowCheck: undefined, keepRow: undefined, liveRows: undefined }, selection.taken.map((selected) => selected.row), undefined, borrowed);
2439
+ for (const at of page.rows) {
2440
+ const i = selection.taken[at].partition;
2441
+ const accepted = pages[i];
2442
+ if (accepted !== undefined)
2443
+ pages[i] = { ...accepted, accepted: accepted.accepted + 1 };
2444
+ }
2445
+ for (const i of selection.drained)
2446
+ yield* report(i);
2447
+ return {
2448
+ run: {
2449
+ merge,
2450
+ estimators,
2451
+ pages,
2452
+ requests: run.requests + needing.length,
2453
+ rounds: needing.length > 0 ? run.rounds + 1 : run.rounds,
2454
+ emitted: run.emitted + page.items.length,
2455
+ },
2456
+ items: page.items,
2457
+ };
2458
+ });
2459
+ /**
2460
+ * @internal Report the pages a fan-out read and never finished consuming: a page
2461
+ * with no row consumed is `discarded`, and a later call reads what remains again.
2462
+ */
2463
+ const reportUnfinished = (run) => Effect.forEach(run.pages.filter((page) => page !== undefined), (page) => notify(page.sent, {
2464
+ kind: "read",
2465
+ request: page.request,
2466
+ limit: page.limitSent,
2467
+ ...page.counts,
2468
+ accepted: page.accepted,
2469
+ discarded: page.accepted === 0,
2470
+ }), { discard: true });
2471
+ /**
2472
+ * @internal `execute` for a sharded index. With a `limit`, rounds until `limit`
2473
+ * items are out, every partition is done, or `maxPages` rounds were read. Without
2474
+ * one, a page is one round, as a page without a plan is one request.
2475
+ */
2476
+ const executeFanOut = (client, tableName, state, start) => Effect.gen(function* () {
2477
+ const limitValue = state.limitValue;
2478
+ const items = [];
2479
+ let run = startFanOut(start);
2480
+ while (!ShardMerge.isFinished(run.merge)) {
2481
+ const stepped = yield* fanOutRound(client, tableName, state, start, run);
2482
+ run = stepped.run;
2483
+ items.push(...stepped.items);
2484
+ if (limitValue === undefined)
2485
+ break;
2486
+ if (run.emitted >= limitValue)
2487
+ break;
2488
+ // A partition must be read, and the rounds are up.
2489
+ if (ShardMerge.needingRead(run.merge).length > 0 && roundsUsed(state, run))
2490
+ break;
2491
+ }
2492
+ yield* reportUnfinished(run);
2493
+ return {
2494
+ items,
2495
+ cursor: yield* fanOutCursor(state, start, run.merge),
2496
+ };
2497
+ });
2498
+ /**
2499
+ * @internal `pageStream` for a sharded index: one array per round. At most one
2500
+ * page per partition is held. The stream ends once `limit` items are out, every
2501
+ * partition is done, or `maxPages` rounds were read.
2502
+ */
2503
+ const fanOutPageStream = (client, tableName, state, start) => Stream.paginate(startFanOut(start), (run) => Effect.gen(function* () {
2504
+ if (ShardMerge.isFinished(run.merge))
2505
+ return [[], Option.none()];
2506
+ const stepped = yield* fanOutRound(client, tableName, state, start, run);
2507
+ const next = stepped.run;
2508
+ const filled = state.limitValue !== undefined && next.emitted >= state.limitValue;
2509
+ const stuck = ShardMerge.needingRead(next.merge).length > 0 && roundsUsed(state, next);
2510
+ const more = !filled && !stuck && !ShardMerge.isFinished(next.merge);
2511
+ if (!more)
2512
+ yield* reportUnfinished(next);
2513
+ return [[stepped.items], more ? Option.some(next) : Option.none()];
2514
+ }));
2515
+ /**
2516
+ * @internal `count` for a sharded index: each partition counted from where it
2517
+ * resumes, `Select: COUNT` or the rows a row check judges, summed and capped at the
2518
+ * `limit`. `maxPages` caps each partition's requests. Any failure fails the count.
2519
+ */
2520
+ const countFanOut = (client, tableName, state, start) => Effect.gen(function* () {
2521
+ const limitValue = state.limitValue;
2522
+ let total = 0;
2523
+ let requests = 0;
2524
+ const reached = () => limitValue !== undefined && total >= limitValue;
2525
+ const counting = start.partitions.flatMap((partition, i) => start.merge[i].boundary._tag === "Done" ? [] : [{ partition, i }]);
2526
+ yield* Effect.forEach(counting, ({ partition, i }) => Effect.gen(function* () {
2527
+ const sent = partitionState(state, partition);
2528
+ const judging = dropsRows(sent);
2529
+ let startKey = fanOutStartKey(state, start.merge[i].boundary);
2530
+ let est = emptyEstimator;
2531
+ let pages = 0;
2532
+ do {
2533
+ if (reached())
2534
+ return;
2535
+ pages++;
2536
+ const remaining = limitValue === undefined ? undefined : limitValue - total;
2537
+ const limitSent = fanOutLimit(sent, remaining, counting.length, est);
2538
+ const cmd = judging
2539
+ ? buildDynamoCommand({ ...sent, projection: judgedAttributes(sent), projectionPaths: undefined }, tableName, { ExclusiveStartKey: startKey, Limit: limitSent })
2540
+ : buildDynamoCommand(sent, tableName, {
2541
+ ExclusiveStartKey: startKey,
2542
+ Select: "COUNT",
2543
+ Limit: limitSent,
2544
+ });
2545
+ const request = ++requests;
2546
+ const result = yield* send(client, sent, cmd);
2547
+ const counts = responseCounts(result);
2548
+ const matched = judging
2549
+ ? (result.Items ?? []).filter((row) => !isExcludedRow(sent, row)).length
2550
+ : (result.Count ?? 0);
2551
+ const scanned = judging ? counts.scannedCount : (result.ScannedCount ?? matched);
2552
+ total += matched;
2553
+ est = observeEstimator(est, { scanned, accepted: matched, limitSent });
2554
+ yield* notify(sent, {
2555
+ kind: "count",
2556
+ request,
2557
+ limit: limitSent,
2558
+ scannedCount: scanned,
2559
+ count: judging ? counts.count : matched,
2560
+ accepted: matched,
2561
+ });
2562
+ startKey = result.LastEvaluatedKey;
2563
+ if (state.maxPagesValue != null && pages >= state.maxPagesValue)
2564
+ return;
2565
+ } while (startKey != null);
2566
+ }), { concurrency: fanOutConcurrency(state, counting.length), discard: true });
2567
+ return limitValue !== undefined && total >= limitValue ? limitValue : total;
2568
+ });
2569
+ /** @internal {@link explain} of a sharded index's query: no cursor is read. */
2570
+ const explainFanOut = (state, spec) => {
2571
+ const partitions = fanOutPartitions(state, spec);
2572
+ return {
2573
+ index: state.indexName ?? "primary",
2574
+ plan: "key",
2575
+ reason: spec.pruned && partitions.length === 1
2576
+ ? "every shard source attribute pinned: one shard"
2577
+ : `one key condition on each of ${partitions.length} partitions, merged`,
2578
+ keyConditions: partitions.map(({ condition }) => {
2579
+ const [lower, upper] = displayKeyCondition(condition);
2580
+ return { lower, upper, exact: true };
2581
+ }),
2582
+ filter: undefined,
2583
+ rowChecks: [],
2584
+ sizing: explainedSizing(state),
2585
+ fanOut: {
2586
+ partitions: partitions.map(({ pkValue }) => pkValue),
2587
+ pruned: spec.pruned,
2588
+ concurrency: fanOutConcurrency(state, partitions.length),
2589
+ },
2590
+ };
2591
+ };
2592
+ // ---------------------------------------------------------------------------
2172
2593
  // Type guard
2173
2594
  // ---------------------------------------------------------------------------
2174
2595
  export const isQuery = (u) => typeof u === "object" && u !== null && QueryTypeId in u;