effect-dynamodb 1.39.0 → 1.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (133) hide show
  1. package/dist/Aggregate.d.ts +119 -15
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +2021 -379
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +9 -5
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +28 -44
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +12 -5
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/ConsumedCapacity.js +1 -1
  13. package/dist/ConsumedCapacity.js.map +1 -1
  14. package/dist/DynamoClient.d.ts +22 -8
  15. package/dist/DynamoClient.d.ts.map +1 -1
  16. package/dist/DynamoClient.js +243 -87
  17. package/dist/DynamoClient.js.map +1 -1
  18. package/dist/Entity.d.ts +87 -22
  19. package/dist/Entity.d.ts.map +1 -1
  20. package/dist/Entity.js +2750 -514
  21. package/dist/Entity.js.map +1 -1
  22. package/dist/EventStore.d.ts +37 -15
  23. package/dist/EventStore.d.ts.map +1 -1
  24. package/dist/EventStore.js +215 -79
  25. package/dist/EventStore.js.map +1 -1
  26. package/dist/Marshaller.d.ts +39 -9
  27. package/dist/Marshaller.d.ts.map +1 -1
  28. package/dist/Marshaller.js +421 -70
  29. package/dist/Marshaller.js.map +1 -1
  30. package/dist/Query.d.ts +23 -0
  31. package/dist/Query.d.ts.map +1 -1
  32. package/dist/Query.js +49 -3
  33. package/dist/Query.js.map +1 -1
  34. package/dist/StorageEncoding.d.ts +7 -1
  35. package/dist/StorageEncoding.d.ts.map +1 -1
  36. package/dist/StorageEncoding.js +8 -2
  37. package/dist/StorageEncoding.js.map +1 -1
  38. package/dist/Table.d.ts +69 -8
  39. package/dist/Table.d.ts.map +1 -1
  40. package/dist/Transaction.d.ts.map +1 -1
  41. package/dist/Transaction.js +10 -4
  42. package/dist/Transaction.js.map +1 -1
  43. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  44. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  45. package/dist/change-feed/ChangeFeed.js +76 -9
  46. package/dist/change-feed/ChangeFeed.js.map +1 -1
  47. package/dist/change-feed/CheckpointStore.js +1 -1
  48. package/dist/change-feed/CheckpointStore.js.map +1 -1
  49. package/dist/change-feed/DynamoStreamsClient.d.ts +12 -5
  50. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  51. package/dist/change-feed/DynamoStreamsClient.js +15 -9
  52. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  53. package/dist/internal/BoundCrud.d.ts +40 -32
  54. package/dist/internal/BoundCrud.d.ts.map +1 -1
  55. package/dist/internal/BoundCrud.js.map +1 -1
  56. package/dist/internal/BoundQuery.d.ts +1 -1
  57. package/dist/internal/BoundQuery.d.ts.map +1 -1
  58. package/dist/internal/BoundQuery.js +22 -12
  59. package/dist/internal/BoundQuery.js.map +1 -1
  60. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  61. package/dist/internal/BoundVectorQuery.js +2 -1
  62. package/dist/internal/BoundVectorQuery.js.map +1 -1
  63. package/dist/internal/Capacity.d.ts +44 -4
  64. package/dist/internal/Capacity.d.ts.map +1 -1
  65. package/dist/internal/Capacity.js +89 -15
  66. package/dist/internal/Capacity.js.map +1 -1
  67. package/dist/internal/ClientOptions.d.ts +72 -0
  68. package/dist/internal/ClientOptions.d.ts.map +1 -0
  69. package/dist/internal/ClientOptions.js +79 -0
  70. package/dist/internal/ClientOptions.js.map +1 -0
  71. package/dist/internal/Cursor.d.ts +19 -10
  72. package/dist/internal/Cursor.d.ts.map +1 -1
  73. package/dist/internal/Cursor.js +25 -10
  74. package/dist/internal/Cursor.js.map +1 -1
  75. package/dist/internal/EntityCombinators.d.ts +22 -7
  76. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  77. package/dist/internal/EntityCombinators.js +6 -2
  78. package/dist/internal/EntityCombinators.js.map +1 -1
  79. package/dist/internal/EntityOps.d.ts +11 -1
  80. package/dist/internal/EntityOps.d.ts.map +1 -1
  81. package/dist/internal/EntityOps.js.map +1 -1
  82. package/dist/internal/EventProjection.d.ts +15 -3
  83. package/dist/internal/EventProjection.d.ts.map +1 -1
  84. package/dist/internal/EventProjection.js +27 -8
  85. package/dist/internal/EventProjection.js.map +1 -1
  86. package/dist/internal/Expr.d.ts.map +1 -1
  87. package/dist/internal/Expr.js +53 -2
  88. package/dist/internal/Expr.js.map +1 -1
  89. package/dist/internal/ExpressionLimits.d.ts +57 -1
  90. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  91. package/dist/internal/ExpressionLimits.js +90 -1
  92. package/dist/internal/ExpressionLimits.js.map +1 -1
  93. package/dist/internal/ItemSize.d.ts +108 -4
  94. package/dist/internal/ItemSize.d.ts.map +1 -1
  95. package/dist/internal/ItemSize.js +190 -3
  96. package/dist/internal/ItemSize.js.map +1 -1
  97. package/dist/internal/MultiProjection.d.ts +7 -2
  98. package/dist/internal/MultiProjection.d.ts.map +1 -1
  99. package/dist/internal/MultiProjection.js +9 -3
  100. package/dist/internal/MultiProjection.js.map +1 -1
  101. package/dist/internal/PathBuilder.d.ts +15 -4
  102. package/dist/internal/PathBuilder.d.ts.map +1 -1
  103. package/dist/internal/PathBuilder.js +20 -10
  104. package/dist/internal/PathBuilder.js.map +1 -1
  105. package/dist/internal/ProjectionEngine.d.ts +76 -2
  106. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  107. package/dist/internal/ProjectionEngine.js +358 -28
  108. package/dist/internal/ProjectionEngine.js.map +1 -1
  109. package/dist/internal/Rekey.d.ts +21 -1
  110. package/dist/internal/Rekey.d.ts.map +1 -1
  111. package/dist/internal/Rekey.js +67 -0
  112. package/dist/internal/Rekey.js.map +1 -1
  113. package/dist/internal/RoundTrip.d.ts +36 -0
  114. package/dist/internal/RoundTrip.d.ts.map +1 -0
  115. package/dist/internal/RoundTrip.js +79 -0
  116. package/dist/internal/RoundTrip.js.map +1 -0
  117. package/dist/internal/SentRequest.d.ts +14 -0
  118. package/dist/internal/SentRequest.d.ts.map +1 -0
  119. package/dist/internal/SentRequest.js +31 -0
  120. package/dist/internal/SentRequest.js.map +1 -0
  121. package/dist/internal/TransactWriteOps.d.ts +69 -15
  122. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  123. package/dist/internal/TransactWriteOps.js +144 -107
  124. package/dist/internal/TransactWriteOps.js.map +1 -1
  125. package/dist/internal/TransactableOps.d.ts +115 -23
  126. package/dist/internal/TransactableOps.d.ts.map +1 -1
  127. package/dist/internal/TransactableOps.js +244 -80
  128. package/dist/internal/TransactableOps.js.map +1 -1
  129. package/dist/internal/WriteDiagnosis.d.ts +31 -3
  130. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  131. package/dist/internal/WriteDiagnosis.js +128 -11
  132. package/dist/internal/WriteDiagnosis.js.map +1 -1
  133. package/package.json +2 -2
@@ -49,20 +49,25 @@ 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";
53
55
  import { isDispatchEligible, packedShape, packValue, unpackStoredSync, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
56
+ import { refuseUnreadable } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
54
57
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
55
- import { Context, DateTime, Effect, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
58
+ import { Context, DateTime, Effect, Exit, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
56
59
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
57
60
  import * as Capacity from "./internal/Capacity.js";
58
61
  import { ProjectionRoutes } from "./internal/EventProjection.js";
59
62
  import { eq } from "./internal/Expr.js";
60
- import { asReadGuard } from "./internal/ExpressionLimits.js";
61
- import { itemBytes, transactItemBytes } from "./internal/ItemSize.js";
63
+ import { asReadGuard, wholeRowGuard } from "./internal/ExpressionLimits.js";
64
+ import { itemBytes, jsonBytes, transactItemBytes, transactWriteBodyBytes, } from "./internal/ItemSize.js";
62
65
  import { isMultiProjection, } from "./internal/MultiProjection.js";
63
66
  import { codecRequirements, currentRegistry, decodeImage, imageEntityType, runtimeCodecCheck, unregisteredCodecError, withRegistry, } from "./internal/Packed.js";
64
67
  import { createPathBuilder } from "./internal/PathBuilder.js";
65
68
  import * as Rekey from "./internal/Rekey.js";
69
+ import { notReadBack, readBackOf } from "./internal/RoundTrip.js";
70
+ import { marshalOrFail } from "./internal/TransactableOps.js";
66
71
  import { buildTransactWriteItems, GUARDED_TRANSACTION_ATTEMPTS, isStreamAppendOp, judgeCancellation, opConditionFailed, StreamAppendTypeId, transactItemTarget, } from "./internal/TransactWriteOps.js";
67
72
  import { diagnosedValidationError, diagnoseFailure, mergeKeyAttributes, withCause, } from "./internal/WriteDiagnosis.js";
68
73
  import { fromAttributeMap, toAttributeMap } from "./Marshaller.js";
@@ -832,6 +837,28 @@ export const makeStream = (config) => {
832
837
  // Snapshot config validation (EDD-9027, EDD-9062) — fail fast at definition time.
833
838
  // -------------------------------------------------------------------------
834
839
  const snapshot = config.snapshot;
840
+ // What a stream stores has to read back (EDD-9125): an append that succeeds and a read that
841
+ // can't decode leaves events nobody can read.
842
+ const streamLabel = `EventStream "${config.streamName}"`;
843
+ config.events.forEach((event, position) => {
844
+ const identifier = event.identifier;
845
+ const named = typeof identifier === "string" ? `event "${identifier}"` : `events[${position}]`;
846
+ refuseUnreadable(`${streamLabel}, ${named}`, "schema", event, { whole: "the event" });
847
+ });
848
+ if (config.events.length > 1) {
849
+ // Read through one union, so what one event stores can be what another reads.
850
+ refuseUnreadable(streamLabel, "schema", Schema.Union(config.events), { whole: "the union of its events" });
851
+ }
852
+ if (config.metadata !== undefined) {
853
+ refuseUnreadable(`${streamLabel}, metadata`, "schema", config.metadata, {
854
+ whole: "the metadata",
855
+ });
856
+ }
857
+ if (snapshot !== undefined) {
858
+ refuseUnreadable(`${streamLabel}, snapshot state`, "schema", snapshot.schema, {
859
+ whole: "the state",
860
+ });
861
+ }
835
862
  if (snapshot !== undefined && snapshot.every !== undefined) {
836
863
  if (!Number.isInteger(snapshot.every) || snapshot.every <= 0) {
837
864
  throw new Error(`[EDD-9027] EventStream "${config.streamName}": snapshot.every must be a positive integer; ` +
@@ -965,19 +992,62 @@ export const makeStream = (config) => {
965
992
  }
966
993
  return eventUnion;
967
994
  };
995
+ const writableCodecs = new Map();
996
+ /** A codec refusing a tuple position its stored list can't keep. Built once per schema. */
997
+ const writableCodec = (declared) => {
998
+ const known = writableCodecs.get(declared);
999
+ if (known !== undefined)
1000
+ return known;
1001
+ const writable = writingTuplePositions(declared);
1002
+ writableCodecs.set(declared, writable);
1003
+ return writable;
1004
+ };
1005
+ /**
1006
+ * What checks a schema's stored values read back (`EDD-9126`), for one holding a custom
1007
+ * declaration. An event is read through the union of the events; anything else through itself.
1008
+ */
1009
+ const readBacks = new Map();
1010
+ const readBackFor = (declared) => {
1011
+ if (readBacks.has(declared))
1012
+ return readBacks.get(declared);
1013
+ const isEvent = declared === eventUnion || config.events.includes(declared);
1014
+ const readBack = readBackOf(declared, () => readingStreamValues(isEvent ? eventUnion : declared));
1015
+ readBacks.set(declared, readBack);
1016
+ return readBack;
1017
+ };
968
1018
  /**
969
1019
  * 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`).
1020
+ * `decode → encode` fallback for inputs already in encoded shape, then refused if it wouldn't read
1021
+ * back. Mirrors the Entity write path (`encodeForWrite` in `Entity.ts`). Everything a stream stores
1022
+ * from its own schemas goes through this.
972
1023
  */
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 }))))));
1024
+ const encodeToWire = (declared, input, operation, errorEntityType = entityType, packed = false) => {
1025
+ const codec = writableCodec(declared);
1026
+ const wire = Schema.encodeUnknownEffect(codec)(input).pipe(Effect.catch((primaryCause) => Schema.decodeUnknownEffect(codec)(input).pipe(Effect.flatMap((decoded) => Schema.encodeUnknownEffect(codec)(decoded)),
1027
+ // Surface the original encode error — its message is keyed on the
1028
+ // caller's input shape, which is what the user expects to see.
1029
+ Effect.catch(() => Effect.fail(new ValidationError({ entityType: errorEntityType, operation, cause: primaryCause }))))));
1030
+ // What's packed doesn't go through the marshaller's map, and packing refuses an instance itself.
1031
+ const readBack = packed ? undefined : readBackFor(declared);
1032
+ return readBack === undefined
1033
+ ? wire
1034
+ : wire.pipe(Effect.tap((encoded) => readBack(encoded).pipe(Effect.mapError((issue) => new ValidationError({
1035
+ entityType: errorEntityType,
1036
+ operation,
1037
+ cause: notReadBack("The value", issue),
1038
+ })))));
1039
+ };
977
1040
  // ---------------------------------------------------------------------------
978
1041
  // Decode a raw DynamoDB item → StreamEvent<TEvent>
979
1042
  // ---------------------------------------------------------------------------
980
1043
  const decodeEnvelope = Schema.decodeUnknownEffect(EventEnvelope);
1044
+ // `undefined` and an empty set are stored as absent attributes, in an event as
1045
+ // anywhere else, and read back as those values. A decode that dies on one fails as
1046
+ // 1.39.0's did, which decoded through the declared schema (`decodingAsBefore`).
1047
+ const decodingStream = (declared) => decodingAsBefore(readingStreamValues(declared), declared);
1048
+ const decodeEventData = decodingStream(eventUnion);
1049
+ const decodeMetadata = decodingStream(metadataSchema ?? Schema.Unknown);
1050
+ const decodeSnapshotState = decodingStream(snapshot?.schema ?? Schema.Unknown);
981
1051
  /**
982
1052
  * An event's stored `data` → its wire form (plain JSON), by the stored
983
1053
  * form. A native value costs one `typeof` check.
@@ -1011,15 +1081,14 @@ export const makeStream = (config) => {
1011
1081
  // JSON string (`S`) parsed, compressed binary (`B`) decompressed and
1012
1082
  // parsed — whatever the stream's current `storedAs` says.
1013
1083
  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")));
1084
+ const data = yield* decodeEventData(wireData).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1016
1085
  // Metadata is decoded through its schema when the stream declares one —
1017
1086
  // the mirror of the encode performed by `append`. Streams without a
1018
1087
  // metadata schema surface the stored attribute map untouched.
1019
1088
  let metadata;
1020
1089
  if (raw.metadata !== undefined) {
1021
1090
  metadata = metadataSchema
1022
- ? yield* Schema.decodeUnknownEffect(metadataSchema)(raw.metadata).pipe(Effect.mapError(toValidationError("EventStore.decode.metadata")))
1091
+ ? yield* decodeMetadata(raw.metadata).pipe(Effect.mapError(toValidationError("EventStore.decode.metadata")))
1023
1092
  : raw.metadata;
1024
1093
  }
1025
1094
  const event = {
@@ -1102,7 +1171,7 @@ export const makeStream = (config) => {
1102
1171
  * accepts as the class type — is decoded into the schema's type first
1103
1172
  * rather than refused with `Expected <Class>`.
1104
1173
  */
1105
- const encodeSnapshotState = (state, operation) => encodeToWire(snapshot.schema, state, operation, snapshotEntityType);
1174
+ const encodeSnapshotState = (state, operation) => encodeToWire(snapshot.schema, state, operation, snapshotEntityType, stateStoredAs !== undefined);
1106
1175
  /**
1107
1176
  * Send an append — see {@link AppendTransaction} for its layout. Resolves to
1108
1177
  * the race a guarded additional put lost (so the transaction is built and
@@ -1406,7 +1475,7 @@ export const makeStream = (config) => {
1406
1475
  // Top-level and native, beside `state`, so packing never touches it.
1407
1476
  if (sealed)
1408
1477
  item[SEALED_ATTRIBUTE] = true;
1409
- return toAttributeMap(item);
1478
+ return yield* marshalOrFail(snapshotEntityType, operation, () => toAttributeMap(item));
1410
1479
  });
1411
1480
  /**
1412
1481
  * The stream's own items of an append — everything but the caller's
@@ -1459,8 +1528,8 @@ export const makeStream = (config) => {
1459
1528
  return yield* snapshotUnavailable("append({ snapshot })");
1460
1529
  }
1461
1530
  // 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).
1531
+ // per-event options are. An index into `additionalItems` is checked
1532
+ // against them by `headProofOp`.
1464
1533
  const headProof = options?.headProof;
1465
1534
  if (headProof !== undefined) {
1466
1535
  const problem = headProofShapeProblem(headProof);
@@ -1596,7 +1665,7 @@ export const makeStream = (config) => {
1596
1665
  const evtType = event._tag ??
1597
1666
  event.constructor.identifier ??
1598
1667
  event.constructor.name;
1599
- const wire = yield* encodeToWire(memberSchemaFor(event), event, "EventStore.append");
1668
+ const wire = yield* encodeToWire(memberSchemaFor(event), event, "EventStore.append", entityType, dataStoredAs !== undefined);
1600
1669
  // Inject _tag for plain Schema.Class events; Schema.TaggedClass
1601
1670
  // events already carry _tag in their encoded form, which wins.
1602
1671
  const eventData = { _tag: evtType, ...wire };
@@ -1684,7 +1753,7 @@ export const makeStream = (config) => {
1684
1753
  return {
1685
1754
  Put: {
1686
1755
  TableName: tableName,
1687
- Item: toAttributeMap(item),
1756
+ Item: yield* marshalOrFail(entityType, "EventStore.append", () => toAttributeMap(item)),
1688
1757
  ConditionExpression: "attribute_not_exists(pk)",
1689
1758
  // The first put of a writer one version behind a seal lands on
1690
1759
  // the sealing event: its item tells `StreamSealed` from a
@@ -1797,13 +1866,12 @@ export const makeStream = (config) => {
1797
1866
  };
1798
1867
  return parts;
1799
1868
  });
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.
1869
+ /**
1870
+ * The additional item a head proof names (#164), which must exist: checked
1871
+ * before anything is read, and ahead of the no-op fast path. Its shape is
1872
+ * checked first, by `buildAppend`'s own rule.
1873
+ */
1874
+ const headProofOp = (headProof, additionalOps) => Effect.gen(function* () {
1807
1875
  const proofOp = typeof headProof === "object" && headProofShapeProblem(headProof) === undefined
1808
1876
  ? headProof.additionalItem
1809
1877
  : undefined;
@@ -1816,11 +1884,18 @@ export const makeStream = (config) => {
1816
1884
  "Nothing was written.",
1817
1885
  });
1818
1886
  }
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;
1887
+ return proofOp;
1888
+ });
1889
+ /**
1890
+ * The append's one transaction, laid out — see {@link AppendTransaction}:
1891
+ * the caller's `additionalItems` compiled through the same builder
1892
+ * `Transaction.transactWrite` uses, so the two APIs cannot drift, and placed
1893
+ * among the stream's own items. `append` builds it for each attempt (a
1894
+ * guarded put among the additional items reads its item) and sends it;
1895
+ * `measureAppend` builds it once and measures it.
1896
+ */
1897
+ const buildAppendTransaction = (parts, additionalOps, expectedVersion, headProof, proofOp) => Effect.gen(function* () {
1898
+ const { tableName, contiguityCheck, eventItems, sentinelPut, snapshotPut } = parts;
1824
1899
  /**
1825
1900
  * Lay out the append's one transaction — see {@link AppendTransaction}:
1826
1901
  * [0, C) version-contiguity ConditionCheck — C is 0 or 1
@@ -1875,33 +1950,44 @@ export const makeStream = (config) => {
1875
1950
  headProof,
1876
1951
  };
1877
1952
  };
1953
+ // Caller-owned items, compiled through the same builder
1954
+ // `Transaction.transactWrite` uses, so the two APIs cannot drift.
1955
+ // Another stream's append (#166) is accepted here, and only here.
1956
+ const additional = yield* buildTransactWriteItems(additionalOps, "EventStore.append.additionalItems", { streams: true });
1957
+ // An item without a condition of its own proves nothing about the
1958
+ // head: accepting it would drop the gap protection silently. Nor
1959
+ // does another stream's append: its conditions are its stream's.
1960
+ if (proofOp !== undefined && !additional.conditioned.has(proofOp)) {
1961
+ const named = additionalOps[proofOp];
1962
+ return yield* new ValidationError({
1963
+ entityType,
1964
+ operation: "EventStore.append.headProof",
1965
+ cause: isStreamAppendOp(named)
1966
+ ? `headProof names additionalItems[${proofOp}], which is an append of stream ` +
1967
+ `"${named.streamName}" (appendOp): its conditions prove that stream's head, ` +
1968
+ "not this one's. Name an item conditioned on this stream being at " +
1969
+ "expectedVersion. Nothing was written."
1970
+ : `headProof names additionalItems[${proofOp}], which carries no condition of its ` +
1971
+ "own: the proof must be conditioned on the stream being at expectedVersion " +
1972
+ "(`.condition()`, `create()` or `Transaction.check`). Nothing was written.",
1973
+ });
1974
+ }
1975
+ return layout(additional);
1976
+ });
1977
+ const append = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1978
+ const additionalOps = options?.additionalItems ?? [];
1979
+ const idempotency = options?.idempotency;
1980
+ const headProof = options?.headProof;
1981
+ const proofOp = yield* headProofOp(headProof, additionalOps);
1982
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
1983
+ if (parts === undefined)
1984
+ return { version: expectedVersion, events: [] };
1985
+ const client = yield* Capacity.client;
1878
1986
  // A guarded put among the additional items reads its item; a race with
1879
1987
  // that read cancels the append, which is then built and written again.
1880
1988
  let lost;
1881
1989
  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);
1990
+ const tx = yield* buildAppendTransaction(parts, additionalOps, expectedVersion, headProof, proofOp);
1905
1991
  // DynamoDB's rules — one operation per item (an additional item
1906
1992
  // repeating an event, the contiguity check, the idempotency sentinel
1907
1993
  // or the inline snapshot, or another additional item), 100 items,
@@ -1909,7 +1995,7 @@ export const makeStream = (config) => {
1909
1995
  // `sendAppendTransaction` diagnoses DynamoDB's rejection (#144). The
1910
1996
  // items carry packed `data` / `state` as stored (#147), so the
1911
1997
  // diagnosis attributes stored bytes.
1912
- const outcome = yield* sendAppendTransaction(client, tx, streamIdStr, idempotency?.commandId);
1998
+ const outcome = yield* sendAppendTransaction(client, tx, parts.streamIdStr, idempotency?.commandId);
1913
1999
  if (outcome === undefined) {
1914
2000
  return { version: expectedVersion + events.length, events };
1915
2001
  }
@@ -1988,38 +2074,62 @@ export const makeStream = (config) => {
1988
2074
  // measureAppend / measureSnapshot — caller-side size planning (#147, R1)
1989
2075
  // ---------------------------------------------------------------------------
1990
2076
  const measureAppend = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1991
- if (options?.additionalItems !== undefined) {
2077
+ const additionalOps = options?.additionalItems;
2078
+ const headProof = options?.headProof;
2079
+ // A `{ additionalItem }` proof is checked against the additional items
2080
+ // when they are given, as `append` checks it. Without them it stands for
2081
+ // an item the caller adds, so the append is a transaction.
2082
+ const proofOp = additionalOps === undefined ? undefined : yield* headProofOp(headProof, additionalOps);
2083
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2084
+ if (parts === undefined) {
2085
+ return {
2086
+ events: [],
2087
+ sentinel: undefined,
2088
+ snapshot: undefined,
2089
+ transactionBytes: 0,
2090
+ requestBytes: 0,
2091
+ };
2092
+ }
2093
+ // The transaction `append` would send, built by the same code: the
2094
+ // stream's items and the items the caller's `additionalItems` build, in
2095
+ // the same places. Nothing is sent: an item `append` reads the table to
2096
+ // build has no size without that read, and fails the measurement.
2097
+ const built = yield* Capacity.withoutRequests(buildAppendTransaction(parts, additionalOps ?? [], expectedVersion, headProof, proofOp));
2098
+ if (built.refused !== undefined) {
2099
+ const { command, input } = built.refused;
1992
2100
  return yield* new ValidationError({
1993
2101
  entityType,
1994
2102
  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.",
2103
+ cause: `an additional item is built from the stored row: append would send ${command}` +
2104
+ (typeof input.TableName === "string" ? ` on table "${input.TableName}"` : "") +
2105
+ " to build it (a put of a versioned or unique-constrained entity, or a create " +
2106
+ "over a projection tombstone, reads its item). measureAppend sends no request, " +
2107
+ "so it has no size to give for this append. Nothing was read or written.",
1998
2108
  });
1999
2109
  }
2000
- const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2001
- if (parts === undefined) {
2002
- return { events: [], sentinel: undefined, snapshot: undefined, transactionBytes: 0 };
2110
+ if (Exit.isFailure(built.exit)) {
2111
+ // No request was refused, so nothing here is a client error.
2112
+ return yield* Effect.failCause(built.exit.cause);
2003
2113
  }
2114
+ const tx = built.exit.value;
2115
+ // An append of one event and nothing else is sent as a `PutItem`
2116
+ // carrying a write token (#173), measured here with a placeholder token
2117
+ // of its length.
2118
+ const single = typeof headProof !== "object" && isSingleEventPut(tx.items, tx.eventCount);
2119
+ const sent = single
2120
+ ? [withWriteToken(tx.items[0], "0".repeat(WRITE_TOKEN_LENGTH))]
2121
+ : tx.items;
2004
2122
  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;
2123
+ // What the client sends beside the items: the request as `append` sends it.
2124
+ const fields = yield* Capacity.requestFields;
2018
2125
  const measurement = {
2019
- events: eventItems.map(putBytes),
2126
+ events: (single ? sent : parts.eventItems).map(putBytes),
2020
2127
  sentinel: parts.sentinelPut === undefined ? undefined : putBytes(parts.sentinelPut),
2021
2128
  snapshot: parts.snapshotPut === undefined ? undefined : putBytes(parts.snapshotPut),
2022
- transactionBytes: owned.reduce((sum, item) => sum + transactItemBytes(item), 0),
2129
+ transactionBytes: sent.reduce((sum, item) => sum + transactItemBytes(item), 0),
2130
+ requestBytes: single
2131
+ ? jsonBytes({ ...sent[0].Put, ...fields })
2132
+ : transactWriteBodyBytes({ TransactItems: sent, ...fields }),
2023
2133
  };
2024
2134
  return measurement;
2025
2135
  });
@@ -2164,7 +2274,7 @@ export const makeStream = (config) => {
2164
2274
  // `stateDispatch` — then decoded through the state schema as before.
2165
2275
  (stateDispatch && (typeof raw.state === "string" || raw.state instanceof Uint8Array)
2166
2276
  ? 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) => ({
2277
+ : Effect.succeed(raw.state)).pipe(Effect.flatMap((state) => decodeSnapshotState(state).pipe(Effect.mapError((cause) => new ValidationError({ entityType: snapshotEntityType, operation, cause })))), Effect.map((state) => ({
2168
2278
  state,
2169
2279
  asOfVersion: raw.asOfVersion,
2170
2280
  timestamp: raw.timestamp,
@@ -2682,6 +2792,7 @@ export const makeStream = (config) => {
2682
2792
  const client = yield* Capacity.client;
2683
2793
  const firstSk = composeEventSk(1);
2684
2794
  const nowSeconds = DateTime.toEpochSeconds(yield* DateTime.now);
2795
+ const unprovable = Rekey.unprovableRow(ctx);
2685
2796
  const live = (row) => {
2686
2797
  const ttl = row[ttlAttribute]?.N;
2687
2798
  return ttl === undefined || Number(ttl) > nowSeconds;
@@ -2757,12 +2868,31 @@ export const makeStream = (config) => {
2757
2868
  }),
2758
2869
  })
2759
2870
  .pipe(Effect.as(true), Effect.catch(cancelled));
2760
- /** Delete `row` at `from` while it is as read. `false` when a write changed it. */
2871
+ /**
2872
+ * `row` as read, whole, or, a row too wide for that, the strongest guard that fits, as
2873
+ * 1.39.0 sent: only a stream already part-moved deletes one (`unguardedRows`).
2874
+ */
2875
+ const guardOfRow = (row) => wholeRowGuard(row, "pk", [], [], []) ?? asReadGuard(row, "pk", []);
2876
+ /**
2877
+ * With writes going on (`unprovable`), the rows of a stream nothing of which has moved that
2878
+ * are too wide to guard whole, each reported `unguarded`, before anything is copied: its rows
2879
+ * move together, so one leaves the stream as it is. One already part-moved (a row of it under
2880
+ * `to`, or flipped) is finished under the strongest guard that fits (`guardOfRow`).
2881
+ */
2882
+ const unguardedRows = (rows) => {
2883
+ if (unprovable === "strongest")
2884
+ return undefined;
2885
+ const unguarded = rows.filter((row) => wholeRowGuard(row, "pk", [], [], []) === undefined);
2886
+ if (unguarded.length === 0)
2887
+ return undefined;
2888
+ return Rekey.mergeTallies(...unguarded.map((row) => conflict("unguarded", `${Rekey.UNGUARDED_MESSAGE} The stream's other rows are left with it.`, skOf(row))));
2889
+ };
2890
+ /** Delete `row` at `from` while it is as read (`guardOfRow`). `false` when a write changed it. */
2761
2891
  const remove = (row) => client
2762
2892
  .deleteItem({
2763
2893
  TableName: ctx.tableName,
2764
2894
  Key: toAttributeMap({ pk: from, sk: skOf(row) }),
2765
- ...asReadGuard(row, "pk", []),
2895
+ ...guardOfRow(row),
2766
2896
  })
2767
2897
  .pipe(Effect.as(true), Effect.catch(cancelled));
2768
2898
  /**
@@ -2825,6 +2955,12 @@ export const makeStream = (config) => {
2825
2955
  const flipped = first === undefined || first[MOVED_ATTRIBUTE] !== undefined;
2826
2956
  if (!flipped) {
2827
2957
  const atTarget = yield* readAll(to);
2958
+ // Nothing of it has moved while no row of it is under `to` (`unguardedRows`).
2959
+ if (!atTarget.some((row) => !elsewhere(row))) {
2960
+ const refused = unguardedRows(rows);
2961
+ if (refused !== undefined)
2962
+ return Rekey.mergeTallies(tally, refused);
2963
+ }
2828
2964
  // Another stream under other key text moves out first.
2829
2965
  const stale = atTarget.find(elsewhere);
2830
2966
  if (stale !== undefined) {