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
@@ -0,0 +1,623 @@
1
+ /**
2
+ * @internal The in-memory `BlobStore` (#179, design §12.3): a faithful test
3
+ * double for the S3 store, behind `BlobStore.memory` / `BlobStore.layerMemory`.
4
+ *
5
+ * - **Versioning.** `"versioned"` (default): stable keys, version ids of 32
6
+ * random lowercase hex characters (like S3's). `"keyPerWrite"`: every upload
7
+ * gets `key + "/" + a 26-character suffix` (a millisecond timestamp and 80
8
+ * random bits, Crockford base32, monotonic per store like a monotonic ULID:
9
+ * within one millisecond the random part counts up, so a family's keys
10
+ * list in write order even under a frozen `TestClock`) and version `""` —
11
+ * the contract's path for stores without versioning (§12.4).
12
+ * - **Like S3.** Uploads are validated as S3 validates them: the body against
13
+ * the request's CRC-64/NVME (`ChecksumMismatch`) and its `contentLength`,
14
+ * keys up to 1,024 bytes, a content type and user metadata of printable
15
+ * US-ASCII, the metadata within 2 KB (`Rejected`).
16
+ * Metadata keys are stored lowercased. Ranged reads honour offsets; a range
17
+ * starting past the end is `Rejected`. Listings are in UTF-8 key order,
18
+ * versions newest first.
19
+ * - **Time and randomness** come from Effect's `Clock` and `Random`, read from
20
+ * the calling fiber (or the `clock` option), so `TestClock` drives
21
+ * `lastModified` — GC and `maxUploadAge` tests — and `Random.withSeed`
22
+ * makes version ids reproducible.
23
+ * - **Multipart, simulated.** A `put` runs the multipart driver S3's does
24
+ * (`Multipart.upload`, design §7): a body of at most `partSize` bytes is one
25
+ * upload, a longer one is created, uploaded in parts of exactly `partSize`
26
+ * bytes (raised for a known `contentLength` past `maxParts` parts) at
27
+ * `uploadConcurrency`, and completed — or aborted on any failure or
28
+ * interruption. A part failing with `Throttled` / `Unavailable` is retried
29
+ * (`partAttempts`), as the SDK retries one; part `maxParts + 1` is
30
+ * `TooLarge`. Unlike S3, any part size is allowed, so tests exercise
31
+ * multipart with small bodies.
32
+ * - **Fault injection.** `failures` is asked about every call, numbered per
33
+ * action, and may fail it with a reason or interrupt it, before it takes
34
+ * effect or after (a lost response), or part-way through a stream. A lost
35
+ * `put` or `copy` response names the version it stored — a test
36
+ * convenience an S3 store cannot offer, which no settlement may rely on.
37
+ * It is also asked about each phase of a multipart upload (create, every
38
+ * part attempt, complete, abort) as its own action, `"multipart"`, with the
39
+ * put's `n` — so a hook keyed on `action === "put"` sees only the put; a
40
+ * lost `complete` response fails the put with `completeLost` and no ref, as
41
+ * S3's does.
42
+ * - **Inspection.** `inspect()` returns the stored versions (bytes, metadata,
43
+ * marks), the number of calls per action, and the multipart calls.
44
+ *
45
+ * Not part of the public API (`BlobStore.memory` is).
46
+ */
47
+ import { MAX_KEY_BYTES } from "@effect-dynamodb/schema/internal/BlobPointer.js";
48
+ import { crc64nvme } from "@effect-dynamodb/schema/internal/Crc64Nvme.js";
49
+ import { Clock, Duration, Effect, Option, Random, Stream } from "effect";
50
+ import { MAX_METADATA_BYTES, metadataBytes } from "./BlobMetadata.js";
51
+ import { BlobStoreFailure, checkMaxUploadAgeOption, checkPositiveInteger, checkPrefix, DEFAULT_READ_CONCURRENCY, DEFAULT_WRITE_CONCURRENCY, invalid, utf8Bytes, } from "./BlobStoreContract.js";
52
+ import * as Multipart from "./Multipart.js";
53
+ import { compareUtf8 } from "./Utf8Order.js";
54
+ const OPTION_KEYS = new Set([
55
+ "versioning",
56
+ "prefix",
57
+ "presign",
58
+ "maxVersionBytes",
59
+ "maxUploadAge",
60
+ "readConcurrency",
61
+ "writeConcurrency",
62
+ "readChunkBytes",
63
+ "partSize",
64
+ "maxParts",
65
+ "uploadConcurrency",
66
+ "partAttempts",
67
+ "clock",
68
+ "failures",
69
+ ]);
70
+ const VERSION_ID_CHARS = 32;
71
+ const KEY_SUFFIX_CHARS = 26;
72
+ const DEFAULT_READ_CHUNK_BYTES = 65_536;
73
+ const WHERE = "BlobStore.memory";
74
+ const CROCKFORD = "0123456789abcdefghjkmnpqrstvwxyz";
75
+ const randomHex = (chars) => Effect.map(Effect.forEach(Array.from({ length: chars }), () => Random.nextIntBetween(0, 16, { halfOpen: true })), (digits) => digits.map((d) => d.toString(16)).join(""));
76
+ const SUFFIX_TIME_CHARS = 10;
77
+ const SUFFIX_RANDOM_CHARS = KEY_SUFFIX_CHARS - SUFFIX_TIME_CHARS;
78
+ /** The random part of a key-per-write suffix: base-32 digits. */
79
+ const randomDigits = Effect.forEach(Array.from({ length: SUFFIX_RANDOM_CHARS }), () => Random.nextIntBetween(0, 32, { halfOpen: true }));
80
+ /** The digits plus one, or `undefined` when every digit is the largest. */
81
+ const incremented = (digits) => {
82
+ const next = [...digits];
83
+ for (let i = next.length - 1; i >= 0; i--) {
84
+ if (next[i] < 31) {
85
+ next[i] = next[i] + 1;
86
+ return next;
87
+ }
88
+ next[i] = 0;
89
+ }
90
+ return undefined;
91
+ };
92
+ /**
93
+ * The suffix after `last` at time `now`, monotonic like a monotonic ULID: a
94
+ * later millisecond takes the fresh digits; the same or an earlier one keeps
95
+ * `last`'s time and counts its digits up (into the next millisecond in the
96
+ * astronomically unlikely case they are all at their largest).
97
+ */
98
+ const nextSuffix = (last, now, fresh) => {
99
+ const time = Math.max(0, Math.floor(now));
100
+ if (last === undefined || time > last.time)
101
+ return { time, digits: fresh };
102
+ const digits = incremented(last.digits);
103
+ return digits === undefined ? { time: last.time + 1, digits: fresh } : { time: last.time, digits };
104
+ };
105
+ const encodeSuffix = (suffix) => {
106
+ let time = "";
107
+ let t = suffix.time;
108
+ for (let i = 0; i < SUFFIX_TIME_CHARS; i++) {
109
+ time = CROCKFORD[t % 32] + time;
110
+ t = Math.floor(t / 32);
111
+ }
112
+ return time + suffix.digits.map((d) => CROCKFORD[d]).join("");
113
+ };
114
+ const isAsciiPrintable = (text) => {
115
+ for (let i = 0; i < text.length; i++) {
116
+ const code = text.charCodeAt(i);
117
+ if (code < 0x20 || code > 0x7e)
118
+ return false;
119
+ }
120
+ return true;
121
+ };
122
+ const concat = (chunks) => {
123
+ const out = new Uint8Array(chunks.reduce((n, chunk) => n + chunk.length, 0));
124
+ let offset = 0;
125
+ for (const chunk of chunks) {
126
+ out.set(chunk, offset);
127
+ offset += chunk.length;
128
+ }
129
+ return out;
130
+ };
131
+ const sameBytes = (a, b) => a.length === b.length && a.every((byte, i) => byte === b[i]);
132
+ const rejected = (message, ref) => new BlobStoreFailure({ reason: "Rejected", ref, cause: new Error(`${WHERE}: ${message}`) });
133
+ const notFound = (ref) => new BlobStoreFailure({
134
+ reason: "NotFound",
135
+ ref,
136
+ cause: new Error(`${WHERE}: no such version`),
137
+ });
138
+ // ---------------------------------------------------------------------------
139
+ // Store
140
+ // ---------------------------------------------------------------------------
141
+ /**
142
+ * Build an in-memory store.
143
+ *
144
+ * @throws `[EDD-9116]` for invalid options: an unknown key; `versioning` not
145
+ * `"versioned"` / `"keyPerWrite"`; a `prefix` over 256 bytes or starting
146
+ * with `/`; `presign` not a boolean; `maxVersionBytes` not an integer from
147
+ * the ids the store makes (32 / 0) to 1,024; `maxUploadAge` outside 1 minute
148
+ * … 7 days; a concurrency, `readChunkBytes`, `partSize`, `maxParts` or
149
+ * `partAttempts` not a positive integer; `clock` not a `Clock`; `failures`
150
+ * not a function.
151
+ */
152
+ export const make = (options = {}) => {
153
+ if (typeof options !== "object" || options === null) {
154
+ return invalid(WHERE, `options must be an object, got ${String(options)}.`);
155
+ }
156
+ for (const key of Object.keys(options)) {
157
+ if (!OPTION_KEYS.has(key)) {
158
+ invalid(WHERE, `unknown option "${key}" (expected ${[...OPTION_KEYS].join(", ")}).`);
159
+ }
160
+ }
161
+ const versioning = options.versioning ?? "versioned";
162
+ if (versioning !== "versioned" && versioning !== "keyPerWrite") {
163
+ invalid(WHERE, `versioning must be "versioned" or "keyPerWrite", got ${JSON.stringify(versioning)}.`);
164
+ }
165
+ const prefix = checkPrefix(WHERE, "prefix", options.prefix ?? "");
166
+ const presign = options.presign ?? false;
167
+ if (typeof presign !== "boolean") {
168
+ invalid(WHERE, `presign must be a boolean, got ${String(presign)}.`);
169
+ }
170
+ const idBytes = versioning === "versioned" ? VERSION_ID_CHARS : 0;
171
+ const maxVersionBytes = options.maxVersionBytes ?? idBytes;
172
+ if (typeof maxVersionBytes !== "number" ||
173
+ !Number.isSafeInteger(maxVersionBytes) ||
174
+ maxVersionBytes < idBytes ||
175
+ maxVersionBytes > 1_024) {
176
+ invalid(WHERE, `maxVersionBytes must be an integer from ${idBytes} (the version ids this store makes) ` +
177
+ `to 1024, got ${String(maxVersionBytes)}.`);
178
+ }
179
+ const maxUploadAge = checkMaxUploadAgeOption(WHERE, options.maxUploadAge);
180
+ const readConcurrency = checkPositiveInteger(WHERE, "readConcurrency", options.readConcurrency ?? DEFAULT_READ_CONCURRENCY);
181
+ const writeConcurrency = checkPositiveInteger(WHERE, "writeConcurrency", options.writeConcurrency ?? DEFAULT_WRITE_CONCURRENCY);
182
+ const readChunkBytes = checkPositiveInteger(WHERE, "readChunkBytes", options.readChunkBytes ?? DEFAULT_READ_CHUNK_BYTES);
183
+ const partSize = checkPositiveInteger(WHERE, "partSize", options.partSize ?? Multipart.DEFAULT_PART_SIZE);
184
+ const maxParts = checkPositiveInteger(WHERE, "maxParts", options.maxParts ?? Multipart.MAX_PARTS);
185
+ const uploadConcurrency = checkPositiveInteger(WHERE, "uploadConcurrency", options.uploadConcurrency ?? Multipart.DEFAULT_UPLOAD_CONCURRENCY);
186
+ const partAttempts = checkPositiveInteger(WHERE, "partAttempts", options.partAttempts ?? 3);
187
+ const clock = options.clock;
188
+ if (clock !== undefined &&
189
+ (typeof clock !== "object" || clock === null || !Effect.isEffect(clock.currentTimeMillis))) {
190
+ invalid(WHERE, "clock must be an Effect Clock.");
191
+ }
192
+ const failures = options.failures;
193
+ if (failures !== undefined && typeof failures !== "function") {
194
+ invalid(WHERE, "failures must be a function.");
195
+ }
196
+ const objects = new Map();
197
+ let lastSuffix;
198
+ const calls = {
199
+ put: 0,
200
+ get: 0,
201
+ delete: 0,
202
+ copy: 0,
203
+ list: 0,
204
+ head: 0,
205
+ mark: 0,
206
+ presign: 0,
207
+ };
208
+ const multipart = { creates: 0, parts: 0, completes: 0, aborts: 0 };
209
+ /** Open multipart uploads: id → their parts by number. */
210
+ const uploads = new Map();
211
+ let nextUpload = 0;
212
+ const now = clock === undefined ? Clock.currentTimeMillis : clock.currentTimeMillis;
213
+ /** Ask the hook about a call. */
214
+ const ask = (call) => Effect.suspend(() => {
215
+ if (failures === undefined)
216
+ return Effect.succeed(undefined);
217
+ const answer = failures(call);
218
+ return Effect.flatMap(Effect.isEffect(answer) ? answer : Effect.succeed(answer), (fault) => fault === undefined || fault._tag === "Fail" || fault._tag === "Interrupt"
219
+ ? Effect.succeed(fault)
220
+ : Effect.die(new Error(`${WHERE}: failures returned an unknown fault`)));
221
+ });
222
+ /** Count the call and ask the hook about it. */
223
+ const begin = (call) => Effect.suspend(() => {
224
+ calls[call.action] += 1;
225
+ return ask({ ...call, n: calls[call.action] });
226
+ });
227
+ const trigger = (fault, action, ref) => fault._tag === "Interrupt"
228
+ ? Effect.interrupt
229
+ : Effect.fail(new BlobStoreFailure({
230
+ reason: fault.reason,
231
+ ref,
232
+ cause: new Error(`${WHERE}: injected ${fault.reason} on ${action}` +
233
+ (fault.at === "response" ? " (after it took effect)" : "")),
234
+ }));
235
+ const atRequest = (fault) => fault !== undefined && fault.at !== "response";
236
+ const atResponse = (fault) => fault !== undefined && fault.at === "response";
237
+ /**
238
+ * Run an effect-shaped call: the fault before or after `body`. A fault at
239
+ * the request names `ref`; one at the response names `responseRef(result)`
240
+ * (default `ref`).
241
+ */
242
+ const call = (info, ref, body, responseRef = () => ref) => Effect.flatMap(begin(info), (fault) => atRequest(fault)
243
+ ? trigger(fault, info.action, ref)
244
+ : Effect.flatMap(body, (result) => atResponse(fault)
245
+ ? trigger(fault, info.action, responseRef(result))
246
+ : Effect.succeed(result)));
247
+ /** Run a stream-shaped call: the fault after `afterChunks` items, or at the end. */
248
+ const streamCall = (info, ref, items) => Stream.unwrap(Effect.flatMap(begin(info), (fault) => {
249
+ if (atRequest(fault) && (fault.afterChunks ?? 0) === 0) {
250
+ return Effect.succeed(Stream.fromEffect(trigger(fault, info.action, ref)));
251
+ }
252
+ return Effect.map(items, (all) => {
253
+ if (fault === undefined)
254
+ return Stream.fromIterable(all);
255
+ const head = atRequest(fault) ? all.slice(0, fault.afterChunks ?? 0) : all;
256
+ return Stream.concat(Stream.fromIterable(head), Stream.fromEffect(trigger(fault, info.action, ref)));
257
+ });
258
+ }));
259
+ const find = (ref) => objects.get(ref.key)?.find((v) => v.version === ref.version);
260
+ const checkKey = (key) => {
261
+ const bytes = typeof key === "string" ? utf8Bytes(key) : undefined;
262
+ if (bytes === undefined || bytes < 1)
263
+ return rejected("the key must be a non-empty string");
264
+ // A key-per-write store appends "/" + the suffix.
265
+ const extended = versioning === "keyPerWrite" ? bytes + 1 + KEY_SUFFIX_CHARS : bytes;
266
+ if (extended > MAX_KEY_BYTES) {
267
+ return rejected(`the key is ${extended} UTF-8 bytes, over S3's ${MAX_KEY_BYTES}-byte limit`);
268
+ }
269
+ return undefined;
270
+ };
271
+ const checkUpload = (request) => {
272
+ const keyFailure = checkKey(request.key);
273
+ if (keyFailure !== undefined)
274
+ return keyFailure;
275
+ if (typeof request.contentType !== "string" ||
276
+ request.contentType.length === 0 ||
277
+ !isAsciiPrintable(request.contentType)) {
278
+ // An HTTP header carries no control character (CR, LF, NUL…).
279
+ return rejected("contentType must be a non-empty printable US-ASCII string");
280
+ }
281
+ const metadata = request.metadata;
282
+ if (typeof metadata !== "object" || metadata === null) {
283
+ return rejected("metadata must be a record of strings");
284
+ }
285
+ for (const [key, value] of Object.entries(metadata)) {
286
+ if (key.length === 0 || typeof value !== "string" || !isAsciiPrintable(key + value)) {
287
+ return rejected(`metadata entry ${JSON.stringify(key)} is not a printable US-ASCII string`);
288
+ }
289
+ }
290
+ const bytes = metadataBytes(metadata);
291
+ if (bytes > MAX_METADATA_BYTES) {
292
+ return rejected(`metadata is ${bytes} bytes, over S3's ${MAX_METADATA_BYTES}-byte limit`);
293
+ }
294
+ return undefined;
295
+ };
296
+ /** Store a new version; returns its ref. */
297
+ const store = (request, bytes) => Effect.gen(function* () {
298
+ const at = yield* now;
299
+ const metadata = {};
300
+ for (const [key, value] of Object.entries(request.metadata)) {
301
+ metadata[key.toLowerCase()] = value;
302
+ }
303
+ let key = request.key;
304
+ let version = "";
305
+ if (versioning === "keyPerWrite") {
306
+ const fresh = yield* randomDigits;
307
+ // From here to the insert nothing yields, so the suffix order is the write order.
308
+ do {
309
+ lastSuffix = nextSuffix(lastSuffix, at, fresh);
310
+ key = `${request.key}/${encodeSuffix(lastSuffix)}`;
311
+ } while (objects.has(key));
312
+ }
313
+ else {
314
+ const existing = objects.get(key) ?? [];
315
+ do {
316
+ version = yield* randomHex(VERSION_ID_CHARS);
317
+ } while (existing.some((v) => v.version === version));
318
+ }
319
+ const versions = objects.get(key) ?? [];
320
+ versions.push({
321
+ version,
322
+ bytes,
323
+ contentType: request.contentType,
324
+ metadata: Object.freeze(metadata),
325
+ lastModified: at,
326
+ mark: undefined,
327
+ });
328
+ objects.set(key, versions);
329
+ return { ref: { key, version }, size: bytes.length };
330
+ });
331
+ /** The stored body checked as S3 checks one: its length and its CRC-64/NVME. */
332
+ const checkBody = (request, bytes) => Effect.gen(function* () {
333
+ if (request.contentLength !== undefined && request.contentLength !== bytes.length) {
334
+ return yield* rejected(`the body is ${bytes.length} bytes, but contentLength is ${request.contentLength}`);
335
+ }
336
+ const checksum = yield* request.checksum;
337
+ if (checksum.algorithm !== "crc64nvme" || !sameBytes(checksum.value, crc64nvme(bytes))) {
338
+ return yield* new BlobStoreFailure({
339
+ reason: "ChecksumMismatch",
340
+ cause: new Error(`${WHERE}: the body does not match its CRC-64/NVME`),
341
+ });
342
+ }
343
+ });
344
+ const RETRIED = new Set(["Throttled", "Unavailable"]);
345
+ /** S3's multipart protocol, simulated, for one put (`n` is its call number). */
346
+ const protocolOf = (request, n) => {
347
+ const phase = (info) => ask({ action: "multipart", n, key: request.key, multipart: info });
348
+ const part = (id, req, attempt) => Effect.gen(function* () {
349
+ multipart.parts += 1;
350
+ const fault = yield* phase({ phase: "part", part: req.number, attempt });
351
+ const open = uploads.get(id);
352
+ if (open === undefined) {
353
+ return yield* rejected(`no multipart upload ${id} is open (NoSuchUpload)`);
354
+ }
355
+ if (req.number > maxParts) {
356
+ return yield* new BlobStoreFailure({
357
+ reason: "TooLarge",
358
+ cause: new Error(`${WHERE}: the body needs more than ${maxParts} parts of ${req.partSize} bytes; ` +
359
+ "give its length (Offload.source(stream, { contentLength })) so the part size " +
360
+ "adapts, or raise partSize"),
361
+ });
362
+ }
363
+ if (atRequest(fault))
364
+ return yield* trigger(fault, "put", undefined);
365
+ open.set(req.number, new Uint8Array(req.bytes));
366
+ if (atResponse(fault))
367
+ return yield* trigger(fault, "put", undefined);
368
+ return req.number;
369
+ }).pipe(Effect.catchIf((failure) => RETRIED.has(failure.reason) && attempt < partAttempts, () => part(id, req, attempt + 1)));
370
+ return {
371
+ single: (bytes) => Effect.gen(function* () {
372
+ yield* checkBody(request, bytes);
373
+ return yield* store(request, new Uint8Array(bytes));
374
+ }),
375
+ create: Effect.gen(function* () {
376
+ multipart.creates += 1;
377
+ const fault = yield* phase({ phase: "create" });
378
+ if (atRequest(fault))
379
+ return yield* trigger(fault, "put", undefined);
380
+ const id = ++nextUpload;
381
+ uploads.set(id, new Map());
382
+ if (atResponse(fault))
383
+ return yield* trigger(fault, "put", undefined);
384
+ return id;
385
+ }),
386
+ part: (id, req) => part(id, req, 1),
387
+ complete: (id, numbers) => Effect.gen(function* () {
388
+ multipart.completes += 1;
389
+ const fault = yield* phase({ phase: "complete" });
390
+ const lost = atResponse(fault) ? fault : undefined;
391
+ if (atRequest(fault))
392
+ return yield* trigger(fault, "put", undefined);
393
+ const open = uploads.get(id);
394
+ if (open === undefined) {
395
+ return yield* rejected(`no multipart upload ${id} is open (NoSuchUpload)`);
396
+ }
397
+ const parts = numbers.map((number) => open.get(number));
398
+ if (parts.some((bytes) => bytes === undefined)) {
399
+ return yield* rejected("a completed part was never uploaded (InvalidPart)");
400
+ }
401
+ const bytes = concat(parts);
402
+ yield* checkBody(request, bytes);
403
+ uploads.delete(id);
404
+ const result = yield* store(request, bytes);
405
+ if (lost !== undefined) {
406
+ if (lost._tag === "Interrupt")
407
+ return yield* Effect.interrupt;
408
+ // S3 never learns the version a lost Complete made.
409
+ return yield* new BlobStoreFailure({
410
+ reason: lost.reason,
411
+ completeLost: true,
412
+ cause: new Error(`${WHERE}: injected ${lost.reason} on put (its multipart upload completed, ` +
413
+ "but the response was lost)"),
414
+ });
415
+ }
416
+ return result;
417
+ }),
418
+ abort: (id) => Effect.gen(function* () {
419
+ multipart.aborts += 1;
420
+ const fault = yield* phase({ phase: "abort" });
421
+ if (atRequest(fault))
422
+ return yield* trigger(fault, "put", undefined);
423
+ uploads.delete(id);
424
+ if (atResponse(fault))
425
+ return yield* trigger(fault, "put", undefined);
426
+ }),
427
+ };
428
+ };
429
+ const put = (request) => Effect.suspend(() => {
430
+ calls.put += 1;
431
+ const n = calls.put;
432
+ return Effect.flatMap(ask({ action: "put", n, key: request.key }), (fault) => Effect.gen(function* () {
433
+ const failure = checkUpload(request);
434
+ if (failure !== undefined)
435
+ return yield* failure;
436
+ let body;
437
+ if (request.body instanceof Uint8Array) {
438
+ body = request.body;
439
+ }
440
+ else if (Stream.isStream(request.body)) {
441
+ body = request.body;
442
+ }
443
+ else {
444
+ return yield* rejected("body must be a Uint8Array or a Stream");
445
+ }
446
+ if (atRequest(fault)) {
447
+ // No effect: the body is consumed (`afterChunks` chunks, default all
448
+ // of it — a single-use stream is drained), then the call fails
449
+ // before it completes (a multipart upload's parts are aborted).
450
+ const limit = fault.afterChunks;
451
+ const chunks = body instanceof Uint8Array ? Stream.succeed(body) : body;
452
+ body = Stream.concat(Stream.mapEffect(chunks, (chunk, i) => limit !== undefined && i >= limit
453
+ ? trigger(fault, "put", undefined)
454
+ : Effect.succeed(chunk)), Stream.fromEffect(trigger(fault, "put", undefined)));
455
+ }
456
+ const result = yield* Multipart.upload(body, request.contentLength, { partSize, concurrency: uploadConcurrency, maxParts, where: WHERE }, protocolOf(request, n));
457
+ if (atResponse(fault))
458
+ return yield* trigger(fault, "put", result.ref);
459
+ return result;
460
+ }));
461
+ });
462
+ const checkRange = (range, size) => {
463
+ if (range === undefined)
464
+ return undefined;
465
+ const { offset, length } = range;
466
+ if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0) {
467
+ return `range offset ${String(offset)} is not a non-negative integer`;
468
+ }
469
+ if (length !== undefined &&
470
+ (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0)) {
471
+ return `range length ${String(length)} is not a non-negative integer`;
472
+ }
473
+ if (offset > size)
474
+ return `range offset ${offset} is past the end (${size} bytes)`;
475
+ return undefined;
476
+ };
477
+ const get = (ref, options) => streamCall({ action: "get", ref }, ref, Effect.suspend(() => {
478
+ const found = find(ref);
479
+ if (found === undefined)
480
+ return Effect.fail(notFound(ref));
481
+ const range = options?.range;
482
+ const problem = checkRange(range, found.bytes.length);
483
+ if (problem !== undefined)
484
+ return Effect.fail(rejected(problem, ref));
485
+ const start = range?.offset ?? 0;
486
+ const end = range?.length === undefined
487
+ ? found.bytes.length
488
+ : Math.min(found.bytes.length, start + range.length);
489
+ const chunks = [];
490
+ for (let at = start; at < end; at += readChunkBytes) {
491
+ chunks.push(found.bytes.slice(at, Math.min(end, at + readChunkBytes)));
492
+ }
493
+ return Effect.succeed(chunks);
494
+ }));
495
+ const deleteRefs = (refs) => call({ action: "delete", refs }, undefined, Effect.sync(() => {
496
+ for (const ref of refs) {
497
+ const versions = objects.get(ref.key);
498
+ if (versions === undefined)
499
+ continue;
500
+ const kept = versions.filter((v) => v.version !== ref.version);
501
+ if (kept.length === 0)
502
+ objects.delete(ref.key);
503
+ else
504
+ objects.set(ref.key, kept);
505
+ }
506
+ }));
507
+ const copy = (source, request) => call({ action: "copy", key: request.key, ref: source }, source, Effect.suspend(() => {
508
+ const found = find(source);
509
+ if (found === undefined)
510
+ return Effect.fail(notFound(source));
511
+ const failure = checkUpload(request);
512
+ if (failure !== undefined)
513
+ return Effect.fail(failure);
514
+ if (request.contentLength !== undefined && request.contentLength !== found.bytes.length) {
515
+ return Effect.fail(rejected(`the source is ${found.bytes.length} bytes, but contentLength is ${request.contentLength}`, source));
516
+ }
517
+ return store(request, found.bytes);
518
+ }),
519
+ // a lost response names the copy it stored, as a put's does
520
+ (result) => result.ref);
521
+ const list = (listPrefix, options) => streamCall({ action: "list", key: listPrefix }, undefined, Effect.sync(() => {
522
+ const startAfter = options?.startAfter;
523
+ const keys = [...objects.keys()]
524
+ .filter((key) => key.startsWith(listPrefix) &&
525
+ (startAfter === undefined || compareUtf8(key, startAfter) > 0))
526
+ .sort((a, b) => compareUtf8(a, b));
527
+ return keys.flatMap((key) => {
528
+ const versions = objects.get(key) ?? [];
529
+ return versions
530
+ .map((v, i) => ({
531
+ ref: { key, version: v.version },
532
+ size: v.bytes.length,
533
+ lastModified: new Date(v.lastModified),
534
+ isLatest: i === versions.length - 1,
535
+ }))
536
+ .reverse();
537
+ });
538
+ }));
539
+ const head = (ref) => call({ action: "head", ref }, ref, Effect.suspend(() => {
540
+ const found = find(ref);
541
+ return found === undefined
542
+ ? Effect.fail(notFound(ref))
543
+ : Effect.succeed({ ...found.metadata });
544
+ }));
545
+ const marks = {
546
+ get: (ref) => call({ action: "mark", ref, mark: "get" }, ref, Effect.sync(() => Option.map(Option.fromNullishOr(find(ref)?.mark), (mark) => new Date(mark)))),
547
+ set: (ref, since) => call({ action: "mark", ref, mark: "set" }, ref, Effect.suspend(() => {
548
+ if (!(since instanceof Date) || Number.isNaN(since.getTime())) {
549
+ return Effect.fail(rejected("a mark must be a valid Date", ref));
550
+ }
551
+ const found = find(ref);
552
+ if (found !== undefined)
553
+ found.mark = since.getTime();
554
+ return Effect.void;
555
+ })),
556
+ clear: (ref) => call({ action: "mark", ref, mark: "clear" }, ref, Effect.sync(() => {
557
+ const found = find(ref);
558
+ if (found !== undefined)
559
+ found.mark = undefined;
560
+ })),
561
+ };
562
+ const presignUrl = (ref, options) => call({ action: "presign", ref }, ref, Effect.suspend(() => {
563
+ const expiresIn = options?.expiresIn;
564
+ if (!Duration.isDuration(expiresIn) ||
565
+ !Duration.isFinite(expiresIn) ||
566
+ !Duration.isPositive(expiresIn)) {
567
+ return Effect.fail(rejected("expiresIn must be a positive, finite Duration", ref));
568
+ }
569
+ const params = new URLSearchParams();
570
+ if (ref.version !== "")
571
+ params.set("versionId", ref.version);
572
+ params.set("expiresIn", String(Math.ceil(Duration.toSeconds(expiresIn))));
573
+ if (options.contentType !== undefined)
574
+ params.set("contentType", options.contentType);
575
+ const path = ref.key
576
+ .split("/")
577
+ .map((segment) => encodeURIComponent(segment))
578
+ .join("/");
579
+ return Effect.succeed(`memory://${path}?${params.toString()}`);
580
+ }));
581
+ const inspect = () => ({
582
+ versions: [...objects.keys()]
583
+ .sort((a, b) => compareUtf8(a, b))
584
+ .flatMap((key) => {
585
+ const versions = objects.get(key) ?? [];
586
+ return versions
587
+ .map((v, i) => ({
588
+ ref: { key, version: v.version },
589
+ size: v.bytes.length,
590
+ bytes: v.bytes.slice(),
591
+ contentType: v.contentType,
592
+ metadata: v.metadata,
593
+ lastModified: new Date(v.lastModified),
594
+ isLatest: i === versions.length - 1,
595
+ mark: Option.map(Option.fromNullishOr(v.mark), (mark) => new Date(mark)),
596
+ }))
597
+ .reverse();
598
+ }),
599
+ calls: { ...calls },
600
+ multipart: { ...multipart, inProgress: uploads.size },
601
+ });
602
+ return {
603
+ name: `memory://${prefix}`,
604
+ prefix,
605
+ limits: {
606
+ maxVersionBytes,
607
+ maxKeySuffixBytes: versioning === "keyPerWrite" ? 1 + KEY_SUFFIX_CHARS : 0,
608
+ },
609
+ maxUploadAge,
610
+ readConcurrency,
611
+ writeConcurrency,
612
+ put,
613
+ get,
614
+ delete: deleteRefs,
615
+ copy,
616
+ list,
617
+ head,
618
+ marks,
619
+ ...(presign ? { presign: presignUrl } : {}),
620
+ inspect,
621
+ };
622
+ };
623
+ //# sourceMappingURL=MemoryBlobStore.js.map