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,770 @@
1
+ /**
2
+ * @internal The S3 `BlobStore` (#179, design §12.2) behind
3
+ * `effect-dynamodb/blob/s3`, written directly against `@aws-sdk/client-s3`
4
+ * (an optional peer dependency; the main entry never imports this module).
5
+ *
6
+ * - **Versions.** Every upload — `PutObject`, `CompleteMultipartUpload`,
7
+ * `CopyObject` — must answer with a real `VersionId`. A missing one (a
8
+ * bucket never versioned, or a suspended one on MinIO) or `"null"` (a
9
+ * suspended bucket on AWS) fails with `Unversioned`, after the object it
10
+ * wrote is deleted by `VersionId: "null"` (no delete marker), or by a plain
11
+ * `DeleteObject` when that is refused. No `GetBucketVersioning` pre-check.
12
+ * - **Checksums.** Every upload carries the library's CRC-64/NVME
13
+ * (`ChecksumAlgorithm: "CRC64NVME"` and the value; never the SDK's CRC32
14
+ * default): a single `PutObject` the body's, a multipart upload each part's
15
+ * and the whole body's (`ChecksumType: "FULL_OBJECT"`), which S3 validates.
16
+ * - **Multipart** runs the shared driver (`internal/Multipart.ts`, design §7):
17
+ * parts of exactly `partSize` bytes at `uploadConcurrency`, aborted on any
18
+ * failure or interruption between create and complete. A completion that
19
+ * may have happened although it failed (a lost or throttled response, a
20
+ * transport failure, a retry finding `NoSuchUpload`, any refusal after the
21
+ * SDK resent it) is `completeLost`.
22
+ * - **Reads** stream `GetObject` by `VersionId` (and `Range`) through
23
+ * `transformToWebStream()`, runtime-neutral; the library verifies sizes and
24
+ * checksums itself (design §8.6).
25
+ * - **Deletes** by `VersionId` through `DeleteObjects`, up to 1,000 a request;
26
+ * a version already gone counts as deleted.
27
+ * - **Listing** is `ListObjectVersions` (delete markers excluded), **head**
28
+ * `HeadObject`, and **marks** the version's `edd-unref-since` tag, merged
29
+ * with any other tags it has (design §11.4).
30
+ *
31
+ * SDK errors become `BlobStoreFailure`s by {@link classify}; the SDK error is
32
+ * the `cause`, after `redactCredentialRefusal` (#186) replaces a signature or
33
+ * credential refusal, whose reply can quote the session token.
34
+ *
35
+ * Not part of the public API (`effect-dynamodb/blob/s3` is).
36
+ */
37
+ import { AbortMultipartUploadCommand, CompleteMultipartUploadCommand, CopyObjectCommand, CreateMultipartUploadCommand, DeleteObjectCommand, DeleteObjectsCommand, GetObjectCommand, GetObjectTaggingCommand, HeadObjectCommand, ListObjectVersionsCommand, PutObjectCommand, PutObjectTaggingCommand, S3Client, UploadPartCommand, UploadPartCopyCommand, } from "@aws-sdk/client-s3";
38
+ import { crc64nvme } from "@effect-dynamodb/schema/internal/Crc64Nvme.js";
39
+ import { Cause, Duration, Effect, Exit, Option, Schedule, Stream } from "effect";
40
+ import { Base64 } from "effect/encoding";
41
+ import { BlobStoreFailure, checkMaxUploadAgeOption, checkPositiveInteger, checkPrefix, DEFAULT_READ_CONCURRENCY, DEFAULT_WRITE_CONCURRENCY, invalid, } from "../internal/BlobStoreContract.js";
42
+ import { redactCredentialRefusal } from "../internal/CredentialRefusal.js";
43
+ import * as Multipart from "../internal/Multipart.js";
44
+ /** S3's largest `CopyObject` source, 5 GiB. */
45
+ export const MAX_COPY_OBJECT_BYTES = 5 * 1024 * 1024 * 1024;
46
+ /** S3's longest `VersionId`, in bytes (F10). */
47
+ export const MAX_S3_VERSION_BYTES = 1_024;
48
+ /** The version tag an unreferenced-since mark is (design §11.4). */
49
+ export const MARK_TAG = "edd-unref-since";
50
+ const DEFAULT_TUNING = {
51
+ maxCopyObjectBytes: MAX_COPY_OBJECT_BYTES,
52
+ maxParts: Multipart.MAX_PARTS,
53
+ };
54
+ const OPTION_KEYS = new Set([
55
+ "bucket",
56
+ "prefix",
57
+ "client",
58
+ "clientConfig",
59
+ "partSize",
60
+ "uploadConcurrency",
61
+ "readConcurrency",
62
+ "writeConcurrency",
63
+ "maxUploadAge",
64
+ "serverSideEncryption",
65
+ "storageClass",
66
+ "notFoundRetry",
67
+ "presign",
68
+ ]);
69
+ const SSE_KEYS = new Set([
70
+ "ServerSideEncryption",
71
+ "SSEKMSKeyId",
72
+ "BucketKeyEnabled",
73
+ ]);
74
+ const show = (value) => typeof value === "string" ? JSON.stringify(value) : String(value);
75
+ /**
76
+ * Check the options.
77
+ *
78
+ * @throws `[EDD-9116]` for an unknown key; an empty `bucket`; a `prefix` over
79
+ * 256 bytes or starting with `/`; both `client` and `clientConfig`, or a
80
+ * `client` without `send`; a `partSize` that is not an integer from 5 MiB to
81
+ * 5 GiB; a concurrency that is not a positive integer; a `maxUploadAge`
82
+ * outside 1 minute … 7 days; `serverSideEncryption` with another key;
83
+ * `storageClass` that is not a non-empty string; `notFoundRetry` that is
84
+ * not a `Schedule`; `presign` without a `getSignedUrl` function.
85
+ */
86
+ export const resolveOptions = (where, options) => {
87
+ if (typeof options !== "object" || options === null) {
88
+ return invalid(where, `options must be an object, got ${show(options)}.`);
89
+ }
90
+ for (const key of Object.keys(options)) {
91
+ if (!OPTION_KEYS.has(key)) {
92
+ invalid(where, `unknown option "${key}" (expected ${[...OPTION_KEYS].join(", ")}).`);
93
+ }
94
+ }
95
+ const bucket = options.bucket;
96
+ if (typeof bucket !== "string" || bucket.length === 0) {
97
+ invalid(where, `bucket must be a non-empty string, got ${show(bucket)}.`);
98
+ }
99
+ const prefix = checkPrefix(where, "prefix", options.prefix ?? "");
100
+ const client = options.client;
101
+ if (client !== undefined) {
102
+ if (options.clientConfig !== undefined) {
103
+ invalid(where, "give client or clientConfig, not both.");
104
+ }
105
+ if (typeof client !== "object" || client === null || typeof client.send !== "function") {
106
+ invalid(where, "client must be an S3Client.");
107
+ }
108
+ }
109
+ const clientConfig = options.clientConfig;
110
+ if (clientConfig !== undefined && (typeof clientConfig !== "object" || clientConfig === null)) {
111
+ invalid(where, "clientConfig must be an S3ClientConfig object.");
112
+ }
113
+ const partSize = options.partSize ?? Multipart.DEFAULT_PART_SIZE;
114
+ if (typeof partSize !== "number" ||
115
+ !Number.isSafeInteger(partSize) ||
116
+ partSize < Multipart.MIN_PART_SIZE ||
117
+ partSize > Multipart.MAX_PART_SIZE) {
118
+ invalid(where, `partSize must be an integer from 5 MiB to 5 GiB, got ${show(partSize)}.`);
119
+ }
120
+ const uploadConcurrency = checkPositiveInteger(where, "uploadConcurrency", options.uploadConcurrency ?? Multipart.DEFAULT_UPLOAD_CONCURRENCY);
121
+ const readConcurrency = checkPositiveInteger(where, "readConcurrency", options.readConcurrency ?? DEFAULT_READ_CONCURRENCY);
122
+ const writeConcurrency = checkPositiveInteger(where, "writeConcurrency", options.writeConcurrency ?? DEFAULT_WRITE_CONCURRENCY);
123
+ const maxUploadAge = checkMaxUploadAgeOption(where, options.maxUploadAge);
124
+ const sse = options.serverSideEncryption ?? {};
125
+ if (typeof sse !== "object" || sse === null) {
126
+ invalid(where, "serverSideEncryption must be an object.");
127
+ }
128
+ for (const key of Object.keys(sse)) {
129
+ if (!SSE_KEYS.has(key)) {
130
+ invalid(where, `serverSideEncryption has an unknown key "${key}" (expected ${[...SSE_KEYS].join(", ")}).`);
131
+ }
132
+ }
133
+ const storageClass = options.storageClass;
134
+ if (storageClass !== undefined &&
135
+ (typeof storageClass !== "string" || storageClass.length === 0)) {
136
+ invalid(where, `storageClass must be a non-empty string, got ${show(storageClass)}.`);
137
+ }
138
+ const notFoundRetry = options.notFoundRetry;
139
+ if (notFoundRetry !== undefined && !Schedule.isSchedule(notFoundRetry)) {
140
+ invalid(where, "notFoundRetry must be a Schedule.");
141
+ }
142
+ const presign = options.presign;
143
+ if (presign !== undefined &&
144
+ (typeof presign !== "object" || presign === null || typeof presign.getSignedUrl !== "function")) {
145
+ invalid(where, "presign must be { getSignedUrl } (from @aws-sdk/s3-request-presigner).");
146
+ }
147
+ return {
148
+ bucket,
149
+ prefix,
150
+ client,
151
+ clientConfig,
152
+ partSize,
153
+ uploadConcurrency,
154
+ readConcurrency,
155
+ writeConcurrency,
156
+ maxUploadAge,
157
+ serverSideEncryption: sse,
158
+ storageClass,
159
+ notFoundRetry,
160
+ presign,
161
+ };
162
+ };
163
+ // ---------------------------------------------------------------------------
164
+ // Errors
165
+ // ---------------------------------------------------------------------------
166
+ /** The S3 error code of an SDK error (its `name`, or its `Code`). */
167
+ export const errorCode = (cause) => {
168
+ if (typeof cause !== "object" || cause === null)
169
+ return undefined;
170
+ const { name, Code } = cause;
171
+ if (typeof Code === "string" && Code !== "")
172
+ return Code;
173
+ return typeof name === "string" && name !== "" && name !== "Error" ? name : undefined;
174
+ };
175
+ /** The HTTP status of an SDK error's response, when it had one. */
176
+ export const httpStatus = (cause) => {
177
+ const status = cause
178
+ ?.$metadata?.httpStatusCode;
179
+ return typeof status === "number" ? status : undefined;
180
+ };
181
+ /** How many times the SDK sent the request that failed (`$metadata.attempts`), when it says. */
182
+ export const sdkAttempts = (cause) => {
183
+ const attempts = cause
184
+ ?.$metadata?.attempts;
185
+ return typeof attempts === "number" ? attempts : undefined;
186
+ };
187
+ const NOT_FOUND = new Set(["NoSuchVersion", "NoSuchKey", "NoSuchBucket"]);
188
+ const THROTTLED = new Set([
189
+ "SlowDown",
190
+ "Throttling",
191
+ "ThrottlingException",
192
+ "TooManyRequests",
193
+ "TooManyRequestsException",
194
+ ]);
195
+ const CHECKSUM = new Set([
196
+ "BadDigest",
197
+ "XAmzContentChecksumMismatch",
198
+ "InvalidDigest",
199
+ ]);
200
+ /** A version (or key) already gone: deleting it, or reading its tags, finds nothing. */
201
+ const GONE = new Set(["NoSuchVersion", "NoSuchKey"]);
202
+ /**
203
+ * The reason of an S3 error code and the HTTP status it came with:
204
+ * `NotFound` for `NoSuchVersion` / `NoSuchKey` / `NoSuchBucket` (and a
205
+ * `HeadObject` 404, which has no body to name it); `AccessDenied` (any 403);
206
+ * `Throttled` for `SlowDown` and 503 / 429; `ChecksumMismatch` for
207
+ * `BadDigest` / `XAmzContentChecksumMismatch` / `InvalidDigest`; `TooLarge`
208
+ * for `EntityTooLarge`; `Unavailable` for other 5xx and for a failure without
209
+ * a response (transport, after the SDK's retries: no code and no status);
210
+ * `Rejected` for any other 4xx. A code without a status is a per-key error
211
+ * of a `DeleteObjects` response.
212
+ */
213
+ export const classifyCode = (code, status) => {
214
+ if (code !== undefined) {
215
+ if (NOT_FOUND.has(code))
216
+ return "NotFound";
217
+ if (code === "AccessDenied")
218
+ return "AccessDenied";
219
+ if (THROTTLED.has(code))
220
+ return "Throttled";
221
+ if (CHECKSUM.has(code))
222
+ return "ChecksumMismatch";
223
+ if (code === "EntityTooLarge")
224
+ return "TooLarge";
225
+ }
226
+ if (status === undefined) {
227
+ if (code === undefined)
228
+ return "Unavailable";
229
+ return code === "InternalError" || code === "ServiceUnavailable" ? "Unavailable" : "Rejected";
230
+ }
231
+ if (status === 404 && code === "NotFound")
232
+ return "NotFound";
233
+ if (status === 503 || status === 429)
234
+ return "Throttled";
235
+ if (status === 403)
236
+ return "AccessDenied";
237
+ if (status >= 500)
238
+ return "Unavailable";
239
+ if (status >= 400)
240
+ return "Rejected";
241
+ return "Unavailable";
242
+ };
243
+ /** The reason of an SDK error. */
244
+ export const classify = (cause) => {
245
+ const status = httpStatus(cause);
246
+ // A failure without a response (a timeout, a reset, an abort) is a
247
+ // transport one, whatever its name.
248
+ return classifyCode(status === undefined ? undefined : errorCode(cause), status);
249
+ };
250
+ const failure = (cause, ref) => new BlobStoreFailure({ reason: classify(cause), ref, cause });
251
+ const refused = (message, ref) => new BlobStoreFailure({ reason: "Rejected", ref, cause: new Error(message) });
252
+ // ---------------------------------------------------------------------------
253
+ // Helpers
254
+ // ---------------------------------------------------------------------------
255
+ /** The `VersionId` of a ref (none for version `""`, an immutable key). */
256
+ const versionIdOf = (ref) => ref.version === "" ? {} : { VersionId: ref.version };
257
+ /** A `CopySource` naming `ref` of `bucket`: each key segment URL-encoded. */
258
+ export const copySourceOf = (bucket, ref) => {
259
+ const path = ref.key
260
+ .split("/")
261
+ .map((segment) => encodeURIComponent(segment))
262
+ .join("/");
263
+ const version = ref.version === "" ? "" : `?versionId=${encodeURIComponent(ref.version)}`;
264
+ return `${bucket}/${path}${version}`;
265
+ };
266
+ /** The `Range` header of `range` (its length positive). */
267
+ const rangeHeader = (range) => range.length === undefined
268
+ ? `bytes=${range.offset}-`
269
+ : `bytes=${range.offset}-${range.offset + range.length - 1}`;
270
+ const checkRange = (range) => {
271
+ const { offset, length } = range;
272
+ if (typeof offset !== "number" || !Number.isSafeInteger(offset) || offset < 0) {
273
+ return `range offset ${String(offset)} is not a non-negative integer`;
274
+ }
275
+ if (length !== undefined &&
276
+ (typeof length !== "number" || !Number.isSafeInteger(length) || length < 0)) {
277
+ return `range length ${String(length)} is not a non-negative integer`;
278
+ }
279
+ return undefined;
280
+ };
281
+ /** A chunk as a plain `Uint8Array` (a Node `Buffer` viewed, not copied). */
282
+ const plain = (chunk) => chunk.constructor === Uint8Array
283
+ ? chunk
284
+ : new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
285
+ const chunked = (items, size) => {
286
+ const out = [];
287
+ for (let at = 0; at < items.length; at += size)
288
+ out.push(items.slice(at, at + size));
289
+ return out;
290
+ };
291
+ /** At most this many keys per `DeleteObjects` request (S3's limit). */
292
+ export const MAX_DELETE_KEYS = 1_000;
293
+ // ---------------------------------------------------------------------------
294
+ // The store
295
+ // ---------------------------------------------------------------------------
296
+ /**
297
+ * The store over `client`.
298
+ */
299
+ export const makeService = (options, client, tuning = DEFAULT_TUNING) => {
300
+ const { bucket, prefix, partSize, uploadConcurrency } = options;
301
+ const name = `s3://${bucket}/${prefix}`;
302
+ const uploadSettings = {
303
+ ...options.serverSideEncryption,
304
+ ...(options.storageClass === undefined ? {} : { StorageClass: options.storageClass }),
305
+ };
306
+ const send = (command, onError) => Effect.tryPromise({
307
+ try: (signal) => client.send(command, { abortSignal: signal }),
308
+ catch: (cause) => onError(redactCredentialRefusal(cause)),
309
+ });
310
+ // -------------------------------------------------------------------------
311
+ // Unversioned answers
312
+ // -------------------------------------------------------------------------
313
+ /**
314
+ * Delete the object an upload wrote to a bucket that gave it no real
315
+ * version: by `VersionId: "null"` (removes exactly it, no delete marker),
316
+ * else a plain `DeleteObject` (in a suspended bucket that leaves a `null`
317
+ * delete marker, harmless). Never fails: says what it did.
318
+ */
319
+ const deleteUnversioned = (key) => send(new DeleteObjectCommand({ Bucket: bucket, Key: key, VersionId: "null" }), (cause) => failure(cause)).pipe(Effect.as("The object it wrote was deleted."), Effect.catch((byVersion) => send(new DeleteObjectCommand({ Bucket: bucket, Key: key }), (cause) => failure(cause)).pipe(Effect.as("The object it wrote was deleted (a null delete marker may remain)."), Effect.catch((plainDelete) => Effect.logWarning(`effect-dynamodb: ${name} could not delete "${key}", written to an unversioned ` +
320
+ "bucket; delete it by hand", byVersion.cause, plainDelete.cause).pipe(Effect.as(`Deleting the object it wrote failed (${String(plainDelete.cause)}); delete it by hand.`))))));
321
+ /**
322
+ * The version an upload's answer names, or — when it names none (or
323
+ * `"null"`) — `Unversioned`, after deleting what it wrote.
324
+ */
325
+ const versionOf = (version, key, action) => {
326
+ if (version !== undefined && version !== "" && version !== "null") {
327
+ return Effect.succeed(version);
328
+ }
329
+ return Effect.uninterruptible(Effect.flatMap(deleteUnversioned(key), (cleanup) => Effect.fail(new BlobStoreFailure({
330
+ reason: "Unversioned",
331
+ cause: new Error(`${name}: ${action} of "${key}" returned ` +
332
+ (version === "null" ? 'VersionId "null"' : "no VersionId") +
333
+ `: bucket "${bucket}" does not have versioning enabled. Offloaded values are ` +
334
+ `pinned by version: enable versioning on the bucket. ${cleanup}`),
335
+ }))));
336
+ };
337
+ // -------------------------------------------------------------------------
338
+ // put
339
+ // -------------------------------------------------------------------------
340
+ const tooLarge = (request, cause) => new BlobStoreFailure({
341
+ reason: "TooLarge",
342
+ cause: new Error(`${name}: the body needs more than ${tuning.maxParts} parts of ${request.partSize} ` +
343
+ "bytes; give its length (Offload.source(stream, { contentLength })) so the part size " +
344
+ `adapts, or raise partSize (${String(cause)})`),
345
+ });
346
+ /**
347
+ * A failed `CompleteMultipartUpload`, `completeLost` unless S3 refused it
348
+ * outright: a 4xx other than 429 and `NoSuchUpload`, on the SDK's only
349
+ * attempt (`$metadata.attempts === 1`). A lost or throttled response, a
350
+ * transport failure, a retry finding the upload gone, or any refusal of a
351
+ * resent request (an earlier attempt may have completed, its answer lost)
352
+ * may each follow a completion nobody reported — as may a refusal whose
353
+ * attempt count is not reported.
354
+ */
355
+ const completeFailure = (cause) => {
356
+ const status = httpStatus(cause);
357
+ const refusedOutright = sdkAttempts(cause) === 1 &&
358
+ status !== undefined &&
359
+ status >= 400 &&
360
+ status < 500 &&
361
+ status !== 429 &&
362
+ errorCode(cause) !== "NoSuchUpload";
363
+ return new BlobStoreFailure({
364
+ reason: classify(cause),
365
+ ...(refusedOutright ? {} : { completeLost: true }),
366
+ cause,
367
+ });
368
+ };
369
+ const createUpload = (key, headers, checksums) => send(new CreateMultipartUploadCommand({
370
+ Bucket: bucket,
371
+ Key: key,
372
+ ...headers,
373
+ ...uploadSettings,
374
+ ...(checksums ? { ChecksumAlgorithm: "CRC64NVME", ChecksumType: "FULL_OBJECT" } : {}),
375
+ }), (cause) => failure(cause)).pipe(Effect.flatMap((out) => out.UploadId === undefined || out.UploadId === ""
376
+ ? Effect.fail(refused(`${name}: CreateMultipartUpload of "${key}" gave no UploadId`))
377
+ : Effect.succeed(out.UploadId)));
378
+ const abortUpload = (key, uploadId) => send(new AbortMultipartUploadCommand({ Bucket: bucket, Key: key, UploadId: uploadId }), (cause) => failure(cause)).pipe(Effect.asVoid,
379
+ // Gone already (completed, or aborted before): what an abort wants.
380
+ Effect.catchIf((f) => errorCode(f.cause) === "NoSuchUpload", () => Effect.void));
381
+ const protocolOf = (request) => {
382
+ const key = request.key;
383
+ const headers = { ContentType: request.contentType, Metadata: { ...request.metadata } };
384
+ return {
385
+ single: (bytes) => Effect.gen(function* () {
386
+ const checksum = yield* request.checksum;
387
+ const out = yield* send(new PutObjectCommand({
388
+ Bucket: bucket,
389
+ Key: key,
390
+ ...headers,
391
+ ...uploadSettings,
392
+ Body: bytes,
393
+ ContentLength: bytes.length,
394
+ ChecksumAlgorithm: "CRC64NVME",
395
+ ChecksumCRC64NVME: Base64.encode(checksum.value),
396
+ }), (cause) => failure(cause));
397
+ const version = yield* versionOf(out.VersionId, key, "PutObject");
398
+ return { ref: { key, version }, size: bytes.length };
399
+ }),
400
+ create: createUpload(key, headers, true),
401
+ part: (uploadId, part) => {
402
+ const checksum = Base64.encode(crc64nvme(part.bytes));
403
+ return send(new UploadPartCommand({
404
+ Bucket: bucket,
405
+ Key: key,
406
+ UploadId: uploadId,
407
+ PartNumber: part.number,
408
+ Body: part.bytes,
409
+ ContentLength: part.bytes.length,
410
+ ChecksumAlgorithm: "CRC64NVME",
411
+ ChecksumCRC64NVME: checksum,
412
+ }),
413
+ // Part 10,001 is S3's to refuse: diagnosed, not pre-checked.
414
+ (cause) => part.number > tuning.maxParts && classify(cause) === "Rejected"
415
+ ? tooLarge(part, cause)
416
+ : failure(cause)).pipe(Effect.flatMap((out) => out.ETag === undefined
417
+ ? Effect.fail(refused(`${name}: UploadPart ${part.number} of "${key}" gave no ETag`))
418
+ : Effect.succeed({
419
+ number: part.number,
420
+ etag: out.ETag,
421
+ checksum: out.ChecksumCRC64NVME ?? checksum,
422
+ size: part.bytes.length,
423
+ })));
424
+ },
425
+ // The driver runs it uninterruptibly — with the `VersionId` check and
426
+ // an unversioned cleanup — so a sent Complete runs to its answer. An
427
+ // interruption meanwhile still discards that answer (the ledger reports
428
+ // the put as `interrupted`).
429
+ complete: (uploadId, parts) => Effect.gen(function* () {
430
+ const checksum = yield* request.checksum;
431
+ const size = parts.reduce((total, part) => total + part.size, 0);
432
+ const out = yield* send(new CompleteMultipartUploadCommand({
433
+ Bucket: bucket,
434
+ Key: key,
435
+ UploadId: uploadId,
436
+ MultipartUpload: {
437
+ Parts: parts.map((part) => ({
438
+ PartNumber: part.number,
439
+ ETag: part.etag,
440
+ ...(part.checksum === undefined ? {} : { ChecksumCRC64NVME: part.checksum }),
441
+ })),
442
+ },
443
+ ChecksumCRC64NVME: Base64.encode(checksum.value),
444
+ ChecksumType: "FULL_OBJECT",
445
+ MpuObjectSize: size,
446
+ }), (cause) => completeFailure(cause));
447
+ const version = yield* versionOf(out.VersionId, key, "CompleteMultipartUpload");
448
+ return { ref: { key, version }, size };
449
+ }),
450
+ abort: (uploadId) => abortUpload(key, uploadId),
451
+ };
452
+ };
453
+ const put = (request) => Effect.suspend(() => Multipart.upload(request.body, request.contentLength, { partSize, concurrency: uploadConcurrency, maxParts: tuning.maxParts, where: name }, protocolOf(request)));
454
+ // -------------------------------------------------------------------------
455
+ // copy
456
+ // -------------------------------------------------------------------------
457
+ const headObject = (ref) => send(new HeadObjectCommand({ Bucket: bucket, Key: ref.key, ...versionIdOf(ref) }), (cause) => failure(cause, ref));
458
+ const sizeOf = (ref) => Effect.flatMap(headObject(ref), (out) => typeof out.ContentLength === "number"
459
+ ? Effect.succeed(out.ContentLength)
460
+ : Effect.fail(refused(`${name}: HeadObject gave no ContentLength`, ref)));
461
+ /** A copy over the `CopyObject` limit: `UploadPartCopy` ranges, completed (or aborted). */
462
+ const multipartCopy = (source, request, length, headers) => Effect.suspend(() => {
463
+ const key = request.key;
464
+ const size = Multipart.partSizeFor(partSize, length, tuning.maxParts);
465
+ const count = Math.max(1, Math.ceil(length / size));
466
+ let created;
467
+ let completed = false;
468
+ const run = Effect.gen(function* () {
469
+ // No checksum algorithm: a server-side part has no client checksum to
470
+ // send (and MinIO refuses part copies into a checksummed upload); the
471
+ // library verifies every full read itself.
472
+ const uploadId = yield* Effect.uninterruptible(Effect.tap(createUpload(key, headers, false), (id) => Effect.sync(() => {
473
+ created = id;
474
+ })));
475
+ const parts = yield* Effect.forEach(Array.from({ length: count }, (_, i) => i), (i) => {
476
+ const start = i * size;
477
+ const end = Math.min(length, start + size) - 1;
478
+ return send(new UploadPartCopyCommand({
479
+ Bucket: bucket,
480
+ Key: key,
481
+ UploadId: uploadId,
482
+ PartNumber: i + 1,
483
+ CopySource: copySourceOf(bucket, source),
484
+ CopySourceRange: `bytes=${start}-${end}`,
485
+ }), (cause) => failure(cause, source)).pipe(Effect.flatMap((out) => {
486
+ const etag = out.CopyPartResult?.ETag;
487
+ return etag === undefined
488
+ ? Effect.fail(refused(`${name}: UploadPartCopy ${i + 1} of "${key}" gave no ETag`))
489
+ : Effect.succeed({ PartNumber: i + 1, ETag: etag });
490
+ }));
491
+ }, { concurrency: uploadConcurrency });
492
+ // As the put's driver does: uninterruptible, `completed` set in the
493
+ // same region, the `VersionId` check (and cleanup) inside it. An
494
+ // interruption meanwhile discards the answer (the ledger reports the
495
+ // copy as `interrupted`).
496
+ return yield* Effect.uninterruptible(Effect.gen(function* () {
497
+ const out = yield* send(new CompleteMultipartUploadCommand({
498
+ Bucket: bucket,
499
+ Key: key,
500
+ UploadId: uploadId,
501
+ MultipartUpload: { Parts: parts },
502
+ MpuObjectSize: length,
503
+ }), (cause) => completeFailure(cause));
504
+ completed = true;
505
+ const version = yield* versionOf(out.VersionId, key, "CompleteMultipartUpload");
506
+ return { ref: { key, version }, size: length };
507
+ }));
508
+ });
509
+ return run.pipe(Effect.onExit((exit) => {
510
+ const uploadId = created;
511
+ if (Exit.isSuccess(exit) || uploadId === undefined || completed)
512
+ return Effect.void;
513
+ return Effect.uninterruptible(abortUpload(key, uploadId).pipe(Effect.catchCause((cause) => Effect.logWarning(`effect-dynamodb: ${name} could not abort a multipart copy; a lifecycle ` +
514
+ "AbortIncompleteMultipartUpload rule reclaims its parts", Cause.squash(cause)))));
515
+ }));
516
+ });
517
+ /**
518
+ * A copy of `source`: `CopyObject`, or `UploadPartCopy` ranges over S3's
519
+ * 5 GiB `CopyObject` limit. A request that gives no `contentLength` learns
520
+ * the source's size from `HeadObject` first — the path depends on it, and
521
+ * nothing is written before it is known.
522
+ */
523
+ const copy = (source, request) => Effect.gen(function* () {
524
+ const key = request.key;
525
+ const headers = { ContentType: request.contentType, Metadata: { ...request.metadata } };
526
+ const length = request.contentLength ?? (yield* sizeOf(source));
527
+ if (length > tuning.maxCopyObjectBytes) {
528
+ return yield* multipartCopy(source, request, length, headers);
529
+ }
530
+ const out = yield* send(new CopyObjectCommand({
531
+ Bucket: bucket,
532
+ Key: key,
533
+ CopySource: copySourceOf(bucket, source),
534
+ ...headers,
535
+ MetadataDirective: "REPLACE",
536
+ // The copy starts without tags: never with the source's
537
+ // unreferenced-since mark (design §11.4).
538
+ TaggingDirective: "REPLACE",
539
+ ChecksumAlgorithm: "CRC64NVME",
540
+ ...uploadSettings,
541
+ }), (cause) => failure(cause, source));
542
+ const version = yield* versionOf(out.VersionId, key, "CopyObject");
543
+ return { ref: { key, version }, size: length };
544
+ });
545
+ // -------------------------------------------------------------------------
546
+ // get / head / list / delete
547
+ // -------------------------------------------------------------------------
548
+ /** `offset` is at most the version's size; past it is `Rejected`. */
549
+ const checkOffset = (ref, offset, cause) => Effect.flatMap(sizeOf(ref), (size) => offset <= size
550
+ ? Effect.void
551
+ : Effect.fail(new BlobStoreFailure({
552
+ reason: "Rejected",
553
+ ref,
554
+ cause: cause ?? new Error(`${name}: range offset ${offset} is past the end (${size})`),
555
+ })));
556
+ const retryNotFound = (effect) => options.notFoundRetry === undefined
557
+ ? effect
558
+ : Effect.retry(effect, {
559
+ schedule: options.notFoundRetry,
560
+ while: (f) => f.reason === "NotFound",
561
+ });
562
+ const get = (ref, getOptions) => Stream.unwrap(Effect.gen(function* () {
563
+ const range = getOptions?.range;
564
+ if (range !== undefined) {
565
+ const problem = checkRange(range);
566
+ if (problem !== undefined)
567
+ return yield* refused(`${name}: ${problem}`, ref);
568
+ if (range.length === 0) {
569
+ yield* checkOffset(ref, range.offset);
570
+ return Stream.empty;
571
+ }
572
+ }
573
+ const request = send(new GetObjectCommand({
574
+ Bucket: bucket,
575
+ Key: ref.key,
576
+ ...versionIdOf(ref),
577
+ ...(range === undefined ? {} : { Range: rangeHeader(range) }),
578
+ }), (cause) => failure(cause, ref));
579
+ const out = yield* retryNotFound(request).pipe(Effect.map(Option.some),
580
+ // A range starting at the very end is empty; past it, refused.
581
+ Effect.catchIf((f) => range !== undefined && errorCode(f.cause) === "InvalidRange", (f) => Effect.as(checkOffset(ref, range?.offset ?? 0, f.cause), Option.none())));
582
+ if (Option.isNone(out))
583
+ return Stream.empty;
584
+ const body = out.value.Body;
585
+ if (body === undefined)
586
+ return Stream.empty;
587
+ return Stream.fromReadableStream({
588
+ evaluate: () => body.transformToWebStream(),
589
+ onError: (cause) => failure(redactCredentialRefusal(cause), ref),
590
+ }).pipe(Stream.mapEffect((chunk) => chunk instanceof Uint8Array
591
+ ? Effect.succeed(plain(chunk))
592
+ : Effect.fail(new BlobStoreFailure({
593
+ reason: "Unavailable",
594
+ ref,
595
+ cause: new Error(`${name}: GetObject's body emitted a chunk that is not bytes`),
596
+ }))));
597
+ }));
598
+ const head = (ref) => Effect.map(headObject(ref), (out) => ({ ...(out.Metadata ?? {}) }));
599
+ const listingOf = (version) => {
600
+ const { Key, VersionId, Size, LastModified, IsLatest } = version;
601
+ if (Key === undefined)
602
+ return "a version without a Key";
603
+ if (VersionId === undefined)
604
+ return `a version of "${Key}" without a VersionId`;
605
+ if (typeof Size !== "number")
606
+ return `version "${VersionId}" of "${Key}" without a Size`;
607
+ if (!(LastModified instanceof Date) || Number.isNaN(LastModified.getTime())) {
608
+ return `version "${VersionId}" of "${Key}" without a LastModified date`;
609
+ }
610
+ return {
611
+ ref: { key: Key, version: VersionId },
612
+ size: Size,
613
+ lastModified: LastModified,
614
+ isLatest: IsLatest === true,
615
+ };
616
+ };
617
+ const list = (listPrefix, listOptions) => Stream.paginate({ key: listOptions?.startAfter, version: undefined }, (marker) => send(new ListObjectVersionsCommand({
618
+ Bucket: bucket,
619
+ Prefix: listPrefix,
620
+ ...(marker.key === undefined ? {} : { KeyMarker: marker.key }),
621
+ ...(marker.version === undefined ? {} : { VersionIdMarker: marker.version }),
622
+ }), (cause) => failure(cause)).pipe(Effect.flatMap((out) => {
623
+ const listings = [];
624
+ // Delete markers (`DeleteMarkers`) are not versions: never listed.
625
+ for (const version of out.Versions ?? []) {
626
+ const listing = listingOf(version);
627
+ if (typeof listing === "string") {
628
+ return Effect.fail(refused(`${name}: ListObjectVersions gave ${listing}`));
629
+ }
630
+ listings.push(listing);
631
+ }
632
+ if (out.IsTruncated !== true) {
633
+ return Effect.succeed([listings, Option.none()]);
634
+ }
635
+ if (out.NextKeyMarker === undefined && out.NextVersionIdMarker === undefined) {
636
+ return Effect.fail(refused(`${name}: ListObjectVersions was truncated without a next marker`));
637
+ }
638
+ return Effect.succeed([
639
+ listings,
640
+ Option.some({ key: out.NextKeyMarker, version: out.NextVersionIdMarker }),
641
+ ]);
642
+ })));
643
+ const deleteRefs = (refs) => Effect.suspend(() => {
644
+ const seen = new Set();
645
+ const unique = refs.filter((ref) => {
646
+ const id = `${ref.key}\u0000${ref.version}`;
647
+ if (seen.has(id))
648
+ return false;
649
+ seen.add(id);
650
+ return true;
651
+ });
652
+ return Effect.forEach(chunked(unique, MAX_DELETE_KEYS), (chunk) => send(new DeleteObjectsCommand({
653
+ Bucket: bucket,
654
+ Delete: {
655
+ Quiet: true,
656
+ Objects: chunk.map((ref) => ({ Key: ref.key, ...versionIdOf(ref) })),
657
+ },
658
+ }), (cause) => failure(cause)).pipe(Effect.flatMap((out) => {
659
+ // A version already gone is deleted: deletes are idempotent.
660
+ const errors = (out.Errors ?? []).filter((error) => error.Code === undefined || !GONE.has(error.Code));
661
+ const first = errors[0];
662
+ if (first === undefined)
663
+ return Effect.void;
664
+ return Effect.fail(new BlobStoreFailure({
665
+ reason: classifyCode(first.Code ?? "InternalError", undefined),
666
+ ref: { key: first.Key ?? "", version: first.VersionId ?? "" },
667
+ cause: new Error(`${name}: DeleteObjects refused ${errors.length} of ${chunk.length} ` +
668
+ "versions: " +
669
+ errors
670
+ .slice(0, 5)
671
+ .map((error) => `${error.Key ?? "?"}@${error.VersionId ?? ""} ${error.Code ?? "?"}` +
672
+ (error.Message === undefined ? "" : ` (${error.Message})`))
673
+ .join("; ")),
674
+ }));
675
+ })), { discard: true });
676
+ });
677
+ // -------------------------------------------------------------------------
678
+ // marks
679
+ // -------------------------------------------------------------------------
680
+ const tagsOf = (ref) => Effect.map(send(new GetObjectTaggingCommand({ Bucket: bucket, Key: ref.key, ...versionIdOf(ref) }), (cause) => failure(cause, ref)), (out) => out.TagSet ?? []);
681
+ const putTags = (ref, tags) => Effect.asVoid(send(new PutObjectTaggingCommand({
682
+ Bucket: bucket,
683
+ Key: ref.key,
684
+ ...versionIdOf(ref),
685
+ Tagging: { TagSet: [...tags] },
686
+ }), (cause) => failure(cause, ref)));
687
+ /** An absent ref: `get` gives `Option.none()`, `set` / `clear` succeed. */
688
+ const whenPresent = (effect, absent) => Effect.catchIf(effect, (f) => {
689
+ const code = errorCode(f.cause);
690
+ return code !== undefined && GONE.has(code);
691
+ }, () => Effect.succeed(absent));
692
+ const others = (tags) => tags.filter((tag) => tag.Key !== MARK_TAG);
693
+ const marks = {
694
+ get: (ref) => whenPresent(Effect.map(tagsOf(ref), (tags) => {
695
+ const value = tags.find((tag) => tag.Key === MARK_TAG)?.Value;
696
+ const at = value === undefined ? Number.NaN : Date.parse(value);
697
+ // An unreadable mark reads as none: the sweep marks the version again,
698
+ // which only defers its deletion.
699
+ return Number.isNaN(at) ? Option.none() : Option.some(new Date(at));
700
+ }), Option.none()),
701
+ set: (ref, since) => Effect.suspend(() => {
702
+ if (!(since instanceof Date) || Number.isNaN(since.getTime())) {
703
+ return Effect.fail(refused(`${name}: a mark must be a valid Date`, ref));
704
+ }
705
+ return whenPresent(Effect.flatMap(tagsOf(ref), (tags) => putTags(ref, [...others(tags), { Key: MARK_TAG, Value: since.toISOString() }])), undefined);
706
+ }),
707
+ clear: (ref) => whenPresent(Effect.flatMap(tagsOf(ref), (tags) => tags.some((tag) => tag.Key === MARK_TAG) ? putTags(ref, others(tags)) : Effect.void), undefined),
708
+ };
709
+ // -------------------------------------------------------------------------
710
+ // presign
711
+ // -------------------------------------------------------------------------
712
+ const presigner = options.presign;
713
+ const presign = presigner === undefined
714
+ ? undefined
715
+ : (ref, presignOptions) => Effect.suspend(() => {
716
+ const expiresIn = presignOptions?.expiresIn;
717
+ if (!Duration.isDuration(expiresIn) ||
718
+ !Duration.isFinite(expiresIn) ||
719
+ !Duration.isPositive(expiresIn)) {
720
+ return Effect.fail(refused(`${name}: expiresIn must be a positive, finite Duration`, ref));
721
+ }
722
+ const command = new GetObjectCommand({
723
+ Bucket: bucket,
724
+ Key: ref.key,
725
+ ...versionIdOf(ref),
726
+ ...(presignOptions.contentType === undefined
727
+ ? {}
728
+ : { ResponseContentType: presignOptions.contentType }),
729
+ });
730
+ return Effect.tryPromise({
731
+ try: () => presigner.getSignedUrl(client, command, {
732
+ expiresIn: Math.max(1, Math.ceil(Duration.toSeconds(expiresIn))),
733
+ }),
734
+ // The presigner signs locally: what it refuses is the request's.
735
+ catch: (cause) => new BlobStoreFailure({
736
+ reason: "Rejected",
737
+ ref,
738
+ cause: redactCredentialRefusal(cause),
739
+ }),
740
+ });
741
+ });
742
+ return {
743
+ name,
744
+ prefix,
745
+ limits: { maxVersionBytes: MAX_S3_VERSION_BYTES, maxKeySuffixBytes: 0 },
746
+ maxUploadAge: options.maxUploadAge,
747
+ readConcurrency: options.readConcurrency,
748
+ writeConcurrency: options.writeConcurrency,
749
+ put,
750
+ get,
751
+ delete: deleteRefs,
752
+ copy,
753
+ list,
754
+ head,
755
+ marks,
756
+ ...(presign === undefined ? {} : { presign }),
757
+ };
758
+ };
759
+ /**
760
+ * The client the store uses: the caller's, or one built from `clientConfig`
761
+ * and destroyed when `scope` closes.
762
+ */
763
+ export const acquireClient = (options) => options.client !== undefined
764
+ ? Effect.succeed(options.client)
765
+ : Effect.acquireRelease(Effect.sync(() => new S3Client({
766
+ // The library verifies every full read itself (design §8.6).
767
+ responseChecksumValidation: "WHEN_REQUIRED",
768
+ ...options.clientConfig,
769
+ })), (client) => Effect.sync(() => client.destroy()));
770
+ //# sourceMappingURL=S3BlobStore.js.map