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
@@ -49,25 +49,31 @@ import { isPackedConfig } from "@effect-dynamodb/schema/DynamoModel.js";
49
49
  import * as DynamoSchema from "@effect-dynamodb/schema/DynamoSchema.js";
50
50
  import { normalizeTtlSeconds } from "@effect-dynamodb/schema/Entity.js";
51
51
  import { AdditionalItemConditionFailed, AppendTooLarge, DuplicateCommand, isAwsConditionalCheckFailed, isAwsTransactionCancelled, isAwsValidationError, StreamSealed, TransactionCancelled, ValidationError, VersionConflict, } from "@effect-dynamodb/schema/Errors.js";
52
+ import { readingStreamValues, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
53
+ import { decodingAsBefore } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
52
54
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
55
+ import { classOf, setOwn } from "@effect-dynamodb/schema/internal/OwnNames.js";
53
56
  import { isDispatchEligible, packedShape, packValue, unpackStoredSync, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
57
+ import { refuseUnreadable } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
54
58
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
55
- import { Context, DateTime, Effect, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
59
+ import { Context, DateTime, Effect, Exit, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
56
60
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
57
61
  import * as Capacity from "./internal/Capacity.js";
58
62
  import { ProjectionRoutes } from "./internal/EventProjection.js";
59
63
  import { eq } from "./internal/Expr.js";
60
- import { asReadGuard } from "./internal/ExpressionLimits.js";
61
- import { itemBytes, transactItemBytes } from "./internal/ItemSize.js";
64
+ import { asReadGuard, wholeRowGuard } from "./internal/ExpressionLimits.js";
65
+ import { itemBytes, jsonBytes, transactItemBytes, transactWriteBodyBytes, } from "./internal/ItemSize.js";
62
66
  import { isMultiProjection, } from "./internal/MultiProjection.js";
63
67
  import { codecRequirements, currentRegistry, decodeImage, imageEntityType, runtimeCodecCheck, unregisteredCodecError, withRegistry, } from "./internal/Packed.js";
64
68
  import { createPathBuilder } from "./internal/PathBuilder.js";
65
69
  import * as Rekey from "./internal/Rekey.js";
70
+ import { notReadBack, readBackOf } from "./internal/RoundTrip.js";
71
+ import { marshalOrFail } from "./internal/TransactableOps.js";
66
72
  import { buildTransactWriteItems, GUARDED_TRANSACTION_ATTEMPTS, isStreamAppendOp, judgeCancellation, opConditionFailed, StreamAppendTypeId, transactItemTarget, } from "./internal/TransactWriteOps.js";
67
73
  import { diagnosedValidationError, diagnoseFailure, mergeKeyAttributes, withCause, } from "./internal/WriteDiagnosis.js";
68
74
  import { fromAttributeMap, toAttributeMap } from "./Marshaller.js";
69
75
  import * as Query from "./Query.js";
70
- import { DEFAULT_TTL_ATTRIBUTE_NAME, resolveTtlAttributeName, } from "./Table.js";
76
+ import { addTableKeyAttributes, DEFAULT_TTL_ATTRIBUTE_NAME, resolveTtlAttributeName, } from "./Table.js";
71
77
  // ---------------------------------------------------------------------------
72
78
  // Envelope schema — validates the persisted event's system fields on read
73
79
  // ---------------------------------------------------------------------------
@@ -84,6 +90,26 @@ const streamCodecRequirements = (streamName, storedAs) => codecRequirements(`str
84
90
  ]);
85
91
  /** The attributes a stream image reads by stored form: event `data` only. */
86
92
  const DATA_ATTRIBUTES = ["data"];
93
+ /**
94
+ * The type an appended event is stored under, read as 1.40.0 read it: its `_tag`, else its
95
+ * constructor's `identifier`, else the constructor's `name`, `event.constructor` read for each.
96
+ * Only where `event.constructor` reads no function, where 1.40.0 stored no type, is the event
97
+ * asked for its class: a field named `constructor` (given by `Object.create`, a class with
98
+ * getters, or as a `Schema.Class` instance's own field, #239) stands where 1.40.0 looked for it,
99
+ * so the class is its nearest prototype's ({@link classOf}).
100
+ */
101
+ const eventTypeOf = (event) => {
102
+ const tag = event._tag;
103
+ if (tag !== undefined && tag !== null)
104
+ return tag;
105
+ const made = event.constructor;
106
+ if (typeof made === "function") {
107
+ return (made.identifier ??
108
+ event.constructor.name);
109
+ }
110
+ const eventClass = classOf(event);
111
+ return eventClass?.identifier ?? eventClass?.name;
112
+ };
87
113
  const EventEnvelope = Schema.Struct({
88
114
  streamId: Schema.String,
89
115
  version: Schema.Number,
@@ -529,7 +555,7 @@ const parseStreamIdWith = (streamName, fields, streamId) => {
529
555
  }
530
556
  const id = {};
531
557
  fields.forEach((field, i) => {
532
- id[field] = parts[i];
558
+ setOwn(id, field, parts[i]);
533
559
  });
534
560
  return Effect.succeed(id);
535
561
  };
@@ -832,6 +858,28 @@ export const makeStream = (config) => {
832
858
  // Snapshot config validation (EDD-9027, EDD-9062) — fail fast at definition time.
833
859
  // -------------------------------------------------------------------------
834
860
  const snapshot = config.snapshot;
861
+ // What a stream stores has to read back (EDD-9125): an append that succeeds and a read that
862
+ // can't decode leaves events nobody can read.
863
+ const streamLabel = `EventStream "${config.streamName}"`;
864
+ config.events.forEach((event, position) => {
865
+ const identifier = event.identifier;
866
+ const named = typeof identifier === "string" ? `event "${identifier}"` : `events[${position}]`;
867
+ refuseUnreadable(`${streamLabel}, ${named}`, "schema", event, { whole: "the event" });
868
+ });
869
+ if (config.events.length > 1) {
870
+ // Read through one union, so what one event stores can be what another reads.
871
+ refuseUnreadable(streamLabel, "schema", Schema.Union(config.events), { whole: "the union of its events" });
872
+ }
873
+ if (config.metadata !== undefined) {
874
+ refuseUnreadable(`${streamLabel}, metadata`, "schema", config.metadata, {
875
+ whole: "the metadata",
876
+ });
877
+ }
878
+ if (snapshot !== undefined) {
879
+ refuseUnreadable(`${streamLabel}, snapshot state`, "schema", snapshot.schema, {
880
+ whole: "the state",
881
+ });
882
+ }
835
883
  if (snapshot !== undefined && snapshot.every !== undefined) {
836
884
  if (!Number.isInteger(snapshot.every) || snapshot.every <= 0) {
837
885
  throw new Error(`[EDD-9027] EventStream "${config.streamName}": snapshot.every must be a positive integer; ` +
@@ -905,6 +953,9 @@ export const makeStream = (config) => {
905
953
  const snapshotIndexes = streamIndexes.filter((idx) => idx.snapshotEntry !== undefined);
906
954
  /** Every attribute the indexes write on an event item. */
907
955
  const indexAttributes = streamIndexes.flatMap((idx) => idx.type === "gsi" ? [idx.pk, idx.sk] : [idx.sk]);
956
+ // They are key attributes of the stream's table: the library adds none of its own under their
957
+ // names (`Table.tableKeyAttributes`, #237).
958
+ addTableKeyAttributes(config.table.Tag, indexAttributes);
908
959
  // Build union schema from event schemas for decoding
909
960
  const eventUnion = config.events.length === 1
910
961
  ? config.events[0]
@@ -965,19 +1016,62 @@ export const makeStream = (config) => {
965
1016
  }
966
1017
  return eventUnion;
967
1018
  };
1019
+ const writableCodecs = new Map();
1020
+ /** A codec refusing a tuple position its stored list can't keep. Built once per schema. */
1021
+ const writableCodec = (declared) => {
1022
+ const known = writableCodecs.get(declared);
1023
+ if (known !== undefined)
1024
+ return known;
1025
+ const writable = writingTuplePositions(declared);
1026
+ writableCodecs.set(declared, writable);
1027
+ return writable;
1028
+ };
1029
+ /**
1030
+ * What checks a schema's stored values read back (`EDD-9126`), for one holding a custom
1031
+ * declaration. An event is read through the union of the events; anything else through itself.
1032
+ */
1033
+ const readBacks = new Map();
1034
+ const readBackFor = (declared) => {
1035
+ if (readBacks.has(declared))
1036
+ return readBacks.get(declared);
1037
+ const isEvent = declared === eventUnion || config.events.includes(declared);
1038
+ const readBack = readBackOf(declared, () => readingStreamValues(isEvent ? eventUnion : declared));
1039
+ readBacks.set(declared, readBack);
1040
+ return readBack;
1041
+ };
968
1042
  /**
969
1043
  * Validate input and produce wire-form output: `Schema.encode` first, with a
970
- * `decode → encode` fallback for inputs already in encoded shape. Mirrors
971
- * the Entity write path (`encodeOrDecodeEncode` in `Entity.ts`).
1044
+ * `decode → encode` fallback for inputs already in encoded shape, then refused if it wouldn't read
1045
+ * back. Mirrors the Entity write path (`encodeForWrite` in `Entity.ts`). Everything a stream stores
1046
+ * from its own schemas goes through this.
972
1047
  */
973
- const encodeToWire = (codec, input, operation, errorEntityType = entityType) => Schema.encodeUnknownEffect(codec)(input).pipe(Effect.catch((primaryCause) => Schema.decodeUnknownEffect(codec)(input).pipe(Effect.flatMap((decoded) => Schema.encodeUnknownEffect(codec)(decoded)),
974
- // Surface the original encode error — its message is keyed on the
975
- // caller's input shape, which is what the user expects to see.
976
- Effect.catch(() => Effect.fail(new ValidationError({ entityType: errorEntityType, operation, cause: primaryCause }))))));
1048
+ const encodeToWire = (declared, input, operation, errorEntityType = entityType, packed = false) => {
1049
+ const codec = writableCodec(declared);
1050
+ const wire = Schema.encodeUnknownEffect(codec)(input).pipe(Effect.catch((primaryCause) => Schema.decodeUnknownEffect(codec)(input).pipe(Effect.flatMap((decoded) => Schema.encodeUnknownEffect(codec)(decoded)),
1051
+ // Surface the original encode error — its message is keyed on the
1052
+ // caller's input shape, which is what the user expects to see.
1053
+ Effect.catch(() => Effect.fail(new ValidationError({ entityType: errorEntityType, operation, cause: primaryCause }))))));
1054
+ // What's packed doesn't go through the marshaller's map, and packing refuses an instance itself.
1055
+ const readBack = packed ? undefined : readBackFor(declared);
1056
+ return readBack === undefined
1057
+ ? wire
1058
+ : wire.pipe(Effect.tap((encoded) => readBack(encoded).pipe(Effect.mapError((issue) => new ValidationError({
1059
+ entityType: errorEntityType,
1060
+ operation,
1061
+ cause: notReadBack(undefined, issue),
1062
+ })))));
1063
+ };
977
1064
  // ---------------------------------------------------------------------------
978
1065
  // Decode a raw DynamoDB item → StreamEvent<TEvent>
979
1066
  // ---------------------------------------------------------------------------
980
1067
  const decodeEnvelope = Schema.decodeUnknownEffect(EventEnvelope);
1068
+ // `undefined` and an empty set are stored as absent attributes, in an event as
1069
+ // anywhere else, and read back as those values. A decode that dies on one fails as
1070
+ // 1.39.0's did, which decoded through the declared schema (`decodingAsBefore`).
1071
+ const decodingStream = (declared) => decodingAsBefore(readingStreamValues(declared), declared);
1072
+ const decodeEventData = decodingStream(eventUnion);
1073
+ const decodeMetadata = decodingStream(metadataSchema ?? Schema.Unknown);
1074
+ const decodeSnapshotState = decodingStream(snapshot?.schema ?? Schema.Unknown);
981
1075
  /**
982
1076
  * An event's stored `data` → its wire form (plain JSON), by the stored
983
1077
  * form. A native value costs one `typeof` check.
@@ -1011,15 +1105,14 @@ export const makeStream = (config) => {
1011
1105
  // JSON string (`S`) parsed, compressed binary (`B`) decompressed and
1012
1106
  // parsed — whatever the stream's current `storedAs` says.
1013
1107
  const wireData = yield* unpackData(raw.data, "EventStore.decode");
1014
- const decoder = Schema.decodeUnknownEffect(eventUnion);
1015
- const data = yield* decoder(wireData).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1108
+ const data = yield* decodeEventData(wireData).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1016
1109
  // Metadata is decoded through its schema when the stream declares one —
1017
1110
  // the mirror of the encode performed by `append`. Streams without a
1018
1111
  // metadata schema surface the stored attribute map untouched.
1019
1112
  let metadata;
1020
1113
  if (raw.metadata !== undefined) {
1021
1114
  metadata = metadataSchema
1022
- ? yield* Schema.decodeUnknownEffect(metadataSchema)(raw.metadata).pipe(Effect.mapError(toValidationError("EventStore.decode.metadata")))
1115
+ ? yield* decodeMetadata(raw.metadata).pipe(Effect.mapError(toValidationError("EventStore.decode.metadata")))
1023
1116
  : raw.metadata;
1024
1117
  }
1025
1118
  const event = {
@@ -1102,7 +1195,7 @@ export const makeStream = (config) => {
1102
1195
  * accepts as the class type — is decoded into the schema's type first
1103
1196
  * rather than refused with `Expected <Class>`.
1104
1197
  */
1105
- const encodeSnapshotState = (state, operation) => encodeToWire(snapshot.schema, state, operation, snapshotEntityType);
1198
+ const encodeSnapshotState = (state, operation) => encodeToWire(snapshot.schema, state, operation, snapshotEntityType, stateStoredAs !== undefined);
1106
1199
  /**
1107
1200
  * Send an append — see {@link AppendTransaction} for its layout. Resolves to
1108
1201
  * the race a guarded additional put lost (so the transaction is built and
@@ -1406,7 +1499,7 @@ export const makeStream = (config) => {
1406
1499
  // Top-level and native, beside `state`, so packing never touches it.
1407
1500
  if (sealed)
1408
1501
  item[SEALED_ATTRIBUTE] = true;
1409
- return toAttributeMap(item);
1502
+ return yield* marshalOrFail(snapshotEntityType, operation, () => toAttributeMap(item));
1410
1503
  });
1411
1504
  /**
1412
1505
  * The stream's own items of an append — everything but the caller's
@@ -1459,8 +1552,8 @@ export const makeStream = (config) => {
1459
1552
  return yield* snapshotUnavailable("append({ snapshot })");
1460
1553
  }
1461
1554
  // The head proof (#164), checked ahead of the no-op fast path, as the
1462
- // per-event options are. An index into `additionalItems` is checked by
1463
- // `append`, which has them (`measureAppend` does not take them).
1555
+ // per-event options are. An index into `additionalItems` is checked
1556
+ // against them by `headProofOp`.
1464
1557
  const headProof = options?.headProof;
1465
1558
  if (headProof !== undefined) {
1466
1559
  const problem = headProofShapeProblem(headProof);
@@ -1593,10 +1686,19 @@ export const makeStream = (config) => {
1593
1686
  const version = expectedVersion + i + 1;
1594
1687
  // In Effect v4, Schema.Class instances don't have _tag as an own property.
1595
1688
  // The identifier is on the constructor (class) itself.
1596
- const evtType = event._tag ??
1597
- event.constructor.identifier ??
1598
- event.constructor.name;
1599
- const wire = yield* encodeToWire(memberSchemaFor(event), event, "EventStore.append");
1689
+ const evtType = eventTypeOf(event);
1690
+ // An event item without a type is one no read decodes, and 1.40.0 died here before
1691
+ // sending anything: an event that names none (no `_tag`, no class) is refused.
1692
+ if (evtType === undefined) {
1693
+ return yield* new ValidationError({
1694
+ entityType,
1695
+ operation: "EventStore.append",
1696
+ cause: `events[${i}] names no event type: it has no \`_tag\`, and no class whose ` +
1697
+ "`identifier` or `name` gives one (an object without a prototype, say). " +
1698
+ "Nothing was written.",
1699
+ });
1700
+ }
1701
+ const wire = yield* encodeToWire(memberSchemaFor(event), event, "EventStore.append", entityType, dataStoredAs !== undefined);
1600
1702
  // Inject _tag for plain Schema.Class events; Schema.TaggedClass
1601
1703
  // events already carry _tag in their encoded form, which wins.
1602
1704
  const eventData = { _tag: evtType, ...wire };
@@ -1684,7 +1786,7 @@ export const makeStream = (config) => {
1684
1786
  return {
1685
1787
  Put: {
1686
1788
  TableName: tableName,
1687
- Item: toAttributeMap(item),
1789
+ Item: yield* marshalOrFail(entityType, "EventStore.append", () => toAttributeMap(item)),
1688
1790
  ConditionExpression: "attribute_not_exists(pk)",
1689
1791
  // The first put of a writer one version behind a seal lands on
1690
1792
  // the sealing event: its item tells `StreamSealed` from a
@@ -1797,13 +1899,12 @@ export const makeStream = (config) => {
1797
1899
  };
1798
1900
  return parts;
1799
1901
  });
1800
- const append = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1801
- const additionalOps = options?.additionalItems ?? [];
1802
- const idempotency = options?.idempotency;
1803
- const headProof = options?.headProof;
1804
- // The additional item a head proof names (#164) must exist — checked
1805
- // before anything is read, and ahead of the no-op fast path. Its shape
1806
- // is checked first, by `buildAppend`'s own rule.
1902
+ /**
1903
+ * The additional item a head proof names (#164), which must exist: checked
1904
+ * before anything is read, and ahead of the no-op fast path. Its shape is
1905
+ * checked first, by `buildAppend`'s own rule.
1906
+ */
1907
+ const headProofOp = (headProof, additionalOps) => Effect.gen(function* () {
1807
1908
  const proofOp = typeof headProof === "object" && headProofShapeProblem(headProof) === undefined
1808
1909
  ? headProof.additionalItem
1809
1910
  : undefined;
@@ -1816,11 +1917,18 @@ export const makeStream = (config) => {
1816
1917
  "Nothing was written.",
1817
1918
  });
1818
1919
  }
1819
- const parts = yield* buildAppend(streamId, events, expectedVersion, options);
1820
- if (parts === undefined)
1821
- return { version: expectedVersion, events: [] };
1822
- const { tableName, streamIdStr, contiguityCheck, eventItems, sentinelPut, snapshotPut } = parts;
1823
- const client = yield* Capacity.client;
1920
+ return proofOp;
1921
+ });
1922
+ /**
1923
+ * The append's one transaction, laid out — see {@link AppendTransaction}:
1924
+ * the caller's `additionalItems` compiled through the same builder
1925
+ * `Transaction.transactWrite` uses, so the two APIs cannot drift, and placed
1926
+ * among the stream's own items. `append` builds it for each attempt (a
1927
+ * guarded put among the additional items reads its item) and sends it;
1928
+ * `measureAppend` builds it once and measures it.
1929
+ */
1930
+ const buildAppendTransaction = (parts, additionalOps, expectedVersion, headProof, proofOp) => Effect.gen(function* () {
1931
+ const { tableName, contiguityCheck, eventItems, sentinelPut, snapshotPut } = parts;
1824
1932
  /**
1825
1933
  * Lay out the append's one transaction — see {@link AppendTransaction}:
1826
1934
  * [0, C) version-contiguity ConditionCheck — C is 0 or 1
@@ -1875,33 +1983,44 @@ export const makeStream = (config) => {
1875
1983
  headProof,
1876
1984
  };
1877
1985
  };
1986
+ // Caller-owned items, compiled through the same builder
1987
+ // `Transaction.transactWrite` uses, so the two APIs cannot drift.
1988
+ // Another stream's append (#166) is accepted here, and only here.
1989
+ const additional = yield* buildTransactWriteItems(additionalOps, "EventStore.append.additionalItems", { streams: true });
1990
+ // An item without a condition of its own proves nothing about the
1991
+ // head: accepting it would drop the gap protection silently. Nor
1992
+ // does another stream's append: its conditions are its stream's.
1993
+ if (proofOp !== undefined && !additional.conditioned.has(proofOp)) {
1994
+ const named = additionalOps[proofOp];
1995
+ return yield* new ValidationError({
1996
+ entityType,
1997
+ operation: "EventStore.append.headProof",
1998
+ cause: isStreamAppendOp(named)
1999
+ ? `headProof names additionalItems[${proofOp}], which is an append of stream ` +
2000
+ `"${named.streamName}" (appendOp): its conditions prove that stream's head, ` +
2001
+ "not this one's. Name an item conditioned on this stream being at " +
2002
+ "expectedVersion. Nothing was written."
2003
+ : `headProof names additionalItems[${proofOp}], which carries no condition of its ` +
2004
+ "own: the proof must be conditioned on the stream being at expectedVersion " +
2005
+ "(`.condition()`, `create()` or `Transaction.check`). Nothing was written.",
2006
+ });
2007
+ }
2008
+ return layout(additional);
2009
+ });
2010
+ const append = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
2011
+ const additionalOps = options?.additionalItems ?? [];
2012
+ const idempotency = options?.idempotency;
2013
+ const headProof = options?.headProof;
2014
+ const proofOp = yield* headProofOp(headProof, additionalOps);
2015
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2016
+ if (parts === undefined)
2017
+ return { version: expectedVersion, events: [] };
2018
+ const client = yield* Capacity.client;
1878
2019
  // A guarded put among the additional items reads its item; a race with
1879
2020
  // that read cancels the append, which is then built and written again.
1880
2021
  let lost;
1881
2022
  for (let attempt = 0; attempt < GUARDED_TRANSACTION_ATTEMPTS; attempt++) {
1882
- // Caller-owned items, compiled through the same builder
1883
- // `Transaction.transactWrite` uses, so the two APIs cannot drift.
1884
- // Another stream's append (#166) is accepted here, and only here.
1885
- const additional = yield* buildTransactWriteItems(additionalOps, "EventStore.append.additionalItems", { streams: true });
1886
- // An item without a condition of its own proves nothing about the
1887
- // head: accepting it would drop the gap protection silently. Nor
1888
- // does another stream's append: its conditions are its stream's.
1889
- if (proofOp !== undefined && !additional.conditioned.has(proofOp)) {
1890
- const named = additionalOps[proofOp];
1891
- return yield* new ValidationError({
1892
- entityType,
1893
- operation: "EventStore.append.headProof",
1894
- cause: isStreamAppendOp(named)
1895
- ? `headProof names additionalItems[${proofOp}], which is an append of stream ` +
1896
- `"${named.streamName}" (appendOp): its conditions prove that stream's head, ` +
1897
- "not this one's. Name an item conditioned on this stream being at " +
1898
- "expectedVersion. Nothing was written."
1899
- : `headProof names additionalItems[${proofOp}], which carries no condition of its ` +
1900
- "own: the proof must be conditioned on the stream being at expectedVersion " +
1901
- "(`.condition()`, `create()` or `Transaction.check`). Nothing was written.",
1902
- });
1903
- }
1904
- const tx = layout(additional);
2023
+ const tx = yield* buildAppendTransaction(parts, additionalOps, expectedVersion, headProof, proofOp);
1905
2024
  // DynamoDB's rules — one operation per item (an additional item
1906
2025
  // repeating an event, the contiguity check, the idempotency sentinel
1907
2026
  // or the inline snapshot, or another additional item), 100 items,
@@ -1909,7 +2028,7 @@ export const makeStream = (config) => {
1909
2028
  // `sendAppendTransaction` diagnoses DynamoDB's rejection (#144). The
1910
2029
  // items carry packed `data` / `state` as stored (#147), so the
1911
2030
  // diagnosis attributes stored bytes.
1912
- const outcome = yield* sendAppendTransaction(client, tx, streamIdStr, idempotency?.commandId);
2031
+ const outcome = yield* sendAppendTransaction(client, tx, parts.streamIdStr, idempotency?.commandId);
1913
2032
  if (outcome === undefined) {
1914
2033
  return { version: expectedVersion + events.length, events };
1915
2034
  }
@@ -1988,38 +2107,62 @@ export const makeStream = (config) => {
1988
2107
  // measureAppend / measureSnapshot — caller-side size planning (#147, R1)
1989
2108
  // ---------------------------------------------------------------------------
1990
2109
  const measureAppend = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1991
- if (options?.additionalItems !== undefined) {
2110
+ const additionalOps = options?.additionalItems;
2111
+ const headProof = options?.headProof;
2112
+ // A `{ additionalItem }` proof is checked against the additional items
2113
+ // when they are given, as `append` checks it. Without them it stands for
2114
+ // an item the caller adds, so the append is a transaction.
2115
+ const proofOp = additionalOps === undefined ? undefined : yield* headProofOp(headProof, additionalOps);
2116
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2117
+ if (parts === undefined) {
2118
+ return {
2119
+ events: [],
2120
+ sentinel: undefined,
2121
+ snapshot: undefined,
2122
+ transactionBytes: 0,
2123
+ requestBytes: 0,
2124
+ };
2125
+ }
2126
+ // The transaction `append` would send, built by the same code: the
2127
+ // stream's items and the items the caller's `additionalItems` build, in
2128
+ // the same places. Nothing is sent: an item `append` reads the table to
2129
+ // build has no size without that read, and fails the measurement.
2130
+ const built = yield* Capacity.withoutRequests(buildAppendTransaction(parts, additionalOps ?? [], expectedVersion, headProof, proofOp));
2131
+ if (built.refused !== undefined) {
2132
+ const { command, input } = built.refused;
1992
2133
  return yield* new ValidationError({
1993
2134
  entityType,
1994
2135
  operation: "EventStore.measureAppend",
1995
- cause: "measureAppend does not measure additionalItems (building a guarded put reads the " +
1996
- "table): measure the stream's own items without them, and add the size of your " +
1997
- "own items.",
2136
+ cause: `an additional item is built from the stored row: append would send ${command}` +
2137
+ (typeof input.TableName === "string" ? ` on table "${input.TableName}"` : "") +
2138
+ " to build it (a put of a versioned or unique-constrained entity, or a create " +
2139
+ "over a projection tombstone, reads its item). measureAppend sends no request, " +
2140
+ "so it has no size to give for this append. Nothing was read or written.",
1998
2141
  });
1999
2142
  }
2000
- const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2001
- if (parts === undefined) {
2002
- return { events: [], sentinel: undefined, snapshot: undefined, transactionBytes: 0 };
2143
+ if (Exit.isFailure(built.exit)) {
2144
+ // No request was refused, so nothing here is a client error.
2145
+ return yield* Effect.failCause(built.exit.cause);
2003
2146
  }
2147
+ const tx = built.exit.value;
2148
+ // An append of one event and nothing else is sent as a `PutItem`
2149
+ // carrying a write token (#173), measured here with a placeholder token
2150
+ // of its length.
2151
+ const single = typeof headProof !== "object" && isSingleEventPut(tx.items, tx.eventCount);
2152
+ const sent = single
2153
+ ? [withWriteToken(tx.items[0], "0".repeat(WRITE_TOKEN_LENGTH))]
2154
+ : tx.items;
2004
2155
  const putBytes = (item) => itemBytes(item.Put?.Item ?? {});
2005
- const laidOut = [
2006
- ...(parts.contiguityCheck === undefined ? [] : [parts.contiguityCheck]),
2007
- ...parts.eventItems,
2008
- ...(parts.sentinelPut === undefined ? [] : [parts.sentinelPut]),
2009
- ...(parts.snapshotPut === undefined ? [] : [parts.snapshotPut]),
2010
- ];
2011
- // A single-item append is sent as a `PutItem` carrying a write token
2012
- // (#173), whose bytes are measured here as a placeholder of its length.
2013
- // A `{ additionalItem }` proof means the append carries that item, so
2014
- // it is a transaction.
2015
- const single = typeof options?.headProof !== "object" && isSingleEventPut(laidOut, parts.eventItems.length);
2016
- const owned = single ? [withWriteToken(laidOut[0], "0".repeat(WRITE_TOKEN_LENGTH))] : laidOut;
2017
- const eventItems = single ? owned : parts.eventItems;
2156
+ // What the client sends beside the items: the request as `append` sends it.
2157
+ const fields = yield* Capacity.requestFields;
2018
2158
  const measurement = {
2019
- events: eventItems.map(putBytes),
2159
+ events: (single ? sent : parts.eventItems).map(putBytes),
2020
2160
  sentinel: parts.sentinelPut === undefined ? undefined : putBytes(parts.sentinelPut),
2021
2161
  snapshot: parts.snapshotPut === undefined ? undefined : putBytes(parts.snapshotPut),
2022
- transactionBytes: owned.reduce((sum, item) => sum + transactItemBytes(item), 0),
2162
+ transactionBytes: sent.reduce((sum, item) => sum + transactItemBytes(item), 0),
2163
+ requestBytes: single
2164
+ ? jsonBytes({ ...sent[0].Put, ...fields })
2165
+ : transactWriteBodyBytes({ TransactItems: sent, ...fields }),
2023
2166
  };
2024
2167
  return measurement;
2025
2168
  });
@@ -2164,7 +2307,7 @@ export const makeStream = (config) => {
2164
2307
  // `stateDispatch` — then decoded through the state schema as before.
2165
2308
  (stateDispatch && (typeof raw.state === "string" || raw.state instanceof Uint8Array)
2166
2309
  ? withRegistry((registry) => unpackStoredSync(raw.state, registry, { entityType: snapshotEntityType, operation }, "state"))
2167
- : Effect.succeed(raw.state)).pipe(Effect.flatMap((state) => Schema.decodeUnknownEffect(snapshot.schema)(state).pipe(Effect.mapError((cause) => new ValidationError({ entityType: snapshotEntityType, operation, cause })))), Effect.map((state) => ({
2310
+ : Effect.succeed(raw.state)).pipe(Effect.flatMap((state) => decodeSnapshotState(state).pipe(Effect.mapError((cause) => new ValidationError({ entityType: snapshotEntityType, operation, cause })))), Effect.map((state) => ({
2168
2311
  state,
2169
2312
  asOfVersion: raw.asOfVersion,
2170
2313
  timestamp: raw.timestamp,
@@ -2678,10 +2821,11 @@ export const makeStream = (config) => {
2678
2821
  * there. Command sentinels whose TTL has passed are gone, whether or not
2679
2822
  * DynamoDB has deleted them yet.
2680
2823
  */
2681
- const moveStream = (ctx, from, to, streamIdText, ttlAttribute, depth) => Effect.gen(function* () {
2824
+ const moveStream = (ctx, from, to, streamIdText, ttlAttribute) => Effect.gen(function* () {
2682
2825
  const client = yield* Capacity.client;
2683
2826
  const firstSk = composeEventSk(1);
2684
2827
  const nowSeconds = DateTime.toEpochSeconds(yield* DateTime.now);
2828
+ const unprovable = Rekey.unprovableRow(ctx);
2685
2829
  const live = (row) => {
2686
2830
  const ttl = row[ttlAttribute]?.N;
2687
2831
  return ttl === undefined || Number(ttl) > nowSeconds;
@@ -2736,35 +2880,122 @@ export const makeStream = (config) => {
2736
2880
  });
2737
2881
  const cancelled = (error) => isAwsConditionalCheckFailed(error.cause) ? Effect.succeed(false) : Effect.fail(error);
2738
2882
  /**
2739
- * Copy `row` to `to`: where nothing is (or only a row whose TTL has
2740
- * passed) — or, a snapshot, over an older one (`older`), so a copy never
2741
- * regresses it. `false` when a write got there first.
2883
+ * The copy of `row` to `to` a move sends over `held`, what `to` holds at its key: where
2884
+ * nothing is (or only a row whose TTL has passed), or, a snapshot, over an older one, so a
2885
+ * copy never regresses it. `undefined` where `to` holds it already: a copy an earlier attempt
2886
+ * or run made, or a snapshot as new.
2742
2887
  */
2743
- const copy = (row, older) => client
2744
- .putItem({
2745
- TableName: ctx.tableName,
2746
- Item: copyOf(row),
2747
- ...(older === undefined
2748
- ? {
2888
+ const copyOver = (row, held) => {
2889
+ if (held === undefined) {
2890
+ return {
2891
+ TableName: ctx.tableName,
2892
+ Item: copyOf(row),
2749
2893
  ConditionExpression: "attribute_not_exists(#pk) OR #ttl <= :now",
2750
2894
  ExpressionAttributeNames: { "#pk": "pk", "#ttl": ttlAttribute },
2751
2895
  ExpressionAttributeValues: { ":now": { N: String(nowSeconds) } },
2752
- }
2753
- : {
2754
- ConditionExpression: "#asOf < :asOf",
2755
- ExpressionAttributeNames: { "#asOf": "asOfVersion" },
2756
- ExpressionAttributeValues: { ":asOf": row.asOfVersion ?? { N: "0" } },
2757
- }),
2758
- })
2759
- .pipe(Effect.as(true), Effect.catch(cancelled));
2760
- /** Delete `row` at `from` while it is as read. `false` when a write changed it. */
2896
+ };
2897
+ }
2898
+ if (skOf(row) !== snapshotSk || asOfOf(row) <= asOfOf(held))
2899
+ return undefined;
2900
+ return {
2901
+ TableName: ctx.tableName,
2902
+ Item: copyOf(row),
2903
+ ConditionExpression: "#asOf < :asOf",
2904
+ ExpressionAttributeNames: { "#asOf": "asOfVersion" },
2905
+ ExpressionAttributeValues: { ":asOf": row.asOfVersion ?? { N: "0" } },
2906
+ };
2907
+ };
2908
+ /**
2909
+ * A dry run's move of `rows`, planned over `there`, what `to` holds: each copy the real run
2910
+ * sends ({@link copyOver}), and each row taken from `from`, as its copy, flip and drain
2911
+ * leave them.
2912
+ */
2913
+ const planMove = (rows, there) => {
2914
+ ctx.plan(rows.flatMap((row) => {
2915
+ const put = copyOver(row, there.get(skOf(row)));
2916
+ return [
2917
+ ...(put === undefined ? [] : [{ Put: put }]),
2918
+ {
2919
+ Delete: {
2920
+ TableName: ctx.tableName,
2921
+ Key: toAttributeMap({ pk: from, sk: skOf(row) }),
2922
+ },
2923
+ },
2924
+ ];
2925
+ }));
2926
+ return Rekey.mergeTallies({ moved: { stream: rows.length } }, strongestGaps(rows));
2927
+ };
2928
+ /**
2929
+ * Copy `row` to `to` over `held` ({@link copyOver}). `false` when a write got there first.
2930
+ */
2931
+ const copy = (row, held) => {
2932
+ const request = copyOver(row, held);
2933
+ return request === undefined
2934
+ ? Effect.succeed(true)
2935
+ : client.putItem(request).pipe(Effect.as(true), Effect.catch(cancelled));
2936
+ };
2937
+ /**
2938
+ * `row` as read, whole, or, a row too wide for that, the strongest guard that fits, as
2939
+ * 1.39.0 sent: only a stream already part-moved deletes one (`unguardedRows`).
2940
+ */
2941
+ const guardOfRow = (row) => wholeRowGuard(row, "pk", [], [], []) ?? asReadGuard(row, "pk", []);
2942
+ /**
2943
+ * The rows of `rows` too wide to guard whole, moved under the strongest guard that fits
2944
+ * (`guardOfRow`): with writes going on, a write to an attribute it leaves out isn't seen
2945
+ * ({@link RekeyGuardGaps} `strongest`).
2946
+ */
2947
+ const strongestGaps = (rows) => Rekey.mergeTallies(...rows
2948
+ .filter((row) => wholeRowGuard(row, "pk", [], [], []) === undefined)
2949
+ .map((row) => Rekey.guardGap(ctx, "strongest", {
2950
+ member: config.streamName,
2951
+ kind: "stream",
2952
+ key: { pk: from, sk: skOf(row) },
2953
+ target: { pk: to, sk: skOf(row) },
2954
+ })));
2955
+ /**
2956
+ * With writes going on (`unprovable`), the rows of a stream nothing of which has moved that
2957
+ * are too wide to guard whole, each reported `unguarded`, before anything is copied: its rows
2958
+ * move together, so one leaves the stream as it is. One already part-moved (a row of it under
2959
+ * `to`, or flipped) is finished under the strongest guard that fits (`guardOfRow`).
2960
+ */
2961
+ const unguardedRows = (rows) => {
2962
+ if (unprovable === "strongest")
2963
+ return undefined;
2964
+ const unguarded = rows.filter((row) => wholeRowGuard(row, "pk", [], [], []) === undefined);
2965
+ if (unguarded.length === 0)
2966
+ return undefined;
2967
+ return Rekey.mergeTallies(...unguarded.map((row) => conflict("unguarded", `${Rekey.UNGUARDED_MESSAGE} The stream's other rows are left with it.`, skOf(row))));
2968
+ };
2969
+ /** Delete `row` at `from` while it is as read (`guardOfRow`). `false` when a write changed it. */
2761
2970
  const remove = (row) => client
2762
2971
  .deleteItem({
2763
2972
  TableName: ctx.tableName,
2764
2973
  Key: toAttributeMap({ pk: from, sk: skOf(row) }),
2765
- ...asReadGuard(row, "pk", []),
2974
+ ...guardOfRow(row),
2766
2975
  })
2767
2976
  .pipe(Effect.as(true), Effect.catch(cancelled));
2977
+ /**
2978
+ * What `to` holds, by sort key, once the stream lives there, and, when a row of `left` (its
2979
+ * rows still under `from`) is held there differently, the conflicts: a row `to` holds
2980
+ * differently (an event or sentinel written under both keys) is left with the rest. A
2981
+ * snapshot only grows newer. The real run's drain and a dry run's plan both judge by it.
2982
+ */
2983
+ const toDrain = (left) => Effect.map(readAll(to), (rows) => {
2984
+ const there = new Map(rows.map((row) => [skOf(row), row]));
2985
+ const differing = left.filter((row) => {
2986
+ const held = there.get(skOf(row));
2987
+ if (held === undefined || sameRow(copyOf(row), held))
2988
+ return false;
2989
+ return skOf(row) !== snapshotSk;
2990
+ });
2991
+ return {
2992
+ there,
2993
+ refused: differing.length === 0
2994
+ ? undefined
2995
+ : Rekey.mergeTallies(...differing.map((row) => conflict("bothKeys", "a row of it is under both partition keys, and the two differ; the rows " +
2996
+ "under its old key are left as they are.", skOf(row)))),
2997
+ };
2998
+ });
2768
2999
  /**
2769
3000
  * Bring every row still under `from` over, once the stream lives at
2770
3001
  * `to`: a row `to` lacks is copied (a command sentinel written beside
@@ -2778,28 +3009,11 @@ export const makeStream = (config) => {
2778
3009
  */
2779
3010
  const drain = Effect.gen(function* () {
2780
3011
  const left = yield* readOwn;
2781
- const there = new Map((yield* readAll(to)).map((row) => [skOf(row), row]));
2782
- const differing = [];
2783
- for (const row of left) {
2784
- const held = there.get(skOf(row));
2785
- if (held === undefined || sameRow(copyOf(row), held))
2786
- continue;
2787
- if (skOf(row) === snapshotSk)
2788
- continue;
2789
- differing.push(row);
2790
- }
2791
- if (differing.length > 0) {
2792
- return Rekey.mergeTallies(...differing.map((row) => conflict("bothKeys", "a row of it is under both partition keys, and the two differ; the rows " +
2793
- "under its old key are left as they are.", skOf(row))));
2794
- }
3012
+ const { there, refused } = yield* toDrain(left);
3013
+ if (refused !== undefined)
3014
+ return refused;
2795
3015
  for (const row of left) {
2796
- const held = there.get(skOf(row));
2797
- const copied = held === undefined
2798
- ? yield* copy(row)
2799
- : skOf(row) === snapshotSk && asOfOf(row) > asOfOf(held)
2800
- ? yield* copy(row, held)
2801
- : true;
2802
- if (!copied)
3016
+ if (!(yield* copy(row, there.get(skOf(row)))))
2803
3017
  return undefined;
2804
3018
  }
2805
3019
  const ordered = [
@@ -2811,9 +3025,9 @@ export const makeStream = (config) => {
2811
3025
  if (!(yield* remove(row)))
2812
3026
  return undefined;
2813
3027
  }
2814
- return { moved: { stream: left.length } };
3028
+ return Rekey.mergeTallies({ moved: { stream: left.length } }, strongestGaps(left));
2815
3029
  });
2816
- let tally = {};
3030
+ const tally = {};
2817
3031
  for (let attempt = 0; attempt < STREAM_MOVE_ATTEMPTS; attempt++) {
2818
3032
  const rows = yield* readOwn;
2819
3033
  // Moved since the scan read it.
@@ -2825,23 +3039,23 @@ export const makeStream = (config) => {
2825
3039
  const flipped = first === undefined || first[MOVED_ATTRIBUTE] !== undefined;
2826
3040
  if (!flipped) {
2827
3041
  const atTarget = yield* readAll(to);
2828
- // Another stream under other key text moves out first.
3042
+ // Nothing of it has moved while no row of it is under `to` (`unguardedRows`).
3043
+ if (!atTarget.some((row) => !elsewhere(row))) {
3044
+ const refused = unguardedRows(rows);
3045
+ if (refused !== undefined)
3046
+ return Rekey.mergeTallies(tally, refused);
3047
+ }
3048
+ // Another stream under other key text moves out first, judged as its own unit.
2829
3049
  const stale = atTarget.find(elsewhere);
2830
3050
  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."));
3051
+ const judged = yield* judgeStream(stale, ctx);
3052
+ // A dry run reads what its plan leaves (`Rekey.RekeyRowContext.plan`).
3053
+ if ((yield* readAll(to)).some(elsewhere)) {
3054
+ return Rekey.mergeTallies(tally, judged === "loop"
3055
+ ? conflict("contended", Rekey.LOOP_MESSAGE)
3056
+ : conflict("taken", "rows of another stream are under its current partition key."));
2833
3057
  }
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;
3058
+ continue;
2845
3059
  }
2846
3060
  const there = new Map(atTarget.filter((row) => !elsewhere(row)).map((row) => [skOf(row), row]));
2847
3061
  const here = new Map(rows.map((row) => [skOf(row), row]));
@@ -2861,17 +3075,11 @@ export const makeStream = (config) => {
2861
3075
  }
2862
3076
  }
2863
3077
  if (ctx.dryRun)
2864
- return Rekey.mergeTallies(tally, { moved: { stream: rows.length } });
3078
+ return Rekey.mergeTallies(tally, planMove(rows, there));
2865
3079
  // COPY
2866
3080
  let copiedAll = true;
2867
3081
  for (const row of rows) {
2868
- const held = there.get(skOf(row));
2869
- const copied = held === undefined
2870
- ? yield* copy(row)
2871
- : skOf(row) === snapshotSk && asOfOf(row) > asOfOf(held)
2872
- ? yield* copy(row, held)
2873
- : true;
2874
- if (!copied) {
3082
+ if (!(yield* copy(row, there.get(skOf(row))))) {
2875
3083
  copiedAll = false;
2876
3084
  break;
2877
3085
  }
@@ -2879,7 +3087,10 @@ export const makeStream = (config) => {
2879
3087
  if (!copiedAll)
2880
3088
  continue;
2881
3089
  // FLIP — conditioned on the stream being as copied: no event past
2882
- // the head, the head (and its seal) and the snapshot unchanged.
3090
+ // the head, the head (and its seal) and the snapshot unchanged. The
3091
+ // first event and the head are this stream's: once a run started at
3092
+ // the same time has moved this stream away, another stream's move can
3093
+ // bring its rows here (#240), and the flip must not mark those.
2883
3094
  const head = rows.reduce((top, row) => Math.max(top, versionOf(row)), 1);
2884
3095
  const headRow = rows.find((row) => versionOf(row) === head);
2885
3096
  const snapshot = rows.find((row) => skOf(row) === snapshotSk);
@@ -2893,14 +3104,15 @@ export const makeStream = (config) => {
2893
3104
  Key: toAttributeMap({ pk: from, sk: firstSk }),
2894
3105
  UpdateExpression: "SET #moved = :to",
2895
3106
  ConditionExpression: head === 1
2896
- ? `attribute_exists(#pk) AND attribute_not_exists(#moved) AND ${sealClause}`
2897
- : "attribute_exists(#pk) AND attribute_not_exists(#moved)",
3107
+ ? `attribute_exists(#pk) AND #sid = :sid AND attribute_not_exists(#moved) AND ${sealClause}`
3108
+ : "attribute_exists(#pk) AND #sid = :sid AND attribute_not_exists(#moved)",
2898
3109
  ExpressionAttributeNames: {
2899
3110
  "#pk": "pk",
3111
+ "#sid": "streamId",
2900
3112
  "#moved": MOVED_ATTRIBUTE,
2901
3113
  ...(head === 1 && { "#sealed": SEALED_ATTRIBUTE }),
2902
3114
  },
2903
- ExpressionAttributeValues: toAttributeMap({ ":to": to }),
3115
+ ExpressionAttributeValues: toAttributeMap({ ":to": to, ":sid": streamIdText }),
2904
3116
  },
2905
3117
  },
2906
3118
  {
@@ -2917,8 +3129,13 @@ export const makeStream = (config) => {
2917
3129
  ConditionCheck: {
2918
3130
  TableName: ctx.tableName,
2919
3131
  Key: toAttributeMap({ pk: from, sk: composeEventSk(head) }),
2920
- ConditionExpression: `attribute_exists(#pk) AND ${sealClause}`,
2921
- ExpressionAttributeNames: { "#pk": "pk", "#sealed": SEALED_ATTRIBUTE },
3132
+ ConditionExpression: `attribute_exists(#pk) AND #sid = :sid AND ${sealClause}`,
3133
+ ExpressionAttributeNames: {
3134
+ "#pk": "pk",
3135
+ "#sid": "streamId",
3136
+ "#sealed": SEALED_ATTRIBUTE,
3137
+ },
3138
+ ExpressionAttributeValues: toAttributeMap({ ":sid": streamIdText }),
2922
3139
  },
2923
3140
  },
2924
3141
  ]
@@ -2949,7 +3166,9 @@ export const makeStream = (config) => {
2949
3166
  continue;
2950
3167
  }
2951
3168
  else if (ctx.dryRun) {
2952
- return Rekey.mergeTallies(tally, { moved: { stream: rows.length } });
3169
+ // The drain's judgement and copies, over the rows just read.
3170
+ const { there, refused } = yield* toDrain(rows);
3171
+ return Rekey.mergeTallies(tally, refused ?? planMove(rows, there));
2953
3172
  }
2954
3173
  // DELETE
2955
3174
  const drained = yield* drain;
@@ -2958,8 +3177,31 @@ export const makeStream = (config) => {
2958
3177
  }
2959
3178
  return Rekey.mergeTallies(tally, conflict("contended", "writes changed it on every attempt to move it."));
2960
3179
  });
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* () {
3180
+ /**
3181
+ * The unit a row of the stream under other key text is judged as, and its move: the stream moves
3182
+ * whole, once per run, from whichever of its rows the scan reaches first, and rows left there
3183
+ * after it moved move after it. `undefined` for a row under its current key, or not readable.
3184
+ */
3185
+ const streamMove = (row, ctx) => Effect.gen(function* () {
3186
+ const tableConfig = yield* config.table.Tag;
3187
+ const keys = streamKeys(row);
3188
+ if (typeof keys !== "object")
3189
+ return undefined;
3190
+ const from = row.pk.S;
3191
+ if (from === keys.current)
3192
+ return undefined;
3193
+ const streamIdText = row.streamId?.S ?? "";
3194
+ return {
3195
+ unit: Rekey.identity("stream", config.streamName, from, streamIdText),
3196
+ work: moveStream(ctx, from, keys.current, streamIdText, resolveTtlAttributeName(tableConfig)),
3197
+ };
3198
+ });
3199
+ /** Judge the stream a row at a key another stream's move needs belongs to, as its unit. */
3200
+ const judgeStream = (row, ctx) => Effect.flatMap(streamMove(row, ctx), (move) => move === undefined
3201
+ ? Effect.succeed("settled")
3202
+ : ctx.judge(config.streamName, move.unit, move.work));
3203
+ /** One scanned row of the stream. */
3204
+ const rekeyStreamRow = (row, ctx) => Effect.gen(function* () {
2963
3205
  const tableConfig = yield* config.table.Tag;
2964
3206
  if (tableConfig.name !== ctx.tableName)
2965
3207
  return undefined;
@@ -2982,18 +3224,16 @@ export const makeStream = (config) => {
2982
3224
  ],
2983
3225
  };
2984
3226
  }
2985
- const from = row.pk.S;
2986
- if (from === keys.current)
3227
+ if (row.pk.S === keys.current)
2987
3228
  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));
3229
+ yield* judgeStream(row, ctx);
3230
+ return {};
2992
3231
  });
2993
3232
  const rekeyHandler = {
2994
3233
  name: config.streamName,
2995
3234
  types: [entityType, snapshotEntityType, commandEntityType],
2996
- row: (row, ctx) => rekeyStreamRow(row, ctx, 0),
3235
+ key: { pk: "pk", sk: "sk" },
3236
+ row: (row, ctx) => rekeyStreamRow(row, ctx),
2997
3237
  };
2998
3238
  return {
2999
3239
  [EventStreamTypeId]: EventStreamTypeId,