effect-dynamodb 1.38.0 → 1.39.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/Aggregate.d.ts.map +1 -1
  2. package/dist/Aggregate.js +312 -338
  3. package/dist/Aggregate.js.map +1 -1
  4. package/dist/Batch.d.ts.map +1 -1
  5. package/dist/Batch.js +72 -191
  6. package/dist/Batch.js.map +1 -1
  7. package/dist/Collection.d.ts.map +1 -1
  8. package/dist/Collection.js +15 -16
  9. package/dist/Collection.js.map +1 -1
  10. package/dist/DynamoClient.d.ts +22 -8
  11. package/dist/DynamoClient.d.ts.map +1 -1
  12. package/dist/DynamoClient.js +57 -80
  13. package/dist/DynamoClient.js.map +1 -1
  14. package/dist/Entity.d.ts +9 -84
  15. package/dist/Entity.d.ts.map +1 -1
  16. package/dist/Entity.js +1079 -2664
  17. package/dist/Entity.js.map +1 -1
  18. package/dist/EventStore.d.ts +2 -2
  19. package/dist/EventStore.d.ts.map +1 -1
  20. package/dist/EventStore.js +179 -289
  21. package/dist/EventStore.js.map +1 -1
  22. package/dist/Query.d.ts +70 -32
  23. package/dist/Query.d.ts.map +1 -1
  24. package/dist/Query.js +501 -80
  25. package/dist/Query.js.map +1 -1
  26. package/dist/Table.d.ts +8 -2
  27. package/dist/Table.d.ts.map +1 -1
  28. package/dist/Table.js +7 -0
  29. package/dist/Table.js.map +1 -1
  30. package/dist/Transaction.d.ts +2 -18
  31. package/dist/Transaction.d.ts.map +1 -1
  32. package/dist/Transaction.js +1 -58
  33. package/dist/Transaction.js.map +1 -1
  34. package/dist/index.d.ts +1 -1
  35. package/dist/index.d.ts.map +1 -1
  36. package/dist/index.js +1 -1
  37. package/dist/index.js.map +1 -1
  38. package/dist/internal/BoundQuery.d.ts +11 -8
  39. package/dist/internal/BoundQuery.d.ts.map +1 -1
  40. package/dist/internal/BoundQuery.js +6 -2
  41. package/dist/internal/BoundQuery.js.map +1 -1
  42. package/dist/internal/Cursor.d.ts +9 -4
  43. package/dist/internal/Cursor.d.ts.map +1 -1
  44. package/dist/internal/Cursor.js +12 -2
  45. package/dist/internal/Cursor.js.map +1 -1
  46. package/dist/internal/ProjectionEngine.d.ts +2 -16
  47. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  48. package/dist/internal/ProjectionEngine.js +44 -229
  49. package/dist/internal/ProjectionEngine.js.map +1 -1
  50. package/dist/internal/RangePlanner.d.ts +0 -76
  51. package/dist/internal/RangePlanner.d.ts.map +1 -1
  52. package/dist/internal/RangePlanner.js +2 -206
  53. package/dist/internal/RangePlanner.js.map +1 -1
  54. package/dist/internal/Rekey.d.ts +28 -6
  55. package/dist/internal/Rekey.d.ts.map +1 -1
  56. package/dist/internal/Rekey.js +46 -10
  57. package/dist/internal/Rekey.js.map +1 -1
  58. package/dist/internal/ShardMerge.d.ts +83 -0
  59. package/dist/internal/ShardMerge.d.ts.map +1 -0
  60. package/dist/internal/ShardMerge.js +182 -0
  61. package/dist/internal/ShardMerge.js.map +1 -0
  62. package/dist/internal/TransactPlan.d.ts +1 -8
  63. package/dist/internal/TransactPlan.d.ts.map +1 -1
  64. package/dist/internal/TransactPlan.js +2 -9
  65. package/dist/internal/TransactPlan.js.map +1 -1
  66. package/dist/internal/TransactWriteOps.d.ts +6 -9
  67. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  68. package/dist/internal/TransactWriteOps.js +3 -79
  69. package/dist/internal/TransactWriteOps.js.map +1 -1
  70. package/dist/internal/TransactableOps.d.ts +8 -6
  71. package/dist/internal/TransactableOps.d.ts.map +1 -1
  72. package/dist/internal/TransactableOps.js +13 -9
  73. package/dist/internal/TransactableOps.js.map +1 -1
  74. package/package.json +4 -2
@@ -56,7 +56,7 @@ import { Context, DateTime, Effect, Function, Option, Pipeable, Result, Schedule
56
56
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
57
57
  import * as Capacity from "./internal/Capacity.js";
58
58
  import { ProjectionRoutes } from "./internal/EventProjection.js";
59
- import { eq, or } from "./internal/Expr.js";
59
+ import { eq } from "./internal/Expr.js";
60
60
  import { asReadGuard } from "./internal/ExpressionLimits.js";
61
61
  import { itemBytes, transactItemBytes } from "./internal/ItemSize.js";
62
62
  import { isMultiProjection, } from "./internal/MultiProjection.js";
@@ -166,12 +166,9 @@ const SEALED_ATTRIBUTE = "__edd_sealed__";
166
166
  */
167
167
  const WRITE_TOKEN_ATTRIBUTE = "__edd_wt__";
168
168
  /**
169
- * @internal Set by `rekey` (#171) on the first event of a stream it moved
170
- * from its 1.36 partition key, once every row is copied to the current one:
171
- * the stream lives there from then on. `locateStream` reads it; an append
172
- * located at the 1.36 key checks it is absent (`AppendParts.locationCheck`),
173
- * so a writer that located the stream before the move fails with
174
- * `VersionConflict` instead of writing where nothing reads.
169
+ * @internal Set by `rekey` on the first event of a stream it moved, once every
170
+ * row is copied to its current partition key: what is left under the old key
171
+ * is then deleted, and a run stopped partway resumes from there.
175
172
  */
176
173
  const MOVED_ATTRIBUTE = "__edd_moved__";
177
174
  /** @internal The write token's length in hex digits: 128 random bits. */
@@ -256,7 +253,7 @@ const putItemReason = (cause) => {
256
253
  };
257
254
  /**
258
255
  * @internal What a cancelled append means for one stream, from the reasons of
259
- * its own items: `[0, guardCount)` the contiguity and location checks,
256
+ * its own items: `[0, guardCount)` the contiguity check,
260
257
  * `[guardCount, guardCount + eventCount)` the event puts, and the snapshot at
261
258
  * `snapshotIndex` (`-1`: none). `StreamSealed` when the contiguity check, the
262
259
  * first event put or the snapshot failed and returned a sealed item (#166);
@@ -333,12 +330,7 @@ const STREAM_INDEX_CONFIG_KEYS = [
333
330
  * stream index several streams (or stream ids) share (#149). The table's `pk`
334
331
  * is projected into every index, whatever its projection.
335
332
  */
336
- const streamPkFilter = (streamPk, streamPk136) => {
337
- const pk = createPathBuilder().pk;
338
- // A stream still under its 1.36 key (#171) has its items there: either
339
- // key, since a stream is never split across the two.
340
- return streamPk136 === undefined ? eq(pk, streamPk) : or(eq(pk, streamPk), eq(pk, streamPk136));
341
- };
333
+ const streamPkFilter = (streamPk) => eq(createPathBuilder().pk, streamPk);
342
334
  /**
343
335
  * @internal Validate `makeStream({ indexes })` at definition time.
344
336
  *
@@ -922,68 +914,12 @@ export const makeStream = (config) => {
922
914
  // ---------------------------------------------------------------------------
923
915
  // Key helpers
924
916
  // ---------------------------------------------------------------------------
925
- const composeStreamPk = (streamId) => {
926
- const composites = KeyComposer.extractComposites(compositeFields, streamId);
927
- return DynamoSchema.composeKey(schema, keyLabel, composites, keyOptions);
928
- };
929
- /**
930
- * The partition key 1.36 composed for `streamId`, when the 1.36 key
931
- * fallback is on and its text differs from {@link composeStreamPk}'s — a
932
- * number stream id composite whose text changed (#171). `force` answers
933
- * with the fallback off too: `rekey` moves streams whatever it is set to.
934
- */
935
- const composeStreamPk136 = (streamId, force = false) => {
936
- if (!force && !KeyText136.enabled(schema))
937
- return undefined;
938
- const composites = KeyText136.extractComposites(compositeFields, streamId);
939
- const pk136 = DynamoSchema.composeKey(schema, keyLabel, composites, keyOptions);
940
- return pk136 === composeStreamPk(streamId) ? undefined : pk136;
941
- };
942
- /**
943
- * The partition key a stream lives under (#171, DESIGN.md §7 "Rows written
944
- * by 1.36"): its current key, unless that key's text changed since 1.36 and
945
- * the stream's first event is under its 1.36 key. A stream 1.36 started is
946
- * read and appended there — its events, snapshot, seal and command
947
- * sentinels — until `rekey` moves it whole (and marks its first event
948
- * there moved); a stream is never split across the two keys, and a new one
949
- * starts under its current key. A stream whose key text did not change
950
- * costs no request; one whose did, one consistent `GetItem` of the first
951
- * event's key.
952
- */
953
- const locateStream = (streamId) => composeStreamPk136(streamId) === undefined
954
- ? Effect.succeed(composeStreamPk(streamId))
955
- : Effect.gen(function* () {
956
- const { name: tableName } = yield* config.table.Tag;
957
- return yield* locateStreamIn(tableName, streamId);
958
- });
959
- /** {@link locateStream} in the table named `tableName`. */
960
- const locateStreamIn = (tableName, streamId) => {
961
- const current = composeStreamPk(streamId);
962
- const pk136 = composeStreamPk136(streamId);
963
- if (pk136 === undefined)
964
- return Effect.succeed(current);
965
- return Effect.gen(function* () {
966
- const client = yield* Capacity.client;
967
- const first = yield* client.getItem({
968
- TableName: tableName,
969
- Key: toAttributeMap({ pk: pk136, sk: composeEventSk(1) }),
970
- ConsistentRead: true,
971
- ProjectionExpression: "#pk, #moved",
972
- ExpressionAttributeNames: { "#pk": "pk", "#moved": MOVED_ATTRIBUTE },
973
- });
974
- return first.Item === undefined || first.Item[MOVED_ATTRIBUTE] !== undefined ? current : pk136;
975
- });
917
+ const composeStreamPkUnder = (under, streamId) => {
918
+ // A stream's own casing, if it has one: its escapes' hex digits are in it too.
919
+ const composites = KeyComposer.extractKeyComposites(under, { casing: config.casing }, compositeFields, streamId);
920
+ return DynamoSchema.composeKey(under, keyLabel, composites, keyOptions);
976
921
  };
977
- /**
978
- * The `prepare` step of a query of the stream's partition: read it where
979
- * the stream lives ({@link locateStream}). Only a stream whose key text
980
- * changed has one.
981
- */
982
- const locatedPrepare = (streamId) => composeStreamPk136(streamId) === undefined
983
- ? {}
984
- : {
985
- prepare: (tableName) => Effect.map(locateStreamIn(tableName, streamId), (pkValue) => ({ pkValue })),
986
- };
922
+ const composeStreamPk = (streamId) => composeStreamPkUnder(schema, streamId);
987
923
  const composeEventSk = (version) => DynamoSchema.composeEventVersionKey(schema, eventKeyLabel, version, keyOptions);
988
924
  /** Sort key of a command's idempotency sentinel. */
989
925
  const composeCommandSk = (commandId) => DynamoSchema.composeKey(schema, commandKeyLabel, [commandId], keyOptions);
@@ -1429,9 +1365,7 @@ export const makeStream = (config) => {
1429
1365
  * `sealed` writes the seal marker (#166): only a sealing append's inline
1430
1366
  * snapshot carries it.
1431
1367
  */
1432
- const buildSnapshotItem = (streamId,
1433
- /** The partition the stream lives under ({@link locateStream}). */
1434
- pk, state, asOfVersion, now, operation, eventPartitions, sealed = false) => Effect.gen(function* () {
1368
+ const buildSnapshotItem = (streamId, state, asOfVersion, now, operation, eventPartitions, sealed = false) => Effect.gen(function* () {
1435
1369
  const encoded = yield* encodeSnapshotState(state, operation);
1436
1370
  const stored = stateStoredAs === undefined
1437
1371
  ? encoded
@@ -1441,7 +1375,7 @@ export const makeStream = (config) => {
1441
1375
  operation: `${operation}.packed`,
1442
1376
  });
1443
1377
  const item = {
1444
- pk,
1378
+ pk: composeStreamPk(streamId),
1445
1379
  sk: snapshotSk,
1446
1380
  __edd_e__: snapshotEntityType,
1447
1381
  streamId: composeStreamIdString(streamId),
@@ -1481,9 +1415,7 @@ export const makeStream = (config) => {
1481
1415
  * the request `append` would send. `undefined` for an append with nothing
1482
1416
  * to write (the historical no-op).
1483
1417
  */
1484
- const buildAppend = (streamId, events, expectedVersion, options,
1485
- /** Where the stream lives ({@link locateStream}); its current key when not given. */
1486
- streamPk) => Effect.gen(function* () {
1418
+ const buildAppend = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1487
1419
  const additionalOps = options?.additionalItems ?? [];
1488
1420
  const idempotency = options?.idempotency;
1489
1421
  const snapshotState = options?.snapshot;
@@ -1633,7 +1565,7 @@ export const makeStream = (config) => {
1633
1565
  "Nothing was written.",
1634
1566
  });
1635
1567
  }
1636
- const pk = streamPk ?? composeStreamPk(streamId);
1568
+ const pk = composeStreamPk(streamId);
1637
1569
  // Clock-backed timestamp (deterministic under TestClock; wall-clock in prod).
1638
1570
  const nowDateTime = yield* DateTime.now;
1639
1571
  const now = DateTime.formatIso(nowDateTime);
@@ -1799,7 +1731,7 @@ export const makeStream = (config) => {
1799
1731
  // transaction-size and item-size diagnosis count its stored bytes.
1800
1732
  let snapshotPut;
1801
1733
  if (snapshotState !== undefined) {
1802
- const item = yield* buildSnapshotItem(streamId, pk, snapshotState, expectedVersion + events.length, now, "EventStore.append.snapshot", eventPartitions, sealing);
1734
+ const item = yield* buildSnapshotItem(streamId, snapshotState, expectedVersion + events.length, now, "EventStore.append.snapshot", eventPartitions, sealing);
1803
1735
  // As a head proof, a sealed snapshot fails the proof (#166), and
1804
1736
  // returns its item so the failure is reported as `StreamSealed`.
1805
1737
  snapshotPut = {
@@ -1844,51 +1776,21 @@ export const makeStream = (config) => {
1844
1776
  * costs nothing; `ALL_OLD` returns the item on failure (response bytes
1845
1777
  * only), so a sealed one is reported as `StreamSealed`.
1846
1778
  */
1847
- // A stream still under its 1.36 key (#171) must not have been moved
1848
- // since it was located: `rekey` marks its first event once the stream
1849
- // is copied (`MOVED_ATTRIBUTE`). Checked on the first event — by the
1850
- // contiguity check when it reads that event — for an append that
1851
- // writes anything into the stream's partition: events onto the
1852
- // stream, or a command sentinel alone (a command that decided no
1853
- // events, recorded for exactly-once), which would otherwise land where
1854
- // nothing reads it. An append writing events from version 0 needs no
1855
- // check: its first Put fails on its own, the first event being there.
1856
- const located136 = streamPk !== undefined &&
1857
- streamPk !== composeStreamPk(streamId) &&
1858
- (events.length > 0 ? expectedVersion > 0 : sentinelPut !== undefined);
1859
- const foldLocation = located136 && needsContiguityCheck && expectedVersion === 1;
1860
1779
  const contiguityCheck = needsContiguityCheck
1861
1780
  ? {
1862
1781
  ConditionCheck: {
1863
1782
  TableName: tableName,
1864
1783
  Key: toAttributeMap({ pk, sk: composeEventSk(expectedVersion) }),
1865
- ConditionExpression: foldLocation
1866
- ? "attribute_exists(#pk) AND attribute_not_exists(#sealed) AND attribute_not_exists(#moved)"
1867
- : "attribute_exists(#pk) AND attribute_not_exists(#sealed)",
1868
- ExpressionAttributeNames: {
1869
- "#pk": "pk",
1870
- "#sealed": SEALED_ATTRIBUTE,
1871
- ...(foldLocation && { "#moved": MOVED_ATTRIBUTE }),
1872
- },
1784
+ ConditionExpression: "attribute_exists(#pk) AND attribute_not_exists(#sealed)",
1785
+ ExpressionAttributeNames: { "#pk": "pk", "#sealed": SEALED_ATTRIBUTE },
1873
1786
  ReturnValuesOnConditionCheckFailure: "ALL_OLD",
1874
1787
  },
1875
1788
  }
1876
1789
  : undefined;
1877
- const locationCheck = located136 && !foldLocation
1878
- ? {
1879
- ConditionCheck: {
1880
- TableName: tableName,
1881
- Key: toAttributeMap({ pk, sk: composeEventSk(1) }),
1882
- ConditionExpression: "attribute_exists(#pk) AND attribute_not_exists(#moved)",
1883
- ExpressionAttributeNames: { "#pk": "pk", "#moved": MOVED_ATTRIBUTE },
1884
- },
1885
- }
1886
- : undefined;
1887
1790
  const parts = {
1888
1791
  tableName,
1889
1792
  streamIdStr,
1890
1793
  contiguityCheck,
1891
- locationCheck,
1892
1794
  eventItems,
1893
1795
  sentinelPut,
1894
1796
  snapshotPut,
@@ -1914,17 +1816,14 @@ export const makeStream = (config) => {
1914
1816
  "Nothing was written.",
1915
1817
  });
1916
1818
  }
1917
- // A stream 1.36 started is appended where it lives (#171).
1918
- const pk = yield* locateStream(streamId);
1919
- const parts = yield* buildAppend(streamId, events, expectedVersion, options, pk);
1819
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
1920
1820
  if (parts === undefined)
1921
1821
  return { version: expectedVersion, events: [] };
1922
- const { tableName, streamIdStr, contiguityCheck, locationCheck, eventItems, sentinelPut, snapshotPut, } = parts;
1822
+ const { tableName, streamIdStr, contiguityCheck, eventItems, sentinelPut, snapshotPut } = parts;
1923
1823
  const client = yield* Capacity.client;
1924
1824
  /**
1925
1825
  * Lay out the append's one transaction — see {@link AppendTransaction}:
1926
- * [0, C) version-contiguity ConditionCheck, then the
1927
- * 1.36 location check (#171) — C is 0 to 2
1826
+ * [0, C) version-contiguity ConditionCheck — C is 0 or 1
1928
1827
  * [C, C + E) event puts
1929
1828
  * [C + E, C + E + A) additional ITEMS (caller op order preserved)
1930
1829
  * then idempotency sentinel, then inline snapshot
@@ -1948,9 +1847,6 @@ export const makeStream = (config) => {
1948
1847
  if (contiguityCheck !== undefined) {
1949
1848
  pushStreamItem(contiguityCheck, entityType, "the version-contiguity check");
1950
1849
  }
1951
- if (locationCheck !== undefined) {
1952
- pushStreamItem(locationCheck, entityType, "the check that rekey has not moved the stream");
1953
- }
1954
1850
  const guardCount = items.length;
1955
1851
  for (const [i, item] of eventItems.entries()) {
1956
1852
  pushStreamItem(item, entityType, `the event at version ${expectedVersion + i + 1}`);
@@ -2044,7 +1940,7 @@ export const makeStream = (config) => {
2044
1940
  return yield* refuse(`An append op of stream "${config.streamName}" needs at least one event: with none ` +
2045
1941
  "it writes nothing. Nothing was written.");
2046
1942
  }
2047
- const parts = (yield* buildAppend(streamId, events, expectedVersion, options, yield* locateStream(streamId)));
1943
+ const parts = (yield* buildAppend(streamId, events, expectedVersion, options));
2048
1944
  const items = [];
2049
1945
  const sources = [];
2050
1946
  const label = `${source} (stream "${config.streamName}", ${parts.streamIdStr})`;
@@ -2052,10 +1948,6 @@ export const makeStream = (config) => {
2052
1948
  items.push(parts.contiguityCheck);
2053
1949
  sources.push([entityType, `${label}: the version-contiguity check`]);
2054
1950
  }
2055
- if (parts.locationCheck !== undefined) {
2056
- items.push(parts.locationCheck);
2057
- sources.push([entityType, `${label}: the check that rekey has not moved the stream`]);
2058
- }
2059
1951
  const guardCount = items.length;
2060
1952
  for (const [i, item] of parts.eventItems.entries()) {
2061
1953
  items.push(item);
@@ -2135,7 +2027,7 @@ export const makeStream = (config) => {
2135
2027
  if (snapshot === undefined)
2136
2028
  return yield* snapshotUnavailable("measureSnapshot");
2137
2029
  const now = DateTime.formatIso(yield* DateTime.now);
2138
- const item = yield* buildSnapshotItem(streamId, composeStreamPk(streamId), state, asOfVersion, now, "EventStore.measureSnapshot");
2030
+ const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.measureSnapshot");
2139
2031
  return itemBytes(item);
2140
2032
  });
2141
2033
  // ---------------------------------------------------------------------------
@@ -2239,69 +2131,29 @@ export const makeStream = (config) => {
2239
2131
  operation: "EventStore.writeSnapshot",
2240
2132
  entityType: snapshotEntityType,
2241
2133
  });
2242
- // A stream located under its 1.36 key (#171) that `rekey` moves after
2243
- // the locate is written at its current key on a second pass.
2244
- for (let pass = 0; pass < 2; pass++) {
2245
- const pk = yield* locateStream(streamId);
2246
- // Packed per `snapshot.storedAs` (#147): the diagnosis below measures
2247
- // the stored bytes.
2248
- const item = yield* buildSnapshotItem(streamId, pk, state, asOfVersion, now, "EventStore.writeSnapshot");
2249
- const put = {
2250
- TableName: tableName,
2251
- Item: item,
2252
- // Monotonic: never regress the cache. Losing this race is a no-op,
2253
- // not an error — the events it summarises are already durable.
2254
- ConditionExpression: "attribute_not_exists(#pk) OR #asOfVersion < :asOfVersion",
2255
- ExpressionAttributeNames: { "#pk": "pk", "#asOfVersion": "asOfVersion" },
2256
- ExpressionAttributeValues: toAttributeMap({ ":asOfVersion": asOfVersion }),
2257
- };
2258
- const target = (written) => () => transactItemTarget(written, tableName, ["pk", "sk"], snapshotEntityType, "the snapshot");
2259
- if (pk === composeStreamPk(streamId)) {
2260
- return yield* client.putItem(put).pipe(Effect.catchIf((error) => isAwsConditionalCheckFailed(error.cause), () => Effect.void),
2261
- // An oversized snapshot is DynamoDB's to reject (#144); named here.
2262
- diagnoseFailure({
2263
- sent: () => ({ _tag: "Item", item: { Put: put }, target: target({ Put: put }) }),
2264
- keys,
2265
- rewrite,
2266
- }));
2267
- }
2268
- // Under its 1.36 key, the snapshot is written there only while the
2269
- // stream is — checked on its first event, as an append checks it.
2270
- const items = [
2271
- { Put: put },
2272
- {
2273
- ConditionCheck: {
2274
- TableName: tableName,
2275
- Key: toAttributeMap({ pk, sk: composeEventSk(1) }),
2276
- ConditionExpression: "attribute_exists(#pk) AND attribute_not_exists(#moved)",
2277
- ExpressionAttributeNames: { "#pk": "pk", "#moved": MOVED_ATTRIBUTE },
2278
- },
2279
- },
2280
- ];
2281
- const moved = yield* client.transactWriteItems({ TransactItems: [...items] }).pipe(Effect.as(false), Effect.catch((error) => {
2282
- if (!isAwsTransactionCancelled(error.cause))
2283
- return Effect.fail(error);
2284
- const reasons = error.cause.CancellationReasons ?? [];
2285
- if (reasons[1]?.Code === "ConditionalCheckFailed")
2286
- return Effect.succeed(true);
2287
- return reasons[0]?.Code === "ConditionalCheckFailed"
2288
- ? Effect.succeed(false)
2289
- : Effect.fail(error);
2290
- }), diagnoseFailure({
2291
- sent: () => ({
2292
- _tag: "Transaction",
2293
- items,
2294
- targets: () => [
2295
- target(items[0])(),
2296
- transactItemTarget(items[1], tableName, ["pk", "sk"], entityType, "the check that rekey has not moved the stream"),
2297
- ],
2298
- }),
2299
- keys,
2300
- rewrite,
2301
- }));
2302
- if (!moved)
2303
- return;
2304
- }
2134
+ // Packed per `snapshot.storedAs` (#147): the diagnosis below measures
2135
+ // the stored bytes.
2136
+ const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.writeSnapshot");
2137
+ const put = {
2138
+ TableName: tableName,
2139
+ Item: item,
2140
+ // Monotonic: never regress the cache. Losing this race is a no-op,
2141
+ // not an error — the events it summarises are already durable.
2142
+ ConditionExpression: "attribute_not_exists(#pk) OR #asOfVersion < :asOfVersion",
2143
+ ExpressionAttributeNames: { "#pk": "pk", "#asOfVersion": "asOfVersion" },
2144
+ ExpressionAttributeValues: toAttributeMap({ ":asOfVersion": asOfVersion }),
2145
+ };
2146
+ yield* client.putItem(put).pipe(Effect.catchIf((error) => isAwsConditionalCheckFailed(error.cause), () => Effect.void),
2147
+ // An oversized snapshot is DynamoDB's to reject (#144); named here.
2148
+ diagnoseFailure({
2149
+ sent: () => ({
2150
+ _tag: "Item",
2151
+ item: { Put: put },
2152
+ target: () => transactItemTarget({ Put: put }, tableName, ["pk", "sk"], snapshotEntityType, "the snapshot"),
2153
+ }),
2154
+ keys,
2155
+ rewrite,
2156
+ }));
2305
2157
  });
2306
2158
  /**
2307
2159
  * Decode a stored snapshot item. A snapshot that fails to decode through the
@@ -2324,7 +2176,7 @@ export const makeStream = (config) => {
2324
2176
  const result = yield* client.getItem({
2325
2177
  TableName: tableName,
2326
2178
  Key: toAttributeMap({
2327
- pk: yield* locateStream(streamId),
2179
+ pk: composeStreamPk(streamId),
2328
2180
  sk: snapshotSk,
2329
2181
  }),
2330
2182
  ...(consistentRead ? { ConsistentRead: true } : {}),
@@ -2338,7 +2190,7 @@ export const makeStream = (config) => {
2338
2190
  const result = yield* client.getItem({
2339
2191
  TableName: tableName,
2340
2192
  Key: toAttributeMap({
2341
- pk: yield* locateStream(streamId),
2193
+ pk: composeStreamPk(streamId),
2342
2194
  sk: composeEventSk(version),
2343
2195
  }),
2344
2196
  ...(consistentRead ? { ConsistentRead: true } : {}),
@@ -2422,7 +2274,7 @@ export const makeStream = (config) => {
2422
2274
  FilterExpression: "#e IN (:eventType, :snapshotType)",
2423
2275
  ExpressionAttributeNames: { "#pk": "pk", "#sk": "sk", "#e": "__edd_e__" },
2424
2276
  ExpressionAttributeValues: toAttributeMap({
2425
- ":pk": yield* locateStream(streamId),
2277
+ ":pk": composeStreamPk(streamId),
2426
2278
  ":first": eventSkPrefix,
2427
2279
  ":snapshot": snapshotSk,
2428
2280
  ":eventType": entityType,
@@ -2509,7 +2361,7 @@ export const makeStream = (config) => {
2509
2361
  const { name: tableName } = yield* config.table.Tag;
2510
2362
  const result = yield* client.getItem({
2511
2363
  TableName: tableName,
2512
- Key: toAttributeMap({ pk: yield* locateStream(streamId), sk: composeCommandSk(commandId) }),
2364
+ Key: toAttributeMap({ pk: composeStreamPk(streamId), sk: composeCommandSk(commandId) }),
2513
2365
  ConsistentRead: true,
2514
2366
  ProjectionExpression: "#pk",
2515
2367
  ExpressionAttributeNames: { "#pk": "pk" },
@@ -2538,8 +2390,6 @@ export const makeStream = (config) => {
2538
2390
  // Consumed capacity reports these queries under the stream name, as
2539
2391
  // every `EventStream.*` operation does (#174).
2540
2392
  operationTarget: config.streamName,
2541
- // A stream 1.36 started is read where it lives (#171).
2542
- ...locatedPrepare(streamId),
2543
2393
  // Bound to the event SK range so non-event items in the stream partition
2544
2394
  // (the snapshot) are excluded at the key-condition level. A caller-supplied
2545
2395
  // `Query.where` replaces this — the `__edd_e__` filter still applies.
@@ -2622,9 +2472,6 @@ export const makeStream = (config) => {
2622
2472
  },
2623
2473
  keyFields: [idx.pk, idx.sk, "pk", "sk"],
2624
2474
  operationTarget: config.streamName,
2625
- // A stream-scoped index of a stream 1.36 started is read in the 1.36
2626
- // partition, as its events are (#171).
2627
- ...(derived ? {} : locatedPrepare(streamId)),
2628
2475
  // A "keys" index holds no events: an LSI has DynamoDB fetch them
2629
2476
  // (`Select: ALL_ATTRIBUTES`), a GSI fetches each page's with
2630
2477
  // `BatchGetItem` on the table key.
@@ -2636,9 +2483,7 @@ export const makeStream = (config) => {
2636
2483
  }
2637
2484
  : {}),
2638
2485
  });
2639
- return derived
2640
- ? Query.filterExpr(query, streamPkFilter(streamPk, composeStreamPk136(streamId)))
2641
- : query;
2486
+ return derived ? Query.filterExpr(query, streamPkFilter(streamPk)) : query;
2642
2487
  };
2643
2488
  /**
2644
2489
  * @internal The decoder of events read through `idx`.
@@ -2717,18 +2562,18 @@ export const makeStream = (config) => {
2717
2562
  // is safe because all operations correctly require DynamoClient | TableConfig at
2718
2563
  // runtime — the user must provide these layers.
2719
2564
  // ---------------------------------------------------------------------------
2720
- // rekey (#171): the stream's part in `db.tables.<Table>.rekey()`
2565
+ // rekey: the stream's part in `db.tables.<Table>.rekey()`
2721
2566
  //
2722
- // A stream 1.36 started under a partition key whose text changed (a number
2723
- // stream id composite) moves whole, while writers keep appending: every row
2724
- // is COPIED to the current key — where nothing is, or a snapshot over an
2725
- // older one; one transaction then FLIPS it — marks its first event moved,
2726
- // conditioned on the head and the snapshot being as copied — so
2727
- // `locateStream` reads the current key from then on, and an append or
2728
- // snapshot write that located the 1.36 key before fails its location
2729
- // check; the 1.36 rows are DELETED last, each while it is as read, the
2730
- // events from the head down and the first event last. A flip or delete
2731
- // that loses to a write reads again.
2567
+ // A stream under a partition key other text composed for its id moves whole:
2568
+ // every row is COPIED to the current key, where nothing is, or a snapshot over
2569
+ // an older one; one transaction then FLIPS it, marking its first event moved,
2570
+ // conditioned on the head and the snapshot being as copied, so a run stopped
2571
+ // after that resumes by finishing the delete; the old rows are DELETED last,
2572
+ // each while it is as read, the events from the head down and the first event
2573
+ // last. A flip or delete that loses to a write reads again. Another stream's
2574
+ // rows at the current key, themselves under other text, move first. Rows of
2575
+ // another stream id that landed in the same partition are its own: nothing is
2576
+ // merged.
2732
2577
  // ---------------------------------------------------------------------------
2733
2578
  /** Attributes holding the stream's partition key: a GSI index's partition. */
2734
2579
  const partitionAttributes = streamIndexes.flatMap((idx) => (idx.type === "gsi" ? [idx.pk] : []));
@@ -2764,7 +2609,7 @@ export const makeStream = (config) => {
2764
2609
  const part = parts[i];
2765
2610
  const values = [part];
2766
2611
  const n = Number(part);
2767
- if (part.trim() !== "" && Number.isFinite(n) && String(n) === part)
2612
+ if (part.trim() !== "" && String(n) === part)
2768
2613
  values.push(n);
2769
2614
  if (/^-?\d+$/.test(part) && String(BigInt(part)) === part)
2770
2615
  values.push(BigInt(part));
@@ -2774,30 +2619,45 @@ export const makeStream = (config) => {
2774
2619
  });
2775
2620
  };
2776
2621
  /**
2777
- * Where a stream row belongs now and where 1.36 put it, from its
2778
- * `streamId`: the readings of the id whose keys hold the row's partition
2779
- * key. `"ambiguous"` when readings disagree on where it belongs.
2622
+ * Where a stream row belongs now, from its `streamId`: the readings of the id
2623
+ * that compose the row's partition key under some key text. `"ambiguous"` when
2624
+ * readings disagree on where it belongs; `undefined` when none composes it.
2780
2625
  */
2781
2626
  const streamKeys = (row) => {
2782
2627
  const pk = row.pk?.S;
2783
2628
  const text = row.streamId?.S;
2784
2629
  if (pk === undefined || text === undefined)
2785
2630
  return undefined;
2631
+ const undersNow = [
2632
+ KeyText136.schema136(schema),
2633
+ KeyText136.schema137(schema),
2634
+ KeyText136.schemaEscaped(schema),
2635
+ ];
2636
+ const holds = (under, candidate) => {
2637
+ try {
2638
+ return composeStreamPkUnder(under, candidate) === pk;
2639
+ }
2640
+ catch {
2641
+ // No key text for it under this form.
2642
+ return false;
2643
+ }
2644
+ };
2786
2645
  let found;
2787
2646
  for (const candidate of streamIdCandidates(text)) {
2647
+ if (!undersNow.some((under) => holds(under, candidate)))
2648
+ continue;
2649
+ let current;
2788
2650
  try {
2789
- const current = composeStreamPk(candidate);
2790
- const old = composeStreamPk136(candidate, true) ?? current;
2791
- if (pk !== current && pk !== old)
2792
- continue;
2793
- if (found === undefined)
2794
- found = { current, old };
2795
- else if (found.current !== current || found.old !== old)
2796
- return "ambiguous";
2651
+ current = composeStreamPk(candidate);
2797
2652
  }
2798
2653
  catch {
2799
- // Not this reading of the id.
2654
+ // `NaN` under `escapeKeys: true`: no key now.
2655
+ continue;
2800
2656
  }
2657
+ if (found === undefined)
2658
+ found = { current };
2659
+ else if (found.current !== current)
2660
+ return "ambiguous";
2801
2661
  }
2802
2662
  return found;
2803
2663
  };
@@ -2813,12 +2673,12 @@ export const makeStream = (config) => {
2813
2673
  /** How many attempts a stream move makes in all: a flip that loses to a write copies again. */
2814
2674
  const STREAM_MOVE_ATTEMPTS = 8;
2815
2675
  /**
2816
- * Move the stream under `from` to `to` — or, when its first event is no
2817
- * longer under `from` (moved by an earlier run), the rows left there.
2818
- * Command sentinels whose TTL has passed are gone, whether or not DynamoDB
2819
- * has deleted them yet.
2676
+ * Move the stream `streamIdText` under `from` to `to` — or, when its first
2677
+ * event is no longer under `from` (moved by an earlier run), the rows left
2678
+ * there. Command sentinels whose TTL has passed are gone, whether or not
2679
+ * DynamoDB has deleted them yet.
2820
2680
  */
2821
- const moveStream = (ctx, from, to, streamIdText, ttlAttribute) => Effect.gen(function* () {
2681
+ const moveStream = (ctx, from, to, streamIdText, ttlAttribute, depth) => Effect.gen(function* () {
2822
2682
  const client = yield* Capacity.client;
2823
2683
  const firstSk = composeEventSk(1);
2824
2684
  const nowSeconds = DateTime.toEpochSeconds(yield* DateTime.now);
@@ -2852,6 +2712,13 @@ export const makeStream = (config) => {
2852
2712
  }
2853
2713
  return copy;
2854
2714
  };
2715
+ /** This stream's rows left under the old key: another id's there are its own to move. */
2716
+ const readOwn = Effect.map(readAll(from), (rows) => rows.filter((row) => row.streamId?.S === streamIdText));
2717
+ /** A row at `to` that belongs elsewhere: another stream's, under other key text. */
2718
+ const elsewhere = (row) => {
2719
+ const keys = streamKeys(row);
2720
+ return typeof keys === "object" && keys.current !== to;
2721
+ };
2855
2722
  const skOf = (row) => row.sk?.S ?? "";
2856
2723
  const versionOf = (row) => row.__edd_e__?.S === entityType ? Number(row.version?.N ?? 0) : 0;
2857
2724
  const asOfOf = (row) => Number(row.asOfVersion?.N ?? 0);
@@ -2901,17 +2768,16 @@ export const makeStream = (config) => {
2901
2768
  /**
2902
2769
  * Bring every row still under `from` over, once the stream lives at
2903
2770
  * `to`: a row `to` lacks is copied (a command sentinel written beside
2904
- * the flip, a row an append that located the stream before the flip
2905
- * wrote), a snapshot newer than `to`'s copied over it, and then each is
2906
- * deleted while it is as read — the events from the head down, the
2907
- * other rows, and the first event last: until it goes, the stream is
2908
- * located here, and an append that located it here fails its check. A
2909
- * row `to` holds differently (an event or sentinel written under both
2910
- * keys) is a conflict, and the rows are left as they are. `undefined`
2911
- * when a write landed in between: read again.
2771
+ * the flip), a snapshot newer than `to`'s copied over it, and then each
2772
+ * is deleted while it is as read — the events from the head down, the
2773
+ * other rows, and the first event last: until it goes, the next run
2774
+ * finds the stream here and finishes the move. A row `to` holds
2775
+ * differently (an event or sentinel written under both keys) is a
2776
+ * conflict, and the rows are left as they are. `undefined` when a write
2777
+ * landed in between: read again.
2912
2778
  */
2913
2779
  const drain = Effect.gen(function* () {
2914
- const left = yield* readAll(from);
2780
+ const left = yield* readOwn;
2915
2781
  const there = new Map((yield* readAll(to)).map((row) => [skOf(row), row]));
2916
2782
  const differing = [];
2917
2783
  for (const row of left) {
@@ -2924,7 +2790,7 @@ export const makeStream = (config) => {
2924
2790
  }
2925
2791
  if (differing.length > 0) {
2926
2792
  return Rekey.mergeTallies(...differing.map((row) => conflict("bothKeys", "a row of it is under both partition keys, and the two differ; the rows " +
2927
- "under its 1.36 key are left as they are.", skOf(row))));
2793
+ "under its old key are left as they are.", skOf(row))));
2928
2794
  }
2929
2795
  for (const row of left) {
2930
2796
  const held = there.get(skOf(row));
@@ -2947,32 +2813,55 @@ export const makeStream = (config) => {
2947
2813
  }
2948
2814
  return { moved: { stream: left.length } };
2949
2815
  });
2816
+ let tally = {};
2950
2817
  for (let attempt = 0; attempt < STREAM_MOVE_ATTEMPTS; attempt++) {
2951
- const rows = yield* readAll(from);
2818
+ const rows = yield* readOwn;
2952
2819
  // Moved since the scan read it.
2953
2820
  if (rows.length === 0)
2954
- return {};
2821
+ return tally;
2955
2822
  const first = rows.find((row) => skOf(row) === firstSk);
2956
2823
  // Flipped by an earlier attempt or run — or never started here: the
2957
2824
  // stream lives at `to`, and the rows left move to it.
2958
2825
  const flipped = first === undefined || first[MOVED_ATTRIBUTE] !== undefined;
2959
2826
  if (!flipped) {
2960
- const there = new Map((yield* readAll(to)).map((row) => [skOf(row), row]));
2827
+ const atTarget = yield* readAll(to);
2828
+ // Another stream under other key text moves out first.
2829
+ const stale = atTarget.find(elsewhere);
2830
+ if (stale !== undefined) {
2831
+ if (depth >= Rekey.DISPLACE_DEPTH) {
2832
+ return Rekey.mergeTallies(tally, conflict("contended", "too many streams under other key text hold each other's current keys."));
2833
+ }
2834
+ const displaced = yield* Rekey.displace(ctx, (under) => rekeyStreamRow(stale, under, depth + 1));
2835
+ tally = Rekey.mergeTallies(tally, displaced);
2836
+ // A dry run moved nothing: what would stop that stream is what would leave it there.
2837
+ const stillThere = ctx.dryRun
2838
+ ? (displaced.conflicts ?? []).length > 0
2839
+ : (yield* readAll(to)).some(elsewhere);
2840
+ if (stillThere) {
2841
+ return Rekey.mergeTallies(tally, conflict("taken", "rows of another stream are under its current partition key."));
2842
+ }
2843
+ if (!ctx.dryRun)
2844
+ continue;
2845
+ }
2846
+ const there = new Map(atTarget.filter((row) => !elsewhere(row)).map((row) => [skOf(row), row]));
2961
2847
  const here = new Map(rows.map((row) => [skOf(row), row]));
2962
- // Rows under the current key are copies of an earlier attempt —
2963
- // anything else is another stream's: a row this one does not have,
2964
- // or one it has differently (a snapshot only grows newer).
2848
+ // Rows under the current key are copies of an earlier attempt, or a stream written
2849
+ // there meanwhile: anything else is a conflict, a row this one does not have, or
2850
+ // one it has differently (a snapshot only grows newer).
2965
2851
  for (const [sk, row] of there) {
2966
2852
  const own = here.get(sk);
2967
2853
  if (own === undefined) {
2968
- return conflict("taken", "rows of another stream are under its current partition key.");
2854
+ const same = row.streamId?.S === streamIdText;
2855
+ return Rekey.mergeTallies(tally, conflict(same ? "bothKeys" : "taken", same
2856
+ ? "the stream has rows under both partition keys."
2857
+ : "rows of another stream are under its current partition key."));
2969
2858
  }
2970
2859
  if (sk !== snapshotSk && !sameRow(copyOf(own), row)) {
2971
- return conflict("bothKeys", "rows of another stream are under its current partition key.", sk);
2860
+ return Rekey.mergeTallies(tally, conflict("bothKeys", "the stream has rows under both partition keys, and the two differ.", sk));
2972
2861
  }
2973
2862
  }
2974
2863
  if (ctx.dryRun)
2975
- return { moved: { stream: rows.length } };
2864
+ return Rekey.mergeTallies(tally, { moved: { stream: rows.length } });
2976
2865
  // COPY
2977
2866
  let copiedAll = true;
2978
2867
  for (const row of rows) {
@@ -3060,50 +2949,51 @@ export const makeStream = (config) => {
3060
2949
  continue;
3061
2950
  }
3062
2951
  else if (ctx.dryRun) {
3063
- return { moved: { stream: rows.length } };
2952
+ return Rekey.mergeTallies(tally, { moved: { stream: rows.length } });
3064
2953
  }
3065
2954
  // DELETE
3066
2955
  const drained = yield* drain;
3067
2956
  if (drained !== undefined)
3068
- return drained;
2957
+ return Rekey.mergeTallies(tally, drained);
3069
2958
  }
3070
- return conflict("contended", "writes changed it on every attempt to move it.");
2959
+ return Rekey.mergeTallies(tally, conflict("contended", "writes changed it on every attempt to move it."));
2960
+ });
2961
+ /** One scanned row of the stream — or one at a key another stream's move needs. */
2962
+ const rekeyStreamRow = (row, ctx, depth) => Effect.gen(function* () {
2963
+ const tableConfig = yield* config.table.Tag;
2964
+ if (tableConfig.name !== ctx.tableName)
2965
+ return undefined;
2966
+ const keys = streamKeys(row);
2967
+ if (keys === undefined)
2968
+ return { skipped: { unrecognizedKey: 1 } };
2969
+ if (keys === "ambiguous") {
2970
+ return {
2971
+ conflicts: [
2972
+ {
2973
+ member: config.streamName,
2974
+ kind: "stream",
2975
+ reason: "failed",
2976
+ key: { pk: row.pk?.S, sk: row.sk?.S },
2977
+ target: undefined,
2978
+ message: `Stream ${JSON.stringify(row.streamId?.S ?? "")}: its stored stream id reads ` +
2979
+ "as more than one id of the stream's composites, and they disagree on where " +
2980
+ "it belongs.",
2981
+ },
2982
+ ],
2983
+ };
2984
+ }
2985
+ const from = row.pk.S;
2986
+ if (from === keys.current)
2987
+ return { unchanged: 1 };
2988
+ // A stream moves whole, once per run, from whichever of its rows the scan reaches
2989
+ // first, and rows left there after it moved move after it.
2990
+ const streamIdText = row.streamId?.S ?? "";
2991
+ return yield* ctx.once(`${config.streamName}\u0000${from}\u0000${streamIdText}`, moveStream(ctx, from, keys.current, streamIdText, resolveTtlAttributeName(tableConfig), depth));
3071
2992
  });
3072
2993
  const rekeyHandler = {
3073
2994
  name: config.streamName,
3074
2995
  types: [entityType, snapshotEntityType, commandEntityType],
3075
- row: (row, ctx) => Effect.gen(function* () {
3076
- const tableConfig = yield* config.table.Tag;
3077
- if (tableConfig.name !== ctx.tableName)
3078
- return undefined;
3079
- const keys = streamKeys(row);
3080
- if (keys === undefined)
3081
- return { skipped: { unrecognizedKey: 1 } };
3082
- if (keys === "ambiguous") {
3083
- return {
3084
- conflicts: [
3085
- {
3086
- member: config.streamName,
3087
- kind: "stream",
3088
- reason: "failed",
3089
- key: { pk: row.pk?.S, sk: row.sk?.S },
3090
- target: undefined,
3091
- message: `Stream ${JSON.stringify(row.streamId?.S ?? "")}: its stored stream id reads ` +
3092
- "as more than one id of the stream's composites, and they disagree on where " +
3093
- "it belongs.",
3094
- },
3095
- ],
3096
- };
3097
- }
3098
- if (row.pk?.S === keys.current)
3099
- return { unchanged: 1 };
3100
- // A stream under its 1.36 key moves whole, once per run, from
3101
- // whichever of its rows the scan reaches first — and rows left there
3102
- // after it moved move after it.
3103
- if (!ctx.claim(`${config.streamName}\u0000${keys.old}`))
3104
- return {};
3105
- return yield* moveStream(ctx, keys.old, keys.current, row.streamId?.S ?? "", resolveTtlAttributeName(tableConfig));
3106
- }),
2996
+ row: (row, ctx) => rekeyStreamRow(row, ctx, 0),
3107
2997
  };
3108
2998
  return {
3109
2999
  [EventStreamTypeId]: EventStreamTypeId,