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.
- package/dist/Aggregate.d.ts +157 -20
- package/dist/Aggregate.d.ts.map +1 -1
- package/dist/Aggregate.js +1219 -286
- package/dist/Aggregate.js.map +1 -1
- package/dist/Batch.d.ts +17 -4
- package/dist/Batch.d.ts.map +1 -1
- package/dist/Batch.js +129 -62
- package/dist/Batch.js.map +1 -1
- package/dist/BlobGc.d.ts +243 -0
- package/dist/BlobGc.d.ts.map +1 -0
- package/dist/BlobGc.js +961 -0
- package/dist/BlobGc.js.map +1 -0
- package/dist/BlobStore.d.ts +83 -0
- package/dist/BlobStore.d.ts.map +1 -0
- package/dist/BlobStore.js +70 -0
- package/dist/BlobStore.js.map +1 -0
- package/dist/Collection.d.ts +88 -8
- package/dist/Collection.d.ts.map +1 -1
- package/dist/Collection.js +22 -26
- package/dist/Collection.js.map +1 -1
- package/dist/Collections.d.ts +0 -7
- package/dist/Collections.d.ts.map +1 -1
- package/dist/Collections.js +0 -16
- package/dist/Collections.js.map +1 -1
- package/dist/DynamoClient.d.ts +68 -35
- package/dist/DynamoClient.d.ts.map +1 -1
- package/dist/DynamoClient.js +58 -12
- package/dist/DynamoClient.js.map +1 -1
- package/dist/Entity.d.ts +403 -104
- package/dist/Entity.d.ts.map +1 -1
- package/dist/Entity.js +1771 -382
- package/dist/Entity.js.map +1 -1
- package/dist/EventStore.d.ts +323 -77
- package/dist/EventStore.d.ts.map +1 -1
- package/dist/EventStore.js +473 -96
- package/dist/EventStore.js.map +1 -1
- package/dist/Offload.d.ts +199 -0
- package/dist/Offload.d.ts.map +1 -0
- package/dist/Offload.js +120 -0
- package/dist/Offload.js.map +1 -0
- package/dist/Query.d.ts +132 -59
- package/dist/Query.d.ts.map +1 -1
- package/dist/Query.js +95 -31
- package/dist/Query.js.map +1 -1
- package/dist/StorageEncoding.d.ts +62 -15
- package/dist/StorageEncoding.d.ts.map +1 -1
- package/dist/StorageEncoding.js +108 -24
- package/dist/StorageEncoding.js.map +1 -1
- package/dist/Table.d.ts +1 -1
- package/dist/Table.d.ts.map +1 -1
- package/dist/Transaction.d.ts +16 -3
- package/dist/Transaction.d.ts.map +1 -1
- package/dist/Transaction.js +28 -9
- package/dist/Transaction.js.map +1 -1
- package/dist/blob/S3BlobStore.d.ts +178 -0
- package/dist/blob/S3BlobStore.d.ts.map +1 -0
- package/dist/blob/S3BlobStore.js +770 -0
- package/dist/blob/S3BlobStore.js.map +1 -0
- package/dist/blob/s3.d.ts +122 -0
- package/dist/blob/s3.d.ts.map +1 -0
- package/dist/blob/s3.js +143 -0
- package/dist/blob/s3.js.map +1 -0
- package/dist/index.d.ts +9 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/AggregateWrite.d.ts +130 -0
- package/dist/internal/AggregateWrite.d.ts.map +1 -0
- package/dist/internal/AggregateWrite.js +341 -0
- package/dist/internal/AggregateWrite.js.map +1 -0
- package/dist/internal/BlobCalls.d.ts +70 -0
- package/dist/internal/BlobCalls.d.ts.map +1 -0
- package/dist/internal/BlobCalls.js +105 -0
- package/dist/internal/BlobCalls.js.map +1 -0
- package/dist/internal/BlobKeys.d.ts +100 -0
- package/dist/internal/BlobKeys.d.ts.map +1 -0
- package/dist/internal/BlobKeys.js +135 -0
- package/dist/internal/BlobKeys.js.map +1 -0
- package/dist/internal/BlobLedger.d.ts +323 -0
- package/dist/internal/BlobLedger.d.ts.map +1 -0
- package/dist/internal/BlobLedger.js +1012 -0
- package/dist/internal/BlobLedger.js.map +1 -0
- package/dist/internal/BlobMetadata.d.ts +109 -0
- package/dist/internal/BlobMetadata.d.ts.map +1 -0
- package/dist/internal/BlobMetadata.js +249 -0
- package/dist/internal/BlobMetadata.js.map +1 -0
- package/dist/internal/BlobResolver.d.ts +146 -0
- package/dist/internal/BlobResolver.d.ts.map +1 -0
- package/dist/internal/BlobResolver.js +417 -0
- package/dist/internal/BlobResolver.js.map +1 -0
- package/dist/internal/BlobStoreContract.d.ts +214 -0
- package/dist/internal/BlobStoreContract.d.ts.map +1 -0
- package/dist/internal/BlobStoreContract.js +181 -0
- package/dist/internal/BlobStoreContract.js.map +1 -0
- package/dist/internal/BoundCrud.d.ts +153 -53
- package/dist/internal/BoundCrud.d.ts.map +1 -1
- package/dist/internal/BoundCrud.js +27 -5
- package/dist/internal/BoundCrud.js.map +1 -1
- package/dist/internal/BoundQuery.d.ts +49 -33
- package/dist/internal/BoundQuery.d.ts.map +1 -1
- package/dist/internal/BoundQuery.js +8 -2
- package/dist/internal/BoundQuery.js.map +1 -1
- package/dist/internal/BoundVectorQuery.d.ts +59 -25
- package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
- package/dist/internal/BoundVectorQuery.js +38 -17
- package/dist/internal/BoundVectorQuery.js.map +1 -1
- package/dist/internal/Capacity.d.ts +17 -2
- package/dist/internal/Capacity.d.ts.map +1 -1
- package/dist/internal/Capacity.js +47 -9
- package/dist/internal/Capacity.js.map +1 -1
- package/dist/internal/ConditionHolds.d.ts.map +1 -1
- package/dist/internal/ConditionHolds.js +2 -8
- package/dist/internal/ConditionHolds.js.map +1 -1
- package/dist/internal/CredentialRefusal.d.ts.map +1 -1
- package/dist/internal/CredentialRefusal.js +4 -0
- package/dist/internal/CredentialRefusal.js.map +1 -1
- package/dist/internal/Digest.d.ts +4 -3
- package/dist/internal/Digest.d.ts.map +1 -1
- package/dist/internal/Digest.js +25 -82
- package/dist/internal/Digest.js.map +1 -1
- package/dist/internal/EntityCombinators.d.ts +93 -45
- package/dist/internal/EntityCombinators.d.ts.map +1 -1
- package/dist/internal/EntityCombinators.js +42 -7
- package/dist/internal/EntityCombinators.js.map +1 -1
- package/dist/internal/EntityOps.d.ts +47 -6
- package/dist/internal/EntityOps.d.ts.map +1 -1
- package/dist/internal/EntityOps.js +30 -10
- package/dist/internal/EntityOps.js.map +1 -1
- package/dist/internal/EventProjection.d.ts +99 -25
- package/dist/internal/EventProjection.d.ts.map +1 -1
- package/dist/internal/EventProjection.js +124 -33
- package/dist/internal/EventProjection.js.map +1 -1
- package/dist/internal/ExpressionLimits.d.ts +22 -3
- package/dist/internal/ExpressionLimits.d.ts.map +1 -1
- package/dist/internal/ExpressionLimits.js +46 -7
- package/dist/internal/ExpressionLimits.js.map +1 -1
- package/dist/internal/GcSupport.d.ts +258 -0
- package/dist/internal/GcSupport.d.ts.map +1 -0
- package/dist/internal/GcSupport.js +284 -0
- package/dist/internal/GcSupport.js.map +1 -0
- package/dist/internal/ItemSize.d.ts +7 -1
- package/dist/internal/ItemSize.d.ts.map +1 -1
- package/dist/internal/ItemSize.js +13 -5
- package/dist/internal/ItemSize.js.map +1 -1
- package/dist/internal/MemoryBlobStore.d.ts +203 -0
- package/dist/internal/MemoryBlobStore.d.ts.map +1 -0
- package/dist/internal/MemoryBlobStore.js +623 -0
- package/dist/internal/MemoryBlobStore.js.map +1 -0
- package/dist/internal/MultiProjection.d.ts +56 -28
- package/dist/internal/MultiProjection.d.ts.map +1 -1
- package/dist/internal/MultiProjection.js +9 -3
- package/dist/internal/MultiProjection.js.map +1 -1
- package/dist/internal/Multipart.d.ts +96 -0
- package/dist/internal/Multipart.d.ts.map +1 -0
- package/dist/internal/Multipart.js +143 -0
- package/dist/internal/Multipart.js.map +1 -0
- package/dist/internal/OffloadChange.d.ts +187 -0
- package/dist/internal/OffloadChange.d.ts.map +1 -0
- package/dist/internal/OffloadChange.js +391 -0
- package/dist/internal/OffloadChange.js.map +1 -0
- package/dist/internal/OffloadInput.d.ts +141 -0
- package/dist/internal/OffloadInput.d.ts.map +1 -0
- package/dist/internal/OffloadInput.js +236 -0
- package/dist/internal/OffloadInput.js.map +1 -0
- package/dist/internal/OffloadRead.d.ts +140 -0
- package/dist/internal/OffloadRead.d.ts.map +1 -0
- package/dist/internal/OffloadRead.js +369 -0
- package/dist/internal/OffloadRead.js.map +1 -0
- package/dist/internal/OffloadTypes.d.ts +182 -0
- package/dist/internal/OffloadTypes.d.ts.map +1 -0
- package/dist/internal/OffloadTypes.js +15 -0
- package/dist/internal/OffloadTypes.js.map +1 -0
- package/dist/internal/OffloadValues.d.ts +87 -0
- package/dist/internal/OffloadValues.d.ts.map +1 -0
- package/dist/internal/OffloadValues.js +114 -0
- package/dist/internal/OffloadValues.js.map +1 -0
- package/dist/internal/OffloadWrite.d.ts +267 -0
- package/dist/internal/OffloadWrite.d.ts.map +1 -0
- package/dist/internal/OffloadWrite.js +766 -0
- package/dist/internal/OffloadWrite.js.map +1 -0
- package/dist/internal/Packed.d.ts +58 -23
- package/dist/internal/Packed.d.ts.map +1 -1
- package/dist/internal/Packed.js +108 -33
- package/dist/internal/Packed.js.map +1 -1
- package/dist/internal/ProjectionEngine.d.ts +28 -3
- package/dist/internal/ProjectionEngine.d.ts.map +1 -1
- package/dist/internal/ProjectionEngine.js +47 -9
- package/dist/internal/ProjectionEngine.js.map +1 -1
- package/dist/internal/RangePlanner.d.ts +3 -6
- package/dist/internal/RangePlanner.d.ts.map +1 -1
- package/dist/internal/RangePlanner.js +3 -29
- package/dist/internal/RangePlanner.js.map +1 -1
- package/dist/internal/Rekey.d.ts +16 -0
- package/dist/internal/Rekey.d.ts.map +1 -1
- package/dist/internal/Rekey.js +31 -2
- package/dist/internal/Rekey.js.map +1 -1
- package/dist/internal/StoredPointer.d.ts +19 -0
- package/dist/internal/StoredPointer.d.ts.map +1 -0
- package/dist/internal/StoredPointer.js +59 -0
- package/dist/internal/StoredPointer.js.map +1 -0
- package/dist/internal/TransactPlan.d.ts +18 -1
- package/dist/internal/TransactPlan.d.ts.map +1 -1
- package/dist/internal/TransactPlan.js +50 -10
- package/dist/internal/TransactPlan.js.map +1 -1
- package/dist/internal/TransactWriteOps.d.ts +33 -12
- package/dist/internal/TransactWriteOps.d.ts.map +1 -1
- package/dist/internal/TransactWriteOps.js +49 -19
- package/dist/internal/TransactWriteOps.js.map +1 -1
- package/dist/internal/TransactableOps.d.ts +58 -11
- package/dist/internal/TransactableOps.d.ts.map +1 -1
- package/dist/internal/TransactableOps.js +95 -19
- package/dist/internal/TransactableOps.js.map +1 -1
- package/dist/internal/Utf8Order.d.ts +21 -0
- package/dist/internal/Utf8Order.d.ts.map +1 -0
- package/dist/internal/Utf8Order.js +44 -0
- package/dist/internal/Utf8Order.js.map +1 -0
- package/dist/internal/WriteDiagnosis.d.ts +7 -1
- package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
- package/dist/internal/WriteDiagnosis.js +12 -16
- package/dist/internal/WriteDiagnosis.js.map +1 -1
- package/package.json +15 -4
|
@@ -0,0 +1,1012 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @internal The upload ledger (#179, design §6.2): who owns an offloaded
|
|
3
|
+
* value's upload until DynamoDB has decided whether the write that carries
|
|
4
|
+
* its pointer committed.
|
|
5
|
+
*
|
|
6
|
+
* - **Root.** The outermost library operation that can upload opens a ledger
|
|
7
|
+
* ({@link root}); nested library calls reuse it. `Capacity.detachContext`
|
|
8
|
+
* clears it from a bound client's captured context, as it clears the
|
|
9
|
+
* current operation, so a bound op joins the ledger of whatever runs it.
|
|
10
|
+
* - **Entries.** Every upload ({@link upload}) becomes an entry — its ref, the
|
|
11
|
+
* store it went to, its target (table, entity, attribute, row key), when it
|
|
12
|
+
* started, and its state, starting `pending`. An upload of the same content
|
|
13
|
+
* to the same key in one ledger is memoised: a re-planned transaction, a
|
|
14
|
+
* rebuilt `additionalItems`, a `commandHandler` retry that decides the same
|
|
15
|
+
* content upload once.
|
|
16
|
+
* - **Streams and handles** (design §3.8, §7). A stream is single-use: it
|
|
17
|
+
* uploads once, for one key of one ledger, memoised by its identity — a
|
|
18
|
+
* second key, a later operation or a retry after its upload failed is
|
|
19
|
+
* refused (`[EDD-9120]`). A handle's content is copied into a new version
|
|
20
|
+
* (the store's `copy` within the handle's own store, else streamed into a
|
|
21
|
+
* `put`), never shared. A `put` (or `copy`) failure that says its multipart
|
|
22
|
+
* upload may have completed (`completeLost`), and a `put` or `copy` an
|
|
23
|
+
* interruption cut short (`interrupted`), are reported at exit.
|
|
24
|
+
* - **Settling.** `Capacity.client`, the one place every library DynamoDB
|
|
25
|
+
* request goes through, hands each write request of a ledger with entries to
|
|
26
|
+
* {@link guard}: it refuses a request carrying an upload older than its
|
|
27
|
+
* store's `maxUploadAge` (`BlobStoreError { reason: "Expired" }`, nothing
|
|
28
|
+
* sent), gives a `TransactWriteItems` or PartiQL `ExecuteTransaction` the
|
|
29
|
+
* library's own `ClientRequestToken` and a single-item write `ReturnValuesOnConditionCheckFailure:
|
|
30
|
+
* "ALL_OLD"`, and settles the entries the request carries by its outcome —
|
|
31
|
+
* `$metadata.attempts`, the token, the `ALL_OLD` / `ALL_NEW` evidence
|
|
32
|
+
* (the table of §6.2).
|
|
33
|
+
* - **Lattice.** `pending < rejected < inDoubt < committed`: an entry only
|
|
34
|
+
* moves up, so a version attempt 2 committed is never deleted because
|
|
35
|
+
* attempt 1 was rejected.
|
|
36
|
+
* - **Exit.** When the root exits — success, failure or interruption — the
|
|
37
|
+
* `pending` and `rejected` entries are deleted (uninterruptibly, one
|
|
38
|
+
* `store.delete` per store, best-effort: a failed delete never replaces the
|
|
39
|
+
* operation's outcome). `inDoubt` entries, failed deletes and uploads whose
|
|
40
|
+
* version no entry names (a lost multipart completion; a store call an
|
|
41
|
+
* interruption cut short; a store answer that names no version of the
|
|
42
|
+
* requested key, which is refused and never deleted) are logged at
|
|
43
|
+
* `Warning` and delivered to the
|
|
44
|
+
* `Offload.layerObserver` observer.
|
|
45
|
+
* - **Read cache.** Each buffered entry's content (the JSON text, or the
|
|
46
|
+
* bytes) is kept by ref, so decoding what the operation just wrote never
|
|
47
|
+
* fetches it. A stream's or a copy's content is never in hand, so is not.
|
|
48
|
+
*
|
|
49
|
+
* No AWS SDK import: requests and responses are read structurally.
|
|
50
|
+
*
|
|
51
|
+
* Not part of the public API (`Offload.layerObserver` is).
|
|
52
|
+
*/
|
|
53
|
+
import { decode as decodePointer, decodeText as decodePointerText, isPointerHeader, isPointerText, make as makePointer, } from "@effect-dynamodb/schema/internal/BlobPointer.js";
|
|
54
|
+
import { crc64nvme, make as makeCrc64nvme } from "@effect-dynamodb/schema/internal/Crc64Nvme.js";
|
|
55
|
+
import { Cause, Clock, Context, Deferred, Duration, Effect, Exit, Layer, Option, Semaphore, Stream, } from "effect";
|
|
56
|
+
import { blobError, call, refKey } from "./BlobCalls.js";
|
|
57
|
+
import { BlobStoreFailure, utf8Bytes, } from "./BlobStoreContract.js";
|
|
58
|
+
import { unusable } from "./OffloadInput.js";
|
|
59
|
+
import { handleStoreOf } from "./OffloadValues.js";
|
|
60
|
+
/** The unsettled-upload observer. Default: none. */
|
|
61
|
+
export const Observer = Context.Reference("effect-dynamodb/Offload/Observer", { defaultValue: () => undefined });
|
|
62
|
+
/**
|
|
63
|
+
* Deliver every upload the library could not settle to `onUnsettled`, for
|
|
64
|
+
* everything run under this layer (and every client bound while it was in
|
|
65
|
+
* context).
|
|
66
|
+
*/
|
|
67
|
+
export const layerObserver = (options) => Layer.succeed(Observer, options);
|
|
68
|
+
const RANK = {
|
|
69
|
+
pending: 0,
|
|
70
|
+
rejected: 1,
|
|
71
|
+
inDoubt: 2,
|
|
72
|
+
committed: 3,
|
|
73
|
+
};
|
|
74
|
+
/** The ledger of the root operation the fiber runs in. Never captured by a bind site. */
|
|
75
|
+
export const CurrentLedger = Context.Reference("effect-dynamodb/Offload/CurrentLedger", { defaultValue: () => undefined });
|
|
76
|
+
const makeLedger = () => ({
|
|
77
|
+
entries: new Map(),
|
|
78
|
+
memo: new Map(),
|
|
79
|
+
cache: new Map(),
|
|
80
|
+
permits: new Map(),
|
|
81
|
+
tokens: new Set(),
|
|
82
|
+
lost: [],
|
|
83
|
+
closed: false,
|
|
84
|
+
});
|
|
85
|
+
/** The open ledger of the current fiber, if any. */
|
|
86
|
+
export const current = Effect.withFiber((fiber) => {
|
|
87
|
+
const ledger = fiber.getRef(CurrentLedger);
|
|
88
|
+
return Effect.succeed(ledger === undefined || ledger.closed ? undefined : ledger);
|
|
89
|
+
});
|
|
90
|
+
/** What the ledger uploaded under `ref`, if it did. */
|
|
91
|
+
export const cached = (ledger, ref) => ledger === undefined ? undefined : ledger.cache.get(refKey(ref));
|
|
92
|
+
/**
|
|
93
|
+
* Keep `content` in the ledger's read cache as what `ref` names, though the
|
|
94
|
+
* ledger did not upload it: a read pointer a projection's row rewrite reuses
|
|
95
|
+
* (design §6.11), whose content the write just compared — decoding the
|
|
96
|
+
* write's result then fetches nothing. No entry: nothing settles or rolls it
|
|
97
|
+
* back.
|
|
98
|
+
*/
|
|
99
|
+
export const remember = (ledger, ref, content) => {
|
|
100
|
+
if (ledger !== undefined && !ledger.closed)
|
|
101
|
+
ledger.cache.set(refKey(ref), content);
|
|
102
|
+
};
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Root
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
/**
|
|
107
|
+
* Run `effect` as the root of a ledger, or in the ledger already open: every
|
|
108
|
+
* upload inside it is settled by the requests that carry it and, at exit,
|
|
109
|
+
* rolled back when DynamoDB provably did not commit it.
|
|
110
|
+
*/
|
|
111
|
+
export const root = (effect) => Effect.withFiber((fiber) => {
|
|
112
|
+
const open = fiber.getRef(CurrentLedger);
|
|
113
|
+
if (open !== undefined && !open.closed)
|
|
114
|
+
return effect;
|
|
115
|
+
const ledger = makeLedger();
|
|
116
|
+
return Effect.onExit(Effect.provideService(effect, CurrentLedger, ledger), () => close(ledger));
|
|
117
|
+
});
|
|
118
|
+
/** {@link root} when `enabled` (a member that offloads something), else `effect`. */
|
|
119
|
+
export const rootIf = (enabled, effect) => (enabled ? root(effect) : effect);
|
|
120
|
+
/** True iff `member` (an entity) offloads a field. */
|
|
121
|
+
export const offloads = (member) => member?.offload !== undefined;
|
|
122
|
+
const encoder = new TextEncoder();
|
|
123
|
+
const hexOf = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
124
|
+
const ctxOf = (target) => ({
|
|
125
|
+
entityType: target.entityType,
|
|
126
|
+
attribute: target.attribute,
|
|
127
|
+
operation: target.operation,
|
|
128
|
+
});
|
|
129
|
+
const permitsOf = (ledger, store) => {
|
|
130
|
+
let permits = ledger.permits.get(store);
|
|
131
|
+
if (permits === undefined) {
|
|
132
|
+
permits = Semaphore.makeUnsafe(store.writeConcurrency);
|
|
133
|
+
ledger.permits.set(store, permits);
|
|
134
|
+
}
|
|
135
|
+
return permits;
|
|
136
|
+
};
|
|
137
|
+
const checkAnswer = (ledger, store, key, action, bodyBytes, result, source) => {
|
|
138
|
+
const answered = result?.ref;
|
|
139
|
+
if (typeof answered?.key !== "string" || typeof answered.version !== "string") {
|
|
140
|
+
return {
|
|
141
|
+
_tag: "Unknown",
|
|
142
|
+
ref: undefined,
|
|
143
|
+
message: `the store's ${action} returned no { key, version } ref`,
|
|
144
|
+
};
|
|
145
|
+
}
|
|
146
|
+
const ref = { key: answered.key, version: answered.version };
|
|
147
|
+
if (source !== undefined && ref.key === source.key && ref.version === source.version) {
|
|
148
|
+
return {
|
|
149
|
+
_tag: "Unknown",
|
|
150
|
+
ref,
|
|
151
|
+
message: "the store's copy returned its source's ref, not a new version's",
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
if (!ref.key.startsWith(key)) {
|
|
155
|
+
return {
|
|
156
|
+
_tag: "Unknown",
|
|
157
|
+
ref,
|
|
158
|
+
message: `the store's ${action} returned key "${ref.key}", outside the requested key "${key}"`,
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
if (ledger.entries.has(refKey(ref))) {
|
|
162
|
+
return {
|
|
163
|
+
_tag: "Unknown",
|
|
164
|
+
ref,
|
|
165
|
+
message: `the store's ${action} returned a ref it already returned for another upload`,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
const refused = (message) => ({ _tag: "Refused", ref, message });
|
|
169
|
+
const suffix = (utf8Bytes(ref.key) ?? Number.POSITIVE_INFINITY) - (utf8Bytes(key) ?? 0);
|
|
170
|
+
if (suffix > store.limits.maxKeySuffixBytes) {
|
|
171
|
+
return refused(`the store's ${action} extended the key by ${suffix} bytes, over its declared ` +
|
|
172
|
+
`limits.maxKeySuffixBytes (${store.limits.maxKeySuffixBytes})`);
|
|
173
|
+
}
|
|
174
|
+
const version = utf8Bytes(ref.version) ?? Number.POSITIVE_INFINITY;
|
|
175
|
+
if (version > store.limits.maxVersionBytes) {
|
|
176
|
+
return refused(`the store's ${action} returned a ${version}-byte version, over its declared ` +
|
|
177
|
+
`limits.maxVersionBytes (${store.limits.maxVersionBytes})`);
|
|
178
|
+
}
|
|
179
|
+
const size = result.size;
|
|
180
|
+
if (size !== bodyBytes) {
|
|
181
|
+
return refused(`the store's ${action} reported ${String(size)} stored bytes for a ${bodyBytes}-byte body`);
|
|
182
|
+
}
|
|
183
|
+
return { _tag: "Accepted", ref };
|
|
184
|
+
};
|
|
185
|
+
/**
|
|
186
|
+
* Record a store's answer: the entry of the version it names (`pending`,
|
|
187
|
+
* rolled back at exit unless a request settles it) and the pointer naming
|
|
188
|
+
* it; a refused answer is recorded, then fails the upload; an unknown one is
|
|
189
|
+
* reported at exit and fails it.
|
|
190
|
+
*/
|
|
191
|
+
const record = (ledger, spec, ctx, answered) => Effect.suspend(() => {
|
|
192
|
+
const checked = checkAnswer(ledger, spec.store, spec.key, answered.action, answered.objectSize, answered.result, answered.source);
|
|
193
|
+
const answer = checked._tag === "Accepted" && answered.problem !== undefined
|
|
194
|
+
? { _tag: "Refused", ref: checked.ref, message: answered.problem }
|
|
195
|
+
: checked;
|
|
196
|
+
if (answer._tag === "Unknown") {
|
|
197
|
+
// Nothing names what the store wrote under the requested key: the
|
|
198
|
+
// key is reported at exit, and no ref the answer gave is deleted.
|
|
199
|
+
const error = blobError(ctx, answered.action, "Rejected", answer.ref, answer.message);
|
|
200
|
+
ledger.lost.push(unsettledOf(spec.target, spec.store, "answerRefused", spec.key, undefined, error));
|
|
201
|
+
return Effect.fail(error);
|
|
202
|
+
}
|
|
203
|
+
const ref = answer.ref;
|
|
204
|
+
const pointer = answer._tag === "Refused"
|
|
205
|
+
? answer.message
|
|
206
|
+
: makePointer({
|
|
207
|
+
kind: answered.kind,
|
|
208
|
+
codec: spec.codec,
|
|
209
|
+
ref,
|
|
210
|
+
objectSize: answered.objectSize,
|
|
211
|
+
contentSize: answered.contentSize,
|
|
212
|
+
checksum: answered.checksum,
|
|
213
|
+
contentType: Option.fromNullishOr(spec.pointerContentType),
|
|
214
|
+
});
|
|
215
|
+
const entry = {
|
|
216
|
+
ref,
|
|
217
|
+
store: spec.store,
|
|
218
|
+
target: spec.target,
|
|
219
|
+
startedAt: answered.startedAt,
|
|
220
|
+
pointer: typeof pointer === "string" ? undefined : pointer,
|
|
221
|
+
state: "pending",
|
|
222
|
+
};
|
|
223
|
+
// Registered before anything else can fail: whatever happens next,
|
|
224
|
+
// the version is deleted at exit unless a request settles it.
|
|
225
|
+
ledger.entries.set(refKey(ref), entry);
|
|
226
|
+
if (typeof pointer === "string") {
|
|
227
|
+
return Effect.fail(blobError(ctx, answered.action, "Rejected", ref, pointer));
|
|
228
|
+
}
|
|
229
|
+
return Effect.succeed({ entry, pointer });
|
|
230
|
+
});
|
|
231
|
+
/**
|
|
232
|
+
* Report a failed upload whose multipart upload may have completed
|
|
233
|
+
* (`completeLost`) at exit: a version may exist that no ref names (design §7).
|
|
234
|
+
*/
|
|
235
|
+
const reportCompleteLost = (ledger, spec, error) => Effect.sync(() => {
|
|
236
|
+
if (error.cause?.completeLost === true) {
|
|
237
|
+
ledger.lost.push(unsettledOf(spec.target, spec.store, "completeLost", spec.key, undefined, error));
|
|
238
|
+
}
|
|
239
|
+
});
|
|
240
|
+
/**
|
|
241
|
+
* Report a store call (`put` or `copy`) that the operation's interruption
|
|
242
|
+
* cut short (`interrupted`) at exit. An interruption discards the call's
|
|
243
|
+
* answer even when the store wrote a version — a `PutObject` it received
|
|
244
|
+
* before the request was aborted, a `CompleteMultipartUpload` that answered
|
|
245
|
+
* as the interruption arrived (the S3 store completes uninterruptibly, so the
|
|
246
|
+
* answer comes, but the caller never sees it). The ledger cannot tell from
|
|
247
|
+
* outside the call whether anything was written, so it reports every
|
|
248
|
+
* interrupted call: a `gc.sweep` of an item with nothing left behind deletes
|
|
249
|
+
* nothing. A call that also failed is the failure's to report.
|
|
250
|
+
*/
|
|
251
|
+
const reportInterrupted = (ledger, spec) => (exit) => Effect.sync(() => {
|
|
252
|
+
if (Exit.isFailure(exit) && Cause.hasInterruptsOnly(exit.cause)) {
|
|
253
|
+
ledger.lost.push(unsettledOf(spec.target, spec.store, "interrupted", spec.key, undefined, undefined));
|
|
254
|
+
}
|
|
255
|
+
});
|
|
256
|
+
/**
|
|
257
|
+
* A store `put`, its failure wrapped (and reported when its completion may be
|
|
258
|
+
* lost, or when an interruption cut it short).
|
|
259
|
+
*/
|
|
260
|
+
const putCall = (ledger, spec, ctx, request) => call(spec.store, "put", ctx, { key: spec.key }, () => spec.store.put(request)).pipe(Effect.tapError((error) => reportCompleteLost(ledger, spec, error)), Effect.onExit(reportInterrupted(ledger, spec)));
|
|
261
|
+
const memoOf = (ledger, store) => {
|
|
262
|
+
let byStore = ledger.memo.get(store);
|
|
263
|
+
if (byStore === undefined) {
|
|
264
|
+
byStore = new Map();
|
|
265
|
+
ledger.memo.set(store, byStore);
|
|
266
|
+
}
|
|
267
|
+
return byStore;
|
|
268
|
+
};
|
|
269
|
+
/**
|
|
270
|
+
* Run `start` once per `memoKey` in the ledger, at the store's write
|
|
271
|
+
* concurrency: a later call with the same key reuses its pointer — unless
|
|
272
|
+
* that upload is too old to commit any more and nothing committed it, when
|
|
273
|
+
* a fresh one runs (the old one is deleted at exit). A failed upload is
|
|
274
|
+
* forgotten, so a retry runs it again.
|
|
275
|
+
*/
|
|
276
|
+
const withMemo = (ledger, spec, memoKey, start) => {
|
|
277
|
+
const byStore = memoOf(ledger, spec.store);
|
|
278
|
+
const hit = byStore.get(memoKey);
|
|
279
|
+
if (hit !== undefined) {
|
|
280
|
+
return Effect.flatMap(Deferred.await(hit.deferred), ({ entry, pointer }) => Effect.flatMap(Clock.currentTimeMillis, (now) => {
|
|
281
|
+
const stale = RANK[entry.state] < RANK.inDoubt &&
|
|
282
|
+
now - entry.startedAt > Duration.toMillis(entry.store.maxUploadAge);
|
|
283
|
+
if (!stale)
|
|
284
|
+
return Effect.succeed(pointer);
|
|
285
|
+
if (byStore.get(memoKey) === hit)
|
|
286
|
+
byStore.delete(memoKey);
|
|
287
|
+
return upload(spec);
|
|
288
|
+
}));
|
|
289
|
+
}
|
|
290
|
+
const memo = { deferred: Deferred.makeUnsafe() };
|
|
291
|
+
byStore.set(memoKey, memo);
|
|
292
|
+
return permitsOf(ledger, spec.store)
|
|
293
|
+
.withPermit(Effect.suspend(start))
|
|
294
|
+
.pipe(Effect.onExit((exit) => {
|
|
295
|
+
if (Exit.isFailure(exit) && byStore.get(memoKey) === memo)
|
|
296
|
+
byStore.delete(memoKey);
|
|
297
|
+
return Deferred.done(memo.deferred, exit);
|
|
298
|
+
}), Effect.map(({ pointer }) => pointer));
|
|
299
|
+
};
|
|
300
|
+
const ZERO_CHECKSUM = { algorithm: "crc64nvme", value: new Uint8Array(8) };
|
|
301
|
+
const metadataOf = (spec, checksum) => typeof spec.metadata === "function" ? spec.metadata(checksum) : spec.metadata;
|
|
302
|
+
/** Buffered content: the bytes, or the JSON text (compressed into `spec.body`). */
|
|
303
|
+
const bufferedUpload = (ledger, spec, ledgerContent) => {
|
|
304
|
+
const kind = ledgerContent.kind;
|
|
305
|
+
const content = ledgerContent.kind === "json" ? encoder.encode(ledgerContent.text) : ledgerContent.bytes;
|
|
306
|
+
if (kind === "bytes" && spec.codec !== "none") {
|
|
307
|
+
return Effect.die(new Error("BlobLedger: a bytes value is never compressed"));
|
|
308
|
+
}
|
|
309
|
+
const body = spec.body ?? content;
|
|
310
|
+
if (spec.codec === "none" && body.length !== content.length) {
|
|
311
|
+
return Effect.die(new Error("BlobLedger: an uncompressed object's body is its content"));
|
|
312
|
+
}
|
|
313
|
+
const checksum = { algorithm: "crc64nvme", value: crc64nvme(content) };
|
|
314
|
+
const memoKey = [spec.key, hexOf(checksum.value), content.length, kind, spec.contentType].join("\u0000");
|
|
315
|
+
const ctx = ctxOf(spec.target);
|
|
316
|
+
return withMemo(ledger, spec, memoKey, () => {
|
|
317
|
+
const metadata = metadataOf(spec, checksum);
|
|
318
|
+
const bodyChecksum = body === content ? checksum : { algorithm: "crc64nvme", value: crc64nvme(body) };
|
|
319
|
+
return Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
320
|
+
const startedAt = yield* Clock.currentTimeMillis;
|
|
321
|
+
const result = yield* restore(putCall(ledger, spec, ctx, {
|
|
322
|
+
key: spec.key,
|
|
323
|
+
body,
|
|
324
|
+
contentLength: body.length,
|
|
325
|
+
checksum: Effect.succeed(bodyChecksum),
|
|
326
|
+
contentType: spec.contentType,
|
|
327
|
+
metadata,
|
|
328
|
+
}));
|
|
329
|
+
const uploaded = yield* record(ledger, spec, ctx, {
|
|
330
|
+
action: "put",
|
|
331
|
+
startedAt,
|
|
332
|
+
result,
|
|
333
|
+
kind,
|
|
334
|
+
objectSize: body.length,
|
|
335
|
+
contentSize: content.length,
|
|
336
|
+
checksum,
|
|
337
|
+
});
|
|
338
|
+
ledger.cache.set(refKey(uploaded.entry.ref), ledgerContent);
|
|
339
|
+
return uploaded;
|
|
340
|
+
}));
|
|
341
|
+
});
|
|
342
|
+
};
|
|
343
|
+
const sourceFailed = (cause) => new BlobStoreFailure({ reason: "SourceFailed", cause });
|
|
344
|
+
/**
|
|
345
|
+
* Upload a stream of bytes with a `put`: the body handed to the store is the
|
|
346
|
+
* stream tapped with the incremental CRC-64/NVME and its length counted
|
|
347
|
+
* (checked against `contentLength`, when given); `request.checksum` resolves
|
|
348
|
+
* when it ends. Its failure is `SourceFailed`.
|
|
349
|
+
*/
|
|
350
|
+
const streamedPut = (ledger, spec, ctx, stream, contentLength) => Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
351
|
+
const hasher = makeCrc64nvme();
|
|
352
|
+
let size = 0;
|
|
353
|
+
let ended = false;
|
|
354
|
+
const checksum = Deferred.makeUnsafe();
|
|
355
|
+
const body = stream.pipe(Stream.mapError((cause) => sourceFailed(cause)), Stream.mapEffect((chunk) => {
|
|
356
|
+
if (!(chunk instanceof Uint8Array)) {
|
|
357
|
+
return Effect.fail(sourceFailed(new Error("the stream emitted a chunk that is not a Uint8Array")));
|
|
358
|
+
}
|
|
359
|
+
size += chunk.length;
|
|
360
|
+
if (contentLength !== undefined && size > contentLength) {
|
|
361
|
+
return Effect.fail(sourceFailed(new Error(`the stream gave more bytes than its contentLength of ${contentLength}`)));
|
|
362
|
+
}
|
|
363
|
+
hasher.update(chunk);
|
|
364
|
+
return Effect.succeed(chunk);
|
|
365
|
+
}), Stream.onEnd(Effect.suspend(() => {
|
|
366
|
+
if (contentLength !== undefined && size !== contentLength) {
|
|
367
|
+
return Effect.fail(sourceFailed(new Error(`the stream gave ${size} bytes, but its contentLength is ${contentLength}`)));
|
|
368
|
+
}
|
|
369
|
+
ended = true;
|
|
370
|
+
const value = { algorithm: "crc64nvme", value: hasher.digest() };
|
|
371
|
+
return Deferred.succeed(checksum, value);
|
|
372
|
+
})));
|
|
373
|
+
const startedAt = yield* Clock.currentTimeMillis;
|
|
374
|
+
const result = yield* restore(putCall(ledger, spec, ctx, {
|
|
375
|
+
key: spec.key,
|
|
376
|
+
body,
|
|
377
|
+
contentLength,
|
|
378
|
+
checksum: Deferred.await(checksum),
|
|
379
|
+
contentType: spec.contentType,
|
|
380
|
+
metadata: metadataOf(spec, ZERO_CHECKSUM),
|
|
381
|
+
}));
|
|
382
|
+
return yield* record(ledger, spec, ctx, {
|
|
383
|
+
action: "put",
|
|
384
|
+
startedAt,
|
|
385
|
+
result,
|
|
386
|
+
kind: "bytes",
|
|
387
|
+
objectSize: size,
|
|
388
|
+
contentSize: size,
|
|
389
|
+
checksum: ended ? yield* Deferred.await(checksum) : ZERO_CHECKSUM,
|
|
390
|
+
problem: ended ? undefined : "the store's put succeeded before its body ended",
|
|
391
|
+
});
|
|
392
|
+
}));
|
|
393
|
+
const streamUses = new WeakMap();
|
|
394
|
+
/**
|
|
395
|
+
* Why a stream cannot be uploaded to `key` of `store` in `ledger`, or
|
|
396
|
+
* `undefined` when it can (its first use, or the same upload again: a
|
|
397
|
+
* re-planned or retried request reuses its pointer). A stream is consumed
|
|
398
|
+
* once, for one target object: never for a second object, by a later
|
|
399
|
+
* operation, or again after its upload failed.
|
|
400
|
+
*/
|
|
401
|
+
export const streamRefusal = (ledger, identity, store, key) => {
|
|
402
|
+
const use = streamUses.get(identity);
|
|
403
|
+
if (use === undefined)
|
|
404
|
+
return undefined;
|
|
405
|
+
if (use.ledger === ledger && use.store === store && use.key === key) {
|
|
406
|
+
return use.failed ? "its upload failed, and a consumed stream is never replayed" : undefined;
|
|
407
|
+
}
|
|
408
|
+
return use.ledger === ledger
|
|
409
|
+
? "it is already the content of another value of this operation"
|
|
410
|
+
: "an earlier operation already consumed it";
|
|
411
|
+
};
|
|
412
|
+
/** The `[EDD-9120]` refusal of a stream {@link streamRefusal} refused. */
|
|
413
|
+
export const singleUseError = (entityType, operation, attribute, why) => unusable(entityType, operation, `the Stream given for attribute "${attribute}" is single-use, and ${why}. Give each ` +
|
|
414
|
+
"value its own Stream (or its bytes, a BlobHandle, or Offload.source(...)).");
|
|
415
|
+
const streamUpload = (ledger, spec, content) => {
|
|
416
|
+
const why = streamRefusal(ledger, content.identity, spec.store, spec.key);
|
|
417
|
+
if (why !== undefined) {
|
|
418
|
+
return Effect.fail(singleUseError(spec.target.entityType, spec.target.operation, spec.target.attribute, why));
|
|
419
|
+
}
|
|
420
|
+
const known = streamUses.get(content.identity);
|
|
421
|
+
if (known !== undefined) {
|
|
422
|
+
// The same upload again: its pointer (a stale one is refused at the
|
|
423
|
+
// choke point with `Expired` — a consumed stream is never re-run).
|
|
424
|
+
return Effect.map(Deferred.await(known.memo.deferred), ({ pointer }) => pointer);
|
|
425
|
+
}
|
|
426
|
+
const use = {
|
|
427
|
+
ledger,
|
|
428
|
+
store: spec.store,
|
|
429
|
+
key: spec.key,
|
|
430
|
+
memo: { deferred: Deferred.makeUnsafe() },
|
|
431
|
+
failed: false,
|
|
432
|
+
};
|
|
433
|
+
streamUses.set(content.identity, use);
|
|
434
|
+
const ctx = ctxOf(spec.target);
|
|
435
|
+
return permitsOf(ledger, spec.store)
|
|
436
|
+
.withPermit(streamedPut(ledger, spec, ctx, content.stream, content.contentLength))
|
|
437
|
+
.pipe(Effect.onExit((exit) => {
|
|
438
|
+
if (Exit.isFailure(exit))
|
|
439
|
+
use.failed = true;
|
|
440
|
+
return Deferred.done(use.memo.deferred, exit);
|
|
441
|
+
}), Effect.map(({ pointer }) => pointer));
|
|
442
|
+
};
|
|
443
|
+
/**
|
|
444
|
+
* A handle's content as a new version under `spec.key`: the store's `copy`
|
|
445
|
+
* when the handle reads from this store (its checksum is the source's), else
|
|
446
|
+
* its content streamed into a `put`. Never the handle's own version — even
|
|
447
|
+
* when it is the field's current one.
|
|
448
|
+
*/
|
|
449
|
+
const copyUpload = (ledger, spec, content) => {
|
|
450
|
+
const { handle } = content;
|
|
451
|
+
const source = Option.getOrUndefined(handle.ref);
|
|
452
|
+
const copy = spec.store.copy;
|
|
453
|
+
const viaCopy = copy !== undefined && source !== undefined && handleStoreOf(handle) === spec.store;
|
|
454
|
+
const memoKey = [
|
|
455
|
+
"copy",
|
|
456
|
+
spec.key,
|
|
457
|
+
source === undefined ? `inline:${hexOf(handle.checksum.value)}` : refKey(source),
|
|
458
|
+
handle.size,
|
|
459
|
+
spec.contentType,
|
|
460
|
+
].join("\u0000");
|
|
461
|
+
const ctx = ctxOf(spec.target);
|
|
462
|
+
return withMemo(ledger, spec, memoKey, () => {
|
|
463
|
+
if (!viaCopy) {
|
|
464
|
+
return streamedPut(ledger, spec, ctx, Stream.suspend(() => handle.stream()), handle.size);
|
|
465
|
+
}
|
|
466
|
+
return Effect.uninterruptibleMask((restore) => Effect.gen(function* () {
|
|
467
|
+
const startedAt = yield* Clock.currentTimeMillis;
|
|
468
|
+
const result = yield* restore(call(spec.store, "copy", ctx, { key: spec.key, ref: source }, () => copy(source, {
|
|
469
|
+
key: spec.key,
|
|
470
|
+
contentLength: handle.size,
|
|
471
|
+
contentType: spec.contentType,
|
|
472
|
+
metadata: metadataOf(spec, handle.checksum),
|
|
473
|
+
})).pipe(
|
|
474
|
+
// A copy over the store's single-request limit is a multipart one too.
|
|
475
|
+
Effect.tapError((error) => reportCompleteLost(ledger, spec, error)), Effect.onExit(reportInterrupted(ledger, spec))));
|
|
476
|
+
return yield* record(ledger, spec, ctx, {
|
|
477
|
+
action: "copy",
|
|
478
|
+
startedAt,
|
|
479
|
+
result,
|
|
480
|
+
kind: "bytes",
|
|
481
|
+
objectSize: handle.size,
|
|
482
|
+
contentSize: handle.size,
|
|
483
|
+
checksum: handle.checksum,
|
|
484
|
+
source,
|
|
485
|
+
});
|
|
486
|
+
}));
|
|
487
|
+
});
|
|
488
|
+
};
|
|
489
|
+
/**
|
|
490
|
+
* Upload one value through the current ledger and return the pointer that
|
|
491
|
+
* names it. The entry is `pending` until a request carrying the pointer
|
|
492
|
+
* settles it. The same content for the same key and store in one ledger
|
|
493
|
+
* uploads once (an upload older than the store's `maxUploadAge` that no
|
|
494
|
+
* request committed is not reused); a stream uploads at most once, for one
|
|
495
|
+
* key (`[EDD-9120]` otherwise). Uploads run at the store's
|
|
496
|
+
* `writeConcurrency` per ledger.
|
|
497
|
+
*
|
|
498
|
+
* Dies when no ledger is open: every write path runs under a root.
|
|
499
|
+
*/
|
|
500
|
+
export const upload = (spec) => Effect.withFiber((fiber) => {
|
|
501
|
+
const ledger = fiber.getRef(CurrentLedger);
|
|
502
|
+
if (ledger === undefined || ledger.closed) {
|
|
503
|
+
return Effect.die(new Error(`BlobLedger: an upload of ${spec.target.entityType} attribute "${spec.target.attribute}" ` +
|
|
504
|
+
"ran outside a ledger root. This is a defect in effect-dynamodb."));
|
|
505
|
+
}
|
|
506
|
+
const content = spec.content;
|
|
507
|
+
switch (content.kind) {
|
|
508
|
+
case "stream":
|
|
509
|
+
return streamUpload(ledger, spec, content);
|
|
510
|
+
case "copy":
|
|
511
|
+
return copyUpload(ledger, spec, content);
|
|
512
|
+
default:
|
|
513
|
+
return bufferedUpload(ledger, spec, content);
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
// ---------------------------------------------------------------------------
|
|
517
|
+
// Settling at the choke point
|
|
518
|
+
// ---------------------------------------------------------------------------
|
|
519
|
+
/**
|
|
520
|
+
* The write commands a ledger settles. A PartiQL request is one too (`insert()`, design §6.2);
|
|
521
|
+
* one that only reads (`SELECT`) carries no pointer to settle ({@link refsOfRequest}).
|
|
522
|
+
*/
|
|
523
|
+
export const WRITE_COMMANDS = new Set([
|
|
524
|
+
"PutItem",
|
|
525
|
+
"UpdateItem",
|
|
526
|
+
"DeleteItem",
|
|
527
|
+
"BatchWriteItem",
|
|
528
|
+
"TransactWriteItems",
|
|
529
|
+
"ExecuteStatement",
|
|
530
|
+
"ExecuteTransaction",
|
|
531
|
+
]);
|
|
532
|
+
/** The ledger a request of `command` settles: an open one with entries, for a write. */
|
|
533
|
+
export const settling = (ledger, command) => ledger !== undefined && !ledger.closed && ledger.entries.size > 0 && WRITE_COMMANDS.has(command)
|
|
534
|
+
? ledger
|
|
535
|
+
: undefined;
|
|
536
|
+
const isObject = (value) => typeof value === "object" && value !== null;
|
|
537
|
+
/** Collect the refs of every pointer in an `AttributeValue`, at any depth. */
|
|
538
|
+
const visitValue = (value, out) => {
|
|
539
|
+
if (!isObject(value))
|
|
540
|
+
return;
|
|
541
|
+
const b = value.B;
|
|
542
|
+
if (b instanceof Uint8Array) {
|
|
543
|
+
if (b.length > 0 && isPointerHeader(b[0])) {
|
|
544
|
+
const pointer = decodePointer(b);
|
|
545
|
+
if (typeof pointer !== "string")
|
|
546
|
+
out.add(refKey(pointer.ref));
|
|
547
|
+
}
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const s = value.S;
|
|
551
|
+
if (typeof s === "string") {
|
|
552
|
+
if (isPointerText(s)) {
|
|
553
|
+
const pointer = decodePointerText(s);
|
|
554
|
+
if (pointer !== undefined && typeof pointer !== "string")
|
|
555
|
+
out.add(refKey(pointer.ref));
|
|
556
|
+
}
|
|
557
|
+
return;
|
|
558
|
+
}
|
|
559
|
+
const m = value.M;
|
|
560
|
+
if (isObject(m)) {
|
|
561
|
+
for (const key in m)
|
|
562
|
+
visitValue(m[key], out);
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
const l = value.L;
|
|
566
|
+
if (Array.isArray(l))
|
|
567
|
+
for (const element of l)
|
|
568
|
+
visitValue(element, out);
|
|
569
|
+
};
|
|
570
|
+
const visitItem = (item, out) => {
|
|
571
|
+
if (!isObject(item))
|
|
572
|
+
return;
|
|
573
|
+
for (const key in item)
|
|
574
|
+
visitValue(item[key], out);
|
|
575
|
+
};
|
|
576
|
+
/**
|
|
577
|
+
* The first attribute of a marshalled row that holds a well-formed blob pointer, in either stored
|
|
578
|
+
* form and at any depth, whatever its member now declares; `undefined` when none does. Rekey's
|
|
579
|
+
* backstop (design §11.10): a row holding one must never move.
|
|
580
|
+
*/
|
|
581
|
+
export const pointerAttributeOf = (item) => {
|
|
582
|
+
if (!isObject(item))
|
|
583
|
+
return undefined;
|
|
584
|
+
for (const key in item) {
|
|
585
|
+
const out = new Set();
|
|
586
|
+
visitValue(item[key], out);
|
|
587
|
+
if (out.size > 0)
|
|
588
|
+
return key;
|
|
589
|
+
}
|
|
590
|
+
return undefined;
|
|
591
|
+
};
|
|
592
|
+
/** The refs of every pointer an item (a marshalled image) holds. */
|
|
593
|
+
export const refsOfItem = (item) => {
|
|
594
|
+
const out = new Set();
|
|
595
|
+
visitItem(item, out);
|
|
596
|
+
return out;
|
|
597
|
+
};
|
|
598
|
+
const isSelect = (statement) => typeof statement === "string" && /^\s*SELECT\b/i.test(statement);
|
|
599
|
+
/** A PartiQL statement's parameters (`AttributeValue`s), unless it only reads. */
|
|
600
|
+
const visitStatement = (entry, out) => {
|
|
601
|
+
if (!isObject(entry) || isSelect(entry.Statement))
|
|
602
|
+
return;
|
|
603
|
+
const parameters = entry.Parameters;
|
|
604
|
+
if (Array.isArray(parameters))
|
|
605
|
+
for (const parameter of parameters)
|
|
606
|
+
visitValue(parameter, out);
|
|
607
|
+
};
|
|
608
|
+
const IF_NOT_EXISTS = /if_not_exists\s*\(\s*[^,()]*,\s*(:[A-Za-z0-9_]+)\s*\)/g;
|
|
609
|
+
/** The refs a request carries, and (UpdateItem) those it writes under `if_not_exists`. */
|
|
610
|
+
const refsOfRequest = (command, input) => {
|
|
611
|
+
const all = new Set();
|
|
612
|
+
const conditional = new Set();
|
|
613
|
+
switch (command) {
|
|
614
|
+
case "PutItem":
|
|
615
|
+
visitItem(input.Item, all);
|
|
616
|
+
visitItem(input.ExpressionAttributeValues, all);
|
|
617
|
+
break;
|
|
618
|
+
case "UpdateItem": {
|
|
619
|
+
const values = input.ExpressionAttributeValues;
|
|
620
|
+
visitItem(values, all);
|
|
621
|
+
const expression = input.UpdateExpression;
|
|
622
|
+
if (typeof expression === "string" && isObject(values)) {
|
|
623
|
+
for (const match of expression.matchAll(IF_NOT_EXISTS)) {
|
|
624
|
+
visitValue(values[match[1]], conditional);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
break;
|
|
628
|
+
}
|
|
629
|
+
case "DeleteItem":
|
|
630
|
+
visitItem(input.ExpressionAttributeValues, all);
|
|
631
|
+
break;
|
|
632
|
+
case "BatchWriteItem":
|
|
633
|
+
visitBatch(input.RequestItems, all);
|
|
634
|
+
break;
|
|
635
|
+
case "TransactWriteItems": {
|
|
636
|
+
const items = input.TransactItems;
|
|
637
|
+
if (Array.isArray(items)) {
|
|
638
|
+
for (const transactItem of items) {
|
|
639
|
+
if (!isObject(transactItem))
|
|
640
|
+
continue;
|
|
641
|
+
for (const part of Object.values(transactItem)) {
|
|
642
|
+
if (!isObject(part))
|
|
643
|
+
continue;
|
|
644
|
+
visitItem(part.Item, all);
|
|
645
|
+
visitItem(part.ExpressionAttributeValues, all);
|
|
646
|
+
}
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
break;
|
|
650
|
+
}
|
|
651
|
+
case "ExecuteStatement":
|
|
652
|
+
visitStatement(input, all);
|
|
653
|
+
break;
|
|
654
|
+
case "ExecuteTransaction": {
|
|
655
|
+
const statements = input.TransactStatements;
|
|
656
|
+
if (Array.isArray(statements))
|
|
657
|
+
for (const entry of statements)
|
|
658
|
+
visitStatement(entry, all);
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
return { all, conditional };
|
|
663
|
+
};
|
|
664
|
+
/** `RequestItems` / `UnprocessedItems`: each put request's item. */
|
|
665
|
+
const forEachPut = (requestItems, f) => {
|
|
666
|
+
if (!isObject(requestItems))
|
|
667
|
+
return;
|
|
668
|
+
for (const table in requestItems) {
|
|
669
|
+
const requests = requestItems[table];
|
|
670
|
+
if (!Array.isArray(requests))
|
|
671
|
+
continue;
|
|
672
|
+
for (const request of requests) {
|
|
673
|
+
if (isObject(request) && isObject(request.PutRequest))
|
|
674
|
+
f(request.PutRequest.Item);
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
};
|
|
678
|
+
/** `RequestItems` / `UnprocessedItems`: the refs of the put requests' items. */
|
|
679
|
+
const visitBatch = (requestItems, out) => forEachPut(requestItems, (item) => visitItem(item, out));
|
|
680
|
+
/** `RequestItems` / `UnprocessedItems`: per ref, how many put requests carry it. */
|
|
681
|
+
const requestsPerRef = (requestItems) => {
|
|
682
|
+
const counts = new Map();
|
|
683
|
+
forEachPut(requestItems, (item) => {
|
|
684
|
+
for (const key of refsOfItem(item))
|
|
685
|
+
counts.set(key, (counts.get(key) ?? 0) + 1);
|
|
686
|
+
});
|
|
687
|
+
return counts;
|
|
688
|
+
};
|
|
689
|
+
const carriedBy = (ledger, command, input) => {
|
|
690
|
+
const refs = refsOfRequest(command, input);
|
|
691
|
+
const entries = [];
|
|
692
|
+
const conditional = new Set();
|
|
693
|
+
for (const key of refs.all) {
|
|
694
|
+
const entry = ledger.entries.get(key);
|
|
695
|
+
if (entry === undefined)
|
|
696
|
+
continue;
|
|
697
|
+
entries.push(entry);
|
|
698
|
+
if (refs.conditional.has(key))
|
|
699
|
+
conditional.add(entry);
|
|
700
|
+
}
|
|
701
|
+
return entries.length === 0 ? undefined : { entries, conditional };
|
|
702
|
+
};
|
|
703
|
+
/** A fresh `ClientRequestToken`: 128 random bits from the platform's Web Crypto, as hex. */
|
|
704
|
+
const makeToken = () => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
705
|
+
const SINGLE_ITEM = new Set(["PutItem", "UpdateItem", "DeleteItem"]);
|
|
706
|
+
/** The transactions whose `ClientRequestToken` the SDK models as an idempotency token. */
|
|
707
|
+
const TRANSACTIONS = new Set(["TransactWriteItems", "ExecuteTransaction"]);
|
|
708
|
+
/**
|
|
709
|
+
* The request as sent: a `TransactWriteItems` or `ExecuteTransaction` carries
|
|
710
|
+
* the library's own `ClientRequestToken` (fresh per request, so a resend of
|
|
711
|
+
* this request object is idempotent and a cancellation proves it did not
|
|
712
|
+
* commit), a single-item
|
|
713
|
+
* write asks for `ALL_OLD` on a failed condition (the evidence a
|
|
714
|
+
* `ConditionalCheckFailed` is settled by). A field the caller set is kept.
|
|
715
|
+
*/
|
|
716
|
+
const prepare = (ledger, command, input) => {
|
|
717
|
+
if (TRANSACTIONS.has(command) && input.ClientRequestToken === undefined) {
|
|
718
|
+
const token = makeToken();
|
|
719
|
+
ledger.tokens.add(token);
|
|
720
|
+
return { ...input, ClientRequestToken: token };
|
|
721
|
+
}
|
|
722
|
+
if (SINGLE_ITEM.has(command) && input.ReturnValuesOnConditionCheckFailure === undefined) {
|
|
723
|
+
return { ...input, ReturnValuesOnConditionCheckFailure: "ALL_OLD" };
|
|
724
|
+
}
|
|
725
|
+
return input;
|
|
726
|
+
};
|
|
727
|
+
const raise = (entry, state) => {
|
|
728
|
+
if (RANK[state] > RANK[entry.state])
|
|
729
|
+
entry.state = state;
|
|
730
|
+
};
|
|
731
|
+
/** The SDK error a client failure carries: its `cause`, or the failure itself. */
|
|
732
|
+
const sdkErrorOf = (error) => {
|
|
733
|
+
const cause = isObject(error) ? error.cause : undefined;
|
|
734
|
+
if (isObject(cause) && typeof cause.name === "string")
|
|
735
|
+
return cause;
|
|
736
|
+
return isObject(error) ? error : undefined;
|
|
737
|
+
};
|
|
738
|
+
/** The library's tagged client errors, by the SDK exception each one wraps. */
|
|
739
|
+
const TAG_NAMES = {
|
|
740
|
+
ThrottlingError: "ThrottlingException",
|
|
741
|
+
DynamoValidationError: "ValidationException",
|
|
742
|
+
ResourceNotFoundError: "ResourceNotFoundException",
|
|
743
|
+
InternalServerError: "InternalServerError",
|
|
744
|
+
};
|
|
745
|
+
/** The SDK exception name of a client failure. */
|
|
746
|
+
export const errorName = (error) => {
|
|
747
|
+
const sdk = sdkErrorOf(error);
|
|
748
|
+
if (sdk !== undefined && sdk !== error && typeof sdk.name === "string")
|
|
749
|
+
return sdk.name;
|
|
750
|
+
const tag = isObject(error) ? error._tag : undefined;
|
|
751
|
+
if (typeof tag === "string" && TAG_NAMES[tag] !== undefined)
|
|
752
|
+
return TAG_NAMES[tag];
|
|
753
|
+
const name = isObject(error) ? error.name : undefined;
|
|
754
|
+
return typeof name === "string" ? name : undefined;
|
|
755
|
+
};
|
|
756
|
+
const attemptsIn = (value) => {
|
|
757
|
+
const metadata = isObject(value) ? value.$metadata : undefined;
|
|
758
|
+
const attempts = isObject(metadata) ? metadata.attempts : undefined;
|
|
759
|
+
return typeof attempts === "number" ? attempts : undefined;
|
|
760
|
+
};
|
|
761
|
+
/** `$metadata.attempts` of a client failure (on the SDK error it wraps), if reported. */
|
|
762
|
+
export const attemptsOf = (error) => attemptsIn(sdkErrorOf(error)) ?? attemptsIn(error);
|
|
763
|
+
const THROTTLING = [
|
|
764
|
+
"ThrottlingException",
|
|
765
|
+
"ProvisionedThroughputExceededException",
|
|
766
|
+
"RequestLimitExceeded",
|
|
767
|
+
];
|
|
768
|
+
/** Refusals of a single-item write: rejected when the SDK sent the request once. */
|
|
769
|
+
const SINGLE_REFUSALS = new Set([
|
|
770
|
+
"ValidationException",
|
|
771
|
+
"ResourceNotFoundException",
|
|
772
|
+
"ItemCollectionSizeLimitExceededException",
|
|
773
|
+
...THROTTLING,
|
|
774
|
+
"TransactionConflictException",
|
|
775
|
+
"AccessDeniedException",
|
|
776
|
+
]);
|
|
777
|
+
/**
|
|
778
|
+
* Refusals of a PartiQL `ExecuteStatement`: rejected when the SDK sent it once. An `INSERT` is
|
|
779
|
+
* not idempotent, so `DuplicateItemException` after a resend may be refusing the item the first
|
|
780
|
+
* attempt wrote: it proves non-commit only for a statement sent once.
|
|
781
|
+
*/
|
|
782
|
+
const STATEMENT_REFUSALS = new Set([
|
|
783
|
+
...SINGLE_REFUSALS,
|
|
784
|
+
"DuplicateItemException",
|
|
785
|
+
// DynamoDB Local's name for it (`isAwsDuplicateItem`).
|
|
786
|
+
"DuplicateItem",
|
|
787
|
+
"ConditionalCheckFailedException",
|
|
788
|
+
]);
|
|
789
|
+
/** A transaction carrying a token: refused outright, so never committed. */
|
|
790
|
+
const TRANSACT_REJECTED = new Set([
|
|
791
|
+
"TransactionCanceledException",
|
|
792
|
+
"ValidationException",
|
|
793
|
+
"ConditionalCheckFailedException",
|
|
794
|
+
]);
|
|
795
|
+
/** A `TransactWriteItems` whose token DynamoDB did not let decide: in doubt. */
|
|
796
|
+
const TRANSACT_IN_DOUBT = new Set([
|
|
797
|
+
"IdempotentParameterMismatchException",
|
|
798
|
+
"TransactionInProgressException",
|
|
799
|
+
]);
|
|
800
|
+
/**
|
|
801
|
+
* Whole-request refusals of a `TransactWriteItems` / `BatchWriteItem`: DynamoDB
|
|
802
|
+
* applies nothing of a request it refuses, so one sent once was not committed.
|
|
803
|
+
*/
|
|
804
|
+
const REQUEST_REFUSALS = new Set([
|
|
805
|
+
"ValidationException",
|
|
806
|
+
"ResourceNotFoundException",
|
|
807
|
+
...THROTTLING,
|
|
808
|
+
"AccessDeniedException",
|
|
809
|
+
]);
|
|
810
|
+
/**
|
|
811
|
+
* Where each entry a request carried moves by the request's outcome (design
|
|
812
|
+
* §6.2's table); `undefined` leaves them as they are (a request never sent).
|
|
813
|
+
*/
|
|
814
|
+
const outcomeOf = (ledger, command, sent, carried, exit, isNotSent) => {
|
|
815
|
+
const every = (state) => () => state;
|
|
816
|
+
if (Exit.isSuccess(exit)) {
|
|
817
|
+
const output = isObject(exit.value) ? exit.value : undefined;
|
|
818
|
+
if (command === "BatchWriteItem") {
|
|
819
|
+
// Per ref, not per request: `UnprocessedItems` holds copies of the
|
|
820
|
+
// requests it left, so a ref is committed when more requests carried it
|
|
821
|
+
// than were left — some processed request wrote it.
|
|
822
|
+
const carrying = requestsPerRef(sent.RequestItems);
|
|
823
|
+
const unprocessed = requestsPerRef(output?.UnprocessedItems);
|
|
824
|
+
// Only in unprocessed requests: rejected only when the SDK sent this request once.
|
|
825
|
+
const left = attemptsIn(output) === 1 ? "rejected" : "inDoubt";
|
|
826
|
+
return (entry) => {
|
|
827
|
+
const key = refKey(entry.ref);
|
|
828
|
+
const leftIn = unprocessed.get(key) ?? 0;
|
|
829
|
+
return leftIn === 0 || (carrying.get(key) ?? 0) > leftIn ? "committed" : left;
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
if (command === "UpdateItem" && carried.conditional.size > 0) {
|
|
833
|
+
const returnValues = sent.ReturnValues;
|
|
834
|
+
const kept = (returnValues === "ALL_NEW" || returnValues === "UPDATED_NEW") &&
|
|
835
|
+
isObject(output?.Attributes)
|
|
836
|
+
? refsOfItem(output.Attributes)
|
|
837
|
+
: undefined;
|
|
838
|
+
return (entry) => !carried.conditional.has(entry)
|
|
839
|
+
? "committed"
|
|
840
|
+
: kept === undefined
|
|
841
|
+
? "inDoubt"
|
|
842
|
+
: kept.has(refKey(entry.ref))
|
|
843
|
+
? "committed"
|
|
844
|
+
: "rejected";
|
|
845
|
+
}
|
|
846
|
+
return every("committed");
|
|
847
|
+
}
|
|
848
|
+
const failure = Cause.findErrorOption(exit.cause);
|
|
849
|
+
// Interrupted in flight, or a defect: the request may have reached DynamoDB.
|
|
850
|
+
if (Option.isNone(failure))
|
|
851
|
+
return every("inDoubt");
|
|
852
|
+
const error = failure.value;
|
|
853
|
+
if (isNotSent(error))
|
|
854
|
+
return undefined;
|
|
855
|
+
const name = errorName(error);
|
|
856
|
+
const once = attemptsOf(error) === 1;
|
|
857
|
+
const refusedOnce = (refusals) => name !== undefined && refusals.has(name) && once ? "rejected" : "inDoubt";
|
|
858
|
+
if (TRANSACTIONS.has(command)) {
|
|
859
|
+
if (name !== undefined && TRANSACT_REJECTED.has(name)) {
|
|
860
|
+
// Only the library's own token proves it: a resend of this request
|
|
861
|
+
// object is idempotent, so a cancellation means no attempt committed.
|
|
862
|
+
const token = sent.ClientRequestToken;
|
|
863
|
+
return every(typeof token === "string" && ledger.tokens.has(token) ? "rejected" : "inDoubt");
|
|
864
|
+
}
|
|
865
|
+
if (name !== undefined && TRANSACT_IN_DOUBT.has(name))
|
|
866
|
+
return every("inDoubt");
|
|
867
|
+
return every(refusedOnce(REQUEST_REFUSALS));
|
|
868
|
+
}
|
|
869
|
+
if (command === "BatchWriteItem")
|
|
870
|
+
return every(refusedOnce(REQUEST_REFUSALS));
|
|
871
|
+
if (command === "ExecuteStatement")
|
|
872
|
+
return every(refusedOnce(STATEMENT_REFUSALS));
|
|
873
|
+
if (name === "ConditionalCheckFailedException") {
|
|
874
|
+
// The evidence: the row as stored, returned because the request asked.
|
|
875
|
+
if (sent.ReturnValuesOnConditionCheckFailure !== "ALL_OLD")
|
|
876
|
+
return every("inDoubt");
|
|
877
|
+
const held = refsOfItem(sdkErrorOf(error)?.Item);
|
|
878
|
+
return (entry) => held.has(refKey(entry.ref))
|
|
879
|
+
? "committed"
|
|
880
|
+
: entry.target.copiesPointers
|
|
881
|
+
? "inDoubt"
|
|
882
|
+
: "rejected";
|
|
883
|
+
}
|
|
884
|
+
return every(refusedOnce(SINGLE_REFUSALS));
|
|
885
|
+
};
|
|
886
|
+
/** Settle what a request carried by its outcome. */
|
|
887
|
+
const settle = (ledger, command, sent, carried, exit, isNotSent) => {
|
|
888
|
+
const next = outcomeOf(ledger, command, sent, carried, exit, isNotSent);
|
|
889
|
+
if (next === undefined)
|
|
890
|
+
return;
|
|
891
|
+
for (const entry of carried.entries)
|
|
892
|
+
raise(entry, next(entry));
|
|
893
|
+
};
|
|
894
|
+
const expiredError = (entry, now) => blobError(ctxOf(entry.target), "put", "Expired", entry.ref, `the upload started ${Duration.format(Duration.millis(now - entry.startedAt))} ago, over the ` +
|
|
895
|
+
`store's maxUploadAge (${Duration.format(entry.store.maxUploadAge)}); nothing was written ` +
|
|
896
|
+
"to DynamoDB");
|
|
897
|
+
/**
|
|
898
|
+
* Send one write request of a ledger with entries (`send` is the choke
|
|
899
|
+
* point's own sending): refuse it with `Expired` when it carries an upload
|
|
900
|
+
* older than its store's `maxUploadAge`, prepare it ({@link prepare}), and
|
|
901
|
+
* settle the entries it carries by its outcome. A request carrying none of
|
|
902
|
+
* the ledger's uploads is sent unchanged.
|
|
903
|
+
*/
|
|
904
|
+
export const guard = (ledger, command, input, send, isNotSent) => Effect.suspend(() => {
|
|
905
|
+
const carried = carriedBy(ledger, command, input);
|
|
906
|
+
if (carried === undefined)
|
|
907
|
+
return send(input);
|
|
908
|
+
return Effect.flatMap(Clock.currentTimeMillis, (now) => {
|
|
909
|
+
const expired = carried.entries.find((entry) => now - entry.startedAt > Duration.toMillis(entry.store.maxUploadAge));
|
|
910
|
+
if (expired !== undefined)
|
|
911
|
+
return Effect.fail(expiredError(expired, now));
|
|
912
|
+
const sent = prepare(ledger, command, input);
|
|
913
|
+
return send(sent).pipe(Effect.onExit((exit) => Effect.sync(() => settle(ledger, command, sent, carried, exit, isNotSent))));
|
|
914
|
+
});
|
|
915
|
+
});
|
|
916
|
+
// ---------------------------------------------------------------------------
|
|
917
|
+
// Exit
|
|
918
|
+
// ---------------------------------------------------------------------------
|
|
919
|
+
const MESSAGES = {
|
|
920
|
+
inDoubt: "the outcome of the DynamoDB write that carried it is unknown, so its object version is " +
|
|
921
|
+
"kept; queue the item for gc.sweep",
|
|
922
|
+
rollbackFailed: "DynamoDB did not commit the write that carried it, but deleting its object version " +
|
|
923
|
+
"failed; the version is left for gc.sweep",
|
|
924
|
+
completeLost: "its multipart upload completed but the response was lost, so the version it made has no " +
|
|
925
|
+
"pointer; it is left for gc.sweep",
|
|
926
|
+
interrupted: "the operation was interrupted while the store call was in flight, so a version the store " +
|
|
927
|
+
"may have written has no pointer; it is left for gc.sweep",
|
|
928
|
+
answerRefused: "the store's answer to it broke the BlobStore contract and was refused, so the version it " +
|
|
929
|
+
"wrote, if any, has no pointer; it is left for gc.sweep",
|
|
930
|
+
};
|
|
931
|
+
const unsettledOf = (target, store, reason, key, ref, cause) => ({
|
|
932
|
+
reason,
|
|
933
|
+
table: target.table,
|
|
934
|
+
entityType: target.entityType,
|
|
935
|
+
attribute: target.attribute,
|
|
936
|
+
operation: target.operation,
|
|
937
|
+
rowKey: target.rowKey,
|
|
938
|
+
key,
|
|
939
|
+
ref: Option.fromNullishOr(ref),
|
|
940
|
+
store: store.name,
|
|
941
|
+
...(cause !== undefined && { cause }),
|
|
942
|
+
});
|
|
943
|
+
/** Log an unsettled upload at `Warning` and deliver it to the observer, if any. */
|
|
944
|
+
const report = (upload) => Effect.withFiber((fiber) => {
|
|
945
|
+
const observer = fiber.getRef(Observer);
|
|
946
|
+
const logged = Effect.logWarning(`effect-dynamodb: an upload of ${upload.entityType} attribute "${upload.attribute}" ` +
|
|
947
|
+
`(${upload.operation}) could not be settled: ${MESSAGES[upload.reason]}`, ...(upload.cause === undefined ? [] : [upload.cause])).pipe(Effect.annotateLogs({
|
|
948
|
+
table: upload.table,
|
|
949
|
+
entityType: upload.entityType,
|
|
950
|
+
attribute: upload.attribute,
|
|
951
|
+
operation: upload.operation,
|
|
952
|
+
rowKey: upload.rowKey,
|
|
953
|
+
objectKey: upload.key,
|
|
954
|
+
...Option.match(upload.ref, {
|
|
955
|
+
onNone: () => ({}),
|
|
956
|
+
onSome: (ref) => (ref.version === "" ? {} : { version: ref.version }),
|
|
957
|
+
}),
|
|
958
|
+
store: upload.store,
|
|
959
|
+
}));
|
|
960
|
+
if (observer === undefined)
|
|
961
|
+
return logged;
|
|
962
|
+
return Effect.andThen(logged, Effect.suspend(() => observer.onUnsettled(upload)).pipe(Effect.exit, Effect.flatMap((observed) => Exit.isFailure(observed) && !Cause.hasInterruptsOnly(observed.cause)
|
|
963
|
+
? Effect.logWarning("effect-dynamodb: the Offload observer failed; the unsettled upload was not delivered", observed.cause)
|
|
964
|
+
: Effect.void)));
|
|
965
|
+
});
|
|
966
|
+
const deleteContext = (entries) => {
|
|
967
|
+
const first = entries[0].target;
|
|
968
|
+
const same = (pick) => entries.every((entry) => pick(entry.target) === pick(first));
|
|
969
|
+
return {
|
|
970
|
+
entityType: same((t) => t.entityType) ? first.entityType : "(several)",
|
|
971
|
+
attribute: same((t) => t.attribute) ? first.attribute : "(several)",
|
|
972
|
+
operation: same((t) => t.operation) ? first.operation : "(several)",
|
|
973
|
+
};
|
|
974
|
+
};
|
|
975
|
+
/** Close a root's ledger: roll back what DynamoDB did not commit, report what is unsettled. */
|
|
976
|
+
const close = (ledger) => Effect.suspend(() => {
|
|
977
|
+
ledger.closed = true;
|
|
978
|
+
if (ledger.entries.size === 0 && ledger.lost.length === 0)
|
|
979
|
+
return Effect.void;
|
|
980
|
+
const rollback = new Map();
|
|
981
|
+
const inDoubt = [];
|
|
982
|
+
for (const entry of ledger.entries.values()) {
|
|
983
|
+
if (entry.state === "pending" || entry.state === "rejected") {
|
|
984
|
+
const group = rollback.get(entry.store);
|
|
985
|
+
if (group === undefined)
|
|
986
|
+
rollback.set(entry.store, [entry]);
|
|
987
|
+
else
|
|
988
|
+
group.push(entry);
|
|
989
|
+
}
|
|
990
|
+
else if (entry.state === "inDoubt") {
|
|
991
|
+
inDoubt.push(entry);
|
|
992
|
+
}
|
|
993
|
+
}
|
|
994
|
+
ledger.cache.clear();
|
|
995
|
+
return Effect.gen(function* () {
|
|
996
|
+
for (const [store, entries] of rollback) {
|
|
997
|
+
const deleted = yield* Effect.exit(call(store, "delete", deleteContext(entries), { ref: entries.length === 1 ? entries[0].ref : undefined }, () => store.delete(entries.map((entry) => entry.ref))));
|
|
998
|
+
if (Exit.isFailure(deleted)) {
|
|
999
|
+
const cause = Cause.squash(deleted.cause);
|
|
1000
|
+
for (const entry of entries) {
|
|
1001
|
+
yield* report(unsettledOf(entry.target, store, "rollbackFailed", entry.ref.key, entry.ref, cause));
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
for (const entry of inDoubt) {
|
|
1006
|
+
yield* report(unsettledOf(entry.target, entry.store, "inDoubt", entry.ref.key, entry.ref, undefined));
|
|
1007
|
+
}
|
|
1008
|
+
for (const upload of ledger.lost)
|
|
1009
|
+
yield* report(upload);
|
|
1010
|
+
}).pipe(Effect.provideService(CurrentLedger, undefined));
|
|
1011
|
+
});
|
|
1012
|
+
//# sourceMappingURL=BlobLedger.js.map
|