effect-dynamodb 1.42.2 → 1.44.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 (221) hide show
  1. package/dist/Aggregate.d.ts +157 -20
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +1219 -286
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +17 -4
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +129 -62
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/BlobGc.d.ts +243 -0
  10. package/dist/BlobGc.d.ts.map +1 -0
  11. package/dist/BlobGc.js +961 -0
  12. package/dist/BlobGc.js.map +1 -0
  13. package/dist/BlobStore.d.ts +83 -0
  14. package/dist/BlobStore.d.ts.map +1 -0
  15. package/dist/BlobStore.js +70 -0
  16. package/dist/BlobStore.js.map +1 -0
  17. package/dist/Collection.d.ts +88 -8
  18. package/dist/Collection.d.ts.map +1 -1
  19. package/dist/Collection.js +22 -26
  20. package/dist/Collection.js.map +1 -1
  21. package/dist/Collections.d.ts +0 -7
  22. package/dist/Collections.d.ts.map +1 -1
  23. package/dist/Collections.js +0 -16
  24. package/dist/Collections.js.map +1 -1
  25. package/dist/DynamoClient.d.ts +68 -35
  26. package/dist/DynamoClient.d.ts.map +1 -1
  27. package/dist/DynamoClient.js +58 -12
  28. package/dist/DynamoClient.js.map +1 -1
  29. package/dist/Entity.d.ts +403 -104
  30. package/dist/Entity.d.ts.map +1 -1
  31. package/dist/Entity.js +1771 -382
  32. package/dist/Entity.js.map +1 -1
  33. package/dist/EventStore.d.ts +323 -77
  34. package/dist/EventStore.d.ts.map +1 -1
  35. package/dist/EventStore.js +473 -96
  36. package/dist/EventStore.js.map +1 -1
  37. package/dist/Offload.d.ts +199 -0
  38. package/dist/Offload.d.ts.map +1 -0
  39. package/dist/Offload.js +120 -0
  40. package/dist/Offload.js.map +1 -0
  41. package/dist/Query.d.ts +132 -59
  42. package/dist/Query.d.ts.map +1 -1
  43. package/dist/Query.js +95 -31
  44. package/dist/Query.js.map +1 -1
  45. package/dist/StorageEncoding.d.ts +62 -15
  46. package/dist/StorageEncoding.d.ts.map +1 -1
  47. package/dist/StorageEncoding.js +108 -24
  48. package/dist/StorageEncoding.js.map +1 -1
  49. package/dist/Table.d.ts +1 -1
  50. package/dist/Table.d.ts.map +1 -1
  51. package/dist/Transaction.d.ts +16 -3
  52. package/dist/Transaction.d.ts.map +1 -1
  53. package/dist/Transaction.js +28 -9
  54. package/dist/Transaction.js.map +1 -1
  55. package/dist/blob/S3BlobStore.d.ts +178 -0
  56. package/dist/blob/S3BlobStore.d.ts.map +1 -0
  57. package/dist/blob/S3BlobStore.js +770 -0
  58. package/dist/blob/S3BlobStore.js.map +1 -0
  59. package/dist/blob/s3.d.ts +122 -0
  60. package/dist/blob/s3.d.ts.map +1 -0
  61. package/dist/blob/s3.js +143 -0
  62. package/dist/blob/s3.js.map +1 -0
  63. package/dist/index.d.ts +9 -3
  64. package/dist/index.d.ts.map +1 -1
  65. package/dist/index.js +4 -1
  66. package/dist/index.js.map +1 -1
  67. package/dist/internal/AggregateWrite.d.ts +130 -0
  68. package/dist/internal/AggregateWrite.d.ts.map +1 -0
  69. package/dist/internal/AggregateWrite.js +341 -0
  70. package/dist/internal/AggregateWrite.js.map +1 -0
  71. package/dist/internal/BlobCalls.d.ts +70 -0
  72. package/dist/internal/BlobCalls.d.ts.map +1 -0
  73. package/dist/internal/BlobCalls.js +105 -0
  74. package/dist/internal/BlobCalls.js.map +1 -0
  75. package/dist/internal/BlobKeys.d.ts +100 -0
  76. package/dist/internal/BlobKeys.d.ts.map +1 -0
  77. package/dist/internal/BlobKeys.js +135 -0
  78. package/dist/internal/BlobKeys.js.map +1 -0
  79. package/dist/internal/BlobLedger.d.ts +323 -0
  80. package/dist/internal/BlobLedger.d.ts.map +1 -0
  81. package/dist/internal/BlobLedger.js +1012 -0
  82. package/dist/internal/BlobLedger.js.map +1 -0
  83. package/dist/internal/BlobMetadata.d.ts +109 -0
  84. package/dist/internal/BlobMetadata.d.ts.map +1 -0
  85. package/dist/internal/BlobMetadata.js +249 -0
  86. package/dist/internal/BlobMetadata.js.map +1 -0
  87. package/dist/internal/BlobResolver.d.ts +146 -0
  88. package/dist/internal/BlobResolver.d.ts.map +1 -0
  89. package/dist/internal/BlobResolver.js +417 -0
  90. package/dist/internal/BlobResolver.js.map +1 -0
  91. package/dist/internal/BlobStoreContract.d.ts +214 -0
  92. package/dist/internal/BlobStoreContract.d.ts.map +1 -0
  93. package/dist/internal/BlobStoreContract.js +181 -0
  94. package/dist/internal/BlobStoreContract.js.map +1 -0
  95. package/dist/internal/BoundCrud.d.ts +153 -53
  96. package/dist/internal/BoundCrud.d.ts.map +1 -1
  97. package/dist/internal/BoundCrud.js +27 -5
  98. package/dist/internal/BoundCrud.js.map +1 -1
  99. package/dist/internal/BoundQuery.d.ts +49 -33
  100. package/dist/internal/BoundQuery.d.ts.map +1 -1
  101. package/dist/internal/BoundQuery.js +8 -2
  102. package/dist/internal/BoundQuery.js.map +1 -1
  103. package/dist/internal/BoundVectorQuery.d.ts +59 -25
  104. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  105. package/dist/internal/BoundVectorQuery.js +38 -17
  106. package/dist/internal/BoundVectorQuery.js.map +1 -1
  107. package/dist/internal/Capacity.d.ts +17 -2
  108. package/dist/internal/Capacity.d.ts.map +1 -1
  109. package/dist/internal/Capacity.js +47 -9
  110. package/dist/internal/Capacity.js.map +1 -1
  111. package/dist/internal/ConditionHolds.d.ts.map +1 -1
  112. package/dist/internal/ConditionHolds.js +2 -8
  113. package/dist/internal/ConditionHolds.js.map +1 -1
  114. package/dist/internal/CredentialRefusal.d.ts.map +1 -1
  115. package/dist/internal/CredentialRefusal.js +4 -0
  116. package/dist/internal/CredentialRefusal.js.map +1 -1
  117. package/dist/internal/Digest.d.ts +4 -3
  118. package/dist/internal/Digest.d.ts.map +1 -1
  119. package/dist/internal/Digest.js +25 -82
  120. package/dist/internal/Digest.js.map +1 -1
  121. package/dist/internal/EntityCombinators.d.ts +93 -45
  122. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  123. package/dist/internal/EntityCombinators.js +42 -7
  124. package/dist/internal/EntityCombinators.js.map +1 -1
  125. package/dist/internal/EntityOps.d.ts +47 -6
  126. package/dist/internal/EntityOps.d.ts.map +1 -1
  127. package/dist/internal/EntityOps.js +30 -10
  128. package/dist/internal/EntityOps.js.map +1 -1
  129. package/dist/internal/EventProjection.d.ts +99 -25
  130. package/dist/internal/EventProjection.d.ts.map +1 -1
  131. package/dist/internal/EventProjection.js +124 -33
  132. package/dist/internal/EventProjection.js.map +1 -1
  133. package/dist/internal/ExpressionLimits.d.ts +22 -3
  134. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  135. package/dist/internal/ExpressionLimits.js +46 -7
  136. package/dist/internal/ExpressionLimits.js.map +1 -1
  137. package/dist/internal/GcSupport.d.ts +258 -0
  138. package/dist/internal/GcSupport.d.ts.map +1 -0
  139. package/dist/internal/GcSupport.js +284 -0
  140. package/dist/internal/GcSupport.js.map +1 -0
  141. package/dist/internal/ItemSize.d.ts +7 -1
  142. package/dist/internal/ItemSize.d.ts.map +1 -1
  143. package/dist/internal/ItemSize.js +13 -5
  144. package/dist/internal/ItemSize.js.map +1 -1
  145. package/dist/internal/MemoryBlobStore.d.ts +203 -0
  146. package/dist/internal/MemoryBlobStore.d.ts.map +1 -0
  147. package/dist/internal/MemoryBlobStore.js +623 -0
  148. package/dist/internal/MemoryBlobStore.js.map +1 -0
  149. package/dist/internal/MultiProjection.d.ts +56 -28
  150. package/dist/internal/MultiProjection.d.ts.map +1 -1
  151. package/dist/internal/MultiProjection.js +9 -3
  152. package/dist/internal/MultiProjection.js.map +1 -1
  153. package/dist/internal/Multipart.d.ts +96 -0
  154. package/dist/internal/Multipart.d.ts.map +1 -0
  155. package/dist/internal/Multipart.js +143 -0
  156. package/dist/internal/Multipart.js.map +1 -0
  157. package/dist/internal/OffloadChange.d.ts +187 -0
  158. package/dist/internal/OffloadChange.d.ts.map +1 -0
  159. package/dist/internal/OffloadChange.js +391 -0
  160. package/dist/internal/OffloadChange.js.map +1 -0
  161. package/dist/internal/OffloadInput.d.ts +141 -0
  162. package/dist/internal/OffloadInput.d.ts.map +1 -0
  163. package/dist/internal/OffloadInput.js +236 -0
  164. package/dist/internal/OffloadInput.js.map +1 -0
  165. package/dist/internal/OffloadRead.d.ts +140 -0
  166. package/dist/internal/OffloadRead.d.ts.map +1 -0
  167. package/dist/internal/OffloadRead.js +369 -0
  168. package/dist/internal/OffloadRead.js.map +1 -0
  169. package/dist/internal/OffloadTypes.d.ts +182 -0
  170. package/dist/internal/OffloadTypes.d.ts.map +1 -0
  171. package/dist/internal/OffloadTypes.js +15 -0
  172. package/dist/internal/OffloadTypes.js.map +1 -0
  173. package/dist/internal/OffloadValues.d.ts +87 -0
  174. package/dist/internal/OffloadValues.d.ts.map +1 -0
  175. package/dist/internal/OffloadValues.js +114 -0
  176. package/dist/internal/OffloadValues.js.map +1 -0
  177. package/dist/internal/OffloadWrite.d.ts +267 -0
  178. package/dist/internal/OffloadWrite.d.ts.map +1 -0
  179. package/dist/internal/OffloadWrite.js +766 -0
  180. package/dist/internal/OffloadWrite.js.map +1 -0
  181. package/dist/internal/Packed.d.ts +58 -23
  182. package/dist/internal/Packed.d.ts.map +1 -1
  183. package/dist/internal/Packed.js +108 -33
  184. package/dist/internal/Packed.js.map +1 -1
  185. package/dist/internal/ProjectionEngine.d.ts +28 -3
  186. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  187. package/dist/internal/ProjectionEngine.js +47 -9
  188. package/dist/internal/ProjectionEngine.js.map +1 -1
  189. package/dist/internal/RangePlanner.d.ts +3 -6
  190. package/dist/internal/RangePlanner.d.ts.map +1 -1
  191. package/dist/internal/RangePlanner.js +3 -29
  192. package/dist/internal/RangePlanner.js.map +1 -1
  193. package/dist/internal/Rekey.d.ts +16 -0
  194. package/dist/internal/Rekey.d.ts.map +1 -1
  195. package/dist/internal/Rekey.js +31 -2
  196. package/dist/internal/Rekey.js.map +1 -1
  197. package/dist/internal/StoredPointer.d.ts +19 -0
  198. package/dist/internal/StoredPointer.d.ts.map +1 -0
  199. package/dist/internal/StoredPointer.js +59 -0
  200. package/dist/internal/StoredPointer.js.map +1 -0
  201. package/dist/internal/TransactPlan.d.ts +18 -1
  202. package/dist/internal/TransactPlan.d.ts.map +1 -1
  203. package/dist/internal/TransactPlan.js +50 -10
  204. package/dist/internal/TransactPlan.js.map +1 -1
  205. package/dist/internal/TransactWriteOps.d.ts +33 -12
  206. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  207. package/dist/internal/TransactWriteOps.js +49 -19
  208. package/dist/internal/TransactWriteOps.js.map +1 -1
  209. package/dist/internal/TransactableOps.d.ts +58 -11
  210. package/dist/internal/TransactableOps.d.ts.map +1 -1
  211. package/dist/internal/TransactableOps.js +95 -19
  212. package/dist/internal/TransactableOps.js.map +1 -1
  213. package/dist/internal/Utf8Order.d.ts +21 -0
  214. package/dist/internal/Utf8Order.d.ts.map +1 -0
  215. package/dist/internal/Utf8Order.js +44 -0
  216. package/dist/internal/Utf8Order.js.map +1 -0
  217. package/dist/internal/WriteDiagnosis.d.ts +7 -1
  218. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  219. package/dist/internal/WriteDiagnosis.js +12 -16
  220. package/dist/internal/WriteDiagnosis.js.map +1 -1
  221. package/package.json +15 -4
@@ -45,26 +45,34 @@
45
45
  * DynamoClient, Marshaller).
46
46
  */
47
47
  import { Compression } from "@effect-dynamodb/schema/Compression.js";
48
- import { isPackedConfig } from "@effect-dynamodb/schema/DynamoModel.js";
48
+ import { isExternalConfig, 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 { resolveOffloadOptions } from "@effect-dynamodb/schema/internal/EntityOffload.js";
52
53
  import { readingStreamValues, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
53
54
  import { decodingAsBefore } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
54
55
  import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
55
56
  import { classOf, setOwn } from "@effect-dynamodb/schema/internal/OwnNames.js";
56
- import { isDispatchEligible, packedShape, packValue, unpackStoredSync, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
57
+ import { isDispatchEligible, packedShape, packValue, } from "@effect-dynamodb/schema/internal/PackedCodec.js";
57
58
  import { refuseUnreadable } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
58
59
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
59
- import { Context, DateTime, Effect, Exit, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
60
+ import { Cause, Context, DateTime, Effect, Exit, Function, Option, Pipeable, Result, Schedule, Schema, } from "effect";
61
+ import { BlobStore } from "./BlobStore.js";
60
62
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
63
+ import { STREAM_FAMILY_SK } from "./internal/BlobKeys.js";
64
+ import * as BlobLedger from "./internal/BlobLedger.js";
61
65
  import * as Capacity from "./internal/Capacity.js";
62
66
  import { ProjectionRoutes } from "./internal/EventProjection.js";
63
67
  import { eq } from "./internal/Expr.js";
64
68
  import { asReadGuard, wholeRowGuard } from "./internal/ExpressionLimits.js";
69
+ import * as GcSupport from "./internal/GcSupport.js";
65
70
  import { itemBytes, jsonBytes, transactItemBytes, transactWriteBodyBytes, } from "./internal/ItemSize.js";
66
71
  import { isMultiProjection, } from "./internal/MultiProjection.js";
67
- import { codecRequirements, currentRegistry, decodeImage, imageEntityType, runtimeCodecCheck, unregisteredCodecError, withRegistry, } from "./internal/Packed.js";
72
+ import * as OffloadRead from "./internal/OffloadRead.js";
73
+ import { isOffloadedValue, makeOffloadedValue, } from "./internal/OffloadValues.js";
74
+ import * as OffloadWrite from "./internal/OffloadWrite.js";
75
+ import { codecRequirements, currentRegistry, imageEntityType, imageForm, normalizeImage, runtimeCodecCheck, unregisteredCodecError, } from "./internal/Packed.js";
68
76
  import { createPathBuilder } from "./internal/PathBuilder.js";
69
77
  import * as Rekey from "./internal/Rekey.js";
70
78
  import { notReadBack, readBackOf } from "./internal/RoundTrip.js";
@@ -88,6 +96,42 @@ const streamCodecRequirements = (streamName, storedAs) => codecRequirements(`str
88
96
  ["data", storedAs.data],
89
97
  ["state", storedAs.state],
90
98
  ]);
99
+ /**
100
+ * The store requirement of a stream that offloads: `[EDD-9146]` on a table
101
+ * whose schema doesn't set `escapeKeys: true`, `[EDD-9115]` when no store is
102
+ * resolvable.
103
+ */
104
+ const streamStoreRequirements = (streamName, offload, escapeKeys) => offload === undefined
105
+ ? []
106
+ : [{ owner: `stream "${streamName}"`, fields: offload.overflow, escapeKeys }];
107
+ /**
108
+ * @internal The store requirements of a stream, bound or not (`[EDD-9146]`,
109
+ * `[EDD-9115]`): checked by {@link bind}, `bindProjection` and the streams a
110
+ * table's `rekey` is given.
111
+ */
112
+ export const storeRequirementsOf = (stream) => stream
113
+ ._storeRequirements ?? streamStoreRequirements(stream.streamName, stream.offload, undefined);
114
+ /**
115
+ * The first-use store check of an unbound stream that offloads (design §13,
116
+ * the `runtimeCodecCheck` pattern): the first operation run with a given
117
+ * store passes it, and one run with no store in context dies with
118
+ * `[EDD-9115]`. `undefined` for a stream that offloads nothing.
119
+ */
120
+ const runtimeStoreCheck = (where, requirements) => {
121
+ if (requirements.length === 0)
122
+ return undefined;
123
+ const passed = new WeakSet();
124
+ return Effect.withFiber((fiber) => {
125
+ const store = Context.getOrUndefined(fiber.context, BlobStore);
126
+ if (store !== undefined && passed.has(store))
127
+ return Effect.void;
128
+ const error = OffloadWrite.missingStoreError(where, requirements, store);
129
+ if (error !== undefined)
130
+ return Effect.die(error);
131
+ passed.add(store);
132
+ return Effect.void;
133
+ });
134
+ };
91
135
  /** The attributes a stream image reads by stored form: event `data` only. */
92
136
  const DATA_ATTRIBUTES = ["data"];
93
137
  /**
@@ -116,6 +160,8 @@ const EventEnvelope = Schema.Struct({
116
160
  eventType: Schema.String,
117
161
  timestamp: Schema.String,
118
162
  });
163
+ /** @internal A `Packed({ external })` config: one whose values may be offloaded. */
164
+ const isOffloadingConfig = (storedAs) => storedAs !== undefined && storedAs.external !== undefined;
119
165
  /**
120
166
  * @internal Why a {@link ReadIndexOptions} key condition cannot be sent, or
121
167
  * `undefined` when it can: the options' own meaning — at most one of
@@ -492,9 +538,12 @@ const resolveStreamStorage = (streamName, storedAs, snapshot) => {
492
538
  };
493
539
  const describe = (value) => value === null
494
540
  ? "null"
495
- : typeof value === "object"
496
- ? "an object that is not a DynamoModel.Packed(...) config"
497
- : `${typeof value} ${JSON.stringify(value)}`;
541
+ : isExternalConfig(value)
542
+ ? "a DynamoModel.External(...) config, which stores a binary entity field — offload " +
543
+ "event data or snapshot state with DynamoModel.Packed({ external })"
544
+ : typeof value === "object"
545
+ ? "an object that is not a DynamoModel.Packed(...) config"
546
+ : `${typeof value} ${JSON.stringify(value)}`;
498
547
  let data;
499
548
  if (storedAs !== undefined) {
500
549
  if (typeof storedAs !== "object" || storedAs === null || Array.isArray(storedAs)) {
@@ -817,6 +866,11 @@ const eventTimestampsProblem = (timestamps, count, label, events) => {
817
866
  * value is not a `DynamoModel.Packed(...)` config.
818
867
  * @throws `[EDD-9073]` when `snapshot.storedAs` is set and the state schema's
819
868
  * encoded side is not object- or array-shaped.
869
+ * @throws `[EDD-9114]` for invalid `offload` options: an unknown key, an
870
+ * `itemBudget` that is not a safe integer in 1 … 409,600, a `prefix` that is
871
+ * not a non-empty string of RFC 3986 unreserved characters and `/` of at
872
+ * most 256 bytes (not starting with `/`), or `offload` on a stream whose
873
+ * `data` and snapshot `state` are not `DynamoModel.Packed({ external })`.
820
874
  *
821
875
  * `storedAs: { data: DynamoModel.Packed(...) }` stores event `data` packed, and
822
876
  * `snapshot.storedAs` the snapshot `state` — see {@link StreamStorageConfig}.
@@ -902,6 +956,38 @@ export const makeStream = (config) => {
902
956
  const dataStoredAs = storage.data;
903
957
  /** Snapshot `state` packing, or `undefined` for the native map. */
904
958
  const stateStoredAs = storage.state;
959
+ // Offloaded storage (#179): `offload` options (EDD-9114), and what the
960
+ // stream sends to the blob store — event `data` and snapshot `state` when
961
+ // `DynamoModel.Packed({ external })`.
962
+ const offloadedKinds = [
963
+ ...(isOffloadingConfig(dataStoredAs) ? ["data"] : []),
964
+ ...(isOffloadingConfig(stateStoredAs) ? ["state"] : []),
965
+ ];
966
+ const offloadOptions = resolveOffloadOptions(`EventStream "${config.streamName}"`, config.offload, { overflow: offloadedKinds.length > 0, offloaded: offloadedKinds.length > 0 });
967
+ const offloadSettings = offloadedKinds.length === 0
968
+ ? undefined
969
+ : {
970
+ itemBudget: offloadOptions.itemBudget,
971
+ prefix: offloadOptions.prefix,
972
+ overflow: offloadedKinds,
973
+ };
974
+ /**
975
+ * How an event item's / a snapshot item's offloaded attribute is routed
976
+ * (design §6.10): the stream's objects are keyed per item under the stream
977
+ * family (§4.5), and its rows never copy pointers (`copiesPointers: false`
978
+ * — an `ALL_OLD` image without the pointer proves a write did not commit).
979
+ */
980
+ const streamOffloadInfo = (attribute, storedAs, owner) => !isOffloadingConfig(storedAs)
981
+ ? undefined
982
+ : {
983
+ entityType: owner,
984
+ overflow: { [attribute]: storedAs },
985
+ binary: {},
986
+ fieldOf: { [attribute]: attribute },
987
+ itemBudget: offloadOptions.itemBudget,
988
+ prefix: offloadOptions.prefix,
989
+ copiesPointers: false,
990
+ };
905
991
  /**
906
992
  * Whether a snapshot's stored `state` is read by its stored form: when it is
907
993
  * configured packed, or when its schema's encoded side is object- or
@@ -909,6 +995,43 @@ export const makeStream = (config) => {
909
995
  * turned packing off still reads its packed snapshot.
910
996
  */
911
997
  const stateDispatch = snapshot !== undefined && (stateStoredAs !== undefined || isDispatchEligible(snapshot.schema));
998
+ /** The routing of an event item's offloaded `data`, or `undefined` (#179). */
999
+ const eventOffload = streamOffloadInfo("data", dataStoredAs, entityType);
1000
+ /** The routing of a snapshot item's offloaded `state`, or `undefined` (#179). */
1001
+ const snapshotOffload = streamOffloadInfo("state", stateStoredAs, snapshotEntityType);
1002
+ /**
1003
+ * How an event row is read (#179): `data` by its stored form — a native
1004
+ * map as it is, a JSON string parsed, compressed binary decompressed and
1005
+ * parsed — and, when it is a blob pointer, resolved per the read's modes.
1006
+ * Rows are always loaded raw (`data` stays its wire form, a lazy value
1007
+ * reads the wire form): the event schema decodes it afterwards.
1008
+ */
1009
+ const eventPlan = {
1010
+ entityType,
1011
+ dispatch: DATA_ATTRIBUTES,
1012
+ binary: [],
1013
+ offloaded: eventOffload === undefined ? {} : { data: "overflow" },
1014
+ fieldOf: { data: "data" },
1015
+ contentTypeOf: {},
1016
+ decodeField: (_field, wire) => Effect.succeed(wire),
1017
+ };
1018
+ /** How a snapshot row is read: `state` by its stored form when it may be packed. */
1019
+ const snapshotPlan = {
1020
+ entityType: snapshotEntityType,
1021
+ dispatch: stateDispatch ? ["state"] : [],
1022
+ binary: [],
1023
+ offloaded: snapshotOffload === undefined ? {} : { state: "overflow" },
1024
+ fieldOf: { state: "state" },
1025
+ contentTypeOf: {},
1026
+ decodeField: (_field, wire) => Effect.succeed(wire),
1027
+ };
1028
+ /**
1029
+ * An unbound stream that offloads checks on its first operation per store
1030
+ * that one is in context (`[EDD-9115]`, a defect, design §13): it meets
1031
+ * pointers on every read and needs the store on every write. `bind`
1032
+ * checks the context it captures up front instead.
1033
+ */
1034
+ const storeCheck = runtimeStoreCheck(`EventStore (first use of stream "${config.streamName}")`, streamStoreRequirements(config.streamName, offloadSettings, schema.escapeKeys === true));
912
1035
  /**
913
1036
  * The first operation run with a given compressor registry checks that it
914
1037
  * has every codec `storedAs` names (`[EDD-9078]`, a defect): the stream
@@ -916,13 +1039,24 @@ export const makeStream = (config) => {
916
1039
  * the registry it captures up front instead.
917
1040
  */
918
1041
  const codecCheck = runtimeCodecCheck(`EventStore (first use of stream "${config.streamName}")`, streamCodecRequirements(config.streamName, storage));
919
- const checked = (op) => codecCheck === undefined ? op : (...args) => Effect.andThen(codecCheck, op(...args));
1042
+ const firstUseCheck = codecCheck === undefined
1043
+ ? storeCheck
1044
+ : storeCheck === undefined
1045
+ ? codecCheck
1046
+ : Effect.andThen(codecCheck, storeCheck);
1047
+ const checked = (op) => firstUseCheck === undefined ? op : (...args) => Effect.andThen(firstUseCheck, op(...args));
920
1048
  /**
921
1049
  * A stream method as a named operation for consumed-capacity reports
922
1050
  * (#174). Internal compositions call the unwrapped closures, so only the
923
1051
  * public method opens a scope.
924
1052
  */
925
1053
  const named = (name, op) => (...args) => Capacity.operation(`EventStream.${name}`, { target: config.streamName }, op(...args));
1054
+ /**
1055
+ * A writing stream method as an upload-ledger root (#179): the uploads of
1056
+ * one call settle by the request that carries them, and are rolled back at
1057
+ * exit when DynamoDB provably did not commit it.
1058
+ */
1059
+ const rooted = (op) => (...args) => BlobLedger.root(op(...args));
926
1060
  /** The `[EDD-9076]` guard for queries of a stream whose `data` is packed. */
927
1061
  const dataGuards = dataStoredAs === undefined
928
1062
  ? []
@@ -1073,39 +1207,55 @@ export const makeStream = (config) => {
1073
1207
  const decodeMetadata = decodingStream(metadataSchema ?? Schema.Unknown);
1074
1208
  const decodeSnapshotState = decodingStream(snapshot?.schema ?? Schema.Unknown);
1075
1209
  /**
1076
- * An event's stored `data` → its wire form (plain JSON), by the stored
1077
- * form. A native value costs one `typeof` check.
1210
+ * Load event rows in place (#179, design §8.2): every `data` read by its
1211
+ * stored form to its wire form (plain JSON) — whatever its stored form (R3:
1212
+ * a stream that switched encoding holds a mix) — and an offloaded one
1213
+ * resolved per `modes`: fetched (eager) or an `OffloadedValue` of its wire
1214
+ * form (lazy). Rows already loaded (a query's page prefetch) are skipped; a
1215
+ * native value costs one `typeof` check.
1078
1216
  */
1079
- const unpackData = (stored, operation) => typeof stored === "string" || stored instanceof Uint8Array
1080
- ? withRegistry((registry) => unpackStoredSync(stored, registry, { entityType, operation }, "data"))
1081
- : Effect.succeed(stored);
1217
+ const loadEventRows = (rows, modes, operation, image = false) => OffloadRead.loadRows(eventPlan, rows, { operation, modes, raw: true, image });
1082
1218
  /**
1083
1219
  * A raw event row (`Query.select`) with its `data` — when projected — as
1084
- * plain parsed JSON, whatever its stored form (R3: a stream that switched
1085
- * encoding holds a mix). Never schema-decoded. Only this stream's event
1220
+ * plain parsed JSON, whatever its stored form, or (lazy, #179) an
1221
+ * `OffloadedValue` of it. Never schema-decoded. Only this stream's event
1086
1222
  * rows are read: a row of another type (`Query.ignoreOwnership`) is handed
1087
1223
  * back untouched, its `__edd_e__` borrowed for the check and stripped again.
1088
1224
  * In place, so the strip reaches the row returned.
1089
1225
  */
1090
- const rawEventRow = Object.assign((raw) => {
1091
- const stored = raw.data;
1092
- if (raw.__edd_e__ !== entityType)
1093
- return Effect.succeed(raw);
1094
- if (typeof stored !== "string" && !(stored instanceof Uint8Array))
1095
- return Effect.succeed(raw);
1096
- return Effect.map(unpackData(stored, "EventStore.select"), (data) => {
1097
- raw.data = data;
1098
- return raw;
1099
- });
1100
- }, { reads: ["__edd_e__"], attributes: ["data"] });
1101
- const decodeStreamEvent = (raw) => Effect.gen(function* () {
1226
+ const rawEventRow = Object.assign((raw, modes) => raw.__edd_e__ !== entityType
1227
+ ? Effect.succeed(raw)
1228
+ : Effect.as(loadEventRows([raw], modes, "EventStore.select"), raw), { reads: ["__edd_e__"], attributes: ["data"] });
1229
+ /** Decode an event's wire `data` through the event schemas. */
1230
+ const decodeEventValue = (wire) => decodeEventData(wire).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: "EventStore.decode", cause })));
1231
+ /**
1232
+ * The lazy `data` of an event (#179, design §10.2): the loaded value of its
1233
+ * wire form, decoded through the event schemas on each `read()`.
1234
+ */
1235
+ const lazyEventData = (wire) => makeOffloadedValue({
1236
+ location: wire.location,
1237
+ ref: wire.ref,
1238
+ size: wire.size,
1239
+ checksum: wire.checksum,
1240
+ read: () => Effect.flatMap(wire.read(), (value) => decodeEventValue(value)),
1241
+ });
1242
+ /**
1243
+ * Decode a raw event row into a {@link StreamEvent}: the envelope first,
1244
+ * then `data` loaded per `modes` (see {@link loadEventRows}) and decoded —
1245
+ * lazily, as a {@link LazyStreamEvent}, when it was loaded lazily.
1246
+ */
1247
+ const decodeStreamEvent = (raw, modes = OffloadRead.EAGER_MODES) => Effect.gen(function* () {
1102
1248
  const toValidationError = (operation) => (cause) => new ValidationError({ entityType, operation, cause });
1103
1249
  const envelope = yield* decodeEnvelope(raw).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1104
1250
  // `data` is read by its stored form (#147): a native map as it is, a
1105
1251
  // JSON string (`S`) parsed, compressed binary (`B`) decompressed and
1106
- // parsed — whatever the stream's current `storedAs` says.
1107
- const wireData = yield* unpackData(raw.data, "EventStore.decode");
1108
- const data = yield* decodeEventData(wireData).pipe(Effect.mapError(toValidationError("EventStore.decode")));
1252
+ // parsed — whatever the stream's current `storedAs` says — and a blob
1253
+ // pointer (#179) resolved per the read's modes.
1254
+ yield* loadEventRows([raw], modes, "EventStore.decode");
1255
+ const stored = raw.data;
1256
+ const data = isOffloadedValue(stored)
1257
+ ? lazyEventData(stored)
1258
+ : yield* decodeEventValue(stored);
1109
1259
  // Metadata is decoded through its schema when the stream declares one —
1110
1260
  // the mirror of the encode performed by `append`. Streams without a
1111
1261
  // metadata schema surface the stored attribute map untouched.
@@ -1128,6 +1278,26 @@ export const makeStream = (config) => {
1128
1278
  };
1129
1279
  return event;
1130
1280
  });
1281
+ /**
1282
+ * The read modes of a stream read's `offloaded` option (#179): `base` when
1283
+ * absent; a `ValidationError` (`[EDD-9117]`) for a value other than
1284
+ * `"eager"` / `"lazy"` (unreachable through the types).
1285
+ */
1286
+ const readModes = (options, where, base = OffloadRead.EAGER_MODES) => {
1287
+ const mode = options?.offloaded;
1288
+ if (mode === undefined)
1289
+ return Effect.succeed(base);
1290
+ if (mode === "eager")
1291
+ return Effect.succeed(OffloadRead.EAGER_MODES);
1292
+ if (mode === "lazy")
1293
+ return Effect.succeed(OffloadRead.LAZY_MODES);
1294
+ return Effect.fail(new ValidationError({
1295
+ entityType,
1296
+ operation: where,
1297
+ cause: OffloadRead.modeError(`${where}: unknown offloaded mode ${JSON.stringify(mode) ?? String(mode)}; expected ` +
1298
+ '"eager" or "lazy".'),
1299
+ }));
1300
+ };
1131
1301
  // ---------------------------------------------------------------------------
1132
1302
  // append
1133
1303
  // ---------------------------------------------------------------------------
@@ -1446,6 +1616,7 @@ export const makeStream = (config) => {
1446
1616
  ` DynamoDB rejected ${request}. Nothing was written.`, original),
1447
1617
  });
1448
1618
  };
1619
+ const WRITE = { _tag: "write" };
1449
1620
  /**
1450
1621
  * The snapshot item for `state` at `asOfVersion`: the state encoded through
1451
1622
  * the state schema, then packed per `snapshot.storedAs` (#147) — so every
@@ -1458,7 +1629,7 @@ export const makeStream = (config) => {
1458
1629
  * `sealed` writes the seal marker (#166): only a sealing append's inline
1459
1630
  * snapshot carries it.
1460
1631
  */
1461
- const buildSnapshotItem = (streamId, state, asOfVersion, now, operation, eventPartitions, sealed = false) => Effect.gen(function* () {
1632
+ const buildSnapshotItem = (streamId, state, asOfVersion, now, operation, tableName, routing, eventPartitions, sealed = false) => Effect.gen(function* () {
1462
1633
  const encoded = yield* encodeSnapshotState(state, operation);
1463
1634
  const stored = stateStoredAs === undefined
1464
1635
  ? encoded
@@ -1499,8 +1670,48 @@ export const makeStream = (config) => {
1499
1670
  // Top-level and native, beside `state`, so packing never touches it.
1500
1671
  if (sealed)
1501
1672
  item[SEALED_ATTRIBUTE] = true;
1673
+ // An offloaded `state` (#179) is routed last, on the item as stored:
1674
+ // its pointer replaces it, keyed by the snapshot SK (§4.5).
1675
+ yield* routeItem(snapshotOffload, item, tableName, operation, routing, "snapshot");
1502
1676
  return yield* marshalOrFail(snapshotEntityType, operation, () => toAttributeMap(item));
1503
1677
  });
1678
+ /**
1679
+ * Route an item's offloaded attribute (#179, design §6.10) in place:
1680
+ * upload it through the operation's ledger (a write), or measure it — a
1681
+ * placeholder of its pointer's upper bound, recorded in the routing — with
1682
+ * nothing uploaded (`measureAppend` / `measureSnapshot`). The stream is the
1683
+ * item family (§4.5): the object is keyed by the item's own sort key.
1684
+ *
1685
+ * Offloading requires `escapeKeys: true` (design §11.10, `[EDD-9146]`): a
1686
+ * bound stream is refused at bind, and an unbound one's write here, before
1687
+ * anything is uploaded. Under it, every item is written at its stream's
1688
+ * final key text, so `rekey` never moves a pointer row.
1689
+ */
1690
+ const routeItem = (info, item, tableName, operation, routing, entry) => {
1691
+ if (info === undefined)
1692
+ return Effect.void;
1693
+ const row = {
1694
+ table: tableName,
1695
+ pkAttribute: "pk",
1696
+ pk: { S: item.pk },
1697
+ skAttribute: "sk",
1698
+ sk: STREAM_FAMILY_SK,
1699
+ rowSk: { S: item.sk },
1700
+ operation,
1701
+ escapeKeys: schema.escapeKeys === true,
1702
+ };
1703
+ if (routing._tag === "write")
1704
+ return Effect.asVoid(OffloadWrite.route(info, item, row));
1705
+ return Effect.map(OffloadWrite.measure(info, item, row), (measured) => {
1706
+ for (const { attribute, objectBytes } of measured) {
1707
+ routing.offloaded.push({
1708
+ item: entry,
1709
+ attribute: attribute,
1710
+ objectBytes,
1711
+ });
1712
+ }
1713
+ });
1714
+ };
1504
1715
  /**
1505
1716
  * The stream's own items of an append — everything but the caller's
1506
1717
  * `additionalItems` — validated and built exactly as `append` sends them.
@@ -1508,7 +1719,7 @@ export const makeStream = (config) => {
1508
1719
  * the request `append` would send. `undefined` for an append with nothing
1509
1720
  * to write (the historical no-op).
1510
1721
  */
1511
- const buildAppend = (streamId, events, expectedVersion, options) => Effect.gen(function* () {
1722
+ const buildAppend = (streamId, events, expectedVersion, options, routing = WRITE) => Effect.gen(function* () {
1512
1723
  const additionalOps = options?.additionalItems ?? [];
1513
1724
  const idempotency = options?.idempotency;
1514
1725
  const snapshotState = options?.snapshot;
@@ -1682,7 +1893,7 @@ export const makeStream = (config) => {
1682
1893
  // Events are encoded to wire form through their schema (codec symmetry
1683
1894
  // with the read path, which decodes through the same schema), so this is
1684
1895
  // an effectful build rather than a plain `map`.
1685
- const eventItems = yield* Effect.forEach(events, (event, i) => Effect.gen(function* () {
1896
+ const eventRecords = yield* Effect.forEach(events, (event, i) => Effect.gen(function* () {
1686
1897
  const version = expectedVersion + i + 1;
1687
1898
  // In Effect v4, Schema.Class instances don't have _tag as an own property.
1688
1899
  // The identifier is on the constructor (class) itself.
@@ -1783,19 +1994,31 @@ export const makeStream = (config) => {
1783
1994
  // the typed envelope, as `metadata` is.
1784
1995
  if (sealing && i === events.length - 1)
1785
1996
  item[SEALED_ATTRIBUTE] = true;
1786
- return {
1787
- Put: {
1788
- TableName: tableName,
1789
- Item: yield* marshalOrFail(entityType, "EventStore.append", () => toAttributeMap(item)),
1790
- ConditionExpression: "attribute_not_exists(pk)",
1791
- // The first put of a writer one version behind a seal lands on
1792
- // the sealing event: its item tells `StreamSealed` from a
1793
- // conflict (#166). Only the first: every put's item would
1794
- // bloat a failure response for writers already far behind.
1795
- ...(i === 0 ? { ReturnValuesOnConditionCheckFailure: "ALL_OLD" } : {}),
1796
- },
1797
- };
1997
+ return item;
1798
1998
  }));
1999
+ // Offloaded `data` (#179) is routed on each item as stored, keyed by
2000
+ // its event SK (§4.5) — once per append (the attempts of its
2001
+ // transaction resend the same items), the events' uploads together:
2002
+ // a failed one fails the append once the others have settled.
2003
+ if (eventOffload !== undefined) {
2004
+ // An item that can't be stored is refused before anything is uploaded.
2005
+ for (const item of eventRecords) {
2006
+ yield* marshalOrFail(entityType, "EventStore.append", () => toAttributeMap(item));
2007
+ }
2008
+ yield* OffloadWrite.forEachSettled(eventRecords.entries(), ([i, item]) => routeItem(eventOffload, item, tableName, "EventStore.append", routing, i));
2009
+ }
2010
+ const eventItems = yield* Effect.forEach(eventRecords, (item, i) => Effect.map(marshalOrFail(entityType, "EventStore.append", () => toAttributeMap(item)), (Item) => ({
2011
+ Put: {
2012
+ TableName: tableName,
2013
+ Item,
2014
+ ConditionExpression: "attribute_not_exists(pk)",
2015
+ // The first put of a writer one version behind a seal lands on
2016
+ // the sealing event: its item tells `StreamSealed` from a
2017
+ // conflict (#166). Only the first: every put's item would
2018
+ // bloat a failure response for writers already far behind.
2019
+ ...(i === 0 ? { ReturnValuesOnConditionCheckFailure: "ALL_OLD" } : {}),
2020
+ },
2021
+ })));
1799
2022
  // The idempotency sentinel: a Put guarded by `attribute_not_exists(pk)`.
1800
2023
  let sentinelPut;
1801
2024
  if (idempotency !== undefined) {
@@ -1833,7 +2056,7 @@ export const makeStream = (config) => {
1833
2056
  // transaction-size and item-size diagnosis count its stored bytes.
1834
2057
  let snapshotPut;
1835
2058
  if (snapshotState !== undefined) {
1836
- const item = yield* buildSnapshotItem(streamId, snapshotState, expectedVersion + events.length, now, "EventStore.append.snapshot", eventPartitions, sealing);
2059
+ const item = yield* buildSnapshotItem(streamId, snapshotState, expectedVersion + events.length, now, "EventStore.append.snapshot", tableName, routing, eventPartitions, sealing);
1837
2060
  // As a head proof, a sealed snapshot fails the proof (#166), and
1838
2061
  // returns its item so the failure is reported as `StreamSealed`.
1839
2062
  snapshotPut = {
@@ -2113,7 +2336,10 @@ export const makeStream = (config) => {
2113
2336
  // when they are given, as `append` checks it. Without them it stands for
2114
2337
  // an item the caller adds, so the append is a transaction.
2115
2338
  const proofOp = additionalOps === undefined ? undefined : yield* headProofOp(headProof, additionalOps);
2116
- const parts = yield* buildAppend(streamId, events, expectedVersion, options);
2339
+ // Offloaded values (#179) are measured, never uploaded: the stream's own
2340
+ // are recorded in `offloaded`, each at its pointer's upper bound.
2341
+ const routing = { _tag: "measure", offloaded: [] };
2342
+ const parts = yield* buildAppend(streamId, events, expectedVersion, options, routing).pipe(Effect.catchTag("BlobStoreError", (cause) => measureFailed(cause, "measureAppend")));
2117
2343
  if (parts === undefined) {
2118
2344
  return {
2119
2345
  events: [],
@@ -2121,13 +2347,16 @@ export const makeStream = (config) => {
2121
2347
  snapshot: undefined,
2122
2348
  transactionBytes: 0,
2123
2349
  requestBytes: 0,
2350
+ offloaded: [],
2124
2351
  };
2125
2352
  }
2126
2353
  // The transaction `append` would send, built by the same code: the
2127
2354
  // stream's items and the items the caller's `additionalItems` build, in
2128
2355
  // 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));
2356
+ // build has no size without that read, and fails the measurement. An
2357
+ // additional item's offloaded value is measured at its pointer's upper
2358
+ // bound and nothing is uploaded (`OffloadWrite.Measuring`).
2359
+ const built = yield* Capacity.withoutRequests(buildAppendTransaction(parts, additionalOps ?? [], expectedVersion, headProof, proofOp).pipe(Effect.provideService(OffloadWrite.Measuring, true)));
2131
2360
  if (built.refused !== undefined) {
2132
2361
  const { command, input } = built.refused;
2133
2362
  return yield* new ValidationError({
@@ -2141,7 +2370,12 @@ export const makeStream = (config) => {
2141
2370
  });
2142
2371
  }
2143
2372
  if (Exit.isFailure(built.exit)) {
2144
- // No request was refused, so nothing here is a client error.
2373
+ // No request was refused, so nothing here is a client error; a store
2374
+ // error is the measurement's own (`measureFailed`).
2375
+ const error = Cause.findErrorOption(built.exit.cause);
2376
+ if (Option.isSome(error) && error.value._tag === "BlobStoreError") {
2377
+ return yield* measureFailed(error.value, "measureAppend");
2378
+ }
2145
2379
  return yield* Effect.failCause(built.exit.cause);
2146
2380
  }
2147
2381
  const tx = built.exit.value;
@@ -2163,14 +2397,24 @@ export const makeStream = (config) => {
2163
2397
  requestBytes: single
2164
2398
  ? jsonBytes({ ...sent[0].Put, ...fields })
2165
2399
  : transactWriteBodyBytes({ TransactItems: sent, ...fields }),
2400
+ // Events in order, then the snapshot.
2401
+ offloaded: routing.offloaded.sort((a, b) => (a.item === "snapshot" ? Infinity : a.item) -
2402
+ (b.item === "snapshot" ? Infinity : b.item)),
2166
2403
  };
2167
2404
  return measurement;
2168
2405
  });
2406
+ /**
2407
+ * A measurement cannot fail with a store error (nothing is uploaded): the
2408
+ * only one is `NotProvided`, which the first-use and bind checks rule out.
2409
+ * Reported as the `ValidationError` it would be, its cause the store error.
2410
+ */
2411
+ const measureFailed = (cause, operation) => Effect.fail(new ValidationError({ entityType, operation: `EventStore.${operation}`, cause }));
2169
2412
  const measureSnapshot = (streamId, state, asOfVersion) => Effect.gen(function* () {
2170
2413
  if (snapshot === undefined)
2171
2414
  return yield* snapshotUnavailable("measureSnapshot");
2172
2415
  const now = DateTime.formatIso(yield* DateTime.now);
2173
- const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.measureSnapshot");
2416
+ const { name: tableName } = yield* config.table.Tag;
2417
+ const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.measureSnapshot", tableName, { _tag: "measure", offloaded: [] }).pipe(Effect.catchTag("BlobStoreError", (cause) => measureFailed(cause, "measureSnapshot")));
2174
2418
  return itemBytes(item);
2175
2419
  });
2176
2420
  // ---------------------------------------------------------------------------
@@ -2187,14 +2431,22 @@ export const makeStream = (config) => {
2187
2431
  imageEntityType(image) !== entityType) {
2188
2432
  return Option.none();
2189
2433
  }
2434
+ // Lazy by default (#179, design §10.2): an offloaded `data` is fetched
2435
+ // only on `read()`, unless `{ offloaded: "eager" }`.
2436
+ const modes = yield* readModes(options, "EventStore.decodeStreamImage", OffloadRead.LAZY_MODES);
2190
2437
  // In DynamoDB JSON the S / B tag says what `data` is; unmarshalled, a
2191
2438
  // string that is base64 of a `B` value is told apart from JSON text.
2192
- const raw = yield* decodeImage(image, DATA_ATTRIBUTES, ctx);
2193
- const event = yield* decodeStreamEvent(raw);
2439
+ const form = imageForm(image);
2440
+ const raw = yield* normalizeImage(image, ctx, { form });
2441
+ // `data` read by its stored form under this operation, as before #179;
2442
+ // the schema decode below stays `EventStore.decode`'s.
2443
+ yield* loadEventRows([raw], modes, ctx.operation, form === "unmarshalled");
2444
+ const event = yield* decodeStreamEvent(raw, modes);
2194
2445
  if (options?.raw !== true)
2195
2446
  return Option.some(event);
2196
2447
  // `raw.data` is the wire form the decode just read: the parsed JSON of a
2197
- // packed value, the unmarshalled map of a native one.
2448
+ // packed value, the unmarshalled map of a native one — or, lazily, its
2449
+ // `OffloadedValue`.
2198
2450
  const withRaw = {
2199
2451
  ...event,
2200
2452
  rawData: raw.data,
@@ -2204,10 +2456,18 @@ export const makeStream = (config) => {
2204
2456
  // ---------------------------------------------------------------------------
2205
2457
  // read
2206
2458
  // ---------------------------------------------------------------------------
2207
- /** Apply {@link ReadOptions} to an event query. */
2208
- const withReadOptions = (query, options) => options?.consistentRead === true ? Query.consistentRead(query) : query;
2459
+ /**
2460
+ * Apply {@link ReadOptions} to an event query: `consistentRead`, and the
2461
+ * read mode of an offloaded `data` (#179; validated, `[EDD-9117]`).
2462
+ */
2463
+ const withReadOptions = (query, options, where) => Effect.map(readModes(options, where), (modes) => {
2464
+ const consistent = options?.consistentRead === true ? Query.consistentRead(query) : query;
2465
+ return modes.overflow === "lazy"
2466
+ ? Query.offloaded(consistent, "lazy")
2467
+ : consistent;
2468
+ });
2209
2469
  const read = (streamId, options) => Effect.gen(function* () {
2210
- const query = withReadOptions(buildEventsQuery(streamId), options);
2470
+ const query = yield* withReadOptions(buildEventsQuery(streamId), options, "EventStore.read");
2211
2471
  return yield* Query.collect(query);
2212
2472
  });
2213
2473
  // ---------------------------------------------------------------------------
@@ -2221,7 +2481,7 @@ export const makeStream = (config) => {
2221
2481
  const upper = options?.toVersion === undefined ? maxEventSk : composeEventSk(options.toVersion);
2222
2482
  if (options?.toVersion !== undefined && options.toVersion <= afterVersion)
2223
2483
  return [];
2224
- const query = withReadOptions(buildEventsQuery(streamId).pipe(Query.where({ between: [composeEventSk(afterVersion + 1), upper] })), options);
2484
+ const query = yield* withReadOptions(buildEventsQuery(streamId).pipe(Query.where({ between: [composeEventSk(afterVersion + 1), upper] })), options, "EventStore.readFrom");
2225
2485
  return yield* Query.collect(query);
2226
2486
  });
2227
2487
  // ---------------------------------------------------------------------------
@@ -2233,7 +2493,9 @@ export const makeStream = (config) => {
2233
2493
  // whole partition one request per item. The `begins_with` bound on
2234
2494
  // `buildEventsQuery` guarantees the single evaluated item is the newest
2235
2495
  // *event* (never the snapshot, which sorts last).
2236
- const query = withReadOptions(buildEventsQuery(streamId).pipe(Query.reverse, Query.limit(1)), options);
2496
+ // Lazily (#179): only the version is read, so an offloaded `data` is
2497
+ // never fetched.
2498
+ const query = yield* withReadOptions(buildEventsQuery(streamId).pipe(Query.reverse, Query.limit(1)), { ...options, offloaded: "lazy" }, "EventStore.currentVersion");
2237
2499
  const page = yield* Query.execute(query);
2238
2500
  const newest = page.items[0];
2239
2501
  if (newest === undefined)
@@ -2245,7 +2507,7 @@ export const makeStream = (config) => {
2245
2507
  // Reverse, `Limit: 1`, bounded below by `floorVersion + 1`: an empty range
2246
2508
  // (the common case — nothing appended past the snapshot) reads no items;
2247
2509
  // otherwise the single evaluated item is the head.
2248
- const query = withReadOptions(buildEventsQuery(streamId).pipe(Query.where({ between: [composeEventSk(floorVersion + 1), maxEventSk] }), Query.reverse, Query.limit(1)), options);
2510
+ const query = yield* withReadOptions(buildEventsQuery(streamId).pipe(Query.where({ between: [composeEventSk(floorVersion + 1), maxEventSk] }), Query.reverse, Query.limit(1)), { ...options, offloaded: "lazy" }, "EventStore.headAbove");
2249
2511
  const page = yield* Query.execute(query);
2250
2512
  const newest = page.items[0];
2251
2513
  return newest === undefined ? floorVersion : newest.version;
@@ -2275,8 +2537,10 @@ export const makeStream = (config) => {
2275
2537
  entityType: snapshotEntityType,
2276
2538
  });
2277
2539
  // Packed per `snapshot.storedAs` (#147): the diagnosis below measures
2278
- // the stored bytes.
2279
- const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.writeSnapshot");
2540
+ // the stored bytes. An offloaded `state` (#179) is uploaded first; a
2541
+ // write that provably did not commit (a lost race, a cancelled
2542
+ // transaction) has the upload deleted.
2543
+ const item = yield* buildSnapshotItem(streamId, state, asOfVersion, now, "EventStore.writeSnapshot", tableName, WRITE);
2280
2544
  const put = {
2281
2545
  TableName: tableName,
2282
2546
  Item: item,
@@ -2302,16 +2566,30 @@ export const makeStream = (config) => {
2302
2566
  * Decode a stored snapshot item. A snapshot that fails to decode through the
2303
2567
  * state schema is a `ValidationError` — never silently discarded.
2304
2568
  */
2305
- const decodeSnapshotItem = (raw, operation) =>
2306
- // `state` is read by its stored form (#147) when it may be packed — see
2307
- // `stateDispatch` — then decoded through the state schema as before.
2308
- (stateDispatch && (typeof raw.state === "string" || raw.state instanceof Uint8Array)
2309
- ? withRegistry((registry) => unpackStoredSync(raw.state, registry, { entityType: snapshotEntityType, operation }, "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) => ({
2311
- state,
2312
- asOfVersion: raw.asOfVersion,
2313
- timestamp: raw.timestamp,
2314
- })));
2569
+ const decodeSnapshotItem = (raw, operation, modes = OffloadRead.EAGER_MODES) => Effect.gen(function* () {
2570
+ // `state` is read by its stored form (#147) when it may be packed — see
2571
+ // `stateDispatch` — and a blob pointer (#179) resolved per `modes`,
2572
+ // then decoded through the state schema as before (on each `read()`
2573
+ // of a lazy one).
2574
+ yield* OffloadRead.loadRows(snapshotPlan, [raw], { operation, modes, raw: true });
2575
+ const decode = (wire) => decodeSnapshotState(wire).pipe(Effect.mapError((cause) => new ValidationError({ entityType: snapshotEntityType, operation, cause })));
2576
+ const stored = raw.state;
2577
+ const state = isOffloadedValue(stored)
2578
+ ? makeOffloadedValue({
2579
+ location: stored.location,
2580
+ ref: stored.ref,
2581
+ size: stored.size,
2582
+ checksum: stored.checksum,
2583
+ read: () => Effect.flatMap(stored.read(), (value) => decode(value)),
2584
+ })
2585
+ : yield* decode(stored);
2586
+ const decoded = {
2587
+ state,
2588
+ asOfVersion: raw.asOfVersion,
2589
+ timestamp: raw.timestamp,
2590
+ };
2591
+ return decoded;
2592
+ });
2315
2593
  /** The raw snapshot item, by its exact key, in one `GetItem`. */
2316
2594
  const getSnapshotItem = (streamId, consistentRead) => Effect.gen(function* () {
2317
2595
  const client = yield* Capacity.client;
@@ -2340,18 +2618,20 @@ export const makeStream = (config) => {
2340
2618
  });
2341
2619
  return result.Item === undefined ? undefined : fromAttributeMap(result.Item);
2342
2620
  });
2343
- const readSnapshot = (streamId) => Effect.gen(function* () {
2621
+ const readSnapshot = (streamId, options) => Effect.gen(function* () {
2344
2622
  if (snapshot === undefined)
2345
2623
  return yield* snapshotUnavailable("readSnapshot");
2624
+ const modes = yield* readModes(options, "EventStore.readSnapshot");
2346
2625
  const raw = yield* getSnapshotItem(streamId, true);
2347
2626
  if (raw === undefined)
2348
2627
  return Option.none();
2349
- return Option.some(yield* decodeSnapshotItem(raw, "EventStore.readSnapshot"));
2628
+ return Option.some(yield* decodeSnapshotItem(raw, "EventStore.readSnapshot", modes));
2350
2629
  });
2351
2630
  // ---------------------------------------------------------------------------
2352
2631
  // readLatest — snapshot + delta + head in one request (#138)
2353
2632
  // ---------------------------------------------------------------------------
2354
2633
  const readLatest = (streamId, options) => Effect.gen(function* () {
2634
+ const modes = yield* readModes(options, "EventStore.readLatest");
2355
2635
  // Without a snapshot config there is nothing to read but the events
2356
2636
  // (`verifySnapshot` is ignored).
2357
2637
  if (snapshot === undefined) {
@@ -2378,7 +2658,7 @@ export const makeStream = (config) => {
2378
2658
  return yield* Effect.die(new Error(refusal));
2379
2659
  const raw = yield* getSnapshotItem(streamId, options.consistentRead === true);
2380
2660
  if (raw !== undefined) {
2381
- const current = yield* decodeSnapshotItem(raw, "EventStore.readLatest");
2661
+ const current = yield* decodeSnapshotItem(raw, "EventStore.readLatest", modes);
2382
2662
  // A snapshot written by a sealing append carries the marker (#166):
2383
2663
  // its version is the seal's, so one `GetItem` of that event returns
2384
2664
  // the sealing event — paid only on a sealed stream.
@@ -2398,7 +2678,7 @@ export const makeStream = (config) => {
2398
2678
  snapshot: Option.some(current),
2399
2679
  events: [],
2400
2680
  version: current.asOfVersion,
2401
- seal: yield* decodeStreamEvent(sealRaw),
2681
+ seal: yield* decodeStreamEvent(sealRaw, modes),
2402
2682
  };
2403
2683
  return state;
2404
2684
  }
@@ -2469,10 +2749,9 @@ export const makeStream = (config) => {
2469
2749
  }
2470
2750
  const latest = snapshotRaw === undefined
2471
2751
  ? Option.none()
2472
- : Option.some(yield* decodeSnapshotItem(snapshotRaw, "EventStore.readLatest"));
2752
+ : Option.some(yield* decodeSnapshotItem(snapshotRaw, "EventStore.readLatest", modes));
2473
2753
  const asOfVersion = Option.isSome(latest) ? latest.value.asOfVersion : 0;
2474
2754
  const delta = eventRaws.filter((raw) => raw.version > asOfVersion).reverse();
2475
- const events = yield* Effect.forEach(delta, (raw) => decodeStreamEvent(raw));
2476
2755
  // The sealing event (#166), from ANY event item the query fetched —
2477
2756
  // including those at or below the snapshot, which `events` leaves out
2478
2757
  // (a snapshot at the seal already folds it in) — with no extra request.
@@ -2483,11 +2762,15 @@ export const makeStream = (config) => {
2483
2762
  if (raw[SEALED_ATTRIBUTE] === true)
2484
2763
  sealRaw = raw;
2485
2764
  }
2765
+ // The rows decoded, loaded together: their offloaded `data` (#179)
2766
+ // resolves at the store's read concurrency (§8.2).
2767
+ yield* loadEventRows(sealRaw === undefined || delta.includes(sealRaw) ? delta : [...delta, sealRaw], modes, "EventStore.decode");
2768
+ const events = yield* Effect.forEach(delta, (raw) => decodeStreamEvent(raw, modes));
2486
2769
  const seal = sealRaw === undefined
2487
2770
  ? undefined
2488
2771
  : sealRaw.version > asOfVersion
2489
2772
  ? events.find((event) => event.version === sealRaw.version)
2490
- : yield* decodeStreamEvent(sealRaw);
2773
+ : yield* decodeStreamEvent(sealRaw, modes);
2491
2774
  const state = {
2492
2775
  snapshot: latest,
2493
2776
  events,
@@ -2514,6 +2797,25 @@ export const makeStream = (config) => {
2514
2797
  // ---------------------------------------------------------------------------
2515
2798
  // query.events helper
2516
2799
  // ---------------------------------------------------------------------------
2800
+ /**
2801
+ * The page prefetch of the stream's event queries (#179, design §8.2): a
2802
+ * window of rows loaded together, so their offloaded `data` resolves at
2803
+ * the store's read concurrency. Raw rows (`Query.select`) of another type
2804
+ * (`Query.ignoreOwnership`) are left as they are. Only for a stream that
2805
+ * offloads `data`; otherwise each row is loaded as it is decoded.
2806
+ */
2807
+ const eventPrefetch = eventOffload === undefined
2808
+ ? undefined
2809
+ : (rows, { modes, raw, operation }) => loadEventRows(raw ? rows.filter((row) => row.__edd_e__ === entityType) : rows, modes, operation);
2810
+ /**
2811
+ * The first-use store check (`[EDD-9115]`, design §13) of `query.events` /
2812
+ * `query.index`: run at the start of each terminal (the query's `prepare`),
2813
+ * so a query of an offloading stream run without a store dies as every
2814
+ * other operation of the stream does. The codec check (`[EDD-9078]`) stays
2815
+ * off the query descriptors, as #147 decided: a compressed row they cannot
2816
+ * read is a `ValidationError` caused by `CompressorNotRegistered`.
2817
+ */
2818
+ const checkedQuery = storeCheck === undefined ? undefined : () => Effect.as(storeCheck, {});
2517
2819
  const buildEventsQuery = (streamId) => {
2518
2820
  const pk = composeStreamPk(streamId);
2519
2821
  return Query.make({
@@ -2523,7 +2825,9 @@ export const makeStream = (config) => {
2523
2825
  pkValue: pk,
2524
2826
  skField: "sk",
2525
2827
  entityTypes: [entityType],
2526
- decoder: (raw) => decodeStreamEvent(raw),
2828
+ decoder: (raw, modes) => decodeStreamEvent(raw, modes),
2829
+ prefetch: eventPrefetch,
2830
+ prepare: checkedQuery,
2527
2831
  // Raw rows (`Query.select`) carry `data` as parsed JSON, whatever its
2528
2832
  // stored form, and a filter inside a packed `data` is refused (#147).
2529
2833
  rawRow: rawEventRow,
@@ -2601,6 +2905,8 @@ export const makeStream = (config) => {
2601
2905
  skField: idx.sk,
2602
2906
  entityTypes: [entityType],
2603
2907
  decoder: indexDecoder(idx),
2908
+ prefetch: eventPrefetch,
2909
+ prepare: checkedQuery,
2604
2910
  // As for `query.events` (#147) — the `"keys"` hydration path decodes
2605
2911
  // its fetched rows through the same hooks.
2606
2912
  rawRow: rawEventRow,
@@ -2641,15 +2947,16 @@ export const makeStream = (config) => {
2641
2947
  * - `"keys"` decodes items fetched from the table, so a missing attribute
2642
2948
  * there is not a projection problem: failures pass through.
2643
2949
  */
2644
- const indexDecoder = (idx) => (raw) => {
2950
+ const indexDecoder = (idx) => (raw, modes) => {
2645
2951
  if (idx.projection === "keys")
2646
- return decodeStreamEvent(raw);
2647
- let row = raw;
2648
- if (idx.projection === "withoutMetadata" && raw.metadata !== undefined) {
2649
- row = { ...raw };
2952
+ return decodeStreamEvent(raw, modes);
2953
+ // In place: a copy would lose the row's loaded state (#179).
2954
+ const row = raw;
2955
+ if (idx.projection === "withoutMetadata")
2650
2956
  delete row.metadata;
2651
- }
2652
- return decodeStreamEvent(row).pipe(Effect.mapError((error) => {
2957
+ return decodeStreamEvent(row, modes).pipe(Effect.mapError((error) => {
2958
+ if (error._tag === "BlobStoreError")
2959
+ return error;
2653
2960
  const missing = PROJECTED_ENVELOPE_ATTRIBUTES.filter((name) => row[name] === undefined);
2654
2961
  if (missing.length === 0)
2655
2962
  return error;
@@ -2688,8 +2995,7 @@ export const makeStream = (config) => {
2688
2995
  query = Query.reverse(query);
2689
2996
  if (limit !== undefined)
2690
2997
  query = Query.limit(query, limit);
2691
- if (options?.consistentRead === true)
2692
- query = Query.consistentRead(query);
2998
+ query = yield* withReadOptions(query, options, "EventStore.readIndex");
2693
2999
  return yield* Query.collect(query);
2694
3000
  });
2695
3001
  const queryNamespace = {
@@ -2699,6 +3005,33 @@ export const makeStream = (config) => {
2699
3005
  // ---------------------------------------------------------------------------
2700
3006
  // Return EventStream
2701
3007
  // ---------------------------------------------------------------------------
3008
+ /**
3009
+ * What `BlobGc` reads of the stream (#179, design §11): one partition per
3010
+ * stream, its rows keyed `pk` / `sk`, its objects under the stream family.
3011
+ * The partition is the current key's: a stream still under its 1.36 key
3012
+ * keeps its offloaded values inline there (design §11.10).
3013
+ */
3014
+ const gcSupport = {
3015
+ kind: "stream",
3016
+ name: config.streamName,
3017
+ tableTag: () => config.table.Tag,
3018
+ pkField: "pk",
3019
+ skField: "sk",
3020
+ eventType: entityType,
3021
+ snapshotType: snapshotEntityType,
3022
+ event: eventOffload,
3023
+ snapshot: snapshotOffload,
3024
+ prefix: offloadOptions.prefix,
3025
+ partitionOfKey: (streamId, operation) => Effect.try({
3026
+ try: () => {
3027
+ if (typeof streamId !== "object" || streamId === null) {
3028
+ throw new Error(`A stream id must be an object, got ${typeof streamId}`);
3029
+ }
3030
+ return composeStreamPk(streamId);
3031
+ },
3032
+ catch: (cause) => new ValidationError({ entityType, operation, cause }),
3033
+ }),
3034
+ };
2702
3035
  // Cast rationale: makeStream builds the stream object from closures that capture
2703
3036
  // the generic config. The Table.Tag service has a dynamically-created tag whose R
2704
3037
  // type parameter is opaque, causing Effect.gen to infer `unknown` for R. The cast
@@ -2856,6 +3189,23 @@ export const makeStream = (config) => {
2856
3189
  }
2857
3190
  return copy;
2858
3191
  };
3192
+ /**
3193
+ * The backstop of design §11.10 (#179): a row holding a blob pointer
3194
+ * names its objects from its own key text and must never move. Offloading
3195
+ * requires `escapeKeys: true`, under which a stream is written only at
3196
+ * its final key text, so this is reached only when `escapeKeys` was
3197
+ * turned off over rows offloading wrote: the run fails naming the row,
3198
+ * with nothing written for it (`[EDD-9146]`).
3199
+ */
3200
+ const refusePointerRows = (rows) => {
3201
+ for (const row of rows) {
3202
+ const attribute = BlobLedger.pointerAttributeOf(row);
3203
+ if (attribute !== undefined) {
3204
+ return Rekey.refusePointerRow(`stream "${config.streamName}"`, { pk: from, sk: skOf(row) }, attribute);
3205
+ }
3206
+ }
3207
+ return Effect.void;
3208
+ };
2859
3209
  /** This stream's rows left under the old key: another id's there are its own to move. */
2860
3210
  const readOwn = Effect.map(readAll(from), (rows) => rows.filter((row) => row.streamId?.S === streamIdText));
2861
3211
  /** A row at `to` that belongs elsewhere: another stream's, under other key text. */
@@ -3009,6 +3359,7 @@ export const makeStream = (config) => {
3009
3359
  */
3010
3360
  const drain = Effect.gen(function* () {
3011
3361
  const left = yield* readOwn;
3362
+ yield* refusePointerRows(left);
3012
3363
  const { there, refused } = yield* toDrain(left);
3013
3364
  if (refused !== undefined)
3014
3365
  return refused;
@@ -3033,6 +3384,9 @@ export const makeStream = (config) => {
3033
3384
  // Moved since the scan read it.
3034
3385
  if (rows.length === 0)
3035
3386
  return tally;
3387
+ // Never a row holding a blob pointer (#179, design §11.10): nothing is
3388
+ // copied, dry run included.
3389
+ yield* refusePointerRows(rows);
3036
3390
  const first = rows.find((row) => skOf(row) === firstSk);
3037
3391
  // Flipped by an earlier attempt or run — or never started here: the
3038
3392
  // stream lives at `to`, and the rows left move to it.
@@ -3248,10 +3602,12 @@ export const makeStream = (config) => {
3248
3602
  parseStreamId: (id) => parseStreamIdWith(config.streamName, compositeFields, id),
3249
3603
  snapshotConfig: snapshotSettings,
3250
3604
  storedAs: storage,
3605
+ offload: offloadSettings,
3606
+ _storeRequirements: streamStoreRequirements(config.streamName, offloadSettings, schema.escapeKeys === true),
3251
3607
  indexes: indexSettings,
3252
- writeSnapshot: checked(named("writeSnapshot", writeSnapshot)),
3608
+ writeSnapshot: checked(named("writeSnapshot", rooted(writeSnapshot))),
3253
3609
  readSnapshot: checked(named("readSnapshot", readSnapshot)),
3254
- append: checked(named("append", append)),
3610
+ append: checked(named("append", rooted(append))),
3255
3611
  appendOp,
3256
3612
  read: checked(named("read", read)),
3257
3613
  readFrom: checked(named("readFrom", readFrom)),
@@ -3266,6 +3622,7 @@ export const makeStream = (config) => {
3266
3622
  [CommandSentinelProbe]: checked(hasCommandSentinel),
3267
3623
  [HeadAboveProbe]: checked(headAbove),
3268
3624
  [Rekey.RekeyHandler]: rekeyHandler,
3625
+ [GcSupport.GcSupportId]: gcSupport,
3269
3626
  };
3270
3627
  };
3271
3628
  // ---------------------------------------------------------------------------
@@ -3288,11 +3645,24 @@ export const makeStream = (config) => {
3288
3645
  export const bind = (stream) => Effect.gen(function* () {
3289
3646
  // Detached: no current operation or parent span is pinned for later calls (#174).
3290
3647
  const ctx = Capacity.detachContext(yield* Effect.context());
3648
+ // A stream that offloads (#179) needs escaped key text (`[EDD-9146]`,
3649
+ // design §11.10): its objects are named from its rows' key text, so a
3650
+ // pointer row must be written only at its final text. Checked first.
3651
+ const requirements = storeRequirementsOf(stream);
3652
+ const keysError = OffloadWrite.unescapedKeysError("EventStore.bind", requirements);
3653
+ if (keysError !== undefined)
3654
+ throw keysError;
3291
3655
  // The stream meets values compressed with every codec its `storedAs`
3292
3656
  // names, so the registry captured here must have them (#147).
3293
3657
  const codecError = unregisteredCodecError("EventStore.bind", streamCodecRequirements(stream.streamName, stream.storedAs), Context.getOrUndefined(ctx, Compression));
3294
3658
  if (codecError !== undefined)
3295
3659
  throw codecError;
3660
+ // A stream that offloads (#179) meets pointers on every read and uploads
3661
+ // on every write, so the context captured here must hold a store
3662
+ // (`[EDD-9115]`, design §13).
3663
+ const storeError = OffloadWrite.missingStoreError("EventStore.bind", requirements, Context.getOrUndefined(ctx, BlobStore));
3664
+ if (storeError !== undefined)
3665
+ throw storeError;
3296
3666
  const provide = (effect) => Effect.provide(effect, ctx);
3297
3667
  const probe = commandSentinelProbeOf(stream);
3298
3668
  const headProbe = headAboveProbeOf(stream);
@@ -3310,9 +3680,11 @@ export const bind = (stream) => Effect.gen(function* () {
3310
3680
  parseStreamId: (id) => stream.parseStreamId(id),
3311
3681
  snapshotConfig: stream.snapshotConfig,
3312
3682
  storedAs: stream.storedAs,
3683
+ offload: stream.offload,
3684
+ _storeRequirements: storeRequirementsOf(stream),
3313
3685
  indexes: stream.indexes,
3314
3686
  writeSnapshot: (streamId, state, asOfVersion) => provide(stream.writeSnapshot(streamId, state, asOfVersion)),
3315
- readSnapshot: (streamId) => provide(stream.readSnapshot(streamId)),
3687
+ readSnapshot: (streamId, options) => provide(stream.readSnapshot(streamId, options)),
3316
3688
  append: (streamId, events, expectedVersion, options) => provide(stream.append(streamId, events, expectedVersion, options)),
3317
3689
  // Built in the captured context (#166): only its TableConfig and
3318
3690
  // Compression are used — the outer append sends the items.
@@ -4033,7 +4405,10 @@ const makeCommandHandlerImpl = (decider, stream, options) => {
4033
4405
  // One report per invocation: the load and the append (and retries) nest
4034
4406
  // under it (#174). A bound stream's captured setting applies, as it does
4035
4407
  // to the bound calls inside.
4036
- return Capacity.operation("EventStore.commandHandler", { target: stream.streamName }, run, stream[Capacity.CapturedReporting]);
4408
+ // The invocation is one upload-ledger root (#179): a retry that decides
4409
+ // the same content uploads it once, and what no attempt committed is
4410
+ // rolled back at exit.
4411
+ return Capacity.operation("EventStore.commandHandler", { target: stream.streamName }, BlobLedger.root(run), stream[Capacity.CapturedReporting]);
4037
4412
  };
4038
4413
  };
4039
4414
  /**
@@ -4177,9 +4552,11 @@ export { removeRow, skipEvent, } from "./internal/ProjectionEngine.js";
4177
4552
  /**
4178
4553
  * Bind a projection to the services its operations need — `DynamoClient`,
4179
4554
  * the `TableConfig`s of the stream's table and the read model's, `evolve`'s
4180
- * requirements, and a `Compression` registry for packed event data — so every
4181
- * operation has `R = never`. Like {@link bind}, it checks the registry holds
4182
- * the codecs the stream's `storedAs` names (`[EDD-9078]`).
4555
+ * requirements, a `Compression` registry for packed event data and the
4556
+ * `BlobStore` for offloaded event data (#179) — so every operation has
4557
+ * `R = never`. Like {@link bind}, it checks the registry holds the codecs the
4558
+ * stream's `storedAs` names (`[EDD-9078]`) and, for a stream that offloads,
4559
+ * that a `BlobStore` is provided (`[EDD-9115]`).
4183
4560
  *
4184
4561
  * @example
4185
4562
  * ```ts