effect-dynamodb 1.39.0 → 1.41.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 (190) hide show
  1. package/README.md +1 -1
  2. package/dist/Aggregate.d.ts +138 -16
  3. package/dist/Aggregate.d.ts.map +1 -1
  4. package/dist/Aggregate.js +4298 -725
  5. package/dist/Aggregate.js.map +1 -1
  6. package/dist/Batch.d.ts +9 -5
  7. package/dist/Batch.d.ts.map +1 -1
  8. package/dist/Batch.js +28 -44
  9. package/dist/Batch.js.map +1 -1
  10. package/dist/Collection.d.ts.map +1 -1
  11. package/dist/Collection.js +16 -9
  12. package/dist/Collection.js.map +1 -1
  13. package/dist/ConsumedCapacity.js +1 -1
  14. package/dist/ConsumedCapacity.js.map +1 -1
  15. package/dist/DynamoClient.d.ts +44 -21
  16. package/dist/DynamoClient.d.ts.map +1 -1
  17. package/dist/DynamoClient.js +342 -124
  18. package/dist/DynamoClient.js.map +1 -1
  19. package/dist/Entity.d.ts +246 -41
  20. package/dist/Entity.d.ts.map +1 -1
  21. package/dist/Entity.js +6818 -1166
  22. package/dist/Entity.js.map +1 -1
  23. package/dist/EventStore.d.ts +37 -15
  24. package/dist/EventStore.d.ts.map +1 -1
  25. package/dist/EventStore.js +403 -163
  26. package/dist/EventStore.js.map +1 -1
  27. package/dist/Expression.d.ts.map +1 -1
  28. package/dist/Expression.js +40 -24
  29. package/dist/Expression.js.map +1 -1
  30. package/dist/Marshaller.d.ts +72 -11
  31. package/dist/Marshaller.d.ts.map +1 -1
  32. package/dist/Marshaller.js +625 -71
  33. package/dist/Marshaller.js.map +1 -1
  34. package/dist/Query.d.ts +103 -5
  35. package/dist/Query.d.ts.map +1 -1
  36. package/dist/Query.js +262 -15
  37. package/dist/Query.js.map +1 -1
  38. package/dist/StorageEncoding.d.ts +7 -1
  39. package/dist/StorageEncoding.d.ts.map +1 -1
  40. package/dist/StorageEncoding.js +8 -2
  41. package/dist/StorageEncoding.js.map +1 -1
  42. package/dist/Table.d.ts +338 -16
  43. package/dist/Table.d.ts.map +1 -1
  44. package/dist/Table.js +30 -2
  45. package/dist/Table.js.map +1 -1
  46. package/dist/Transaction.d.ts.map +1 -1
  47. package/dist/Transaction.js +70 -7
  48. package/dist/Transaction.js.map +1 -1
  49. package/dist/VectorSearchEmulation.d.ts.map +1 -1
  50. package/dist/VectorSearchEmulation.js +4 -3
  51. package/dist/VectorSearchEmulation.js.map +1 -1
  52. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  53. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  54. package/dist/change-feed/ChangeFeed.js +76 -9
  55. package/dist/change-feed/ChangeFeed.js.map +1 -1
  56. package/dist/change-feed/CheckpointStore.js +1 -1
  57. package/dist/change-feed/CheckpointStore.js.map +1 -1
  58. package/dist/change-feed/DynamoStreamsClient.d.ts +19 -10
  59. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  60. package/dist/change-feed/DynamoStreamsClient.js +24 -14
  61. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  62. package/dist/index.d.ts +2 -2
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +1 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/internal/BoundCrud.d.ts +78 -32
  67. package/dist/internal/BoundCrud.d.ts.map +1 -1
  68. package/dist/internal/BoundCrud.js +25 -0
  69. package/dist/internal/BoundCrud.js.map +1 -1
  70. package/dist/internal/BoundQuery.d.ts +46 -3
  71. package/dist/internal/BoundQuery.d.ts.map +1 -1
  72. package/dist/internal/BoundQuery.js +402 -37
  73. package/dist/internal/BoundQuery.js.map +1 -1
  74. package/dist/internal/BoundVectorQuery.d.ts +6 -0
  75. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  76. package/dist/internal/BoundVectorQuery.js +7 -4
  77. package/dist/internal/BoundVectorQuery.js.map +1 -1
  78. package/dist/internal/Capacity.d.ts +46 -5
  79. package/dist/internal/Capacity.d.ts.map +1 -1
  80. package/dist/internal/Capacity.js +177 -26
  81. package/dist/internal/Capacity.js.map +1 -1
  82. package/dist/internal/ClientOptions.d.ts +144 -0
  83. package/dist/internal/ClientOptions.d.ts.map +1 -0
  84. package/dist/internal/ClientOptions.js +290 -0
  85. package/dist/internal/ClientOptions.js.map +1 -0
  86. package/dist/internal/ConditionHolds.d.ts +29 -0
  87. package/dist/internal/ConditionHolds.d.ts.map +1 -0
  88. package/dist/internal/ConditionHolds.js +453 -0
  89. package/dist/internal/ConditionHolds.js.map +1 -0
  90. package/dist/internal/Cursor.d.ts +19 -10
  91. package/dist/internal/Cursor.d.ts.map +1 -1
  92. package/dist/internal/Cursor.js +25 -10
  93. package/dist/internal/Cursor.js.map +1 -1
  94. package/dist/internal/Digest.d.ts +20 -0
  95. package/dist/internal/Digest.d.ts.map +1 -0
  96. package/dist/internal/Digest.js +106 -0
  97. package/dist/internal/Digest.js.map +1 -0
  98. package/dist/internal/DynamoArithmetic.d.ts +33 -0
  99. package/dist/internal/DynamoArithmetic.d.ts.map +1 -0
  100. package/dist/internal/DynamoArithmetic.js +112 -0
  101. package/dist/internal/DynamoArithmetic.js.map +1 -0
  102. package/dist/internal/EntityCombinators.d.ts +23 -8
  103. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  104. package/dist/internal/EntityCombinators.js +6 -2
  105. package/dist/internal/EntityCombinators.js.map +1 -1
  106. package/dist/internal/EntityOps.d.ts +69 -8
  107. package/dist/internal/EntityOps.d.ts.map +1 -1
  108. package/dist/internal/EntityOps.js.map +1 -1
  109. package/dist/internal/EventProjection.d.ts +18 -4
  110. package/dist/internal/EventProjection.d.ts.map +1 -1
  111. package/dist/internal/EventProjection.js +36 -8
  112. package/dist/internal/EventProjection.js.map +1 -1
  113. package/dist/internal/Expr.d.ts +72 -2
  114. package/dist/internal/Expr.d.ts.map +1 -1
  115. package/dist/internal/Expr.js +264 -5
  116. package/dist/internal/Expr.js.map +1 -1
  117. package/dist/internal/ExpressionLimits.d.ts +57 -1
  118. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  119. package/dist/internal/ExpressionLimits.js +97 -4
  120. package/dist/internal/ExpressionLimits.js.map +1 -1
  121. package/dist/internal/FormGuard.d.ts +52 -0
  122. package/dist/internal/FormGuard.d.ts.map +1 -0
  123. package/dist/internal/FormGuard.js +83 -0
  124. package/dist/internal/FormGuard.js.map +1 -0
  125. package/dist/internal/Hydrate.d.ts.map +1 -1
  126. package/dist/internal/Hydrate.js +2 -1
  127. package/dist/internal/Hydrate.js.map +1 -1
  128. package/dist/internal/InputForm.d.ts +24 -0
  129. package/dist/internal/InputForm.d.ts.map +1 -0
  130. package/dist/internal/InputForm.js +44 -0
  131. package/dist/internal/InputForm.js.map +1 -0
  132. package/dist/internal/InsertStatement.d.ts +15 -0
  133. package/dist/internal/InsertStatement.d.ts.map +1 -0
  134. package/dist/internal/InsertStatement.js +18 -0
  135. package/dist/internal/InsertStatement.js.map +1 -0
  136. package/dist/internal/ItemSize.d.ts +108 -4
  137. package/dist/internal/ItemSize.d.ts.map +1 -1
  138. package/dist/internal/ItemSize.js +190 -3
  139. package/dist/internal/ItemSize.js.map +1 -1
  140. package/dist/internal/MultiProjection.d.ts +7 -2
  141. package/dist/internal/MultiProjection.d.ts.map +1 -1
  142. package/dist/internal/MultiProjection.js +18 -12
  143. package/dist/internal/MultiProjection.js.map +1 -1
  144. package/dist/internal/OperandReaders.d.ts +36 -0
  145. package/dist/internal/OperandReaders.d.ts.map +1 -0
  146. package/dist/internal/OperandReaders.js +176 -0
  147. package/dist/internal/OperandReaders.js.map +1 -0
  148. package/dist/internal/Packed.d.ts.map +1 -1
  149. package/dist/internal/Packed.js +11 -10
  150. package/dist/internal/Packed.js.map +1 -1
  151. package/dist/internal/PathBuilder.d.ts +57 -8
  152. package/dist/internal/PathBuilder.d.ts.map +1 -1
  153. package/dist/internal/PathBuilder.js +98 -24
  154. package/dist/internal/PathBuilder.js.map +1 -1
  155. package/dist/internal/ProjectionEngine.d.ts +196 -3
  156. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  157. package/dist/internal/ProjectionEngine.js +1251 -86
  158. package/dist/internal/ProjectionEngine.js.map +1 -1
  159. package/dist/internal/Rekey.d.ts +187 -21
  160. package/dist/internal/Rekey.d.ts.map +1 -1
  161. package/dist/internal/Rekey.js +1349 -63
  162. package/dist/internal/Rekey.js.map +1 -1
  163. package/dist/internal/ReturnedItem.d.ts +23 -0
  164. package/dist/internal/ReturnedItem.d.ts.map +1 -0
  165. package/dist/internal/ReturnedItem.js +39 -0
  166. package/dist/internal/ReturnedItem.js.map +1 -0
  167. package/dist/internal/RoundTrip.d.ts +45 -0
  168. package/dist/internal/RoundTrip.d.ts.map +1 -0
  169. package/dist/internal/RoundTrip.js +106 -0
  170. package/dist/internal/RoundTrip.js.map +1 -0
  171. package/dist/internal/SentRequest.d.ts +14 -0
  172. package/dist/internal/SentRequest.d.ts.map +1 -0
  173. package/dist/internal/SentRequest.js +31 -0
  174. package/dist/internal/SentRequest.js.map +1 -0
  175. package/dist/internal/TransactPlan.d.ts.map +1 -1
  176. package/dist/internal/TransactPlan.js +4 -0
  177. package/dist/internal/TransactPlan.js.map +1 -1
  178. package/dist/internal/TransactWriteOps.d.ts +70 -15
  179. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  180. package/dist/internal/TransactWriteOps.js +166 -112
  181. package/dist/internal/TransactWriteOps.js.map +1 -1
  182. package/dist/internal/TransactableOps.d.ts +230 -27
  183. package/dist/internal/TransactableOps.d.ts.map +1 -1
  184. package/dist/internal/TransactableOps.js +549 -92
  185. package/dist/internal/TransactableOps.js.map +1 -1
  186. package/dist/internal/WriteDiagnosis.d.ts +66 -3
  187. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  188. package/dist/internal/WriteDiagnosis.js +261 -15
  189. package/dist/internal/WriteDiagnosis.js.map +1 -1
  190. package/package.json +5 -5
@@ -17,16 +17,62 @@
17
17
  * (`unrecognizedKey`). That makes a run idempotent: a rerun finds every moved
18
18
  * row current. Conflicts — a row under both keys, a current key another row
19
19
  * holds — are reported, never overwritten.
20
+ *
21
+ * What a run decides over a table nothing else writes to doesn't depend on the order its segments,
22
+ * pages and concurrent visits meet the rows (DESIGN.md §7 "`rekey`", "One outcome whatever the
23
+ * order"):
24
+ *
25
+ * - **One verdict per row.** A row (by its stored key), an aggregate partition and an event stream
26
+ * are each a unit judged once per run ({@link RekeyRowContext.judge}): the first visit judges it
27
+ * — the scan's, or a move's that needs it out of the way — and a visit meanwhile waits for that
28
+ * verdict instead of judging it again. A wait that would close a loop (a row in the way of a row
29
+ * in the way of it) isn't taken: every unit on the loop is told so, and each reports `contended`.
30
+ * - **The run doesn't meet its own writes** ({@link Journal}). The scan passes a row the run put,
31
+ * and a row the run took that a page read before the take still returned; `scanned` counts each
32
+ * row stored at the start once, whether the scan returned it or a move took it first.
33
+ * - **A dry run plans the writes a real run sends** ({@link RekeyRowContext.plan}) and reads
34
+ * through the plan, so a later decision sees what an earlier one would have done.
35
+ * - **Conflicts are reported one per row**, the first by precedence, in a fixed order.
20
36
  */
21
37
  import { ValidationError } from "@effect-dynamodb/schema/Errors.js";
22
- import { Deferred, Effect, Option } from "effect";
38
+ import { Context, Deferred, Effect, Option } from "effect";
39
+ import { DynamoClient } from "../DynamoClient.js";
23
40
  import * as Capacity from "./Capacity.js";
24
41
  import { fromBase64, isWireKey, keyFromWire, keyToWire, toBase64Url, } from "./Cursor.js";
42
+ import { digest } from "./Digest.js";
43
+ /**
44
+ * What a move does with a row it can't prove unchanged ({@link UnprovableRow}): with writes to the
45
+ * table stopped, nothing can change it, so it moves under the strongest guard that fits; otherwise
46
+ * it's left and reported `unguarded`, unless its aggregate or stream is already part-moved.
47
+ */
48
+ export const unprovableRow = (ctx) => ctx.writesStopped ? "strongest" : "report";
49
+ /** A row left where it is because nothing proves it unchanged when it moves ({@link unprovableRow}). */
50
+ export const UNGUARDED_MESSAGE = "It can't be proven unchanged in one condition: guarded whole, it's over DynamoDB's limits on " +
51
+ "one expression, and it has no version or updatedAt the library stamps to stand in. It's left " +
52
+ "where it is: stop writes to the table, then run rekey with writesStopped: true.";
53
+ /**
54
+ * One text for a tuple of texts, the same only for tuples equal part by part: each part is quoted
55
+ * as JSON, so nothing a part holds (a NUL, a quote, a comma) can pass for the end of one part and
56
+ * the start of the next. Every unit, claim and key the run tells apart is one of these.
57
+ */
58
+ export const identity = (...parts) => JSON.stringify(parts);
59
+ /** A key attribute's value as an {@link identity} part: its type and value. A string is an S value. */
60
+ const keyPart = (value) => value === undefined ? "" : canonicalValue(typeof value === "string" ? { S: value } : value);
61
+ /** The unit a stored row is judged as ({@link RekeyRowContext.judge}): its stored key. */
62
+ export const rowUnit = (pk, sk) => identity("row", keyPart(pk), keyPart(sk));
25
63
  /**
26
- * How many rows still to move a row's own move goes through first: one chain, `foo%20bar`'s row
27
- * where `foo bar`'s belongs and so on. Past it the row is reported, and the next run goes on.
64
+ * The unit a unique sentinel is judged as for its reservation ({@link RekeyRowContext.judge}): is
65
+ * it held, and if not, is it reported or released. Apart from {@link rowUnit}, the unit that moves
66
+ * it, since a sentinel no row holds may still move with the tombstone it names.
28
67
  */
29
- export const DISPLACE_DEPTH = 4;
68
+ export const reservationUnit = (pk, sk) => identity("reservation", keyPart(pk), keyPart(sk));
69
+ /** What a row in a loop of rows holding each other's current keys is reported with. */
70
+ export const LOOP_MESSAGE = "Rows under other key text hold each other's current keys in a loop: none can move first.";
71
+ /** A tally saying only that the member couldn't read the row's key back. */
72
+ const onlyUnrecognized = (tally) => Object.keys(tally).length === 1 &&
73
+ tally.skipped !== undefined &&
74
+ Object.keys(tally.skipped).length === 1 &&
75
+ (tally.skipped.unrecognizedKey ?? 0) > 0;
30
76
  const CLIENT_ERROR_TAGS = new Set([
31
77
  "DynamoError",
32
78
  "ThrottlingError",
@@ -62,6 +108,8 @@ const SKIP_REASONS = [
62
108
  "notLibrary",
63
109
  "unregistered",
64
110
  "unrecognizedKey",
111
+ "rootNotSeen",
112
+ "ambiguousOwner",
65
113
  ];
66
114
  const zeroCounts = () => ({
67
115
  item: 0,
@@ -72,36 +120,159 @@ const zeroCounts = () => ({
72
120
  aggregate: 0,
73
121
  stream: 0,
74
122
  });
75
- /** The run's counts, merged as handlers finish. */
123
+ const INDEX_KEY_COUNTS = [
124
+ "missing",
125
+ "truncated",
126
+ "lagging",
127
+ "ambiguous",
128
+ "repaired",
129
+ "skipped",
130
+ ];
131
+ const zeroIndexKeys = () => ({
132
+ missing: 0,
133
+ truncated: 0,
134
+ lagging: 0,
135
+ ambiguous: 0,
136
+ repaired: 0,
137
+ skipped: 0,
138
+ });
139
+ const GUARD_GAPS = ["stamp", "sparse", "strongest"];
140
+ const zeroGuardGaps = () => ({ stamp: 0, sparse: 0, strongest: 0 });
141
+ /**
142
+ * A row moved under `guard`, with writes going on: counted in {@link RekeyGuardGaps} when the guard
143
+ * can miss a write. Nothing with writes stopped.
144
+ */
145
+ export const guardGap = (ctx, gap,
146
+ /** The row: the report names it ({@link RekeyGuardGapRow}). */
147
+ row) => gap === undefined || ctx.writesStopped
148
+ ? {}
149
+ : { guardGaps: { [gap]: 1 }, guardGapRows: [{ ...row, gap }] };
150
+ /** How many rows {@link RekeyReport.guardGaps} names: the first by member, kind and key. */
151
+ const GUARD_GAP_ROWS = 100;
152
+ const guardGapRowOrder = (row) => [
153
+ row.member,
154
+ row.kind,
155
+ stableText(row.key),
156
+ row.gap,
157
+ stableText(row.target),
158
+ ];
159
+ /** The first {@link GUARD_GAP_ROWS} of `rows` by {@link guardGapRowOrder}. */
160
+ const firstGuardGapRows = (rows) => rows
161
+ .map((row) => ({ row, order: guardGapRowOrder(row) }))
162
+ .sort((a, b) => compareOrders(a.order, b.order))
163
+ .slice(0, GUARD_GAP_ROWS)
164
+ .map(({ row }) => row);
165
+ const zeroReservations = () => ({
166
+ orphaned: 0,
167
+ released: 0,
168
+ skipped: 0,
169
+ raced: 0,
170
+ undecided: 0,
171
+ });
172
+ /**
173
+ * Count a reservation by its outcome: `orphaned` counts every one found and still orphaned when
174
+ * released or left ({@link RekeyReservationCounts}).
175
+ */
176
+ const countReservation = (into, entry) => {
177
+ if (entry.outcome === "undecided") {
178
+ into.undecided += 1;
179
+ return;
180
+ }
181
+ if (entry.outcome === "raced") {
182
+ into.raced += 1;
183
+ return;
184
+ }
185
+ into.orphaned += 1;
186
+ if (entry.outcome === "released")
187
+ into.released += 1;
188
+ if (entry.outcome === "skipped")
189
+ into.skipped += 1;
190
+ };
191
+ /** A value as text whose order is the same whatever order its object's properties were set in. */
192
+ const stableText = (value) => {
193
+ if (typeof value !== "object" || value === null)
194
+ return JSON.stringify(value) ?? "undefined";
195
+ if (Array.isArray(value))
196
+ return `[${value.map(stableText).join(",")}]`;
197
+ const entries = Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0);
198
+ return `{${entries.map(([k, v]) => `${JSON.stringify(k)}:${stableText(v)}`).join(",")}}`;
199
+ };
200
+ /** Which of a row's conflicts is reported when it is met more than once: the first that applies. */
201
+ const REASON_ORDER = [
202
+ "failed",
203
+ "unguarded",
204
+ "uncomposable",
205
+ "bothKeys",
206
+ "contended",
207
+ "taken",
208
+ ];
209
+ const reasonRank = (reason) => {
210
+ const at = REASON_ORDER.indexOf(reason);
211
+ return at === -1 ? REASON_ORDER.length : at;
212
+ };
213
+ /** The order conflicts are reported in, and the tie-break between two of one row. */
214
+ const conflictOrder = (conflict) => [
215
+ conflict.member,
216
+ conflict.kind,
217
+ stableText(conflict.key),
218
+ String(reasonRank(conflict.reason)).padStart(2, "0"),
219
+ stableText(conflict.target),
220
+ conflict.message,
221
+ ];
222
+ const compareOrders = (a, b) => {
223
+ for (let i = 0; i < a.length; i++) {
224
+ if (a[i] < b[i])
225
+ return -1;
226
+ if (a[i] > b[i])
227
+ return 1;
228
+ }
229
+ return 0;
230
+ };
231
+ /** The run's counts, merged as units settle. */
76
232
  class Totals {
77
233
  scanned = 0;
78
234
  unchanged = 0;
79
235
  moved = zeroCounts();
80
236
  indexKeysRewritten = 0;
237
+ zonesRewritten = 0;
81
238
  sentinelsMoved = 0;
82
- conflicts = [];
83
- conflicted = new Set();
239
+ indexKeys = zeroIndexKeys();
240
+ reservations = zeroReservations();
241
+ guardGaps = zeroGuardGaps();
242
+ /** One entry per sentinel: a sentinel is its own unit, judged once a run. */
243
+ reservationEntries = [];
244
+ /** The rows counted in `guardGaps`, kept to the first {@link GUARD_GAP_ROWS} as they come. */
245
+ guardGapRows = [];
246
+ /** One conflict per row (member, kind, key): the first by {@link REASON_ORDER}, then by text. */
247
+ conflicts = new Map();
84
248
  skipped = {
85
249
  notLibrary: 0,
86
250
  unregistered: 0,
87
251
  unrecognizedKey: 0,
252
+ rootNotSeen: 0,
253
+ ambiguousOwner: 0,
88
254
  };
255
+ ambiguous = [];
89
256
  byMember = new Map();
257
+ memberOf(member) {
258
+ const known = this.byMember.get(member);
259
+ if (known !== undefined)
260
+ return known;
261
+ const fresh = {
262
+ unchanged: 0,
263
+ moved: zeroCounts(),
264
+ indexKeysRewritten: 0,
265
+ zonesRewritten: 0,
266
+ sentinelsMoved: 0,
267
+ indexKeys: zeroIndexKeys(),
268
+ reservations: zeroReservations(),
269
+ guardGaps: zeroGuardGaps(),
270
+ };
271
+ this.byMember.set(member, fresh);
272
+ return fresh;
273
+ }
90
274
  add(member, tally) {
91
- const into = member === undefined
92
- ? undefined
93
- : (this.byMember.get(member) ??
94
- (() => {
95
- const fresh = {
96
- unchanged: 0,
97
- moved: zeroCounts(),
98
- indexKeysRewritten: 0,
99
- sentinelsMoved: 0,
100
- conflicts: 0,
101
- };
102
- this.byMember.set(member, fresh);
103
- return fresh;
104
- })());
275
+ const into = member === undefined ? undefined : this.memberOf(member);
105
276
  const unchanged = tally.unchanged ?? 0;
106
277
  this.unchanged += unchanged;
107
278
  if (into !== undefined)
@@ -116,32 +287,69 @@ class Totals {
116
287
  this.indexKeysRewritten += rewritten;
117
288
  if (into !== undefined)
118
289
  into.indexKeysRewritten += rewritten;
290
+ const zones = tally.zonesRewritten ?? 0;
291
+ this.zonesRewritten += zones;
292
+ if (into !== undefined)
293
+ into.zonesRewritten += zones;
119
294
  const sentinels = tally.sentinelsMoved ?? 0;
120
295
  this.sentinelsMoved += sentinels;
121
296
  if (into !== undefined)
122
297
  into.sentinelsMoved += sentinels;
123
- for (const conflict of tally.conflicts ?? []) {
124
- // A row that can't move is met again by what wants its key, and by the scan.
125
- const row = `${conflict.member}\u0000${conflict.kind}\u0000${JSON.stringify(conflict.key)}`;
126
- if (this.conflicted.has(row))
127
- continue;
128
- this.conflicted.add(row);
129
- this.conflicts.push(conflict);
298
+ for (const count of INDEX_KEY_COUNTS) {
299
+ const n = tally.indexKeys?.[count] ?? 0;
300
+ this.indexKeys[count] += n;
130
301
  if (into !== undefined)
131
- into.conflicts += 1;
302
+ into.indexKeys[count] += n;
303
+ }
304
+ for (const gap of GUARD_GAPS) {
305
+ const n = tally.guardGaps?.[gap] ?? 0;
306
+ this.guardGaps[gap] += n;
307
+ if (into !== undefined)
308
+ into.guardGaps[gap] += n;
309
+ }
310
+ if (tally.guardGapRows !== undefined && tally.guardGapRows.length > 0) {
311
+ const rows = [...this.guardGapRows, ...tally.guardGapRows];
312
+ // Bounded: sorted and cut once twice the list has come in, so memory stays flat.
313
+ this.guardGapRows = rows.length > 2 * GUARD_GAP_ROWS ? firstGuardGapRows(rows) : rows;
314
+ }
315
+ for (const entry of tally.reservations ?? []) {
316
+ this.reservationEntries.push(entry);
317
+ countReservation(this.reservations, entry);
318
+ countReservation(this.memberOf(entry.member).reservations, entry);
319
+ }
320
+ for (const conflict of tally.conflicts ?? []) {
321
+ // A row that can't move is met again by what wants its key, and by the scan: whichever
322
+ // reaches it first, it's reported once, and the same way.
323
+ this.memberOf(conflict.member);
324
+ const row = identity(conflict.member, conflict.kind, stableText(conflict.key));
325
+ const known = this.conflicts.get(row);
326
+ if (known === undefined || compareOrders(conflictOrder(conflict), conflictOrder(known)) < 0) {
327
+ this.conflicts.set(row, conflict);
328
+ }
132
329
  }
133
330
  for (const reason of SKIP_REASONS)
134
331
  this.skipped[reason] += tally.skipped?.[reason] ?? 0;
332
+ for (const ambiguity of tally.ambiguous ?? [])
333
+ this.ambiguous.push(ambiguity);
135
334
  }
136
- report(dryRun, capacity, resume) {
335
+ report(dryRun, capacity, resume, budget) {
336
+ // By member, kind, key, reason, target and message: the same whatever order the run met them.
337
+ const conflicts = [...this.conflicts.values()]
338
+ .map((conflict) => ({ conflict, order: conflictOrder(conflict) }))
339
+ .sort((a, b) => compareOrders(a.order, b.order))
340
+ .map(({ conflict }) => conflict);
137
341
  const byMember = {};
138
342
  for (const [name, m] of [...this.byMember.entries()].sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) {
139
343
  byMember[name] = {
140
344
  unchanged: m.unchanged,
141
345
  moved: { ...m.moved },
142
346
  indexKeysRewritten: m.indexKeysRewritten,
347
+ zonesRewritten: m.zonesRewritten,
143
348
  sentinelsMoved: m.sentinelsMoved,
144
- conflicts: m.conflicts,
349
+ indexKeys: { ...m.indexKeys },
350
+ reservations: { ...m.reservations },
351
+ guardGaps: { ...m.guardGaps },
352
+ conflicts: conflicts.filter((conflict) => conflict.member === name).length,
145
353
  };
146
354
  }
147
355
  return {
@@ -150,15 +358,68 @@ class Totals {
150
358
  unchanged: this.unchanged,
151
359
  moved: { ...this.moved },
152
360
  indexKeysRewritten: this.indexKeysRewritten,
361
+ zonesRewritten: this.zonesRewritten,
153
362
  sentinelsMoved: this.sentinelsMoved,
154
- conflicts: [...this.conflicts],
363
+ indexKeys: { ...this.indexKeys },
364
+ // By member, then key: the same whatever order the run met them.
365
+ reservations: {
366
+ ...this.reservations,
367
+ entries: this.reservationEntries
368
+ .map((entry) => ({ entry, order: [entry.member, stableText(entry.key)] }))
369
+ .sort((a, b) => compareOrders(a.order, b.order))
370
+ .map(({ entry }) => entry),
371
+ },
372
+ guardGaps: { ...this.guardGaps, rows: firstGuardGapRows(this.guardGapRows) },
373
+ conflicts,
155
374
  skipped: { ...this.skipped },
375
+ ambiguous: this.ambiguous
376
+ .map((ambiguity) => ({ ambiguity, order: [ambiguity.member, stableText(ambiguity.key)] }))
377
+ .sort((a, b) => compareOrders(a.order, b.order))
378
+ .map(({ ambiguity }) => ambiguity),
156
379
  byMember,
157
380
  capacity,
381
+ journal: {
382
+ capacity: budget.capacity,
383
+ used: budget.used,
384
+ full: budget.full,
385
+ inexact: budget.full ? (dryRun ? INEXACT_DRY : INEXACT_REAL) : [],
386
+ },
158
387
  resume: Option.fromUndefinedOr(resume),
159
388
  };
160
389
  }
161
390
  }
391
+ /**
392
+ * What a real run past its journal's capacity may count wrong ({@link RekeyJournal}): a row it put
393
+ * is met by the scan as a row stored there (`scanned`, `unchanged`, `indexKeys`, as 1.40.0 counted
394
+ * them), a unit reached again is judged again (`unchanged`, `reservations`), a row stored under two
395
+ * old key texts may count as two moves (`moved`), a row or sentinel in another's way may be
396
+ * reported where a run with room moves both (`conflicts`, `sentinelsMoved`), and a row with no root
397
+ * found may go unreported and a unique sentinel no row holds may be counted though a move took it
398
+ * (`skipped`).
399
+ */
400
+ const INEXACT_REAL = [
401
+ "scanned",
402
+ "unchanged",
403
+ "moved",
404
+ "sentinelsMoved",
405
+ "indexKeys",
406
+ "reservations",
407
+ "conflicts",
408
+ "skipped",
409
+ ];
410
+ /** What a dry run past its journal's capacity may count wrong: anything, as its reads no longer see the whole plan. */
411
+ const INEXACT_DRY = [
412
+ "scanned",
413
+ "unchanged",
414
+ "moved",
415
+ "indexKeysRewritten",
416
+ "sentinelsMoved",
417
+ "indexKeys",
418
+ "reservations",
419
+ "guardGaps",
420
+ "conflicts",
421
+ "skipped",
422
+ ];
162
423
  const TOKEN_PREFIX = "rk1.";
163
424
  const encoder = new TextEncoder();
164
425
  const decoder = new TextDecoder("utf-8", { fatal: true });
@@ -196,6 +457,941 @@ const optionError = (cause) => new ValidationError({ entityType: "Table", operat
196
457
  const positiveInteger = (value, name) => value === undefined || (Number.isInteger(value) && value > 0)
197
458
  ? undefined
198
459
  : `${name} must be a positive integer; received ${String(value)}.`;
460
+ /** The unit the current fiber is judging, innermost first. */
461
+ const CurrentUnit = Context.Reference("effect-dynamodb/Rekey/CurrentUnit", {
462
+ defaultValue: () => undefined,
463
+ });
464
+ /**
465
+ * What the run remembers, and how much: at most `capacity` entries, shared by the journal's keys,
466
+ * the settled units and the claims ({@link RekeyOptions.journalCapacity}). Each is a 128-bit
467
+ * {@link digest}, never key text or a row. An entry the budget refuses isn't kept: the run goes on
468
+ * without it, and `full` says the counts it would have kept exact may not be
469
+ * ({@link RekeyJournal}).
470
+ */
471
+ class Budget {
472
+ capacity;
473
+ used = 0;
474
+ full = false;
475
+ constructor(capacity) {
476
+ this.capacity = capacity;
477
+ }
478
+ /** Room for `n` more entries: taken, or, past the capacity, refused and `full` set. */
479
+ admit(n = 1) {
480
+ if (this.used + n > this.capacity) {
481
+ this.full = true;
482
+ return false;
483
+ }
484
+ this.used += n;
485
+ return true;
486
+ }
487
+ }
488
+ /**
489
+ * The run's units ({@link RekeyRowContext.judge}). A visit of a unit being judged waits for its
490
+ * verdict, unless the wait would close a loop — the unit waits, through the units each waits on,
491
+ * on the caller — which can't end: then every unit on it is marked, and each is told `loop`. The
492
+ * waits that are taken never form a loop, so every wait ends.
493
+ *
494
+ * A unit being judged is held as itself, for its waits: as many as the run judges at once. Once
495
+ * settled it is its unit's digest and one bit (on a loop or not), within the {@link Budget}. One the
496
+ * budget has no room for is judged again when reached again: its work reads what's stored, and
497
+ * finds its rows moved.
498
+ */
499
+ class Units {
500
+ totals;
501
+ budget;
502
+ judging = new Map();
503
+ /** Settled units, by digest: whether each was on a loop. */
504
+ settled = new Map();
505
+ constructor(totals, budget) {
506
+ this.totals = totals;
507
+ this.budget = budget;
508
+ }
509
+ judge(member, unitText, work) {
510
+ return Effect.withFiber((fiber) => {
511
+ const key = digest(unitText);
512
+ const caller = fiber.getRef(CurrentUnit);
513
+ const verdict = (loop) => (caller?.loop && loop ? "loop" : "settled");
514
+ const known = this.judging.get(key);
515
+ if (known === undefined) {
516
+ const settled = this.settled.get(key);
517
+ if (settled !== undefined)
518
+ return Effect.succeed(verdict(settled));
519
+ const unit = { state: "judging", waitingOn: undefined, loop: false, done: undefined };
520
+ this.judging.set(key, unit);
521
+ if (caller !== undefined)
522
+ caller.waitingOn = unit;
523
+ return work.pipe(Effect.provideService(CurrentUnit, unit), Effect.tap((tally) => Effect.sync(() => this.totals.add(member, tally))), Effect.ensuring(Effect.sync(() => {
524
+ unit.state = "settled";
525
+ unit.waitingOn = undefined;
526
+ if (caller !== undefined && caller.waitingOn === unit)
527
+ caller.waitingOn = undefined;
528
+ this.judging.delete(key);
529
+ if (this.budget.admit())
530
+ this.settled.set(key, unit.loop);
531
+ if (unit.done !== undefined)
532
+ Deferred.doneUnsafe(unit.done, Effect.void);
533
+ unit.done = undefined;
534
+ })), Effect.map(() => verdict(unit.loop)));
535
+ }
536
+ if (known.state === "settled")
537
+ return Effect.succeed(verdict(known.loop));
538
+ if (caller !== undefined) {
539
+ for (let at = known; at !== undefined; at = at.waitingOn) {
540
+ if (at !== caller)
541
+ continue;
542
+ for (let on = known; on !== undefined && on !== caller;) {
543
+ on.loop = true;
544
+ on = on.waitingOn;
545
+ }
546
+ caller.loop = true;
547
+ return Effect.succeed("loop");
548
+ }
549
+ caller.waitingOn = known;
550
+ }
551
+ known.done ??= Deferred.makeUnsafe();
552
+ return Deferred.await(known.done).pipe(Effect.ensuring(Effect.sync(() => {
553
+ if (caller !== undefined && caller.waitingOn === known)
554
+ caller.waitingOn = undefined;
555
+ })), Effect.map(() => verdict(known.loop)));
556
+ });
557
+ }
558
+ }
559
+ // ---------------------------------------------------------------------------
560
+ // Fingerprints: a row's image as a hash
561
+ // ---------------------------------------------------------------------------
562
+ /**
563
+ * A number as DynamoDB keeps it, from its text, never through `Number`: its significant digits,
564
+ * without leading or trailing zeros, where the point falls, and its sign; zero is `0`.
565
+ */
566
+ export const canonicalNumber = (text) => {
567
+ const match = /^\s*([+-]?)(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?\s*$/.exec(text);
568
+ if (match === null)
569
+ return `?${text}`;
570
+ const whole = match[2] ?? "";
571
+ let digits = whole + (match[3] ?? "");
572
+ let point = whole.length + Number(match[4] ?? 0);
573
+ let lead = 0;
574
+ while (lead < digits.length && digits[lead] === "0")
575
+ lead++;
576
+ digits = digits.slice(lead);
577
+ point -= lead;
578
+ digits = digits.replace(/0+$/, "");
579
+ if (digits === "")
580
+ return "0";
581
+ return `${match[1] === "-" ? "-" : ""}${digits}e${point}`;
582
+ };
583
+ const hexOf = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
584
+ /**
585
+ * An attribute value as one canonical text, type-tagged and recursive: two values DynamoDB stores
586
+ * alike give the same text. A set's elements sorted, a map's entries by name, a list in order.
587
+ */
588
+ export const canonicalValue = (value) => {
589
+ if (value.S !== undefined)
590
+ return `S${JSON.stringify(value.S)}`;
591
+ if (value.N !== undefined)
592
+ return `N${canonicalNumber(value.N)}`;
593
+ if (value.B !== undefined)
594
+ return `B${hexOf(value.B)}`;
595
+ if (value.BOOL !== undefined)
596
+ return value.BOOL ? "BOOL1" : "BOOL0";
597
+ if (value.NULL !== undefined)
598
+ return "NULL";
599
+ if (value.SS !== undefined) {
600
+ return `SS[${value.SS.map((s) => JSON.stringify(s))
601
+ .sort()
602
+ .join(",")}]`;
603
+ }
604
+ if (value.NS !== undefined)
605
+ return `NS[${value.NS.map(canonicalNumber).sort().join(",")}]`;
606
+ if (value.BS !== undefined)
607
+ return `BS[${value.BS.map(hexOf).sort().join(",")}]`;
608
+ if (value.L !== undefined)
609
+ return `L[${value.L.map(canonicalValue).join(",")}]`;
610
+ if (value.M !== undefined)
611
+ return `M${canonicalItem(value.M)}`;
612
+ return `?${JSON.stringify(value)}`;
613
+ };
614
+ /** An item as one canonical text: its attributes sorted by name ({@link canonicalValue}). */
615
+ export const canonicalItem = (item) => `{${Object.keys(item)
616
+ .filter((name) => item[name] !== undefined)
617
+ .sort()
618
+ .map((name) => `${JSON.stringify(name)}:${canonicalValue(item[name])}`)
619
+ .join(",")}}`;
620
+ /**
621
+ * A row's image as its {@link canonicalItem} text's {@link digest}: 128 bits of SHA-256, so two
622
+ * different rows share one only by a SHA-256 collision. A row near 400 KB costs a few milliseconds.
623
+ */
624
+ export const fingerprint = (item) => digest(canonicalItem(item));
625
+ // ---------------------------------------------------------------------------
626
+ // The journal: the run's writes, by key
627
+ // ---------------------------------------------------------------------------
628
+ /** An update's SET and REMOVE clauses, applied to `image`: `undefined` for any other update. */
629
+ export const updated = (image, update) => {
630
+ const names = update.ExpressionAttributeNames ?? {};
631
+ const values = update.ExpressionAttributeValues ?? {};
632
+ const nameOf = (token) => (token.startsWith("#") ? names[token] : token);
633
+ const next = { ...image };
634
+ const clauses = (update.UpdateExpression ?? "").split(/\b(?=SET\b|REMOVE\b|ADD\b|DELETE\b)/);
635
+ for (const clause of clauses) {
636
+ const text = clause.trim();
637
+ if (text === "")
638
+ continue;
639
+ if (text.startsWith("SET ")) {
640
+ for (const assignment of text.slice(4).split(",")) {
641
+ const match = /^\s*(#?[\w.-]+)\s*=\s*(:[\w-]+)\s*$/.exec(assignment);
642
+ const name = match === null ? undefined : nameOf(match[1]);
643
+ const value = match === null ? undefined : values[match[2]];
644
+ if (name === undefined || value === undefined)
645
+ return undefined;
646
+ next[name] = value;
647
+ }
648
+ }
649
+ else if (text.startsWith("REMOVE ")) {
650
+ for (const token of text.slice(7).split(",")) {
651
+ const name = nameOf(token.trim());
652
+ if (name === undefined)
653
+ return undefined;
654
+ delete next[name];
655
+ }
656
+ }
657
+ else {
658
+ return undefined;
659
+ }
660
+ }
661
+ return next;
662
+ };
663
+ /** A query's key condition, read: the partition it names, and a test of each item's sort key. */
664
+ const keyConditionOf = (input) => {
665
+ const names = input.ExpressionAttributeNames ?? {};
666
+ const values = input.ExpressionAttributeValues ?? {};
667
+ const nameOf = (token) => (token.startsWith("#") ? names[token] : token);
668
+ const match = /^\s*\(?\s*(#?\w+)\s*=\s*(:\w+)\s*\)?\s*(?:AND\s+(.*?))?\s*$/i.exec(input.KeyConditionExpression ?? "");
669
+ if (match === null)
670
+ return undefined;
671
+ const attribute = nameOf(match[1]);
672
+ const value = values[match[2]];
673
+ if (attribute === undefined || value === undefined)
674
+ return undefined;
675
+ // The sort key condition, out of the parentheses around it, if any (not a function's own).
676
+ const raw = match[3]?.trim();
677
+ const rest = raw?.startsWith("(") && raw.endsWith(")") ? raw.slice(1, -1).trim() : raw;
678
+ const same = (item) => {
679
+ const at = item[attribute];
680
+ return at !== undefined && canonicalValue(at) === canonicalValue(value);
681
+ };
682
+ if (rest === undefined)
683
+ return { attribute, sort: undefined, holds: same };
684
+ const text = (v) => v?.S ?? undefined;
685
+ const begins = /^begins_with\(\s*(#?\w+)\s*,\s*(:\w+)\s*\)$/i.exec(rest);
686
+ if (begins !== null) {
687
+ const sort = nameOf(begins[1]);
688
+ const prefix = text(values[begins[2]]);
689
+ if (sort === undefined || prefix === undefined)
690
+ return undefined;
691
+ return {
692
+ attribute,
693
+ sort,
694
+ holds: (item) => same(item) && (text(item[sort]) ?? "￿").startsWith(prefix),
695
+ };
696
+ }
697
+ const between = /^(#?\w+)\s+BETWEEN\s+(:\w+)\s+AND\s+(:\w+)$/i.exec(rest);
698
+ if (between !== null) {
699
+ const sort = nameOf(between[1]);
700
+ const lo = text(values[between[2]]);
701
+ const hi = text(values[between[3]]);
702
+ if (sort === undefined || lo === undefined || hi === undefined)
703
+ return undefined;
704
+ return {
705
+ attribute,
706
+ sort,
707
+ holds: (item) => {
708
+ const at = text(item[sort]);
709
+ return same(item) && at !== undefined && at >= lo && at <= hi;
710
+ },
711
+ };
712
+ }
713
+ const compare = /^(#?\w+)\s*(<=|>=|<|>|=)\s*(:\w+)$/.exec(rest);
714
+ if (compare !== null) {
715
+ const sort = nameOf(compare[1]);
716
+ const bound = text(values[compare[3]]);
717
+ if (sort === undefined || bound === undefined)
718
+ return undefined;
719
+ const op = compare[2];
720
+ return {
721
+ attribute,
722
+ sort,
723
+ holds: (item) => {
724
+ const at = text(item[sort]);
725
+ if (!same(item) || at === undefined)
726
+ return false;
727
+ return op === "<"
728
+ ? at < bound
729
+ : op === "<="
730
+ ? at <= bound
731
+ : op === ">"
732
+ ? at > bound
733
+ : op === ">="
734
+ ? at >= bound
735
+ : at === bound;
736
+ },
737
+ };
738
+ }
739
+ return undefined;
740
+ };
741
+ /** Images one key holds, past which the scan passes whatever it finds there ({@link KeyState.any}). */
742
+ const MAX_PRINTS = 8;
743
+ /** Rows a real run keeps the image of, the latest it put, to follow its own updates of them. */
744
+ const RECENT_IMAGES = 64;
745
+ /** How many bytes of a row a dry run plans to put take one more entry of the capacity. */
746
+ const IMAGE_ENTRY_BYTES = 256;
747
+ /** The default {@link RekeyOptions.journalCapacity}. */
748
+ export const DEFAULT_JOURNAL_CAPACITY = 1_000_000;
749
+ /** The largest {@link RekeyOptions.journalCapacity}: a `Map` holds 2^24 entries at most. */
750
+ export const MAX_JOURNAL_CAPACITY = 16_000_000;
751
+ /** A put's condition is on the row it replaces, as read: it writes over a row stored there. */
752
+ const overwrites = (condition) => condition !== undefined && condition.trim() !== "" && !condition.includes("attribute_not_exists");
753
+ /**
754
+ * The run's writes, by key — sent and answered, or (a dry run) planned — within the run's
755
+ * {@link Budget}. Each key is a 128-bit {@link digest} of its typed values, and a real run keeps no
756
+ * image of a row, only its {@link fingerprint}: an entry is the same size whatever the key or the
757
+ * row. A dry run also keeps each row it plans to put, which its reads see.
758
+ *
759
+ * - `scanned` counts each row stored at the start once: when the scan returns it, or when the run
760
+ * takes it (moves it away, or writes over it as read) before the scan gets to it. A row the scan
761
+ * returns costs nothing past its visit: a take while its visit runs ({@link inFlight}) is of a
762
+ * row already counted. A row left for another unit's move after its visit, the journal is told of
763
+ * ({@link RekeyRowContext.awaitsMove}).
764
+ * - The scan passes a row the run put (its image is one the run left there), and a row the run took
765
+ * that a page read before the take still returned. Anything else at such a key — a row written
766
+ * there since by someone else — is a new row, counted and judged.
767
+ * - A dry run plans its writes ({@link Journal.plan}), and its reads ({@link Journal.view}) see the
768
+ * plan: a row it would take is gone, one it would put is there.
769
+ *
770
+ * Past the capacity, a key the budget has no room for isn't kept: a row the run put there is met
771
+ * by the scan as a new row, and one it took is counted again if the scan returns it.
772
+ */
773
+ class Journal {
774
+ tableName;
775
+ names;
776
+ totals;
777
+ budget;
778
+ dryRun;
779
+ /** How many takes the run has made: a scan page records it when it is read. */
780
+ seq = 0;
781
+ keys = new Map();
782
+ /** The keys whose scanned rows are being judged now, each with how many visits hold it. */
783
+ inFlight = new Map();
784
+ /** A real run's latest images of rows it put, by key, oldest first ({@link RECENT_IMAGES}). */
785
+ recent = new Map();
786
+ /** A dry run's planned rows, by the digest of the partition key value ({@link canonicalValue}). */
787
+ placedIn = new Map();
788
+ /**
789
+ * A dry run's planned rows by the value of an attribute a secondary index is partitioned on,
790
+ * built on the first query of that index ({@link placedWith}).
791
+ */
792
+ placedBy = new Map();
793
+ constructor(tableName, names, totals, budget, dryRun) {
794
+ this.tableName = tableName;
795
+ this.names = names;
796
+ this.totals = totals;
797
+ this.budget = budget;
798
+ this.dryRun = dryRun;
799
+ }
800
+ /** The digest of an item's table key, its typed values ({@link canonicalValue}). */
801
+ keyOf(item) {
802
+ if (this.names === undefined || item === undefined)
803
+ return undefined;
804
+ const pk = item[this.names.pk];
805
+ if (pk === undefined)
806
+ return undefined;
807
+ const sk = item[this.names.sk];
808
+ return digest(identity(canonicalValue(pk), sk === undefined ? "" : canonicalValue(sk)));
809
+ }
810
+ /** `key`'s state, made if the budget has room: `undefined` when it has none. */
811
+ state(key) {
812
+ const known = this.keys.get(key);
813
+ if (known !== undefined)
814
+ return known;
815
+ if (!this.budget.admit())
816
+ return undefined;
817
+ const fresh = {
818
+ counted: false,
819
+ takenAt: undefined,
820
+ last: undefined,
821
+ prints: undefined,
822
+ sending: undefined,
823
+ any: false,
824
+ patches: undefined,
825
+ partition: undefined,
826
+ };
827
+ this.keys.set(key, fresh);
828
+ return fresh;
829
+ }
830
+ /** The row stored at `key` at the start is met: counted, once. */
831
+ count(state) {
832
+ if (state.counted)
833
+ return;
834
+ state.counted = true;
835
+ this.totals.scanned++;
836
+ }
837
+ /**
838
+ * The row stored at `key` at the start is taken, or written over, by the run: counted unless the
839
+ * scan counted it — its visit is running, or it was left for this ({@link awaitsMove}). A dry run
840
+ * counts it when its scan meets it, since a dry run takes nothing.
841
+ */
842
+ countTaken(key, state) {
843
+ if (this.dryRun)
844
+ return;
845
+ if (state?.counted === true)
846
+ return;
847
+ if (state !== undefined)
848
+ state.counted = true;
849
+ if (!this.inFlight.has(key))
850
+ this.totals.scanned++;
851
+ }
852
+ addPrint(state, print) {
853
+ if (state.any)
854
+ return;
855
+ if (state.prints === undefined)
856
+ state.prints = [print];
857
+ else if (state.prints.length >= MAX_PRINTS) {
858
+ state.any = true;
859
+ state.prints = undefined;
860
+ }
861
+ else
862
+ state.prints.push(print);
863
+ }
864
+ dropPrint(state, print) {
865
+ const at = state.prints?.indexOf(print) ?? -1;
866
+ if (at >= 0)
867
+ state.prints.splice(at, 1);
868
+ }
869
+ /** A put sent with `print` is answered (or failed): no longer on its way. */
870
+ answered(state, print) {
871
+ const at = state.sending?.indexOf(print) ?? -1;
872
+ if (at >= 0)
873
+ state.sending.splice(at, 1);
874
+ if (state.sending?.length === 0)
875
+ state.sending = undefined;
876
+ }
877
+ /** Whether the row at `key` is the run's own: one it put, or left by an update of one it put. */
878
+ ours(state) {
879
+ return state.last !== undefined && state.last !== "taken";
880
+ }
881
+ /** A real run's latest image of a row it put at `key`. */
882
+ remember(key, image) {
883
+ this.recent.delete(key);
884
+ this.recent.set(key, image);
885
+ if (this.recent.size > RECENT_IMAGES) {
886
+ this.recent.delete(this.recent.keys().next().value);
887
+ }
888
+ }
889
+ /**
890
+ * The scan returned `row`, on a page read when {@link seq} was `pageSeq`: the row to judge (in
891
+ * a dry run, with the plan's updates applied), or `undefined` when the scan passes it. A row
892
+ * judged holds its key until {@link left}.
893
+ */
894
+ visit(row, pageSeq) {
895
+ // A row that isn't the library's is one the run never writes, nor writes over.
896
+ if (row.__edd_e__ === undefined) {
897
+ this.totals.scanned++;
898
+ return { row, key: undefined };
899
+ }
900
+ const key = this.keyOf(row);
901
+ if (key === undefined) {
902
+ this.totals.scanned++;
903
+ return { row, key: undefined };
904
+ }
905
+ const state = this.keys.get(key);
906
+ if (state === undefined) {
907
+ this.totals.scanned++;
908
+ }
909
+ else {
910
+ // A dry run writes nothing, so what its scan returns where its plan took the row is that row,
911
+ // whatever the plan put there since, however alike.
912
+ if (this.dryRun && state.takenAt !== undefined) {
913
+ this.count(state);
914
+ return undefined;
915
+ }
916
+ if (state.any || state.prints?.includes(fingerprint(row)) === true) {
917
+ return undefined;
918
+ }
919
+ // The row the run took, returned by a page read before the take.
920
+ if (state.takenAt !== undefined && state.takenAt > pageSeq) {
921
+ this.count(state);
922
+ return undefined;
923
+ }
924
+ // Counted already: a row written there since the run took the one stored at the start.
925
+ if (state.counted)
926
+ this.totals.scanned++;
927
+ else
928
+ this.count(state);
929
+ }
930
+ this.inFlight.set(key, (this.inFlight.get(key) ?? 0) + 1);
931
+ return { row: state?.patches === undefined ? row : this.patched(state, row), key };
932
+ }
933
+ /** The visit is over: its key is no longer held. */
934
+ left(visit) {
935
+ if (visit.key === undefined)
936
+ return;
937
+ const n = this.inFlight.get(visit.key) ?? 0;
938
+ if (n <= 1)
939
+ this.inFlight.delete(visit.key);
940
+ else
941
+ this.inFlight.set(visit.key, n - 1);
942
+ }
943
+ /**
944
+ * `row`, scanned and judged, stays where it is for another unit's move to take it once its visit
945
+ * is over ({@link RekeyRowContext.awaitsMove}): kept as counted, so the take doesn't count it too.
946
+ */
947
+ awaitsMove(row) {
948
+ const key = this.keyOf(row);
949
+ if (key === undefined)
950
+ return;
951
+ const state = this.state(key);
952
+ if (state !== undefined)
953
+ state.counted = true;
954
+ }
955
+ vacated(key) {
956
+ const digested = this.keys.size === 0 ? undefined : this.keyOf(key);
957
+ return digested !== undefined && this.keys.get(digested)?.last === "taken";
958
+ }
959
+ placed(key) {
960
+ const digested = this.keys.size === 0 ? undefined : this.keyOf(key);
961
+ const state = digested === undefined ? undefined : this.keys.get(digested);
962
+ return state !== undefined && this.ours(state);
963
+ }
964
+ /** A put of the run's at `key` took effect or is on its way: placed, or sent (its print kept). */
965
+ putting(key) {
966
+ const digested = this.keys.size === 0 ? undefined : this.keyOf(key);
967
+ const state = digested === undefined ? undefined : this.keys.get(digested);
968
+ return (state !== undefined &&
969
+ (this.ours(state) || state.any || (state.prints !== undefined && state.prints.length > 0)));
970
+ }
971
+ /** A take of the row at `key` took effect (or was planned). */
972
+ take(key) {
973
+ const state = this.state(key);
974
+ // A row the run never put there was stored there at the start.
975
+ if (state === undefined || !this.ours(state))
976
+ this.countTaken(key, state);
977
+ this.seq++;
978
+ this.recent.delete(key);
979
+ if (state === undefined)
980
+ return;
981
+ state.takenAt = this.seq;
982
+ state.last = "taken";
983
+ // A put here still on its way may land after the take (the take's answer came first): its
984
+ // print stays, so the scan passes the row it puts.
985
+ state.prints = state.sending === undefined ? undefined : [...state.sending];
986
+ state.any = false;
987
+ state.patches = undefined;
988
+ if (state.partition !== undefined)
989
+ this.placedIn.get(state.partition)?.delete(key);
990
+ state.partition = undefined;
991
+ this.indexPlaced(key, undefined);
992
+ }
993
+ /** `key`'s planned image is now `image` (`undefined`: none): the secondary index maps follow. */
994
+ indexPlaced(key, image) {
995
+ for (const [attribute, byValue] of this.placedBy) {
996
+ for (const keys of byValue.values())
997
+ keys.delete(key);
998
+ const value = image?.[attribute];
999
+ if (value === undefined)
1000
+ continue;
1001
+ const text = digest(canonicalValue(value));
1002
+ const keys = byValue.get(text);
1003
+ if (keys === undefined)
1004
+ byValue.set(text, new Set([key]));
1005
+ else
1006
+ keys.add(key);
1007
+ }
1008
+ }
1009
+ /** The keys of planned rows whose `attribute` holds `value`. */
1010
+ placedWith(attribute, value) {
1011
+ let byValue = this.placedBy.get(attribute);
1012
+ if (byValue === undefined) {
1013
+ byValue = new Map();
1014
+ this.placedBy.set(attribute, byValue);
1015
+ for (const keys of this.placedIn.values()) {
1016
+ for (const key of keys) {
1017
+ const image = this.keys.get(key)?.last;
1018
+ const held = typeof image === "object" ? image[attribute] : undefined;
1019
+ if (held === undefined)
1020
+ continue;
1021
+ const text = digest(canonicalValue(held));
1022
+ const same = byValue.get(text);
1023
+ if (same === undefined)
1024
+ byValue.set(text, new Set([key]));
1025
+ else
1026
+ same.add(key);
1027
+ }
1028
+ }
1029
+ }
1030
+ return byValue.get(digest(canonicalValue(value))) ?? [];
1031
+ }
1032
+ /** A put of `image` took effect (or was planned); `replaced`: over the row there, as read. */
1033
+ put(key, image, replaced) {
1034
+ const state = this.state(key);
1035
+ if (replaced && (state === undefined || !this.ours(state))) {
1036
+ this.countTaken(key, state);
1037
+ this.seq++;
1038
+ if (state !== undefined)
1039
+ state.takenAt = this.seq;
1040
+ }
1041
+ if (state === undefined)
1042
+ return;
1043
+ state.patches = undefined;
1044
+ if (!this.dryRun) {
1045
+ state.last = "ours";
1046
+ this.remember(key, image);
1047
+ return;
1048
+ }
1049
+ // A dry run keeps the image it plans, which its reads see: its size, in entries.
1050
+ const text = canonicalItem(image);
1051
+ this.addPrint(state, digest(text));
1052
+ if (state.partition !== undefined)
1053
+ this.placedIn.get(state.partition)?.delete(key);
1054
+ state.partition = undefined;
1055
+ if (!this.budget.admit(Math.ceil((text.length * 2) / IMAGE_ENTRY_BYTES))) {
1056
+ // No room for the image: the plan has a row here, as nothing it can read.
1057
+ state.last = "ours";
1058
+ state.any = true;
1059
+ this.indexPlaced(key, undefined);
1060
+ return;
1061
+ }
1062
+ state.last = image;
1063
+ const partition = digest(canonicalValue(image[this.names.pk]));
1064
+ state.partition = partition;
1065
+ const set = this.placedIn.get(partition);
1066
+ if (set === undefined)
1067
+ this.placedIn.set(partition, new Set([key]));
1068
+ else
1069
+ set.add(key);
1070
+ this.indexPlaced(key, image);
1071
+ }
1072
+ /** An update took effect (or was planned) at `key`. */
1073
+ update(key, update) {
1074
+ const known = this.keys.get(key);
1075
+ if (known !== undefined && this.ours(known)) {
1076
+ const image = typeof known.last === "object" ? known.last : this.recent.get(key);
1077
+ const next = image === undefined ? undefined : updated(image, update);
1078
+ if (next === undefined) {
1079
+ known.any = true;
1080
+ known.prints = undefined;
1081
+ return;
1082
+ }
1083
+ this.addPrint(known, fingerprint(next));
1084
+ if (!this.dryRun) {
1085
+ this.remember(key, next);
1086
+ return;
1087
+ }
1088
+ known.last = next;
1089
+ this.indexPlaced(key, next);
1090
+ return;
1091
+ }
1092
+ // The row stored at the start, updated in place: the scan meets it as it is. A dry run's
1093
+ // reads see the update.
1094
+ if (this.dryRun) {
1095
+ const state = known ?? this.state(key);
1096
+ if (state === undefined || !this.budget.admit())
1097
+ return;
1098
+ if (state.patches === undefined)
1099
+ state.patches = [];
1100
+ state.patches.push(update);
1101
+ }
1102
+ }
1103
+ patched(state, row) {
1104
+ return state.patches === undefined
1105
+ ? row
1106
+ : state.patches.reduce((image, update) => updated(image, update) ?? image, row);
1107
+ }
1108
+ /** A dry run's write ({@link RekeyRowContext.plan}). */
1109
+ plan(items) {
1110
+ // What a condition asks of the row at its key: that there be none, that there be one, or what
1111
+ // only DynamoDB can judge (assumed to hold, as the run assumes of every request).
1112
+ const asks = (condition) => {
1113
+ const text = condition?.trim() ?? "";
1114
+ if (text === "")
1115
+ return undefined;
1116
+ if (/^attribute_not_exists\(\s*#?\w+\s*\)$/.test(text))
1117
+ return "absent";
1118
+ if (text.includes("attribute_not_exists"))
1119
+ return undefined;
1120
+ return "present";
1121
+ };
1122
+ const mine = items.filter((item) => {
1123
+ const table = item.Put?.TableName ??
1124
+ item.Delete?.TableName ??
1125
+ item.Update?.TableName ??
1126
+ item.ConditionCheck?.TableName;
1127
+ return table === this.tableName;
1128
+ });
1129
+ for (const item of mine) {
1130
+ const write = item.Put !== undefined
1131
+ ? { key: item.Put.Item, condition: item.Put.ConditionExpression }
1132
+ : item.Delete !== undefined
1133
+ ? { key: item.Delete.Key, condition: item.Delete.ConditionExpression }
1134
+ : item.Update !== undefined
1135
+ ? { key: item.Update.Key, condition: item.Update.ConditionExpression }
1136
+ : {
1137
+ key: item.ConditionCheck?.Key,
1138
+ condition: item.ConditionCheck?.ConditionExpression,
1139
+ };
1140
+ const key = this.keyOf(write.key);
1141
+ if (key === undefined)
1142
+ continue;
1143
+ const last = this.keys.get(key)?.last;
1144
+ const there = last === undefined ? undefined : last !== "taken";
1145
+ const asked = asks(write.condition);
1146
+ if (asked === "absent" && there === true)
1147
+ return false;
1148
+ if (asked === "present" && there === false)
1149
+ return false;
1150
+ }
1151
+ for (const item of mine)
1152
+ this.applied(item);
1153
+ return true;
1154
+ }
1155
+ /** What one write item did, once it took effect (or was planned). */
1156
+ applied(item) {
1157
+ if (item.Put?.Item !== undefined) {
1158
+ const key = this.keyOf(item.Put.Item);
1159
+ if (key !== undefined) {
1160
+ this.put(key, item.Put.Item, overwrites(item.Put.ConditionExpression));
1161
+ }
1162
+ }
1163
+ else if (item.Delete !== undefined) {
1164
+ const key = this.keyOf(item.Delete.Key);
1165
+ if (key !== undefined)
1166
+ this.take(key);
1167
+ }
1168
+ else if (item.Update !== undefined) {
1169
+ const key = this.keyOf(item.Update.Key);
1170
+ if (key !== undefined)
1171
+ this.update(key, item.Update);
1172
+ }
1173
+ }
1174
+ /** A row a dry run's read returned, as the plan leaves it: `undefined` if the plan took it. */
1175
+ reconcile(key, item) {
1176
+ const state = key === undefined ? undefined : this.keys.get(key);
1177
+ if (state === undefined)
1178
+ return item;
1179
+ if (state.last === "taken")
1180
+ return undefined;
1181
+ if (typeof state.last === "object")
1182
+ return state.last;
1183
+ // A row planned with no room for its image reads as what's stored.
1184
+ if (state.last === "ours")
1185
+ return item;
1186
+ return item === undefined ? undefined : this.patched(state, item);
1187
+ }
1188
+ /**
1189
+ * `send`, a real run's write: the rows it puts are the run's own from when it's sent (the scan
1190
+ * may return one before the answer comes), and what it did is noted once it's answered.
1191
+ */
1192
+ writing(puts, send, done) {
1193
+ return Effect.suspend(() => {
1194
+ const sent = [];
1195
+ for (const item of puts) {
1196
+ const key = this.keyOf(item);
1197
+ if (key === undefined || item === undefined)
1198
+ continue;
1199
+ const state = this.state(key);
1200
+ if (state === undefined)
1201
+ continue;
1202
+ const print = fingerprint(item);
1203
+ this.addPrint(state, print);
1204
+ if (state.sending === undefined)
1205
+ state.sending = [print];
1206
+ else
1207
+ state.sending.push(print);
1208
+ sent.push({ state, print });
1209
+ }
1210
+ return send.pipe(Effect.tap((output) => Effect.sync(() => {
1211
+ for (const { state, print } of sent)
1212
+ this.answered(state, print);
1213
+ for (const item of done(output))
1214
+ this.applied(item);
1215
+ })), Effect.tapError(() => Effect.sync(() => {
1216
+ for (const { state, print } of sent) {
1217
+ this.answered(state, print);
1218
+ this.dropPrint(state, print);
1219
+ }
1220
+ })));
1221
+ });
1222
+ }
1223
+ /**
1224
+ * The client the handlers use: in a real run, `client` with each write on this table noted as
1225
+ * it's answered; in a dry run, `client` with its reads seeing the plan, and every write refused
1226
+ * (a dry run writes nothing). Built over the instrumented client, it is itself one, so
1227
+ * `Capacity.client` hands it out as is and each request is reported once.
1228
+ */
1229
+ view(client) {
1230
+ const view = Object.create(client);
1231
+ const onTable = (name) => name === this.tableName;
1232
+ if (this.dryRun) {
1233
+ const refuse = (operation) => () => Effect.die(new Error(`rekey: a dry run sent a write (${operation})`));
1234
+ view.putItem = refuse("PutItem");
1235
+ view.deleteItem = refuse("DeleteItem");
1236
+ view.updateItem = refuse("UpdateItem");
1237
+ view.transactWriteItems = refuse("TransactWriteItems");
1238
+ view.batchWriteItem = refuse("BatchWriteItem");
1239
+ view.getItem = (input) => onTable(input.TableName)
1240
+ ? Effect.map(client.getItem(input), (output) => {
1241
+ const item = this.reconcile(this.keyOf(input.Key), output.Item);
1242
+ return item === output.Item ? output : { ...output, Item: item };
1243
+ })
1244
+ : client.getItem(input);
1245
+ view.query = (input) => onTable(input.TableName)
1246
+ ? Effect.map(client.query(input), (output) => this.reconcileQuery(input, output))
1247
+ : client.query(input);
1248
+ view.batchGetItem = (input) => Effect.map(client.batchGetItem(input), (output) => {
1249
+ const responses = { ...output.Responses };
1250
+ const rows = output.Responses?.[this.tableName];
1251
+ const asked = input.RequestItems?.[this.tableName];
1252
+ if (rows === undefined || asked === undefined)
1253
+ return output;
1254
+ const answered = new Set();
1255
+ const kept = [];
1256
+ for (const row of rows) {
1257
+ const key = this.keyOf(row);
1258
+ if (key !== undefined)
1259
+ answered.add(key);
1260
+ const item = this.reconcile(key, row);
1261
+ if (item !== undefined)
1262
+ kept.push(item);
1263
+ }
1264
+ const unprocessed = new Set((output.UnprocessedKeys?.[this.tableName]?.Keys ?? []).map((key) => this.keyOf(key)));
1265
+ for (const ask of asked.Keys ?? []) {
1266
+ const key = this.keyOf(ask);
1267
+ if (key === undefined || answered.has(key) || unprocessed.has(key))
1268
+ continue;
1269
+ const item = this.reconcile(key, undefined);
1270
+ if (item !== undefined)
1271
+ kept.push(item);
1272
+ }
1273
+ responses[this.tableName] = kept;
1274
+ return { ...output, Responses: responses };
1275
+ });
1276
+ return view;
1277
+ }
1278
+ view.putItem = (input) => onTable(input.TableName)
1279
+ ? this.writing([input.Item], client.putItem(input), () => [
1280
+ {
1281
+ Put: {
1282
+ TableName: input.TableName,
1283
+ Item: input.Item,
1284
+ ConditionExpression: input.ConditionExpression,
1285
+ },
1286
+ },
1287
+ ])
1288
+ : client.putItem(input);
1289
+ view.deleteItem = (input) => onTable(input.TableName)
1290
+ ? this.writing([], client.deleteItem(input), () => [
1291
+ { Delete: { TableName: input.TableName, Key: input.Key } },
1292
+ ])
1293
+ : client.deleteItem(input);
1294
+ view.updateItem = (input) => onTable(input.TableName)
1295
+ ? this.writing([], client.updateItem(input), () => [{ Update: input }])
1296
+ : client.updateItem(input);
1297
+ view.transactWriteItems = (input) => {
1298
+ const items = (input.TransactItems ?? []).filter((item) => onTable(item.Put?.TableName ??
1299
+ item.Delete?.TableName ??
1300
+ item.Update?.TableName ??
1301
+ item.ConditionCheck?.TableName));
1302
+ return this.writing(items.map((item) => item.Put?.Item), client.transactWriteItems(input), () => items);
1303
+ };
1304
+ view.batchWriteItem = (input) => {
1305
+ const writes = input.RequestItems?.[this.tableName] ?? [];
1306
+ return this.writing(writes.map((write) => write.PutRequest?.Item), client.batchWriteItem(input), (output) => {
1307
+ const left = new Set((output.UnprocessedItems?.[this.tableName] ?? []).map((write) => this.keyOf(write.PutRequest?.Item ?? write.DeleteRequest?.Key)));
1308
+ return writes.flatMap((write) => {
1309
+ const key = this.keyOf(write.PutRequest?.Item ?? write.DeleteRequest?.Key);
1310
+ if (key === undefined || left.has(key))
1311
+ return [];
1312
+ return write.PutRequest?.Item !== undefined
1313
+ ? [{ Put: { TableName: this.tableName, Item: write.PutRequest.Item } }]
1314
+ : [{ Delete: { TableName: this.tableName, Key: write.DeleteRequest.Key } }];
1315
+ });
1316
+ });
1317
+ };
1318
+ return view;
1319
+ }
1320
+ /**
1321
+ * A dry run's query page, reconciled with the plan: rows it took dropped, rows it put in their
1322
+ * place, and rows it put that match the key condition, inside the page's range, added in order.
1323
+ */
1324
+ reconcileQuery(input, output) {
1325
+ if (output.Items === undefined || input.Select === "COUNT")
1326
+ return output;
1327
+ const condition = keyConditionOf(input);
1328
+ const names = this.names;
1329
+ const rows = [];
1330
+ const answered = new Set();
1331
+ let changed = false;
1332
+ for (const item of output.Items) {
1333
+ const key = this.keyOf(item);
1334
+ if (key !== undefined)
1335
+ answered.add(key);
1336
+ const row = this.reconcile(key, item);
1337
+ if (row !== item)
1338
+ changed = true;
1339
+ // An index holds a row only while its key does: one the plan's update moved off it is gone.
1340
+ if (row !== undefined && (row === item || condition === undefined || condition.holds(row))) {
1341
+ rows.push(row);
1342
+ }
1343
+ }
1344
+ const added = [];
1345
+ if (condition !== undefined && names !== undefined) {
1346
+ // The table orders by its sort key, an index by the attribute its condition names: rows of
1347
+ // an index queried by partition alone, whose order isn't known here, join its last page.
1348
+ const sort = condition.sort ?? (input.IndexName === undefined ? names.sk : undefined);
1349
+ const order = (item) => item === undefined || sort === undefined ? undefined : item[sort]?.S;
1350
+ const forward = input.ScanIndexForward !== false;
1351
+ const start = order(input.ExclusiveStartKey);
1352
+ const end = order(output.LastEvaluatedKey);
1353
+ const value = input.ExpressionAttributeValues?.[/=\s*(:\w+)/.exec(input.KeyConditionExpression ?? "")?.[1] ?? ""];
1354
+ const candidates = value === undefined
1355
+ ? []
1356
+ : condition.attribute === names.pk
1357
+ ? (this.placedIn.get(digest(canonicalValue(value))) ?? [])
1358
+ : this.placedWith(condition.attribute, value);
1359
+ for (const key of candidates) {
1360
+ if (answered.has(key))
1361
+ continue;
1362
+ const image = this.reconcile(key, undefined);
1363
+ if (image === undefined || !condition.holds(image))
1364
+ continue;
1365
+ if (sort === undefined) {
1366
+ if (output.LastEvaluatedKey === undefined)
1367
+ added.push(image);
1368
+ continue;
1369
+ }
1370
+ const at = order(image);
1371
+ if (at === undefined)
1372
+ continue;
1373
+ if (start !== undefined && (forward ? at <= start : at >= start))
1374
+ continue;
1375
+ if (end !== undefined && (forward ? at > end : at < end))
1376
+ continue;
1377
+ added.push(image);
1378
+ }
1379
+ if (added.length > 0) {
1380
+ const merged = sort === undefined
1381
+ ? [...rows, ...added]
1382
+ : [...rows, ...added].sort((a, b) => {
1383
+ const x = order(a) ?? "";
1384
+ const y = order(b) ?? "";
1385
+ return (x < y ? -1 : x > y ? 1 : 0) * (forward ? 1 : -1);
1386
+ });
1387
+ return { ...output, Items: merged, Count: merged.length };
1388
+ }
1389
+ }
1390
+ if (!changed)
1391
+ return output;
1392
+ return { ...output, Items: rows, Count: rows.length };
1393
+ }
1394
+ }
199
1395
  // ---------------------------------------------------------------------------
200
1396
  // The run
201
1397
  // ---------------------------------------------------------------------------
@@ -210,9 +1406,17 @@ export const run = (args) => Capacity.measured("Table.rekey", { target: args.tab
210
1406
  const problem = positiveInteger(options.segments, "segments") ??
211
1407
  positiveInteger(options.concurrency, "concurrency") ??
212
1408
  positiveInteger(options.pageSize, "pageSize") ??
213
- positiveInteger(options.maxPages, "maxPages");
1409
+ positiveInteger(options.maxPages, "maxPages") ??
1410
+ positiveInteger(options.journalCapacity, "journalCapacity") ??
1411
+ ((options.journalCapacity ?? 0) > MAX_JOURNAL_CAPACITY
1412
+ ? `journalCapacity must be at most ${MAX_JOURNAL_CAPACITY}; received ${options.journalCapacity}.`
1413
+ : undefined);
214
1414
  if (problem !== undefined)
215
1415
  return yield* optionError(problem);
1416
+ if (options.releaseOrphanedReservations === true && options.writesStopped !== true) {
1417
+ return yield* optionError("releaseOrphanedReservations needs writesStopped: true. Releasing is a maintenance step: " +
1418
+ "stop every writer to the table first, another cleanup releasing reservations included.");
1419
+ }
216
1420
  let positions;
217
1421
  if (options.resume !== undefined) {
218
1422
  const decoded = decodeToken(options.resume, tableName);
@@ -228,6 +1432,7 @@ export const run = (args) => Capacity.measured("Table.rekey", { target: args.tab
228
1432
  else {
229
1433
  positions = Array.from({ length: options.segments ?? 1 }, () => 0);
230
1434
  }
1435
+ const startedAtTheBeginning = positions.every((position) => position === 0);
231
1436
  // Members by the `__edd_e__` values they claim, in registration order.
232
1437
  const byType = new Map();
233
1438
  for (const member of members) {
@@ -238,66 +1443,123 @@ export const run = (args) => Capacity.measured("Table.rekey", { target: args.tab
238
1443
  }
239
1444
  }
240
1445
  const prefixed = members.flatMap((member) => (member.typePrefixes ?? []).map((prefix) => ({ prefix, member })));
1446
+ const totals = new Totals();
1447
+ const budget = new Budget(options.journalCapacity ?? DEFAULT_JOURNAL_CAPACITY);
1448
+ const journal = new Journal(tableName, members.find((member) => member.key !== undefined)?.key, totals, budget, dryRun);
1449
+ const units = new Units(totals, budget);
241
1450
  const claimed = new Set();
242
- const running = new Map();
1451
+ const atEnd = [];
243
1452
  const ctx = {
244
1453
  tableName,
245
1454
  dryRun,
1455
+ repairIndexKeys: options.repairIndexKeys === true,
1456
+ reservations: options.reservations === true || options.releaseOrphanedReservations === true,
1457
+ releaseOrphanedReservations: options.releaseOrphanedReservations === true,
1458
+ writesStopped: options.writesStopped === true,
1459
+ sawWholeTable: () => startedAtTheBeginning && positions.every((position) => position === 1),
246
1460
  claim: (unit) => {
247
- if (claimed.has(unit))
1461
+ const key = digest(unit);
1462
+ if (claimed.has(key))
248
1463
  return false;
249
- claimed.add(unit);
1464
+ if (budget.admit())
1465
+ claimed.add(key);
250
1466
  return true;
251
1467
  },
252
- once: (unit, work) => Effect.suspend(() => {
253
- const under = running.get(unit);
254
- if (under !== undefined)
255
- return Effect.as(Deferred.await(under), {});
256
- const done = Deferred.makeUnsafe();
257
- running.set(unit, done);
258
- return Effect.ensuring(work, Deferred.succeed(done, undefined));
1468
+ claimed: (unit) => claimed.has(digest(unit)),
1469
+ keep: () => budget.admit(),
1470
+ awaitsMove: (row) => journal.awaitsMove(row),
1471
+ atEnd: (member, judge) => {
1472
+ if (budget.admit())
1473
+ atEnd.push({ member, judge });
1474
+ else
1475
+ totals.add(member, judge());
1476
+ },
1477
+ judge: (member, unit, work) => units.judge(member, unit, work),
1478
+ plan: (items) => journal.plan(items),
1479
+ vacated: (key) => journal.vacated(key),
1480
+ journalFull: () => budget.full,
1481
+ placed: (key) => journal.placed(key),
1482
+ putting: (key) => journal.putting(key),
1483
+ yieldTo: (row, rows) => Effect.gen(function* () {
1484
+ const type = row.__edd_e__?.S;
1485
+ if (type === undefined)
1486
+ return undefined;
1487
+ for (const member of byType.get(type) ?? []) {
1488
+ if (member.holder === undefined)
1489
+ continue;
1490
+ const judged = yield* member.holder(row, rows, ctx);
1491
+ if (judged !== undefined)
1492
+ return judged;
1493
+ }
1494
+ return undefined;
259
1495
  }),
260
1496
  };
261
- const totals = new Totals();
262
- const handle = (row) => Effect.gen(function* () {
1497
+ const handle = (found, pageSeq) => Effect.suspend(() => {
1498
+ const visit = journal.visit(found, pageSeq);
1499
+ if (visit === undefined)
1500
+ return Effect.void;
1501
+ return judgeRow(visit.row).pipe(Effect.ensuring(Effect.sync(() => journal.left(visit))));
1502
+ });
1503
+ const judgeRow = (row) => Effect.gen(function* () {
263
1504
  const type = row.__edd_e__?.S;
264
1505
  if (type === undefined) {
265
1506
  totals.add(undefined, { skipped: { notLibrary: 1 } });
266
1507
  return;
267
1508
  }
268
- const candidates = [
1509
+ const claiming = [
269
1510
  ...(byType.get(type) ?? []),
270
1511
  ...prefixed.filter((p) => type.startsWith(p.prefix)).map((p) => p.member),
271
1512
  ];
1513
+ const exclusive = claiming.filter((member) => member.exclusive === true);
1514
+ const candidates = exclusive.length > 0 ? exclusive : claiming;
1515
+ // A member that can't read the row's key back (`unrecognizedKey`) isn't its owner: the
1516
+ // key names another member's key space. The search goes on, so the order members are
1517
+ // listed in doesn't choose one, and the row is counted unrecognized only when no member
1518
+ // recognises it.
1519
+ let unrecognized;
272
1520
  for (const member of candidates) {
273
1521
  const tally = yield* member.row(row, ctx);
274
1522
  if (tally === undefined)
275
1523
  continue;
1524
+ if (onlyUnrecognized(tally)) {
1525
+ unrecognized ??= { member, tally };
1526
+ continue;
1527
+ }
276
1528
  totals.add(member.name, tally);
277
1529
  return;
278
1530
  }
1531
+ if (unrecognized !== undefined) {
1532
+ totals.add(unrecognized.member.name, unrecognized.tally);
1533
+ return;
1534
+ }
279
1535
  totals.add(undefined, { skipped: { unregistered: 1 } });
280
1536
  });
281
1537
  const token = () => positions.every((p) => p === 1) ? undefined : encodeToken(tableName, positions);
282
- const snapshot = () => totals.report(dryRun, capacity(), token());
1538
+ const snapshot = () => totals.report(dryRun, capacity(), token(), budget);
283
1539
  let pagesLeft = options.maxPages ?? Number.POSITIVE_INFINITY;
284
1540
  const concurrency = options.concurrency ?? 4;
1541
+ // The scan reads through the instrumented client; handlers read and write through the
1542
+ // journal's view of it, which `Capacity.client` hands them as is.
285
1543
  const client = yield* Capacity.client;
1544
+ const view = journal.view(client);
1545
+ const viaView = (effect) => Effect.provideService(effect, DynamoClient, view);
286
1546
  const scanSegment = (segment) => Effect.gen(function* () {
287
1547
  while (positions[segment] !== 1) {
288
1548
  if (pagesLeft <= 0)
289
1549
  return;
290
1550
  pagesLeft--;
291
1551
  const at = positions[segment];
1552
+ const pageSeq = journal.seq;
292
1553
  const page = yield* client.scan({
293
1554
  TableName: tableName,
294
1555
  ...(positions.length > 1 && { Segment: segment, TotalSegments: positions.length }),
295
1556
  ...(options.pageSize !== undefined && { Limit: options.pageSize }),
296
1557
  ...(at !== 0 && { ExclusiveStartKey: keyFromWire(at) }),
297
1558
  });
298
- const rows = page.Items ?? [];
299
- totals.scanned += rows.length;
300
- yield* Effect.forEach(rows, handle, { concurrency, discard: true });
1559
+ yield* viaView(Effect.forEach(page.Items ?? [], (row) => handle(row, pageSeq), {
1560
+ concurrency,
1561
+ discard: true,
1562
+ }));
301
1563
  const last = page.LastEvaluatedKey;
302
1564
  positions[segment] = last === undefined ? 1 : (keyToWire(last) ?? 1);
303
1565
  if (options.onProgress !== undefined)
@@ -305,40 +1567,51 @@ export const run = (args) => Capacity.measured("Table.rekey", { target: args.tab
305
1567
  }
306
1568
  });
307
1569
  yield* Effect.forEach(positions.map((_, segment) => segment), scanSegment, { concurrency: "unbounded", discard: true });
1570
+ for (const { member, judge } of atEnd)
1571
+ totals.add(member, judge());
308
1572
  for (const member of members) {
309
- if (member.finish !== undefined)
310
- totals.add(member.name, yield* member.finish(ctx));
1573
+ if (member.finish !== undefined) {
1574
+ totals.add(member.name, yield* viaView(member.finish(ctx)));
1575
+ }
311
1576
  }
312
1577
  return snapshot();
313
1578
  }));
314
1579
  /** Tallies added up, field by field. */
315
- /**
316
- * Get a row out of the way of another row's move, `run` being its own handler under the context
317
- * given: for real in a real run. In a dry run nothing moves, so the row is only judged, under a
318
- * context that counts nothing and takes no claim, since the scan counts it when it reaches it:
319
- * what comes back is what would stop it, the same conflicts the real run gets, and so a dry run
320
- * agrees with the real run about a chain. A row that's met more than once is reported once
321
- * ({@link RekeyReport.conflicts}).
322
- */
323
- export const displace = (ctx, run) => ctx.dryRun
324
- ? Effect.map(run({ ...ctx, claim: () => false, once: (_unit, work) => work }), (tally) => (tally?.conflicts ?? []).length > 0 ? { conflicts: tally.conflicts } : {})
325
- : Effect.map(run(ctx), (tally) => tally ?? {});
326
1580
  export const mergeTallies = (...tallies) => {
327
1581
  const moved = {};
328
1582
  const skipped = {};
329
1583
  const conflicts = [];
1584
+ const reservations = [];
1585
+ const ambiguous = [];
1586
+ const indexKeys = {};
1587
+ const guardGaps = {};
1588
+ const guardGapRows = [];
330
1589
  let unchanged = 0;
331
1590
  let indexKeysRewritten = 0;
1591
+ let zonesRewritten = 0;
332
1592
  let sentinelsMoved = 0;
1593
+ let worked = false;
333
1594
  for (const tally of tallies) {
1595
+ worked ||= tally.worked === true;
334
1596
  unchanged += tally.unchanged ?? 0;
335
1597
  indexKeysRewritten += tally.indexKeysRewritten ?? 0;
1598
+ zonesRewritten += tally.zonesRewritten ?? 0;
336
1599
  sentinelsMoved += tally.sentinelsMoved ?? 0;
1600
+ for (const count of INDEX_KEY_COUNTS) {
1601
+ const n = tally.indexKeys?.[count];
1602
+ if (n !== undefined)
1603
+ indexKeys[count] = (indexKeys[count] ?? 0) + n;
1604
+ }
337
1605
  for (const kind of ROW_KINDS) {
338
1606
  const n = tally.moved?.[kind];
339
1607
  if (n !== undefined)
340
1608
  moved[kind] = (moved[kind] ?? 0) + n;
341
1609
  }
1610
+ for (const gap of GUARD_GAPS) {
1611
+ const n = tally.guardGaps?.[gap];
1612
+ if (n !== undefined)
1613
+ guardGaps[gap] = (guardGaps[gap] ?? 0) + n;
1614
+ }
342
1615
  for (const reason of SKIP_REASONS) {
343
1616
  const n = tally.skipped?.[reason];
344
1617
  if (n !== undefined)
@@ -346,14 +1619,27 @@ export const mergeTallies = (...tallies) => {
346
1619
  }
347
1620
  for (const conflict of tally.conflicts ?? [])
348
1621
  conflicts.push(conflict);
1622
+ for (const entry of tally.reservations ?? [])
1623
+ reservations.push(entry);
1624
+ for (const row of tally.guardGapRows ?? [])
1625
+ guardGapRows.push(row);
1626
+ for (const ambiguity of tally.ambiguous ?? [])
1627
+ ambiguous.push(ambiguity);
349
1628
  }
350
1629
  return {
351
1630
  ...(unchanged > 0 && { unchanged }),
352
1631
  ...(Object.keys(moved).length > 0 && { moved }),
353
1632
  ...(indexKeysRewritten > 0 && { indexKeysRewritten }),
1633
+ ...(zonesRewritten > 0 && { zonesRewritten }),
354
1634
  ...(sentinelsMoved > 0 && { sentinelsMoved }),
1635
+ ...(Object.keys(indexKeys).length > 0 && { indexKeys }),
1636
+ ...(reservations.length > 0 && { reservations }),
1637
+ ...(Object.keys(guardGaps).length > 0 && { guardGaps }),
1638
+ ...(guardGapRows.length > 0 && { guardGapRows }),
355
1639
  ...(conflicts.length > 0 && { conflicts }),
356
1640
  ...(Object.keys(skipped).length > 0 && { skipped }),
1641
+ ...(worked && { worked }),
1642
+ ...(ambiguous.length > 0 && { ambiguous }),
357
1643
  };
358
1644
  };
359
1645
  //# sourceMappingURL=Rekey.js.map