effect-dynamodb 1.38.0 → 1.40.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 (152) hide show
  1. package/dist/Aggregate.d.ts +119 -15
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +2286 -670
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +9 -5
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +97 -232
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +27 -21
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/ConsumedCapacity.js +1 -1
  13. package/dist/ConsumedCapacity.js.map +1 -1
  14. package/dist/DynamoClient.d.ts +44 -16
  15. package/dist/DynamoClient.d.ts.map +1 -1
  16. package/dist/DynamoClient.js +299 -166
  17. package/dist/DynamoClient.js.map +1 -1
  18. package/dist/Entity.d.ts +94 -104
  19. package/dist/Entity.d.ts.map +1 -1
  20. package/dist/Entity.js +3673 -3022
  21. package/dist/Entity.js.map +1 -1
  22. package/dist/EventStore.d.ts +39 -17
  23. package/dist/EventStore.d.ts.map +1 -1
  24. package/dist/EventStore.js +392 -366
  25. package/dist/EventStore.js.map +1 -1
  26. package/dist/Marshaller.d.ts +39 -9
  27. package/dist/Marshaller.d.ts.map +1 -1
  28. package/dist/Marshaller.js +421 -70
  29. package/dist/Marshaller.js.map +1 -1
  30. package/dist/Query.d.ts +93 -32
  31. package/dist/Query.d.ts.map +1 -1
  32. package/dist/Query.js +550 -83
  33. package/dist/Query.js.map +1 -1
  34. package/dist/StorageEncoding.d.ts +7 -1
  35. package/dist/StorageEncoding.d.ts.map +1 -1
  36. package/dist/StorageEncoding.js +8 -2
  37. package/dist/StorageEncoding.js.map +1 -1
  38. package/dist/Table.d.ts +71 -4
  39. package/dist/Table.d.ts.map +1 -1
  40. package/dist/Table.js +7 -0
  41. package/dist/Table.js.map +1 -1
  42. package/dist/Transaction.d.ts +2 -18
  43. package/dist/Transaction.d.ts.map +1 -1
  44. package/dist/Transaction.js +11 -62
  45. package/dist/Transaction.js.map +1 -1
  46. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  47. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  48. package/dist/change-feed/ChangeFeed.js +76 -9
  49. package/dist/change-feed/ChangeFeed.js.map +1 -1
  50. package/dist/change-feed/CheckpointStore.js +1 -1
  51. package/dist/change-feed/CheckpointStore.js.map +1 -1
  52. package/dist/change-feed/DynamoStreamsClient.d.ts +12 -5
  53. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  54. package/dist/change-feed/DynamoStreamsClient.js +15 -9
  55. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  56. package/dist/index.d.ts +1 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/internal/BoundCrud.d.ts +40 -32
  61. package/dist/internal/BoundCrud.d.ts.map +1 -1
  62. package/dist/internal/BoundCrud.js.map +1 -1
  63. package/dist/internal/BoundQuery.d.ts +12 -9
  64. package/dist/internal/BoundQuery.d.ts.map +1 -1
  65. package/dist/internal/BoundQuery.js +26 -12
  66. package/dist/internal/BoundQuery.js.map +1 -1
  67. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  68. package/dist/internal/BoundVectorQuery.js +2 -1
  69. package/dist/internal/BoundVectorQuery.js.map +1 -1
  70. package/dist/internal/Capacity.d.ts +44 -4
  71. package/dist/internal/Capacity.d.ts.map +1 -1
  72. package/dist/internal/Capacity.js +89 -15
  73. package/dist/internal/Capacity.js.map +1 -1
  74. package/dist/internal/ClientOptions.d.ts +72 -0
  75. package/dist/internal/ClientOptions.d.ts.map +1 -0
  76. package/dist/internal/ClientOptions.js +79 -0
  77. package/dist/internal/ClientOptions.js.map +1 -0
  78. package/dist/internal/Cursor.d.ts +28 -14
  79. package/dist/internal/Cursor.d.ts.map +1 -1
  80. package/dist/internal/Cursor.js +37 -12
  81. package/dist/internal/Cursor.js.map +1 -1
  82. package/dist/internal/EntityCombinators.d.ts +22 -7
  83. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  84. package/dist/internal/EntityCombinators.js +6 -2
  85. package/dist/internal/EntityCombinators.js.map +1 -1
  86. package/dist/internal/EntityOps.d.ts +11 -1
  87. package/dist/internal/EntityOps.d.ts.map +1 -1
  88. package/dist/internal/EntityOps.js.map +1 -1
  89. package/dist/internal/EventProjection.d.ts +15 -3
  90. package/dist/internal/EventProjection.d.ts.map +1 -1
  91. package/dist/internal/EventProjection.js +27 -8
  92. package/dist/internal/EventProjection.js.map +1 -1
  93. package/dist/internal/Expr.d.ts.map +1 -1
  94. package/dist/internal/Expr.js +53 -2
  95. package/dist/internal/Expr.js.map +1 -1
  96. package/dist/internal/ExpressionLimits.d.ts +57 -1
  97. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  98. package/dist/internal/ExpressionLimits.js +90 -1
  99. package/dist/internal/ExpressionLimits.js.map +1 -1
  100. package/dist/internal/ItemSize.d.ts +108 -4
  101. package/dist/internal/ItemSize.d.ts.map +1 -1
  102. package/dist/internal/ItemSize.js +190 -3
  103. package/dist/internal/ItemSize.js.map +1 -1
  104. package/dist/internal/MultiProjection.d.ts +7 -2
  105. package/dist/internal/MultiProjection.d.ts.map +1 -1
  106. package/dist/internal/MultiProjection.js +9 -3
  107. package/dist/internal/MultiProjection.js.map +1 -1
  108. package/dist/internal/PathBuilder.d.ts +15 -4
  109. package/dist/internal/PathBuilder.d.ts.map +1 -1
  110. package/dist/internal/PathBuilder.js +20 -10
  111. package/dist/internal/PathBuilder.js.map +1 -1
  112. package/dist/internal/ProjectionEngine.d.ts +78 -18
  113. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  114. package/dist/internal/ProjectionEngine.js +402 -257
  115. package/dist/internal/ProjectionEngine.js.map +1 -1
  116. package/dist/internal/RangePlanner.d.ts +0 -76
  117. package/dist/internal/RangePlanner.d.ts.map +1 -1
  118. package/dist/internal/RangePlanner.js +2 -206
  119. package/dist/internal/RangePlanner.js.map +1 -1
  120. package/dist/internal/Rekey.d.ts +49 -7
  121. package/dist/internal/Rekey.d.ts.map +1 -1
  122. package/dist/internal/Rekey.js +113 -10
  123. package/dist/internal/Rekey.js.map +1 -1
  124. package/dist/internal/RoundTrip.d.ts +36 -0
  125. package/dist/internal/RoundTrip.d.ts.map +1 -0
  126. package/dist/internal/RoundTrip.js +79 -0
  127. package/dist/internal/RoundTrip.js.map +1 -0
  128. package/dist/internal/SentRequest.d.ts +14 -0
  129. package/dist/internal/SentRequest.d.ts.map +1 -0
  130. package/dist/internal/SentRequest.js +31 -0
  131. package/dist/internal/SentRequest.js.map +1 -0
  132. package/dist/internal/ShardMerge.d.ts +83 -0
  133. package/dist/internal/ShardMerge.d.ts.map +1 -0
  134. package/dist/internal/ShardMerge.js +182 -0
  135. package/dist/internal/ShardMerge.js.map +1 -0
  136. package/dist/internal/TransactPlan.d.ts +1 -8
  137. package/dist/internal/TransactPlan.d.ts.map +1 -1
  138. package/dist/internal/TransactPlan.js +2 -9
  139. package/dist/internal/TransactPlan.js.map +1 -1
  140. package/dist/internal/TransactWriteOps.d.ts +75 -24
  141. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  142. package/dist/internal/TransactWriteOps.js +147 -186
  143. package/dist/internal/TransactWriteOps.js.map +1 -1
  144. package/dist/internal/TransactableOps.d.ts +123 -29
  145. package/dist/internal/TransactableOps.d.ts.map +1 -1
  146. package/dist/internal/TransactableOps.js +255 -87
  147. package/dist/internal/TransactableOps.js.map +1 -1
  148. package/dist/internal/WriteDiagnosis.d.ts +31 -3
  149. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  150. package/dist/internal/WriteDiagnosis.js +128 -11
  151. package/dist/internal/WriteDiagnosis.js.map +1 -1
  152. package/package.json +4 -2
package/dist/Query.js CHANGED
@@ -16,8 +16,9 @@ import * as Cursor from "./internal/Cursor.js";
16
16
  import { compileExpr, ExprTag, emptyPartProblem, isEmptyExpr } from "./internal/Expr.js";
17
17
  import { batchGetRaw } from "./internal/Hydrate.js";
18
18
  import { packedExprRefusal, packedProjectionRefusal, } from "./internal/Packed.js";
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";
19
+ import { compilePath, storedPath } from "./internal/PathBuilder.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,115 @@ 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
+ /**
224
+ * @internal A query whose terminals fail with `refusal`: building one has no error
225
+ * channel to fail into, and a value a key can't hold is the caller's error, not a
226
+ * defect. Nothing is sent.
227
+ */
228
+ export const refuse = (self, refusal) => new QueryImpl({ ...self._state, refusal });
229
+ /** @internal Has {@link refuse} refused this query? Its builders have nothing left to do. */
230
+ export const isRefused = (self) => self._state.refusal !== undefined;
231
+ /** @internal A query that could not even be built: a composite it was given has no key. */
232
+ export const refused = (indexName, refusal) => refuse(make({
233
+ tableName: "",
234
+ indexName,
235
+ pkField: "",
236
+ pkValue: "",
237
+ skField: undefined,
238
+ entityTypes: [],
239
+ decoder: () => Effect.die(refusal),
240
+ }), refusal);
241
+ /**
242
+ * @internal What `build` returns, or `onRefusal` of the `ValidationError` for a value it
243
+ * threw for (`Capacity.isRefusedValue`). Any other throw is a misuse of the API and stays one.
244
+ */
245
+ export const orRefusal = (operation, build, onRefusal) => {
246
+ try {
247
+ return build();
248
+ }
249
+ catch (cause) {
250
+ if (!Capacity.isRefusedValue(cause))
251
+ throw cause;
252
+ const name = operation?.name ?? "query";
253
+ return onRefusal(new ValidationError({ entityType: operation?.target ?? name, operation: name, cause }));
254
+ }
255
+ };
256
+ /** @internal Does this query read a sharded index's partitions (#183)? */
257
+ export const isFanOut = (self) => self._state.fanOut !== undefined;
258
+ /**
259
+ * How many requests a query of a sharded index sends at once, per round of its
260
+ * fan-out (#183). The default is one per partition. A query with no fan-out sends
261
+ * one request at a time whatever this says. Anything but a positive integer
262
+ * throws `[EDD-9105]`.
263
+ *
264
+ * ```ts
265
+ * query.pipe(Query.concurrency(4), Query.collect)
266
+ * ```
267
+ */
268
+ export const concurrency = Function.dual(2, (self, n) => {
269
+ if (!Number.isInteger(n) || n < 1) {
270
+ throw new Error(`[EDD-9105] concurrency(${JSON.stringify(n)}) is not a number of requests: pass a ` +
271
+ `positive integer.`);
272
+ }
273
+ return new QueryImpl({ ...self._state, concurrencyValue: n });
274
+ });
209
275
  /**
210
276
  * Return **at most `n` items** — a contract on results, not on round trips.
211
277
  *
@@ -334,16 +400,34 @@ export const startFrom = Function.dual(2, (self, cursor) => cursor === ""
334
400
  * combinators that follow (`reverse`, `startFrom`, …) still apply. Not a
335
401
  * combinator: Z-order and skip-scan are reached through `BoundQuery`.
336
402
  */
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 });
403
+ export const plan = (self, install) => {
404
+ if (self._state.fanOut !== undefined)
405
+ throw shardedPlanRefusal(self._state);
406
+ return new QueryImpl("zorder" in install
407
+ ? { ...self._state, zorderOptions: { ...self._state.zorderOptions, ...install.zorder } }
408
+ : { ...self._state, planner: install.planner, maxSkips: install.maxSkips });
409
+ };
410
+ /**
411
+ * @internal `[EDD-9104]`: `.within()`, skip-scan and `.zorder()` plan one
412
+ * partition's reads, so a sharded index would need a plan per shard. A follow-up.
413
+ */
414
+ const shardedPlanRefusal = (state) => new Error(`[EDD-9104] Index "${state.indexName}" of ${state.entityTypes.join(", ") || "this query"} is ` +
415
+ `sharded: .within(), skip-scan and .zorder() aren't supported on a sharded index. Use the ` +
416
+ `accessor's sort key composites or .where(), or .filter() for the rest.`);
417
+ /** @internal {@link shardedPlanRefusal}, for an accessor to raise before it plans. */
418
+ export const refuseShardedPlan = (self) => {
419
+ if (self._state.fanOut !== undefined)
420
+ throw shardedPlanRefusal(self._state);
421
+ };
340
422
  /**
341
423
  * @internal A query no stored row satisfies (#171) — a `.history()` bound with
342
424
  * no key text below it (`lt("")` on a string orderBy) — planned `empty`, as a
343
425
  * `.within()` whose bounds admit no value is: nothing is sent, the terminals
344
426
  * return no items, and `explain()` reports the `empty` plan.
345
427
  */
346
- export const planEmpty = (self) => plan(self, {
428
+ export const planEmpty = (self) =>
429
+ // Nothing is read, so no partition is: a fan-out has nothing left to merge.
430
+ plan(new QueryImpl({ ...self._state, fanOut: undefined }), {
347
431
  planner: compositePlanner({
348
432
  entityType: self._state.entityTypes.join(", ") || "unknown",
349
433
  index: self._state.indexName ?? "primary",
@@ -423,7 +507,7 @@ export const selectProjected = (self, storedPaths, decode) => {
423
507
  */
424
508
  export const selectRenamed = (self, paths, resolveDbName) => {
425
509
  const heads = [...new Set(paths.map((path) => String(path[0])))];
426
- return selectProjected(self, paths.map((path) => [resolveDbName(String(path[0])), ...path.slice(1)]), (raw) => {
510
+ return selectProjected(self, paths.map((path) => storedPath(path, resolveDbName)), (raw) => {
427
511
  const item = {};
428
512
  for (const head of heads) {
429
513
  const value = raw[resolveDbName(head)];
@@ -784,13 +868,17 @@ const sizingMode = (state) => {
784
868
  return "natural";
785
869
  if (state.limitValue === undefined)
786
870
  return "none";
787
- // Planned queries (`.within()`) are new, so they adapt under `maxPages` too.
788
- if (state.maxPagesValue !== undefined && state.planner === undefined)
871
+ // Planned queries (`.within()`) and fan-outs are new, so they adapt under
872
+ // `maxPages` too: there is no 1.36 sizing to keep.
873
+ if (state.maxPagesValue !== undefined && state.planner === undefined && !isFanOutState(state)) {
789
874
  return "natural";
875
+ }
790
876
  if (filtered(state) || dropsRows(state))
791
877
  return "adaptive";
792
878
  return "budget";
793
879
  };
880
+ /** @internal Does this state read a sharded index's partitions? */
881
+ const isFanOutState = (state) => state.fanOut !== undefined;
794
882
  /**
795
883
  * @internal Whether rows are filtered — server-side (the caller's filter or a
796
884
  * plan's own, #171), with a client predicate or by a plan's row check — so a
@@ -998,6 +1086,8 @@ const refuseEmptyFilterParts = (state) => {
998
1086
  * first step (#171).
999
1087
  */
1000
1088
  const prepared = (state, tableName) => {
1089
+ if (state.refusal !== undefined)
1090
+ return Effect.fail(state.refusal);
1001
1091
  // `.within()` is offered only where no prepare step is installed (an
1002
1092
  // entity's `versions` installs one).
1003
1093
  if (state.planner !== undefined && state.prepare !== undefined) {
@@ -1010,11 +1100,10 @@ const prepared = (state, tableName) => {
1010
1100
  const filterRefusal = refuseEmptyFilterParts(state);
1011
1101
  if (filterRefusal !== undefined)
1012
1102
  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) {
1103
+ // A sharded index's query reads its partitions (#183), resumed from its cursor.
1104
+ if (state.fanOut !== undefined) {
1016
1105
  return Effect.flatMap(applyPrepare(state, tableName), (ready) => {
1017
- const resumed = resume(ready);
1106
+ const resumed = resumeFanOut(ready, ready.fanOut);
1018
1107
  return resumed instanceof ValidationError ? Effect.fail(resumed) : Effect.succeed(resumed);
1019
1108
  });
1020
1109
  }
@@ -1031,7 +1120,6 @@ const applyPrepare = (state, tableName) => state.prepare === undefined
1031
1120
  return {
1032
1121
  ...state,
1033
1122
  prepare: undefined,
1034
- pkValue: prep.pkValue ?? state.pkValue,
1035
1123
  keepRow: prep.keep,
1036
1124
  skConditions: swap === undefined
1037
1125
  ? state.skConditions
@@ -1040,20 +1128,6 @@ const applyPrepare = (state, tableName) => state.prepare === undefined
1040
1128
  : c),
1041
1129
  };
1042
1130
  });
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
1131
  /** @internal The planner a `.within()` installed, resolved against the final state. */
1058
1132
  const resolvePlanner = (state, factory) => factory({
1059
1133
  reverse: !state.scanForward,
@@ -1073,20 +1147,13 @@ const resume = (state) => {
1073
1147
  if (state.cursorText !== undefined && cursor === undefined) {
1074
1148
  return cursorRefusal(entityType, "it is not a cursor a query returned");
1075
1149
  }
1076
- const factory = state.planner ?? keyPasses(state);
1150
+ if (cursor?.z !== undefined) {
1151
+ return cursorRefusal(entityType, "it comes from a query of a sharded index, and this isn't one");
1152
+ }
1153
+ const factory = state.planner;
1077
1154
  if (factory === undefined) {
1078
1155
  if (cursor === undefined)
1079
1156
  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
1157
  if (cursor.k === undefined ||
1091
1158
  cursor.f !== undefined ||
1092
1159
  cursor.s !== undefined ||
@@ -1109,7 +1176,6 @@ const plannedConditions = (state, range) => {
1109
1176
  /** @internal The state one planned read is sent with: its range and its row check. */
1110
1177
  const readState = (state, step) => ({
1111
1178
  ...state,
1112
- pkValue: step.pkValue ?? state.pkValue,
1113
1179
  skConditions: plannedConditions(state, step.range),
1114
1180
  rowCheck: step.rowCheck,
1115
1181
  });
@@ -1276,7 +1342,11 @@ forCursor) => {
1276
1342
  ]);
1277
1343
  if (projected.size === 0)
1278
1344
  return [];
1279
- const borrowed = new Set(!forCursor || state.limitValue === undefined || !state.keyFields ? [] : state.keyFields);
1345
+ // A fan-out always reads them: the merge compares each row's sort key, and a
1346
+ // cursor resumes each partition after its last row (#183).
1347
+ const borrowed = new Set((!isFanOutState(state) && (!forCursor || state.limitValue === undefined)) || !state.keyFields
1348
+ ? []
1349
+ : state.keyFields);
1280
1350
  // A query that drops rows reads what it judges them by (#133, #171).
1281
1351
  for (const attr of judgedAttributes(state))
1282
1352
  borrowed.add(attr);
@@ -1322,7 +1392,7 @@ const examinePage = (client, tableName, state, returned, budget, borrowedFields)
1322
1392
  // (`end` stays at `next`) — or, under a predicate, accepts one row past
1323
1393
  // the budget. No terminal asks; a guard all the same (#171).
1324
1394
  if (budget === 0)
1325
- return { items: [], stoppedAt: -1, accepted: 0 };
1395
+ return { items: [], stoppedAt: -1, accepted: 0, rows: [] };
1326
1396
  const hasPredicate = state.predicates.length > 0 || dropsRows(state);
1327
1397
  // Borrowed attributes the raw-row hook reads are stripped after it ran:
1328
1398
  // borrowed into the request's projection, or — on a `BatchGet`-hydrated
@@ -1343,6 +1413,7 @@ const examinePage = (client, tableName, state, returned, budget, borrowedFields)
1343
1413
  }
1344
1414
  }
1345
1415
  const items = [];
1416
+ const rows = [];
1346
1417
  let next = 0;
1347
1418
  while (next < returned.length) {
1348
1419
  const end = budget === undefined || hasPredicate
@@ -1369,13 +1440,14 @@ const examinePage = (client, tableName, state, returned, budget, borrowedFields)
1369
1440
  if (hasPredicate && !accepts(state, item))
1370
1441
  continue;
1371
1442
  items.push(item);
1443
+ rows.push(positions[k]);
1372
1444
  if (budget !== undefined && items.length >= budget) {
1373
- return { items, stoppedAt: positions[k], accepted: items.length };
1445
+ return { items, stoppedAt: positions[k], accepted: items.length, rows };
1374
1446
  }
1375
1447
  }
1376
1448
  next = end;
1377
1449
  }
1378
- return { items, stoppedAt: -1, accepted: items.length };
1450
+ return { items, stoppedAt: -1, accepted: items.length, rows };
1379
1451
  });
1380
1452
  /**
1381
1453
  * @internal The subject of a query for consumed-capacity reports: its
@@ -1496,6 +1568,9 @@ const executeCore = (self) => Effect.gen(function* () {
1496
1568
  if (limitValue !== undefined && limitValue <= 0) {
1497
1569
  return { items: [], cursor: Option.none() };
1498
1570
  }
1571
+ if (state.fanOutStart !== undefined) {
1572
+ return yield* executeFanOut(client, tableName, state, state.fanOutStart);
1573
+ }
1499
1574
  if (state.plan !== undefined)
1500
1575
  return yield* executePlanned(client, tableName, state, state.plan);
1501
1576
  // Key attributes borrowed into an active projection so an over-reading
@@ -1730,6 +1805,9 @@ const pageStream = (client, tableName, state) => {
1730
1805
  if (limitValue !== undefined && limitValue <= 0) {
1731
1806
  return Stream.empty;
1732
1807
  }
1808
+ if (state.fanOutStart !== undefined) {
1809
+ return fanOutPageStream(client, tableName, state, state.fanOutStart);
1810
+ }
1733
1811
  if (state.plan !== undefined)
1734
1812
  return plannedPageStream(client, tableName, state, state.plan);
1735
1813
  return Stream.paginate({
@@ -1941,6 +2019,9 @@ const countCore = (self) => Effect.gen(function* () {
1941
2019
  const items = yield* collect(self);
1942
2020
  return items.length;
1943
2021
  }
2022
+ if (state.fanOutStart !== undefined) {
2023
+ return yield* countFanOut(client, tableName, state, state.fanOutStart);
2024
+ }
1944
2025
  if (state.plan !== undefined)
1945
2026
  return yield* countPlanned(client, tableName, state, state.plan);
1946
2027
  // Rows that may be history are judged by a few attributes, so only those
@@ -2112,7 +2193,20 @@ const countPlanned = (client, tableName, state, plan) => Effect.gen(function* ()
2112
2193
  */
2113
2194
  export const explain = (self) => Effect.sync(() => {
2114
2195
  const state = self._state;
2115
- const factory = state.planner ?? keyPasses(state);
2196
+ if (state.refusal !== undefined) {
2197
+ return {
2198
+ index: state.indexName ?? "primary",
2199
+ plan: "empty",
2200
+ reason: `refused: ${state.refusal.message}`,
2201
+ keyConditions: [],
2202
+ filter: undefined,
2203
+ rowChecks: [],
2204
+ sizing: explainedSizing(state),
2205
+ };
2206
+ }
2207
+ if (state.fanOut !== undefined)
2208
+ return explainFanOut(state, state.fanOut);
2209
+ const factory = state.planner;
2116
2210
  if (factory === undefined) {
2117
2211
  const [lower, upper] = displayKeyCondition(state.skConditions[0]?.condition);
2118
2212
  return {
@@ -2147,7 +2241,7 @@ const explainedSizing = (state) => {
2147
2241
  */
2148
2242
  export const asParams = (self) => Effect.gen(function* () {
2149
2243
  const state = self._state;
2150
- const refusal = refuseEmptyFilterParts(state);
2244
+ const refusal = state.refusal ?? refuseEmptyFilterParts(state);
2151
2245
  if (refusal !== undefined)
2152
2246
  return yield* refusal;
2153
2247
  const tableName = state.resolveTableName ? yield* state.resolveTableName : state.tableName;
@@ -2164,11 +2258,384 @@ export const asParams = (self) => Effect.gen(function* () {
2164
2258
  }
2165
2259
  }
2166
2260
  // 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.
2261
+ // that follows each page is not part of these parameters.
2169
2262
  return buildDynamoCommand(indexQueryState(state), tableName);
2170
2263
  });
2171
2264
  // ---------------------------------------------------------------------------
2265
+ // Sharded indexes (#183, docs/designs/gsi-write-sharding.md §6)
2266
+ // ---------------------------------------------------------------------------
2267
+ /** @internal The partitions a fan-out reads, in merge order: its layouts'. */
2268
+ const fanOutPartitions = (state, spec) => {
2269
+ const condition = state.skConditions[0]?.condition;
2270
+ return spec.partitions.map((pkValue) => ({ pkValue, condition }));
2271
+ };
2272
+ /** @internal What a sharded query's cursor must have come from. */
2273
+ const fanOutFingerprint = (state, spec, partitions) => fnv1a32(canonicalJson({
2274
+ index: state.indexName,
2275
+ entityTypes: state.entityTypes,
2276
+ count: spec.count,
2277
+ source: spec.source,
2278
+ previous: spec.previous,
2279
+ partitions: partitions.map(({ pkValue, condition }) => ({ pkValue, condition })),
2280
+ reverse: !state.scanForward,
2281
+ }));
2282
+ /** @internal The checksum of a cursor's positions. */
2283
+ const positionsChecksum = (positions) => fnv1a32(canonicalJson(positions));
2284
+ /**
2285
+ * @internal A fan-out's partitions, resumed from its {@link startFrom} cursor: a
2286
+ * cursor from another layout or query, a position it can't hold or an altered one
2287
+ * is `[EDD-9094]`.
2288
+ */
2289
+ const resumeFanOut = (state, spec) => {
2290
+ const partitions = fanOutPartitions(state, spec);
2291
+ const fingerprint = fanOutFingerprint(state, spec, partitions);
2292
+ const started = (merge) => ({
2293
+ ...state,
2294
+ fanOutStart: { partitions, fingerprint, merge },
2295
+ });
2296
+ if (state.cursorText === undefined)
2297
+ return started(ShardMerge.fromStart(partitions.length));
2298
+ const entityType = state.entityTypes.join(", ") || "unknown";
2299
+ const refuse = (why) => cursorRefusal(entityType, why);
2300
+ const cursor = Cursor.decode(state.cursorText);
2301
+ if (cursor === undefined)
2302
+ return refuse("it is not a cursor a query returned");
2303
+ if (cursor.z === undefined) {
2304
+ return refuse("this index is sharded, and it comes from a query that wasn't");
2305
+ }
2306
+ if (cursor.f !== fingerprint) {
2307
+ return refuse("its shard layout or its query differs from this one's");
2308
+ }
2309
+ if (cursor.c !== positionsChecksum(cursor.z))
2310
+ return refuse("its positions were altered");
2311
+ if (cursor.z.length !== partitions.length) {
2312
+ return refuse("it doesn't hold one position per partition");
2313
+ }
2314
+ const keyNames = new Set((state.keyFields ?? []).filter((name) => name !== state.pkField));
2315
+ const boundaries = [];
2316
+ for (let i = 0; i < partitions.length; i++) {
2317
+ const at = cursor.z[i];
2318
+ if (at === 0) {
2319
+ boundaries.push({ _tag: "Start" });
2320
+ continue;
2321
+ }
2322
+ if (at === 1) {
2323
+ boundaries.push({ _tag: "Done" });
2324
+ continue;
2325
+ }
2326
+ const names = Object.keys(at);
2327
+ if (names.length !== keyNames.size || !names.every((name) => keyNames.has(name))) {
2328
+ return refuse("a position isn't a key of this index");
2329
+ }
2330
+ const partition = partitions[i];
2331
+ const sort = state.skField === undefined ? undefined : at[state.skField];
2332
+ const value = sort === undefined ? undefined : Cursor.wireToKeyValue(sort);
2333
+ if (partition.condition !== undefined &&
2334
+ (value === undefined || !keyConditionHolds(partition.condition, value))) {
2335
+ return refuse("a position is outside the query's key condition");
2336
+ }
2337
+ boundaries.push({
2338
+ _tag: "At",
2339
+ key: Cursor.keyFromWire({ ...at, [state.pkField]: { S: partition.pkValue } }),
2340
+ });
2341
+ }
2342
+ return started(ShardMerge.initial(boundaries));
2343
+ };
2344
+ /** @internal A boundary as a cursor records it. */
2345
+ const positionOf = (state, boundary) => {
2346
+ if (boundary._tag === "Start")
2347
+ return Effect.succeed(0);
2348
+ if (boundary._tag === "Done")
2349
+ return Effect.succeed(1);
2350
+ const key = boundary._tag === "At" ? boundary.key : keyOfItem(boundary.row, state.keyFields);
2351
+ const wire = key === undefined ? undefined : Cursor.keyToWire(key);
2352
+ if (wire === undefined) {
2353
+ return Effect.die(new Error(`[internal] A row read from sharded index "${state.indexName}" lacks a key attribute ` +
2354
+ `of ${JSON.stringify(state.keyFields)}, which the cursor resumes after.`));
2355
+ }
2356
+ const { [state.pkField]: _partition, ...position } = wire;
2357
+ return Effect.succeed(position);
2358
+ };
2359
+ /** @internal The cursor of a fan-out at `merge`: v2, or `None` once every partition is done. */
2360
+ const fanOutCursor = (state, start, merge) => ShardMerge.isFinished(merge)
2361
+ ? Effect.succeed(Option.none())
2362
+ : Effect.map(Effect.forEach(merge, (partition) => positionOf(state, partition.boundary)), (z) => Option.some(Cursor.encodeV2({
2363
+ v: 2,
2364
+ f: start.fingerprint,
2365
+ s: "key",
2366
+ z,
2367
+ c: positionsChecksum(z),
2368
+ })));
2369
+ /** @internal One partition's request, as `state` sends it. */
2370
+ const partitionState = (state, partition) => ({
2371
+ ...state,
2372
+ pkValue: partition.pkValue,
2373
+ skConditions: partition.condition === undefined || state.skField === undefined
2374
+ ? []
2375
+ : [{ field: state.skField, condition: partition.condition }],
2376
+ rowCheck: undefined,
2377
+ });
2378
+ /** @internal The `ExclusiveStartKey` a boundary resumes from. */
2379
+ const fanOutStartKey = (state, boundary) => boundary._tag === "At"
2380
+ ? boundary.key
2381
+ : boundary._tag === "After"
2382
+ ? keyOfItem(boundary.row, state.keyFields)
2383
+ : undefined;
2384
+ /**
2385
+ * @internal The `Limit` of a partition's next request (design §6.5), `remaining`
2386
+ * items still owed and `active` partitions unfinished: the partition's share of
2387
+ * what is owed, growing where it keeps running dry.
2388
+ */
2389
+ const fanOutLimit = (sent, remaining, active, est) => {
2390
+ const mode = sizingMode(sent);
2391
+ if (remaining === undefined || mode === "none")
2392
+ return legacyRequestLimit(sent, remaining);
2393
+ const share = Math.ceil(remaining / Math.max(active, 1));
2394
+ if (mode === "adaptive")
2395
+ return nextLimit(est, share, filtered(sent));
2396
+ if (mode === "budget") {
2397
+ return Math.min(remaining, Math.max(Math.ceil(share * SAFETY), est.lastLimit * GROWTH));
2398
+ }
2399
+ return legacyRequestLimit(sent, remaining, est.requests + 1);
2400
+ };
2401
+ const startFanOut = (start) => ({
2402
+ merge: start.merge,
2403
+ estimators: start.partitions.map(() => emptyEstimator),
2404
+ pages: start.partitions.map(() => undefined),
2405
+ requests: 0,
2406
+ rounds: 0,
2407
+ emitted: 0,
2408
+ });
2409
+ /** @internal How many requests a fan-out's round sends at once. */
2410
+ const fanOutConcurrency = (state, partitions) => state.concurrencyValue ?? Math.max(partitions, 1);
2411
+ /** @internal Are `maxPages` rounds used up? */
2412
+ const roundsUsed = (state, run) => state.maxPagesValue != null && run.rounds >= state.maxPagesValue;
2413
+ /**
2414
+ * @internal One round of a fan-out: read every partition with nothing buffered
2415
+ * and more to read (at most one page each), unless `read` is false, then emit
2416
+ * what is proven in order, up to the `limit`. Any request's failure fails the
2417
+ * round, with the others interrupted. A page is reported to the observers when
2418
+ * its rows are consumed, so `accepted` is exact.
2419
+ */
2420
+ const fanOutRound = (client, tableName, state, start, run) => Effect.gen(function* () {
2421
+ const limitValue = state.limitValue;
2422
+ const remainingBefore = limitValue === undefined ? undefined : limitValue - run.emitted;
2423
+ const needing = ShardMerge.needingRead(run.merge);
2424
+ const active = ShardMerge.unfinished(run.merge);
2425
+ let merge = run.merge;
2426
+ const estimators = [...run.estimators];
2427
+ const pages = [...run.pages];
2428
+ // The same attributes for every partition: a row check on one borrows what it
2429
+ // judges, and `examinePage` strips the lot.
2430
+ const borrowed = [
2431
+ ...new Set(start.partitions.flatMap((partition) => cursorProjectionFields(indexQueryState(partitionState(state, partition)), true))),
2432
+ ];
2433
+ const report = (i) => {
2434
+ const page = pages[i];
2435
+ if (page === undefined)
2436
+ return Effect.void;
2437
+ pages[i] = undefined;
2438
+ estimators[i] = observeEstimator(estimators[i], {
2439
+ scanned: page.counts.scannedCount,
2440
+ accepted: page.accepted,
2441
+ limitSent: page.limitSent,
2442
+ });
2443
+ return notify(page.sent, {
2444
+ kind: "read",
2445
+ request: page.request,
2446
+ limit: page.limitSent,
2447
+ ...page.counts,
2448
+ accepted: page.accepted,
2449
+ });
2450
+ };
2451
+ const responses = yield* Effect.forEach(needing, (i, n) => Effect.gen(function* () {
2452
+ const sent = partitionState(state, start.partitions[i]);
2453
+ const limitSent = fanOutLimit(sent, remainingBefore, active, estimators[i]);
2454
+ const cmd = buildDynamoCommand(indexQueryState(sent), tableName, { ExclusiveStartKey: fanOutStartKey(state, run.merge[i].boundary), Limit: limitSent }, borrowed);
2455
+ const result = yield* send(client, sent, cmd);
2456
+ return {
2457
+ i,
2458
+ request: run.requests + n + 1,
2459
+ sent,
2460
+ limitSent,
2461
+ result,
2462
+ };
2463
+ }), { concurrency: fanOutConcurrency(state, needing.length) });
2464
+ for (const { i, request, sent, limitSent, result } of responses) {
2465
+ const returned = (result.Items ?? []);
2466
+ const kept = returned.filter((row) => !isExcludedRow(sent, row));
2467
+ merge = ShardMerge.absorb(merge, i, kept, result.LastEvaluatedKey);
2468
+ pages[i] = { sent, request, limitSent, counts: responseCounts(result), accepted: 0 };
2469
+ // Nothing left in the page: nothing will ever be consumed from it.
2470
+ if (kept.length === 0)
2471
+ yield* report(i);
2472
+ }
2473
+ const budget = limitValue === undefined ? Number.POSITIVE_INFINITY : limitValue - run.emitted;
2474
+ const selection = yield* Effect.try({
2475
+ try: () => ShardMerge.select(merge, budget, {
2476
+ skField: state.skField ?? "",
2477
+ reverse: !state.scanForward,
2478
+ }),
2479
+ catch: (error) => error,
2480
+ }).pipe(Effect.orDie);
2481
+ merge = selection.state;
2482
+ // Rows dropped at the read aren't examined again; the rest are decoded
2483
+ // together, which is what lets a `BatchGet`-hydrated query fetch them at once.
2484
+ const page = yield* examinePage(client, tableName, { ...state, rowCheck: undefined, keepRow: undefined, liveRows: undefined }, selection.taken.map((selected) => selected.row), undefined, borrowed);
2485
+ for (const at of page.rows) {
2486
+ const i = selection.taken[at].partition;
2487
+ const accepted = pages[i];
2488
+ if (accepted !== undefined)
2489
+ pages[i] = { ...accepted, accepted: accepted.accepted + 1 };
2490
+ }
2491
+ for (const i of selection.drained)
2492
+ yield* report(i);
2493
+ return {
2494
+ run: {
2495
+ merge,
2496
+ estimators,
2497
+ pages,
2498
+ requests: run.requests + needing.length,
2499
+ rounds: needing.length > 0 ? run.rounds + 1 : run.rounds,
2500
+ emitted: run.emitted + page.items.length,
2501
+ },
2502
+ items: page.items,
2503
+ };
2504
+ });
2505
+ /**
2506
+ * @internal Report the pages a fan-out read and never finished consuming: a page
2507
+ * with no row consumed is `discarded`, and a later call reads what remains again.
2508
+ */
2509
+ const reportUnfinished = (run) => Effect.forEach(run.pages.filter((page) => page !== undefined), (page) => notify(page.sent, {
2510
+ kind: "read",
2511
+ request: page.request,
2512
+ limit: page.limitSent,
2513
+ ...page.counts,
2514
+ accepted: page.accepted,
2515
+ discarded: page.accepted === 0,
2516
+ }), { discard: true });
2517
+ /**
2518
+ * @internal `execute` for a sharded index. With a `limit`, rounds until `limit`
2519
+ * items are out, every partition is done, or `maxPages` rounds were read. Without
2520
+ * one, a page is one round, as a page without a plan is one request.
2521
+ */
2522
+ const executeFanOut = (client, tableName, state, start) => Effect.gen(function* () {
2523
+ const limitValue = state.limitValue;
2524
+ const items = [];
2525
+ let run = startFanOut(start);
2526
+ while (!ShardMerge.isFinished(run.merge)) {
2527
+ const stepped = yield* fanOutRound(client, tableName, state, start, run);
2528
+ run = stepped.run;
2529
+ items.push(...stepped.items);
2530
+ if (limitValue === undefined)
2531
+ break;
2532
+ if (run.emitted >= limitValue)
2533
+ break;
2534
+ // A partition must be read, and the rounds are up.
2535
+ if (ShardMerge.needingRead(run.merge).length > 0 && roundsUsed(state, run))
2536
+ break;
2537
+ }
2538
+ yield* reportUnfinished(run);
2539
+ return {
2540
+ items,
2541
+ cursor: yield* fanOutCursor(state, start, run.merge),
2542
+ };
2543
+ });
2544
+ /**
2545
+ * @internal `pageStream` for a sharded index: one array per round. At most one
2546
+ * page per partition is held. The stream ends once `limit` items are out, every
2547
+ * partition is done, or `maxPages` rounds were read.
2548
+ */
2549
+ const fanOutPageStream = (client, tableName, state, start) => Stream.paginate(startFanOut(start), (run) => Effect.gen(function* () {
2550
+ if (ShardMerge.isFinished(run.merge))
2551
+ return [[], Option.none()];
2552
+ const stepped = yield* fanOutRound(client, tableName, state, start, run);
2553
+ const next = stepped.run;
2554
+ const filled = state.limitValue !== undefined && next.emitted >= state.limitValue;
2555
+ const stuck = ShardMerge.needingRead(next.merge).length > 0 && roundsUsed(state, next);
2556
+ const more = !filled && !stuck && !ShardMerge.isFinished(next.merge);
2557
+ if (!more)
2558
+ yield* reportUnfinished(next);
2559
+ return [[stepped.items], more ? Option.some(next) : Option.none()];
2560
+ }));
2561
+ /**
2562
+ * @internal `count` for a sharded index: each partition counted from where it
2563
+ * resumes, `Select: COUNT` or the rows a row check judges, summed and capped at the
2564
+ * `limit`. `maxPages` caps each partition's requests. Any failure fails the count.
2565
+ */
2566
+ const countFanOut = (client, tableName, state, start) => Effect.gen(function* () {
2567
+ const limitValue = state.limitValue;
2568
+ let total = 0;
2569
+ let requests = 0;
2570
+ const reached = () => limitValue !== undefined && total >= limitValue;
2571
+ const counting = start.partitions.flatMap((partition, i) => start.merge[i].boundary._tag === "Done" ? [] : [{ partition, i }]);
2572
+ yield* Effect.forEach(counting, ({ partition, i }) => Effect.gen(function* () {
2573
+ const sent = partitionState(state, partition);
2574
+ const judging = dropsRows(sent);
2575
+ let startKey = fanOutStartKey(state, start.merge[i].boundary);
2576
+ let est = emptyEstimator;
2577
+ let pages = 0;
2578
+ do {
2579
+ if (reached())
2580
+ return;
2581
+ pages++;
2582
+ const remaining = limitValue === undefined ? undefined : limitValue - total;
2583
+ const limitSent = fanOutLimit(sent, remaining, counting.length, est);
2584
+ const cmd = judging
2585
+ ? buildDynamoCommand({ ...sent, projection: judgedAttributes(sent), projectionPaths: undefined }, tableName, { ExclusiveStartKey: startKey, Limit: limitSent })
2586
+ : buildDynamoCommand(sent, tableName, {
2587
+ ExclusiveStartKey: startKey,
2588
+ Select: "COUNT",
2589
+ Limit: limitSent,
2590
+ });
2591
+ const request = ++requests;
2592
+ const result = yield* send(client, sent, cmd);
2593
+ const counts = responseCounts(result);
2594
+ const matched = judging
2595
+ ? (result.Items ?? []).filter((row) => !isExcludedRow(sent, row)).length
2596
+ : (result.Count ?? 0);
2597
+ const scanned = judging ? counts.scannedCount : (result.ScannedCount ?? matched);
2598
+ total += matched;
2599
+ est = observeEstimator(est, { scanned, accepted: matched, limitSent });
2600
+ yield* notify(sent, {
2601
+ kind: "count",
2602
+ request,
2603
+ limit: limitSent,
2604
+ scannedCount: scanned,
2605
+ count: judging ? counts.count : matched,
2606
+ accepted: matched,
2607
+ });
2608
+ startKey = result.LastEvaluatedKey;
2609
+ if (state.maxPagesValue != null && pages >= state.maxPagesValue)
2610
+ return;
2611
+ } while (startKey != null);
2612
+ }), { concurrency: fanOutConcurrency(state, counting.length), discard: true });
2613
+ return limitValue !== undefined && total >= limitValue ? limitValue : total;
2614
+ });
2615
+ /** @internal {@link explain} of a sharded index's query: no cursor is read. */
2616
+ const explainFanOut = (state, spec) => {
2617
+ const partitions = fanOutPartitions(state, spec);
2618
+ return {
2619
+ index: state.indexName ?? "primary",
2620
+ plan: "key",
2621
+ reason: spec.pruned && partitions.length === 1
2622
+ ? "every shard source attribute pinned: one shard"
2623
+ : `one key condition on each of ${partitions.length} partitions, merged`,
2624
+ keyConditions: partitions.map(({ condition }) => {
2625
+ const [lower, upper] = displayKeyCondition(condition);
2626
+ return { lower, upper, exact: true };
2627
+ }),
2628
+ filter: undefined,
2629
+ rowChecks: [],
2630
+ sizing: explainedSizing(state),
2631
+ fanOut: {
2632
+ partitions: partitions.map(({ pkValue }) => pkValue),
2633
+ pruned: spec.pruned,
2634
+ concurrency: fanOutConcurrency(state, partitions.length),
2635
+ },
2636
+ };
2637
+ };
2638
+ // ---------------------------------------------------------------------------
2172
2639
  // Type guard
2173
2640
  // ---------------------------------------------------------------------------
2174
2641
  export const isQuery = (u) => typeof u === "object" && u !== null && QueryTypeId in u;