effect-dynamodb 1.39.0 → 1.40.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Aggregate.d.ts +119 -15
- package/dist/Aggregate.d.ts.map +1 -1
- package/dist/Aggregate.js +2021 -379
- package/dist/Aggregate.js.map +1 -1
- package/dist/Batch.d.ts +9 -5
- package/dist/Batch.d.ts.map +1 -1
- package/dist/Batch.js +28 -44
- package/dist/Batch.js.map +1 -1
- package/dist/Collection.d.ts.map +1 -1
- package/dist/Collection.js +12 -5
- package/dist/Collection.js.map +1 -1
- package/dist/ConsumedCapacity.js +1 -1
- package/dist/ConsumedCapacity.js.map +1 -1
- package/dist/DynamoClient.d.ts +22 -8
- package/dist/DynamoClient.d.ts.map +1 -1
- package/dist/DynamoClient.js +243 -87
- package/dist/DynamoClient.js.map +1 -1
- package/dist/Entity.d.ts +87 -22
- package/dist/Entity.d.ts.map +1 -1
- package/dist/Entity.js +2750 -514
- package/dist/Entity.js.map +1 -1
- package/dist/EventStore.d.ts +37 -15
- package/dist/EventStore.d.ts.map +1 -1
- package/dist/EventStore.js +215 -79
- package/dist/EventStore.js.map +1 -1
- package/dist/Marshaller.d.ts +39 -9
- package/dist/Marshaller.d.ts.map +1 -1
- package/dist/Marshaller.js +421 -70
- package/dist/Marshaller.js.map +1 -1
- package/dist/Query.d.ts +23 -0
- package/dist/Query.d.ts.map +1 -1
- package/dist/Query.js +49 -3
- package/dist/Query.js.map +1 -1
- package/dist/StorageEncoding.d.ts +7 -1
- package/dist/StorageEncoding.d.ts.map +1 -1
- package/dist/StorageEncoding.js +8 -2
- package/dist/StorageEncoding.js.map +1 -1
- package/dist/Table.d.ts +69 -8
- package/dist/Table.d.ts.map +1 -1
- package/dist/Transaction.d.ts.map +1 -1
- package/dist/Transaction.js +10 -4
- package/dist/Transaction.js.map +1 -1
- package/dist/change-feed/ChangeFeed.d.ts +8 -3
- package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
- package/dist/change-feed/ChangeFeed.js +76 -9
- package/dist/change-feed/ChangeFeed.js.map +1 -1
- package/dist/change-feed/CheckpointStore.js +1 -1
- package/dist/change-feed/CheckpointStore.js.map +1 -1
- package/dist/change-feed/DynamoStreamsClient.d.ts +12 -5
- package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
- package/dist/change-feed/DynamoStreamsClient.js +15 -9
- package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
- package/dist/internal/BoundCrud.d.ts +40 -32
- package/dist/internal/BoundCrud.d.ts.map +1 -1
- package/dist/internal/BoundCrud.js.map +1 -1
- package/dist/internal/BoundQuery.d.ts +1 -1
- package/dist/internal/BoundQuery.d.ts.map +1 -1
- package/dist/internal/BoundQuery.js +22 -12
- package/dist/internal/BoundQuery.js.map +1 -1
- package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
- package/dist/internal/BoundVectorQuery.js +2 -1
- package/dist/internal/BoundVectorQuery.js.map +1 -1
- package/dist/internal/Capacity.d.ts +44 -4
- package/dist/internal/Capacity.d.ts.map +1 -1
- package/dist/internal/Capacity.js +89 -15
- package/dist/internal/Capacity.js.map +1 -1
- package/dist/internal/ClientOptions.d.ts +72 -0
- package/dist/internal/ClientOptions.d.ts.map +1 -0
- package/dist/internal/ClientOptions.js +79 -0
- package/dist/internal/ClientOptions.js.map +1 -0
- package/dist/internal/Cursor.d.ts +19 -10
- package/dist/internal/Cursor.d.ts.map +1 -1
- package/dist/internal/Cursor.js +25 -10
- package/dist/internal/Cursor.js.map +1 -1
- package/dist/internal/EntityCombinators.d.ts +22 -7
- package/dist/internal/EntityCombinators.d.ts.map +1 -1
- package/dist/internal/EntityCombinators.js +6 -2
- package/dist/internal/EntityCombinators.js.map +1 -1
- package/dist/internal/EntityOps.d.ts +11 -1
- package/dist/internal/EntityOps.d.ts.map +1 -1
- package/dist/internal/EntityOps.js.map +1 -1
- package/dist/internal/EventProjection.d.ts +15 -3
- package/dist/internal/EventProjection.d.ts.map +1 -1
- package/dist/internal/EventProjection.js +27 -8
- package/dist/internal/EventProjection.js.map +1 -1
- package/dist/internal/Expr.d.ts.map +1 -1
- package/dist/internal/Expr.js +53 -2
- package/dist/internal/Expr.js.map +1 -1
- package/dist/internal/ExpressionLimits.d.ts +57 -1
- package/dist/internal/ExpressionLimits.d.ts.map +1 -1
- package/dist/internal/ExpressionLimits.js +90 -1
- package/dist/internal/ExpressionLimits.js.map +1 -1
- package/dist/internal/ItemSize.d.ts +108 -4
- package/dist/internal/ItemSize.d.ts.map +1 -1
- package/dist/internal/ItemSize.js +190 -3
- package/dist/internal/ItemSize.js.map +1 -1
- package/dist/internal/MultiProjection.d.ts +7 -2
- 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/PathBuilder.d.ts +15 -4
- package/dist/internal/PathBuilder.d.ts.map +1 -1
- package/dist/internal/PathBuilder.js +20 -10
- package/dist/internal/PathBuilder.js.map +1 -1
- package/dist/internal/ProjectionEngine.d.ts +76 -2
- package/dist/internal/ProjectionEngine.d.ts.map +1 -1
- package/dist/internal/ProjectionEngine.js +358 -28
- package/dist/internal/ProjectionEngine.js.map +1 -1
- package/dist/internal/Rekey.d.ts +21 -1
- package/dist/internal/Rekey.d.ts.map +1 -1
- package/dist/internal/Rekey.js +67 -0
- package/dist/internal/Rekey.js.map +1 -1
- package/dist/internal/RoundTrip.d.ts +36 -0
- package/dist/internal/RoundTrip.d.ts.map +1 -0
- package/dist/internal/RoundTrip.js +79 -0
- package/dist/internal/RoundTrip.js.map +1 -0
- package/dist/internal/SentRequest.d.ts +14 -0
- package/dist/internal/SentRequest.d.ts.map +1 -0
- package/dist/internal/SentRequest.js +31 -0
- package/dist/internal/SentRequest.js.map +1 -0
- package/dist/internal/TransactWriteOps.d.ts +69 -15
- package/dist/internal/TransactWriteOps.d.ts.map +1 -1
- package/dist/internal/TransactWriteOps.js +144 -107
- package/dist/internal/TransactWriteOps.js.map +1 -1
- package/dist/internal/TransactableOps.d.ts +115 -23
- package/dist/internal/TransactableOps.d.ts.map +1 -1
- package/dist/internal/TransactableOps.js +244 -80
- package/dist/internal/TransactableOps.js.map +1 -1
- package/dist/internal/WriteDiagnosis.d.ts +31 -3
- package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
- package/dist/internal/WriteDiagnosis.js +128 -11
- package/dist/internal/WriteDiagnosis.js.map +1 -1
- package/package.json +2 -2
package/dist/Aggregate.js
CHANGED
|
@@ -10,33 +10,39 @@
|
|
|
10
10
|
*/
|
|
11
11
|
import { TypeId as SchemaAggregateTypeId } from "@effect-dynamodb/schema/Aggregate.js";
|
|
12
12
|
import * as DynamoModel from "@effect-dynamodb/schema/DynamoModel.js";
|
|
13
|
-
import { composeCollectionKey, composeKey, KEY_DELIMITER, } from "@effect-dynamodb/schema/DynamoSchema.js";
|
|
14
|
-
import { AggregateAssemblyError, AggregateDecompositionError, AggregateTransactionOverflow, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, RefNotFound, TransactionCancelled, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
|
|
15
|
-
import { makeCompositeKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
|
|
13
|
+
import { composeCollectionKey, composeKey, composeUniqueKey, KEY_DELIMITER, } from "@effect-dynamodb/schema/DynamoSchema.js";
|
|
14
|
+
import { AggregateAssemblyError, AggregateDecompositionError, AggregateTransactionOverflow, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, RefNotFound, TRANSACT_WRITE_ITEMS_LIMIT, TransactionCancelled, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
|
|
15
|
+
import { fieldAtPath, kindReadingOf, kindTargets, makeCompositeKeyForm, readBackAs, readBackUnsure, readsBackOtherwise, refuseInexact, storedNaNKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
|
|
16
16
|
import { buildDateTransform, containsWireTransform, matchDateRepresentation, optionalField, resolveSystemFields, substituteSchemaDeep, validateNoTransformOverride, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
|
|
17
|
+
import { failingAsBefore, issueDecoding } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
|
|
18
|
+
import { readingInstances } from "@effect-dynamodb/schema/internal/InstanceReads.js";
|
|
17
19
|
import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
|
|
20
|
+
import { KeyValueError } from "@effect-dynamodb/schema/internal/NumericKey.js";
|
|
18
21
|
import { isDispatchEligible } from "@effect-dynamodb/schema/internal/PackedCodec.js";
|
|
19
|
-
import { extractArrayElement, getSchemaFields, hasEncodingTransformation, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
|
|
22
|
+
import { extractArrayElement, extractKeyedValue, getSchemaFields, hasEncodingTransformation, holdsCustomDeclaration, refuseUnreadable, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
|
|
20
23
|
import { refuseAggregateKeyInTableKey } from "@effect-dynamodb/schema/internal/SharedKeyAttribute.js";
|
|
21
24
|
import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
|
|
22
|
-
import { DateTime, Effect, Equal, Option, Schema, SchemaAST, } from "effect";
|
|
25
|
+
import { DateTime, Effect, Equal, Exit, Option, Schema, SchemaAST, } from "effect";
|
|
23
26
|
import * as Batch from "./Batch.js";
|
|
24
27
|
import { fromDefinition as entityFromDefinition } from "./Entity.js";
|
|
25
28
|
import * as Capacity from "./internal/Capacity.js";
|
|
29
|
+
import { decodeKeyCursor, encodeKeyCursor } from "./internal/Cursor.js";
|
|
26
30
|
import { compileExpr, createConditionOps, emptyPartProblem, isEmptyExpr, parseSimpleShorthand, } from "./internal/Expr.js";
|
|
27
|
-
import { asReadGuard } from "./internal/ExpressionLimits.js";
|
|
31
|
+
import { asReadGuard, preferredGuard, wholeRowGuard, } from "./internal/ExpressionLimits.js";
|
|
32
|
+
import { packRequests, transactWriteShape, transactWriteUnit } from "./internal/ItemSize.js";
|
|
28
33
|
import { hasStoredForm, packItemSync, unpackItemSync, withRegistry } from "./internal/Packed.js";
|
|
29
34
|
import { createPathBuilder } from "./internal/PathBuilder.js";
|
|
30
35
|
import * as Rekey from "./internal/Rekey.js";
|
|
31
|
-
import {
|
|
36
|
+
import { asRead, notReadBack, notStoredForm, readBackRefusal } from "./internal/RoundTrip.js";
|
|
37
|
+
import { composePrimaryKeyOrFail, generateTimestampPrimitive, INCARNATION_TOKEN, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, } from "./internal/TransactableOps.js";
|
|
32
38
|
import { diagnosedValidationError, diagnoseFailure, explainDiagnosis, mergeKeyAttributes, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
|
|
33
|
-
import { fromAttributeMap, toAttributeMap, toAttributeValue } from "./Marshaller.js";
|
|
39
|
+
import { fromAttributeMap, toAttributeMap, toAttributeValue, } from "./Marshaller.js";
|
|
34
40
|
import { resolvePrimaryKey } from "./Table.js";
|
|
35
41
|
// Internal modules (decomposed from Aggregate.ts)
|
|
36
42
|
export { isManyEdge, isOneEdge, isRefEdge, many, one, ref, } from "@effect-dynamodb/schema/internal/AggregateEdges.js";
|
|
37
43
|
export { deriveAggregateSchemas, deriveElementInputSchema, deriveEntityFieldName, extractArrayElement, getSchemaFields, isFieldOptional, isSchemaMatchingEntity, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
38
44
|
import { makeCursor, } from "@effect-dynamodb/schema/internal/AggregateCursor.js";
|
|
39
|
-
import { deriveAggregateSchemas, deriveEntityFieldName, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
45
|
+
import { deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, manyEdgePaths, manyElementFields, manyElementSchema, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseManySortKeysOverMovingValue, resolveAggregateStamps, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
40
46
|
// ---------------------------------------------------------------------------
|
|
41
47
|
// TypeId
|
|
42
48
|
// ---------------------------------------------------------------------------
|
|
@@ -48,6 +54,9 @@ import { deriveAggregateSchemas, deriveEntityFieldName, } from "@effect-dynamodb
|
|
|
48
54
|
// that dual-package hazard.
|
|
49
55
|
export const TypeId = SchemaAggregateTypeId;
|
|
50
56
|
export function make(schema, config) {
|
|
57
|
+
refuseUnreadable(`Aggregate "${config.root.entityType}"`, "aggregate", unwrapModel(schema), {
|
|
58
|
+
manyEdges: manyEdgePaths(config.edges),
|
|
59
|
+
});
|
|
51
60
|
if (!("table" in config) || config.table === undefined) {
|
|
52
61
|
// Sub-aggregate form
|
|
53
62
|
return makeSubAggregate(schema, config);
|
|
@@ -73,43 +82,38 @@ const makeSubAggregate = (schema, config) => {
|
|
|
73
82
|
return sub;
|
|
74
83
|
};
|
|
75
84
|
/**
|
|
76
|
-
*
|
|
85
|
+
* The date encodings a schema AST holds, handling Schema.optional() wrappers: one, or one per date
|
|
86
|
+
* member of a union, in the order they're declared.
|
|
77
87
|
* Optional fields have Union AST with [InnerType, Undefined] — unwrap to find dates.
|
|
78
88
|
*/
|
|
79
|
-
const
|
|
89
|
+
const inferDateEncodings = (ast) => {
|
|
80
90
|
// Try SchemaAST.resolve first (works for non-optional date fields)
|
|
81
91
|
const resolved = SchemaAST.resolve(ast);
|
|
82
92
|
if (resolved) {
|
|
83
93
|
const direct = matchDateRepresentation(resolved);
|
|
84
94
|
if (direct)
|
|
85
|
-
return direct;
|
|
95
|
+
return [direct];
|
|
86
96
|
}
|
|
87
97
|
// Handle optional wrapper: Union with Undefined + inner type.
|
|
88
98
|
// SchemaAST.resolve returns undefined for Union ASTs, so check the raw AST.
|
|
89
99
|
const rawAst = ast;
|
|
90
|
-
if (rawAst._tag
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
const enc = matchDateRepresentation(member.annotations);
|
|
103
|
-
if (enc)
|
|
104
|
-
return enc;
|
|
105
|
-
}
|
|
106
|
-
}
|
|
107
|
-
return undefined;
|
|
100
|
+
if (rawAst._tag !== "Union" || !rawAst.types)
|
|
101
|
+
return [];
|
|
102
|
+
return rawAst.types.flatMap((member) => {
|
|
103
|
+
if (member._tag === "Undefined")
|
|
104
|
+
return [];
|
|
105
|
+
// Try SchemaAST.resolve on the inner member (e.g., Declaration for Schema.Date)
|
|
106
|
+
const memberResolved = SchemaAST.resolve(member);
|
|
107
|
+
// Fallback: check raw member annotations (same record shape, nested under .annotations)
|
|
108
|
+
const encoding = (memberResolved ? matchDateRepresentation(memberResolved) : undefined) ??
|
|
109
|
+
matchDateRepresentation(member.annotations);
|
|
110
|
+
return encoding ? [encoding] : [];
|
|
111
|
+
});
|
|
108
112
|
};
|
|
109
113
|
/**
|
|
110
114
|
* A union that holds a date member alongside a member that is neither a date
|
|
111
115
|
* nor `Undefined` / `Null` — `Union([DateTimeUtcFromString, Number])`.
|
|
112
|
-
* `
|
|
116
|
+
* `inferDateEncodings` looks through unions to find the date in `optional(date)`,
|
|
113
117
|
* so it reports such a field as a date, and encoding a `5` through a date
|
|
114
118
|
* transform throws. Its stored form is the union's own business: it is encoded
|
|
115
119
|
* member by member through the substituted union instead.
|
|
@@ -133,19 +137,45 @@ const isMixedDateUnion = (ast) => {
|
|
|
133
137
|
const dateAttrEncoder = (fieldSchema, options) => {
|
|
134
138
|
if (options?.mixedUnions !== true && isMixedDateUnion(fieldSchema.ast))
|
|
135
139
|
return undefined;
|
|
136
|
-
const
|
|
137
|
-
|
|
140
|
+
const encodings = storedDateEncodings(fieldSchema);
|
|
141
|
+
const last = encodings.at(-1);
|
|
142
|
+
if (!last)
|
|
138
143
|
return undefined;
|
|
139
|
-
|
|
140
|
-
|
|
144
|
+
// A union of dates of different kinds: a value is stored in the form of the kind it is.
|
|
145
|
+
const earlier = encodings
|
|
146
|
+
.slice(0, -1)
|
|
147
|
+
.map((encoding) => Schema.encodeUnknownOption(buildDateTransform(encoding)));
|
|
148
|
+
const encode = Schema.encodeUnknownSync(buildDateTransform(last));
|
|
149
|
+
return (value) => {
|
|
150
|
+
for (const encodeEarlier of earlier) {
|
|
151
|
+
const encoded = encodeEarlier(value);
|
|
152
|
+
if (Option.isSome(encoded))
|
|
153
|
+
return encoded.value;
|
|
154
|
+
}
|
|
155
|
+
return encode(value);
|
|
156
|
+
};
|
|
157
|
+
};
|
|
158
|
+
/**
|
|
159
|
+
* The encodings a date field's values are stored in, the last for a value of no earlier one's kind:
|
|
160
|
+
* the field's own annotation, else those its schema's dates imply. Read off the field as declared, so
|
|
161
|
+
* an annotation inside `Schema.optional`'s union isn't seen, and such a field's values are stored as
|
|
162
|
+
* its date's default, ISO text, as 1.39.0 stored them. A stamp in a field a row declares is stored
|
|
163
|
+
* the same way (`rowStampsOf`).
|
|
164
|
+
*/
|
|
165
|
+
const storedDateEncodings = (fieldSchema) => {
|
|
166
|
+
const explicit = DynamoModel.getEncoding(fieldSchema);
|
|
167
|
+
return explicit ? [explicit] : inferDateEncodings(fieldSchema.ast);
|
|
168
|
+
};
|
|
169
|
+
/** Whether a value is a date field's stored form: one its date encodings decode. */
|
|
170
|
+
const storedDateForm = (fieldSchema) => {
|
|
171
|
+
const decoders = storedDateEncodings(fieldSchema).map((encoding) => Schema.decodeUnknownOption(buildDateTransform(encoding)));
|
|
172
|
+
return (value) => decoders.some((decode) => Option.isSome(decode(value)));
|
|
141
173
|
};
|
|
142
174
|
/**
|
|
143
175
|
* The field's own encode, with `decode -> encode` as the fallback so a caller
|
|
144
176
|
* who already supplied wire form round-trips to itself (the same strategy
|
|
145
|
-
* `Entity.put` uses).
|
|
146
|
-
* Encoded for this field
|
|
147
|
-
* write-time failure mode — that shape is already unreadable, and the tolerant
|
|
148
|
-
* read path reports it.
|
|
177
|
+
* `Entity.put` uses). `None` when neither works: the value is neither Type nor
|
|
178
|
+
* Encoded for this field, and what's stored is the caller's to decide.
|
|
149
179
|
*/
|
|
150
180
|
const ownAttrEncoder = (fieldSchema) => {
|
|
151
181
|
const codec = fieldSchema;
|
|
@@ -154,14 +184,70 @@ const ownAttrEncoder = (fieldSchema) => {
|
|
|
154
184
|
return (value) => {
|
|
155
185
|
const direct = encode(value);
|
|
156
186
|
if (Option.isSome(direct))
|
|
157
|
-
return direct
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
187
|
+
return direct;
|
|
188
|
+
return Option.flatMap(decode(value), encode);
|
|
189
|
+
};
|
|
190
|
+
};
|
|
191
|
+
/**
|
|
192
|
+
* Whether a caller's object holds `field`: as its own property or one its class gives it (a
|
|
193
|
+
* getter, a prototype's property), as `in` says, but never as a member every object inherits
|
|
194
|
+
* (`toString`, `constructor`).
|
|
195
|
+
*/
|
|
196
|
+
const holdsField = (holder, field) => {
|
|
197
|
+
for (let at = holder; at !== null && at !== Object.prototype; at = Object.getPrototypeOf(at)) {
|
|
198
|
+
if (Object.hasOwn(at, field))
|
|
199
|
+
return true;
|
|
200
|
+
}
|
|
201
|
+
return false;
|
|
202
|
+
};
|
|
203
|
+
/** The caller's value of `field`, under `written`. */
|
|
204
|
+
const writtenField = (written, field) => {
|
|
205
|
+
if (written === undefined)
|
|
206
|
+
return undefined;
|
|
207
|
+
const holder = written.present ? written.value : undefined;
|
|
208
|
+
const present = holder !== null && typeof holder === "object" && holdsField(holder, field);
|
|
209
|
+
return {
|
|
210
|
+
present,
|
|
211
|
+
value: present ? holder[field] : undefined,
|
|
212
|
+
update: written.update,
|
|
213
|
+
};
|
|
214
|
+
};
|
|
215
|
+
/**
|
|
216
|
+
* What a `many` edge's custom `decompose` is handed on a write: the caller's own value of the edge
|
|
217
|
+
* read stored form first, once, as 1.39.0 read every write's input. A write's value is otherwise
|
|
218
|
+
* taken as the domain value a caller holds, but a `decompose` written for 1.39.0 was handed this,
|
|
219
|
+
* and what it returns is stored and keyed as it is: handed the domain value instead, a `decompose`
|
|
220
|
+
* that returns a field's stored form (`f / 10` on a field that multiplies by 10) has that encoded
|
|
221
|
+
* once more, its sort key moves, and every `update` compounds the value and adds a row. Handed
|
|
222
|
+
* this, its rows store, key and read exactly as on 1.39.0, and an `update` of a row 1.39.0 wrote
|
|
223
|
+
* finds it. A `decompose` that hands such a field back unchanged stores it decoded once more, as
|
|
224
|
+
* on 1.39.0.
|
|
225
|
+
*
|
|
226
|
+
* It reads what the caller gave, never the value the write already decoded: read again, a decoding
|
|
227
|
+
* default (`5`, read as 50) or a stored form the domain side refuses (`"5"`, read as 50) would be
|
|
228
|
+
* decoded twice, to 500. Only a transformation with one type on both sides reads differently, and
|
|
229
|
+
* a class whose fields hold none reads as given, so undefined when the field holds no
|
|
230
|
+
* transformation beneath its classes: nothing is read again. What was read (update's old state,
|
|
231
|
+
* `rekey`) is handed to `decompose` as it was read, as 1.39.0 did. None where the caller's value
|
|
232
|
+
* doesn't read, and `decompose` is handed the decoded value.
|
|
233
|
+
*/
|
|
234
|
+
const storedFormFirst = (field, fieldSchema, resolveRef) => {
|
|
235
|
+
if (fieldSchema === undefined || !containsWireTransform(fieldSchema, { throughClasses: true })) {
|
|
236
|
+
return undefined;
|
|
237
|
+
}
|
|
238
|
+
const reader = (update) => Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [field]: fieldSchema }), {
|
|
239
|
+
tolerantTransforms: true,
|
|
240
|
+
decodeOnly: true,
|
|
241
|
+
resolveRef,
|
|
242
|
+
// A mutation's plain state holds a set as a list and an `Option` as a tagged object.
|
|
243
|
+
...(update && { plainStateForms: true }),
|
|
244
|
+
}));
|
|
245
|
+
const readers = {};
|
|
246
|
+
return (written) => {
|
|
247
|
+
const which = written.update ? "update" : "create";
|
|
248
|
+
const read = readers[which] ?? reader(written.update);
|
|
249
|
+
readers[which] = read;
|
|
250
|
+
return Option.map(read(written.present ? { [field]: written.value } : {}), (asRead) => asRead[field]);
|
|
165
251
|
};
|
|
166
252
|
};
|
|
167
253
|
/**
|
|
@@ -177,7 +263,8 @@ const ownAttrEncoder = (fieldSchema) => {
|
|
|
177
263
|
*
|
|
178
264
|
* Exactly ONE encoder per field, so nothing is ever encoded twice:
|
|
179
265
|
*
|
|
180
|
-
* 1. **A date encoding** — see {@link dateAttrEncoder}.
|
|
266
|
+
* 1. **A date encoding** — see {@link dateAttrEncoder}. With `storedDates`, a value already in
|
|
267
|
+
* the field's stored form is stored as it is ({@link storedDateForm}).
|
|
181
268
|
* 2. **Anything that holds a wire transform AT ANY DEPTH** — a leaf transform, a
|
|
182
269
|
* `Schema.Class`, and also an `Array` / `Struct` / `Union` containing one, or
|
|
183
270
|
* a self date or `Redacted` nested anywhere ({@link containsWireTransform}).
|
|
@@ -186,7 +273,11 @@ const ownAttrEncoder = (fieldSchema) => {
|
|
|
186
273
|
* `tolerantTransforms`, with the aggregate's ref resolver), so the stored
|
|
187
274
|
* form is exactly what assembly reads back — nested date leaves included —
|
|
188
275
|
* and a `DynamoModel.ref`-annotated field is encoded through the ref
|
|
189
|
-
* target's model. The field's own encode is the fallback.
|
|
276
|
+
* target's model. The field's own encode is the fallback. A value none of
|
|
277
|
+
* them takes is stored as given, and reported through `asGiven`: the write
|
|
278
|
+
* then stores it only if its rows read back (`refuseNotReadBack`,
|
|
279
|
+
* `EDD-9127`). A schema that can't encode a value it decodes to, such as a
|
|
280
|
+
* transformation over itself, gets here with every value a caller holds.
|
|
190
281
|
*
|
|
191
282
|
* Gating on the TOP-LEVEL node instead (as before #133) skipped every
|
|
192
283
|
* container, because an `Arrays` / `Objects` node carries no encoding of its
|
|
@@ -199,36 +290,69 @@ const ownAttrEncoder = (fieldSchema) => {
|
|
|
199
290
|
* Type-side values (`numericTypeWithStringEncoding`), so the aggregate is never
|
|
200
291
|
* encoded as a whole before it is decomposed.
|
|
201
292
|
*/
|
|
202
|
-
const buildAttrEncoders = (fields, resolveRef
|
|
293
|
+
const buildAttrEncoders = (fields, resolveRef,
|
|
294
|
+
/**
|
|
295
|
+
* A keyed (`Schema.Record`) `many` edge without an `entity` only: 1.39.0 gave it no encoders, so
|
|
296
|
+
* it stored a date its custom `decompose` returned in the field's stored form as it was.
|
|
297
|
+
*/
|
|
298
|
+
storedDates = false) => {
|
|
203
299
|
const encoders = {};
|
|
204
300
|
if (!fields)
|
|
205
301
|
return encoders;
|
|
206
302
|
for (const field of Object.keys(fields)) {
|
|
207
303
|
const fieldSchema = fields[field];
|
|
208
|
-
// 1. Date encoding.
|
|
304
|
+
// 1. Date encoding. With `storedDates`, a value already in the field's stored form (a custom
|
|
305
|
+
// `decompose` that returns the ISO text of a `DateTimeUtcFromString`) is stored as it is, as
|
|
306
|
+
// 1.39.0 stored it there; anything else is stored as given, and the write refuses it unless
|
|
307
|
+
// it reads back. Elsewhere a value the encoding doesn't take fails the write, as on 1.39.0.
|
|
209
308
|
const date = dateAttrEncoder(fieldSchema);
|
|
210
|
-
if (date) {
|
|
309
|
+
if (date && !storedDates) {
|
|
211
310
|
encoders[field] = date;
|
|
212
311
|
continue;
|
|
213
312
|
}
|
|
313
|
+
if (date) {
|
|
314
|
+
const stored = storedDateForm(fieldSchema);
|
|
315
|
+
encoders[field] = (value, asGiven) => {
|
|
316
|
+
try {
|
|
317
|
+
return date(value);
|
|
318
|
+
}
|
|
319
|
+
catch {
|
|
320
|
+
if (!stored(value))
|
|
321
|
+
asGiven?.();
|
|
322
|
+
return value;
|
|
323
|
+
}
|
|
324
|
+
};
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
214
327
|
// 3. Nothing anywhere in the value has a wire form distinct from its domain form.
|
|
215
328
|
if (!containsWireTransform(fieldSchema))
|
|
216
329
|
continue;
|
|
217
330
|
// 2. Encode through the read path's own (substituted, tolerant) schema. A
|
|
218
331
|
// one-field struct carries the field's optionality and lets `resolveRef`
|
|
219
332
|
// re-point the field itself, exactly as it does inside `decodeSchema`.
|
|
220
|
-
const
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
333
|
+
const encoderOver = (options) => {
|
|
334
|
+
const encode = Schema.encodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [field]: fieldSchema }), {
|
|
335
|
+
...options,
|
|
336
|
+
tolerantTransforms: true,
|
|
337
|
+
resolveRef,
|
|
338
|
+
}));
|
|
339
|
+
return (value) => {
|
|
340
|
+
const encoded = encode({ [field]: value });
|
|
341
|
+
return Option.isSome(encoded)
|
|
342
|
+
? Option.some(encoded.value[field])
|
|
343
|
+
: Option.none();
|
|
344
|
+
};
|
|
231
345
|
};
|
|
346
|
+
const encodeSubstituted = encoderOver({});
|
|
347
|
+
// A read reaches beneath a decoding default and this doesn't, and what it takes there isn't
|
|
348
|
+
// always what the field's own schema takes: a redacted value of another label. What's stored
|
|
349
|
+
// is the first's; this only keeps such a value from being marshalled as it is.
|
|
350
|
+
const encodeAsRead = encoderOver({ decodeOnly: true });
|
|
351
|
+
const own = ownAttrEncoder(fieldSchema);
|
|
352
|
+
encoders[field] = (value, asGiven) => encodeSubstituted(value).pipe(Option.orElse(() => encodeAsRead(value)), Option.orElse(() => own(value)), Option.getOrElse(() => {
|
|
353
|
+
asGiven?.();
|
|
354
|
+
return value;
|
|
355
|
+
}));
|
|
232
356
|
}
|
|
233
357
|
return encoders;
|
|
234
358
|
};
|
|
@@ -266,8 +390,11 @@ const buildKeyAttrEncoders = (fields) => {
|
|
|
266
390
|
}
|
|
267
391
|
};
|
|
268
392
|
}
|
|
269
|
-
else if (hasEncodingTransformation(fieldSchema))
|
|
270
|
-
|
|
393
|
+
else if (hasEncodingTransformation(fieldSchema)) {
|
|
394
|
+
// A key composed from a value no encoder takes is composed from the value as it is.
|
|
395
|
+
const own = ownAttrEncoder(fieldSchema);
|
|
396
|
+
encoders[field] = (value) => Option.getOrElse(own(value), () => value);
|
|
397
|
+
}
|
|
271
398
|
}
|
|
272
399
|
return encoders;
|
|
273
400
|
};
|
|
@@ -299,17 +426,6 @@ const isOpaqueRefField = (field) => {
|
|
|
299
426
|
const inner = unwrapOptionalField(field);
|
|
300
427
|
return getSchemaFields(inner) === undefined && SchemaAST.isDeclaration(inner.ast);
|
|
301
428
|
};
|
|
302
|
-
/**
|
|
303
|
-
* The fields of a `many` edge's ELEMENT, read off the parent model's array
|
|
304
|
-
* field (`players: Schema.Array(PlayerSheet)` → `PlayerSheet`'s fields).
|
|
305
|
-
* `undefined` when the field is not array-shaped (a custom `decompose`) or its
|
|
306
|
-
* element exposes no fields (a scalar, or an opaque ref).
|
|
307
|
-
*/
|
|
308
|
-
const manyElementFields = (parentFields, edgeName) => {
|
|
309
|
-
const field = parentFields?.[edgeName];
|
|
310
|
-
const element = field === undefined ? undefined : extractArrayElement(field);
|
|
311
|
-
return element === undefined ? undefined : getSchemaFields(element);
|
|
312
|
-
};
|
|
313
429
|
/**
|
|
314
430
|
* A sub-aggregate nested in another inherits its parent's discriminator, and
|
|
315
431
|
* its rows carry both (#133). Re-using an inherited attribute name would
|
|
@@ -435,15 +551,19 @@ const collectRefTargets = (rootFields, rootEdges) => {
|
|
|
435
551
|
* Apply a node's attribute encoders in place — puts each attribute into its
|
|
436
552
|
* stored form before the decomposed item is marshalled (#72, #133: without
|
|
437
553
|
* this, a `DateTime` marshals to a `{ epochMilliseconds, … }` map that the
|
|
438
|
-
* read path cannot decode as the wire form).
|
|
554
|
+
* read path cannot decode as the wire form). Returns the fields stored as
|
|
555
|
+
* given (see {@link AttrEncoder}).
|
|
439
556
|
*/
|
|
440
557
|
const applyNodeAttrEncoders = (attrs, encoders) => {
|
|
558
|
+
const asGiven = [];
|
|
441
559
|
if (!encoders)
|
|
442
|
-
return;
|
|
560
|
+
return asGiven;
|
|
443
561
|
for (const [field, encode] of Object.entries(encoders)) {
|
|
444
|
-
if (field in attrs && attrs[field] != null)
|
|
445
|
-
attrs[field] = encode(attrs[field]);
|
|
562
|
+
if (field in attrs && attrs[field] != null) {
|
|
563
|
+
attrs[field] = encode(attrs[field], () => asGiven.push(field));
|
|
564
|
+
}
|
|
446
565
|
}
|
|
566
|
+
return asGiven;
|
|
447
567
|
};
|
|
448
568
|
// ---------------------------------------------------------------------------
|
|
449
569
|
// Top-level aggregate construction
|
|
@@ -487,17 +607,97 @@ const makeAggregate = (schema, config) => {
|
|
|
487
607
|
// same-named field anywhere in the model.
|
|
488
608
|
const refTargets = collectRefTargets(schemaFields, config.edges);
|
|
489
609
|
const resolveRef = (_name, field) => refTargets.get(field);
|
|
610
|
+
// System timestamps (#98). Aggregates compose their DynamoDB items directly
|
|
611
|
+
// rather than routing through Entity write ops, so Entity's timestamp
|
|
612
|
+
// machinery never reached these rows. Resolution goes through the SAME
|
|
613
|
+
// resolver as Entity, which means field names, `DynamoModel` storage
|
|
614
|
+
// annotations and the EDD-9044 guard on an un-annotated `schema` all behave
|
|
615
|
+
// identically here. Passing the root schema's fields also inherits Entity's
|
|
616
|
+
// collision rule: a date-compatible root field of the same name supplies the
|
|
617
|
+
// encoding, and a non-date one means the user owns the attribute outright, on
|
|
618
|
+
// every row. As on an entity, `Schema.optional` wraps the value that's read.
|
|
619
|
+
const resolveStampsOver = (fields) => resolveAggregateStamps(config.timestamps, fields, `Aggregate "${aggregateName}"`);
|
|
620
|
+
const timestampFields = resolveStampsOver(schemaFields);
|
|
621
|
+
refuseAggregateKeyOverMovingValue(aggregateName, config.timestamps, schemaFields, config.pk.composite);
|
|
622
|
+
// The form a stamp is stored in: on a row declaring its field, the form the row stores any value of
|
|
623
|
+
// that field in ({@link storedDateEncodings}, as `buildAttrEncoders` reads it), else the stamp's
|
|
624
|
+
// own encoding. A row that doesn't declare it holds what the root's would.
|
|
625
|
+
const storedIn = (fields, name, declared, encoding) => {
|
|
626
|
+
const field = declared && name !== null ? fields?.[name] : undefined;
|
|
627
|
+
return (field === undefined ? undefined : storedDateEncodings(field).at(-1)) ?? encoding;
|
|
628
|
+
};
|
|
629
|
+
const stampFields = timestampFields.createdAt !== null || timestampFields.updatedAt !== null
|
|
630
|
+
? {
|
|
631
|
+
createdAt: timestampFields.createdAt,
|
|
632
|
+
createdEncoding: storedIn(schemaFields, timestampFields.createdAt, timestampFields.createdAtCollision, timestampFields.createdAtEncoding),
|
|
633
|
+
updatedAt: timestampFields.updatedAt,
|
|
634
|
+
updatedEncoding: storedIn(schemaFields, timestampFields.updatedAt, timestampFields.updatedAtCollision, timestampFields.updatedAtEncoding),
|
|
635
|
+
}
|
|
636
|
+
: undefined;
|
|
637
|
+
// What the read path may drop before decoding: each node drops those its rows
|
|
638
|
+
// don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object.
|
|
639
|
+
const systemAttrs = new Set([timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null));
|
|
640
|
+
const requiredIn = (fields, name) => name !== null && fields?.[name] !== undefined && !isFieldOptional(fields[name]);
|
|
641
|
+
// On `create`, a stamp replaces a value the input holds, as on 1.39.0, except under a date the root
|
|
642
|
+
// declares `Schema.optional`: 1.39.0 left that field the caller's and stored a value passed for it.
|
|
643
|
+
// That is 1.39.0's verdict, the resolver's over the root's fields as declared: `Schema.optional`'s
|
|
644
|
+
// union isn't a date there, while a required date and a `Schema.optionalKey` one are the library's.
|
|
645
|
+
const asDeclared = resolveSystemFields(config.timestamps, undefined, undefined, schemaFields, {}, `Aggregate "${aggregateName}"`);
|
|
646
|
+
const createdReplaces = !timestampFields.createdAtCollision || asDeclared.createdAtCollision;
|
|
647
|
+
const updatedReplaces = !timestampFields.updatedAtCollision || asDeclared.updatedAtCollision;
|
|
648
|
+
/**
|
|
649
|
+
* What the rows of a value with these fields do with each timestamp, as an entity's do: a date the
|
|
650
|
+
* value declares is the library's, under the field's encoding, and `create` stamps it over what the
|
|
651
|
+
* input holds unless the root declares it `Schema.optional` ({@link fillStamps}), where an `update`
|
|
652
|
+
* takes a value the mutation changed; any other field of that name is the caller's and the row
|
|
653
|
+
* isn't stamped. Undeclared, the row is stamped.
|
|
654
|
+
*/
|
|
655
|
+
const rowStampsOf = (fields) => {
|
|
656
|
+
if (stampFields === undefined)
|
|
657
|
+
return undefined;
|
|
658
|
+
const own = resolveStampsOver(fields);
|
|
659
|
+
return {
|
|
660
|
+
createdAt: stampFields.createdAt === null ? null : own.createdAt,
|
|
661
|
+
createdEncoding: own.createdAtCollision ? own.createdAtEncoding : stampFields.createdEncoding,
|
|
662
|
+
createdStored: own.createdAtCollision
|
|
663
|
+
? storedIn(fields, own.createdAt, true, own.createdAtEncoding)
|
|
664
|
+
: stampFields.createdEncoding,
|
|
665
|
+
createdDeclared: own.createdAtCollision,
|
|
666
|
+
createdRequired: own.createdAtCollision && requiredIn(fields, own.createdAt),
|
|
667
|
+
createdReplaces,
|
|
668
|
+
updatedAt: stampFields.updatedAt === null ? null : own.updatedAt,
|
|
669
|
+
updatedEncoding: own.updatedAtCollision ? own.updatedAtEncoding : stampFields.updatedEncoding,
|
|
670
|
+
updatedStored: own.updatedAtCollision
|
|
671
|
+
? storedIn(fields, own.updatedAt, true, own.updatedAtEncoding)
|
|
672
|
+
: stampFields.updatedEncoding,
|
|
673
|
+
updatedDeclared: own.updatedAtCollision,
|
|
674
|
+
updatedRequired: own.updatedAtCollision && requiredIn(fields, own.updatedAt),
|
|
675
|
+
updatedReplaces,
|
|
676
|
+
};
|
|
677
|
+
};
|
|
678
|
+
refuseManySortKeysOverMovingValue(aggregateName, config.timestamps, schemaFields, config.edges);
|
|
679
|
+
refuseAggregateKeysOverBothKinds(aggregateName, schemaFields, config, config.edges);
|
|
680
|
+
const withRowStamps = (node) => ({
|
|
681
|
+
...node,
|
|
682
|
+
rowStamps: rowStampsOf(node.ownFields),
|
|
683
|
+
children: node.children.map(withRowStamps),
|
|
684
|
+
});
|
|
490
685
|
// Build resolved graph by walking edges recursively. Each node's attribute
|
|
491
686
|
// encoders come from the schema its decomposed values actually have — for a
|
|
492
687
|
// `many` edge that is the aggregate model's array ELEMENT (#133).
|
|
493
|
-
const rootNode = resolveNode({
|
|
688
|
+
const rootNode = withRowStamps(resolveNode({
|
|
494
689
|
fieldName: null,
|
|
495
690
|
entityType: config.root.entityType,
|
|
496
691
|
cardinality: "root",
|
|
497
692
|
edges: config.edges,
|
|
498
693
|
parentFields: schemaFields,
|
|
499
694
|
resolveRef,
|
|
500
|
-
});
|
|
695
|
+
}));
|
|
696
|
+
// Rows that hold a stamp in the domain object: what `update` returns has to say what it wrote.
|
|
697
|
+
const declaresStamp = (node) => node.rowStamps?.createdDeclared === true ||
|
|
698
|
+
node.rowStamps?.updatedDeclared === true ||
|
|
699
|
+
node.children.some(declaresStamp);
|
|
700
|
+
const returnsStamps = declaresStamp(rootNode);
|
|
501
701
|
// Packed edge attributes, and those read by stored form, by item entity type (#147).
|
|
502
702
|
const packedByType = collectPackedByType(rootNode);
|
|
503
703
|
const dispatchByType = collectDispatchByType(rootNode);
|
|
@@ -518,22 +718,55 @@ const makeAggregate = (schema, config) => {
|
|
|
518
718
|
// - update re-decodes the mutated state, which carries domain `DateTime`
|
|
519
719
|
// values → accepted as-is (a strict `*FromString` decoder would reject
|
|
520
720
|
// them). It is decode-only, so making transforms tolerant is safe — the
|
|
521
|
-
// stored wire format is still produced by the attribute encoders
|
|
721
|
+
// stored wire format is still produced by the attribute encoders;
|
|
722
|
+
// - an absent attribute reads as the value it stands for: `undefined`, or an
|
|
723
|
+
// empty set, neither of which DynamoDB can store (`absentReading`).
|
|
522
724
|
// Nested edge / ref classes round-trip with their class instance identity
|
|
523
725
|
// preserved (Option A). Returns the raw `schema` unchanged when it carries no
|
|
524
726
|
// such leaf at all (zero overhead).
|
|
525
727
|
const decodeSchema = substituteSchemaDeep(schema, {
|
|
526
728
|
tolerantTransforms: true,
|
|
729
|
+
decodeOnly: true,
|
|
527
730
|
resolveRef,
|
|
731
|
+
absentReads: true,
|
|
528
732
|
});
|
|
733
|
+
// What assembly decodes the rows with: `decodeSchema`, with each of Effect's look-alike
|
|
734
|
+
// declarations (a `BigDecimal`, a `Duration`, a date in an `Option`, ...) reading back as a real
|
|
735
|
+
// instance (`readingInstances`). Reads only: the plain state `update` hands a mutation
|
|
736
|
+
// (`readToPlain`) is `decodeSchema`'s.
|
|
737
|
+
//
|
|
738
|
+
// A read that dies on an absent attribute fails as 1.39.0's did, with the issue `decodeSchema`
|
|
739
|
+
// without its absent reads gives (`failingAsBefore`), built only once a read has died.
|
|
740
|
+
let asBefore;
|
|
741
|
+
const assembly = {
|
|
742
|
+
schema: readingInstances(decodeSchema),
|
|
743
|
+
before: () => (asBefore ??= substituteSchemaDeep(schema, {
|
|
744
|
+
tolerantTransforms: true,
|
|
745
|
+
decodeOnly: true,
|
|
746
|
+
resolveRef,
|
|
747
|
+
})),
|
|
748
|
+
};
|
|
529
749
|
// The same schema for WRITES — `create` input and `update`'s mutated state —
|
|
530
750
|
// with the container `.check()` refinements the substitution rebuilds kept, so
|
|
531
|
-
// a write that breaks one is rejected (#133)
|
|
751
|
+
// a write that breaks one is rejected (#133), and a value is asked as the domain
|
|
752
|
+
// value first, since that's what a caller holds. Assembly keeps `decodeSchema`:
|
|
532
753
|
// a row written while those checks were not enforced must stay readable.
|
|
533
754
|
const writeSchema = substituteSchemaDeep(schema, {
|
|
534
755
|
tolerantTransforms: true,
|
|
756
|
+
decodeOnly: true,
|
|
757
|
+
resolveRef,
|
|
758
|
+
enforceChecks: true,
|
|
759
|
+
domainValues: true,
|
|
760
|
+
});
|
|
761
|
+
// `update`'s mutated state: the plain state a mutation is handed holds a set as a list and
|
|
762
|
+
// an `Option` as a tagged object (`Schema.toIso`), and it can hand that straight back.
|
|
763
|
+
const mutatedStateSchema = substituteSchemaDeep(schema, {
|
|
764
|
+
tolerantTransforms: true,
|
|
765
|
+
decodeOnly: true,
|
|
535
766
|
resolveRef,
|
|
536
767
|
enforceChecks: true,
|
|
768
|
+
plainStateForms: true,
|
|
769
|
+
domainValues: true,
|
|
537
770
|
});
|
|
538
771
|
// Validate the collection index against the table's primary key. Best effort: a
|
|
539
772
|
// table registering only aggregates has no primary key to resolve, in which case
|
|
@@ -567,29 +800,6 @@ const makeAggregate = (schema, config) => {
|
|
|
567
800
|
`sort by — declare both to assemble through an index, or neither to assemble off the ` +
|
|
568
801
|
`base table.`);
|
|
569
802
|
}
|
|
570
|
-
// System timestamps (#98). Aggregates compose their DynamoDB items directly
|
|
571
|
-
// rather than routing through Entity write ops, so Entity's timestamp
|
|
572
|
-
// machinery never reached these rows. Resolution goes through the SAME
|
|
573
|
-
// resolver as Entity, which means field names, `DynamoModel` storage
|
|
574
|
-
// annotations and the EDD-9044 guard on an un-annotated `schema` all behave
|
|
575
|
-
// identically here. Passing the root schema's fields also inherits Entity's
|
|
576
|
-
// collision rule: a date-compatible root field of the same name supplies the
|
|
577
|
-
// encoding, and a non-date one means the user owns the attribute outright.
|
|
578
|
-
const timestampFields = resolveSystemFields(config.timestamps, undefined, undefined, schemaFields ?? {}, {}, `Aggregate "${aggregateName}"`);
|
|
579
|
-
const stampFields = timestampFields.createdAt !== null || timestampFields.updatedAt !== null
|
|
580
|
-
? {
|
|
581
|
-
createdAt: timestampFields.createdAt,
|
|
582
|
-
createdEncoding: timestampFields.createdAtEncoding,
|
|
583
|
-
updatedAt: timestampFields.updatedAt,
|
|
584
|
-
updatedEncoding: timestampFields.updatedAtEncoding,
|
|
585
|
-
}
|
|
586
|
-
: undefined;
|
|
587
|
-
// Attributes the read path must drop before decoding. A field the root model
|
|
588
|
-
// declares itself is NOT stripped — it belongs to the domain object.
|
|
589
|
-
const systemAttrs = new Set([
|
|
590
|
-
timestampFields.createdAtCollision ? null : timestampFields.createdAt,
|
|
591
|
-
timestampFields.updatedAtCollision ? null : timestampFields.updatedAt,
|
|
592
|
-
].filter((name) => name !== null));
|
|
593
803
|
/** Read stored `created` values back, keyed by sk, so a rewrite preserves them. */
|
|
594
804
|
const readExistingCreated = (allItems) => {
|
|
595
805
|
const createdField = stampFields?.createdAt;
|
|
@@ -605,9 +815,11 @@ const makeAggregate = (schema, config) => {
|
|
|
605
815
|
return map;
|
|
606
816
|
};
|
|
607
817
|
/** Bind the per-write stamp: config + the Clock-backed instant + carry-forward. */
|
|
608
|
-
const stampFor = (now, existingCreated, existingUpdated) => stampFields === undefined
|
|
609
|
-
|
|
610
|
-
|
|
818
|
+
const stampFor = (now, existingCreated, existingUpdated, updatedBefore) => stampFields === undefined ? undefined : { now, existingCreated, existingUpdated, updatedBefore };
|
|
819
|
+
/** Compose keys and marshal rows: a value it can't place is a `ValidationError`, not a defect. */
|
|
820
|
+
const composeOrFail = (operation, compose) => marshalOrFail(aggregateName, `aggregate.${operation}`, compose);
|
|
821
|
+
/** The partition key `record` composes. Throws what {@link composeOrFail} turns into its failure. */
|
|
822
|
+
const collectionPkOf = (record) => composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(aggregateName, "its partition key", config.schema, config.pk.composite, keyRecord(record)));
|
|
611
823
|
// Build optics at construction time (once per aggregate definition)
|
|
612
824
|
const classToPlain = Schema.toIso(schema);
|
|
613
825
|
const opticRoot = Schema.toIsoFocus(schema);
|
|
@@ -629,12 +841,21 @@ const makeAggregate = (schema, config) => {
|
|
|
629
841
|
// domain objects, so without this a `DateEpochMs` composite would key on its
|
|
630
842
|
// ISO form here and its epoch form on the entity path, and a numeric
|
|
631
843
|
// composite with a string encoding would not be zero-padded on either.
|
|
632
|
-
|
|
844
|
+
//
|
|
845
|
+
// 1.39.0's form (`text139`): a codec `encode` takes on its own output (a
|
|
846
|
+
// number scaled, `x:` prepended) is encoded whatever it's given. The
|
|
847
|
+
// aggregate's keys are its own — `create`, `get`, `list` and `rekey` all
|
|
848
|
+
// compose them here, from domain values, encoded once — so no other path
|
|
849
|
+
// missed what it wrote, and they keep every byte.
|
|
850
|
+
const compositeKeyForm = makeCompositeKeyForm(schema, (attr, value, reason) => {
|
|
851
|
+
if (reason !== undefined) {
|
|
852
|
+
return refuseInexact(`Composite "${attr}" on aggregate "${aggregateName}"`, value, reason);
|
|
853
|
+
}
|
|
633
854
|
throw new Error(`[EDD-9050] Composite "${attr}" on aggregate "${aggregateName}" could not be put into ` +
|
|
634
855
|
`its key form. The attribute's schema carries an encoding transformation, but ` +
|
|
635
856
|
`${JSON.stringify(String(value))} resolves under neither encode nor decode->encode. ` +
|
|
636
857
|
`Supply a value of the attribute's own type.`);
|
|
637
|
-
});
|
|
858
|
+
}, { text139: true });
|
|
638
859
|
// Only the attributes a key is ever composed from are put into key form. The
|
|
639
860
|
// rest of the record is never read off the result, and normalising it could
|
|
640
861
|
// only fail: a stored value that breaks a field's `.check()` (#133) made
|
|
@@ -664,28 +885,246 @@ const makeAggregate = (schema, config) => {
|
|
|
664
885
|
const readPartition = (key, rejected, rekeyRead) => Effect.flatMap(readPartitionRaw(key, rejected, rekeyRead), (read) =>
|
|
665
886
|
// Packed edge attributes, read by their stored form (#147).
|
|
666
887
|
Effect.as(unpackAggregateItems(read.allItems, dispatchByType, aggregateName), read));
|
|
888
|
+
// A root row's partition key composites as a read takes them: decoded through their fields, as
|
|
889
|
+
// assembly decodes the root row. `create` composes the key from the value it holds, so a key
|
|
890
|
+
// composed again from a stored row (`list`, `rekey`) is composed from these, never from the
|
|
891
|
+
// stored form: a transformation that isn't its own inverse on the other side (a value stored
|
|
892
|
+
// divided by ten, an `Option` holding one) keys the stored form elsewhere.
|
|
893
|
+
const decodeRootKey = (() => {
|
|
894
|
+
const fields = {};
|
|
895
|
+
for (const attr of config.pk.composite) {
|
|
896
|
+
const field = schemaFields?.[attr];
|
|
897
|
+
if (field !== undefined)
|
|
898
|
+
fields[attr] = field;
|
|
899
|
+
}
|
|
900
|
+
return Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct(fields), {
|
|
901
|
+
tolerantTransforms: true,
|
|
902
|
+
decodeOnly: true,
|
|
903
|
+
resolveRef,
|
|
904
|
+
absentReads: true,
|
|
905
|
+
}));
|
|
906
|
+
})();
|
|
907
|
+
/**
|
|
908
|
+
* `row` (a stored root row) with its partition key composites as a read takes them. A row whose
|
|
909
|
+
* composites a read can't take is left as it is: its key composes as the stored form does, and its
|
|
910
|
+
* read fails as assembly's does.
|
|
911
|
+
*/
|
|
912
|
+
const rootKeyAsRead = (row) => {
|
|
913
|
+
const composites = {};
|
|
914
|
+
for (const attr of config.pk.composite) {
|
|
915
|
+
if (attr in row)
|
|
916
|
+
composites[attr] = row[attr];
|
|
917
|
+
}
|
|
918
|
+
const read = decodeRootKey(composites);
|
|
919
|
+
return Option.isSome(read) ? { ...row, ...read.value } : row;
|
|
920
|
+
};
|
|
667
921
|
/** The collection partition key `record`'s values compose under `under`. */
|
|
668
922
|
const collectionPkUnder = (under, record) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, keyRecord(record)));
|
|
669
923
|
/** {@link readPartition} without unpacking — `delete` needs only the keys. */
|
|
670
924
|
const readPartitionRaw = (key, rejected, rekeyRead) => Effect.gen(function* () {
|
|
671
925
|
const client = yield* Capacity.client;
|
|
672
926
|
const tableConfig = yield* config.table.Tag;
|
|
673
|
-
const
|
|
674
|
-
const pkValue = composeCollectionKey(config.schema, config.collection.name, composites);
|
|
927
|
+
const pkValue = yield* composeOrFail("key", () => collectionPkOf(key));
|
|
675
928
|
const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead, rejected, rekeyRead?.stored);
|
|
676
929
|
const from = rekeyRead?.from;
|
|
677
930
|
const allItems = from === undefined
|
|
678
931
|
? yield* read(pkValue)
|
|
679
932
|
: [...(yield* read(from)), ...(rekeyRead?.fromOnly === true ? [] : yield* read(pkValue))];
|
|
680
|
-
return { client, tableConfig, pkValue,
|
|
933
|
+
return { client, tableConfig, pkValue, allItems };
|
|
681
934
|
});
|
|
935
|
+
const holdsCustom = holdsCustomDeclaration(schema.ast);
|
|
936
|
+
/**
|
|
937
|
+
* Refuses the rows of a write that wouldn't read back: the rows it's about to write, through the read
|
|
938
|
+
* path a `get` takes. Only two kinds of write pay for it: one of an aggregate holding a custom
|
|
939
|
+
* declaration (`EDD-9126`), and one that stored a value as given, which no encoder of its field
|
|
940
|
+
* takes (`asGiven`, `EDD-9127`). Every other write has nothing to do here.
|
|
941
|
+
*/
|
|
942
|
+
const refuseNotReadBack = (groups, key, operation, asGiven) => !holdsCustom && asGiven.length === 0
|
|
943
|
+
? Effect.void
|
|
944
|
+
: Effect.gen(function* () {
|
|
945
|
+
const rows = groups.flatMap((group) => group.items.map((item) => fromAttributeMap(item)));
|
|
946
|
+
yield* unpackAggregateItems(rows, dispatchByType, aggregateName);
|
|
947
|
+
yield* assembleAggregate(assembly, rootNode, rows, contextFields, key, aggregateName, systemAttrs).pipe(Effect.mapError((error) => new ValidationError({
|
|
948
|
+
entityType: aggregateName,
|
|
949
|
+
operation,
|
|
950
|
+
cause: asGiven.length > 0
|
|
951
|
+
? notStoredForm(asGiven, error.cause ?? error)
|
|
952
|
+
: notReadBack("The aggregate", error.cause ?? error),
|
|
953
|
+
})));
|
|
954
|
+
});
|
|
955
|
+
/**
|
|
956
|
+
* `[EDD-9128]`, by value: each key composite whose numeric kinds can't be read at load
|
|
957
|
+
* (`Schema.Unknown`, `Schema.Any`, a declaration, or a transformation from one), with what composes
|
|
958
|
+
* it and the test of a stored value that reads back otherwise (`readsBackOtherwise`), per node
|
|
959
|
+
* whose key composes it. A composite that's a path into a value (`nested.n`) is followed to the
|
|
960
|
+
* field it names (`fieldAtPath`). A declared one is refused at load. Empty for an aggregate with
|
|
961
|
+
* none, which pays nothing more on a write.
|
|
962
|
+
*/
|
|
963
|
+
const otherKindKeys = (() => {
|
|
964
|
+
// A composite judged by the value at its path alone.
|
|
965
|
+
const leafJudge = (path, readsOther) => (item) => {
|
|
966
|
+
const held = readCompositePath(item.attributes, path);
|
|
967
|
+
const readsAs = held == null ? undefined : readsOther(held);
|
|
968
|
+
return readsAs === undefined ? undefined : { held, readsAs };
|
|
969
|
+
};
|
|
970
|
+
// A dotted composite of `node`'s sort key (`nested.n`), judged through the field holding it:
|
|
971
|
+
// the text `node` composes for it from the element written against the text composed again
|
|
972
|
+
// from the row as a read takes it, its field decoded as assembly decodes it and its key read
|
|
973
|
+
// off the result as `decompose` reads it. A transformation of what holds the value (a struct
|
|
974
|
+
// decoded to another) is a read's too, so the value at the path alone isn't what a key read
|
|
975
|
+
// back is composed from.
|
|
976
|
+
const throughFieldJudge = (node, fields, path) => {
|
|
977
|
+
const top = path.slice(0, path.indexOf("."));
|
|
978
|
+
const decode = Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct({ [top]: fields[top] }), {
|
|
979
|
+
tolerantTransforms: true,
|
|
980
|
+
decodeOnly: true,
|
|
981
|
+
resolveRef,
|
|
982
|
+
absentReads: true,
|
|
983
|
+
}));
|
|
984
|
+
const keyEncoder = node.keyAttrEncoders?.[top];
|
|
985
|
+
// The value at the path of a top-level value decoded, as `decompose` reads a key off it.
|
|
986
|
+
const leafOf = (value) => Option.map(decode({ [top]: value }), (decoded) => {
|
|
987
|
+
const held = decoded[top];
|
|
988
|
+
return readCompositePath({ [top]: keyEncoder === undefined ? held : keyEncoder(held) }, path);
|
|
989
|
+
});
|
|
990
|
+
return (item) => {
|
|
991
|
+
const stored = item.attributes[top];
|
|
992
|
+
if (stored == null)
|
|
993
|
+
return undefined;
|
|
994
|
+
// Only a `many` element has a sort key `node` composes from it.
|
|
995
|
+
const written = item.skTextFor?.(node, path);
|
|
996
|
+
if (written === undefined)
|
|
997
|
+
return undefined;
|
|
998
|
+
let returned;
|
|
999
|
+
try {
|
|
1000
|
+
returned = asRead(stored);
|
|
1001
|
+
}
|
|
1002
|
+
catch {
|
|
1003
|
+
// A value the marshaller refuses is the write's own marshalling's to report.
|
|
1004
|
+
return undefined;
|
|
1005
|
+
}
|
|
1006
|
+
const read = Option.filter(leafOf(returned), (leaf) => leaf != null);
|
|
1007
|
+
if (Option.isSome(read) &&
|
|
1008
|
+
isScalarComposite(read.value) &&
|
|
1009
|
+
KeyComposer.keyValueText(config.schema, read.value, config.schema.casing) === written) {
|
|
1010
|
+
return undefined;
|
|
1011
|
+
}
|
|
1012
|
+
const was = Option.getOrUndefined(leafOf(stored));
|
|
1013
|
+
return {
|
|
1014
|
+
held: was ?? readCompositePath(item.attributes, path),
|
|
1015
|
+
readsAs: readBackAs(read, was),
|
|
1016
|
+
};
|
|
1017
|
+
};
|
|
1018
|
+
};
|
|
1019
|
+
// The text the root's key composes from a composite's value, written and read back alike: the
|
|
1020
|
+
// key form takes a value read back as its field reads it.
|
|
1021
|
+
const rootKeyText = (path) => (value) => {
|
|
1022
|
+
try {
|
|
1023
|
+
return KeyComposer.compositeText(config.schema, compositeKeyForm(path, value));
|
|
1024
|
+
}
|
|
1025
|
+
catch {
|
|
1026
|
+
return undefined;
|
|
1027
|
+
}
|
|
1028
|
+
};
|
|
1029
|
+
const checksOf = (fields, into, composites, root = false) => composites.flatMap((path) => {
|
|
1030
|
+
const fieldSchema = fieldAtPath(fields, path);
|
|
1031
|
+
const text = rootKeyText(path);
|
|
1032
|
+
const readsOther = fieldSchema === undefined
|
|
1033
|
+
? undefined
|
|
1034
|
+
: readsBackOtherwise(fieldSchema, {
|
|
1035
|
+
asRead,
|
|
1036
|
+
texts: root ? [{ written: text, read: text }] : [],
|
|
1037
|
+
});
|
|
1038
|
+
return readsOther === undefined ? [] : [{ path, into, judge: leafJudge(path, readsOther) }];
|
|
1039
|
+
});
|
|
1040
|
+
// An edge's sort key: a dotted composite is judged through the field holding it when that field's
|
|
1041
|
+
// read-back can't be guaranteed at load, and any other composite by its value.
|
|
1042
|
+
const edgeChecksOf = (node, composites) => {
|
|
1043
|
+
const into = `edge "${node.fieldName}"'s sort key`;
|
|
1044
|
+
const fields = node.ownFields;
|
|
1045
|
+
return composites.flatMap((path) => {
|
|
1046
|
+
const top = fields?.[path.slice(0, path.indexOf("."))];
|
|
1047
|
+
const leaf = fieldAtPath(fields, path);
|
|
1048
|
+
return fields !== undefined &&
|
|
1049
|
+
top !== undefined &&
|
|
1050
|
+
path.includes(".") &&
|
|
1051
|
+
(readBackUnsure(top) || (leaf !== undefined && readBackUnsure(leaf)))
|
|
1052
|
+
? [{ path, into, judge: throughFieldJudge(node, fields, path) }]
|
|
1053
|
+
: checksOf(fields, into, [path]);
|
|
1054
|
+
});
|
|
1055
|
+
};
|
|
1056
|
+
// Each node's own checks: a row is judged by every node assembly hands it to (`assemblyWalk`).
|
|
1057
|
+
const byNode = new Map();
|
|
1058
|
+
const add = (node, checks) => {
|
|
1059
|
+
if (checks.length > 0)
|
|
1060
|
+
byNode.set(node, checks);
|
|
1061
|
+
};
|
|
1062
|
+
add(rootNode, [
|
|
1063
|
+
...checksOf(schemaFields, "its partition key", config.pk.composite, true),
|
|
1064
|
+
...checksOf(schemaFields, "its collection sort key", config.collection.sk?.composite ?? [], true),
|
|
1065
|
+
...(config.list === undefined
|
|
1066
|
+
? []
|
|
1067
|
+
: [
|
|
1068
|
+
...checksOf(schemaFields, "its list partition key", config.list.pk.composite, true),
|
|
1069
|
+
...checksOf(schemaFields, "its list sort key", config.list.sk.composite, true),
|
|
1070
|
+
]),
|
|
1071
|
+
]);
|
|
1072
|
+
const walk = (node) => {
|
|
1073
|
+
if (node.cardinality === "many" && node.skComposite !== undefined) {
|
|
1074
|
+
add(node, edgeChecksOf(node, node.skComposite));
|
|
1075
|
+
}
|
|
1076
|
+
for (const child of node.children)
|
|
1077
|
+
walk(child);
|
|
1078
|
+
};
|
|
1079
|
+
walk(rootNode);
|
|
1080
|
+
return byNode;
|
|
1081
|
+
})();
|
|
1082
|
+
/**
|
|
1083
|
+
* Refuses a write storing, for a key composite whose numeric kinds can't be read at load, a value
|
|
1084
|
+
* that reads back otherwise: a stored row would compose other key text (`EDD-9128`). `groups` is
|
|
1085
|
+
* the whole decomposition of the value stored, rows a diff leaves alone included: a read of the
|
|
1086
|
+
* aggregate takes them all. A row is judged by the checks of each node a read hands it to
|
|
1087
|
+
* (`assemblyWalk`), its composites read off its stored attributes, a path into a value followed.
|
|
1088
|
+
*/
|
|
1089
|
+
const refuseOtherKindKeys = (groups, operation) => {
|
|
1090
|
+
if (otherKindKeys.size === 0)
|
|
1091
|
+
return Effect.void;
|
|
1092
|
+
const reached = assemblyWalk(rootNode, groups.flatMap((group) => group.items),
|
|
1093
|
+
// An attribute as a read has it: a discriminator is matched against what's read back.
|
|
1094
|
+
(node, item) => takesRow(node, item.entityType, (attr) => {
|
|
1095
|
+
try {
|
|
1096
|
+
return asRead(item.attributes[attr]);
|
|
1097
|
+
}
|
|
1098
|
+
catch {
|
|
1099
|
+
return undefined;
|
|
1100
|
+
}
|
|
1101
|
+
}));
|
|
1102
|
+
for (const [node, taken] of reached) {
|
|
1103
|
+
const checks = otherKindKeys.get(node);
|
|
1104
|
+
if (checks === undefined)
|
|
1105
|
+
continue;
|
|
1106
|
+
for (const item of taken) {
|
|
1107
|
+
for (const { path, into, judge } of checks) {
|
|
1108
|
+
const refused = judge(item);
|
|
1109
|
+
if (refused === undefined)
|
|
1110
|
+
continue;
|
|
1111
|
+
return Effect.fail(new ValidationError({
|
|
1112
|
+
entityType: aggregateName,
|
|
1113
|
+
operation,
|
|
1114
|
+
cause: readBackRefusal(`Field "${path}" of "${item.member}" is composed into ${into}`, refused.held, refused.readsAs),
|
|
1115
|
+
}));
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
return Effect.void;
|
|
1120
|
+
};
|
|
682
1121
|
/** Shared: compose PK and query all items, a rejected read a `ValidationError`. */
|
|
683
1122
|
const fetchPartition = (key, operation, rekeyRead) => readPartition(key, (diagnosis, original) => new ValidationError({
|
|
684
1123
|
entityType: aggregateName,
|
|
685
1124
|
operation: `${operation}.consistentRead`,
|
|
686
1125
|
cause: assemblyReadCause(operation, diagnosis, original),
|
|
687
1126
|
}), rekeyRead);
|
|
688
|
-
const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite);
|
|
1127
|
+
const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps);
|
|
689
1128
|
/** A stored row's position: its partition and sort key. */
|
|
690
1129
|
const positionOf = (pk, sk) => `${pk}\u0000${sk}`;
|
|
691
1130
|
/**
|
|
@@ -708,9 +1147,216 @@ const makeAggregate = (schema, config) => {
|
|
|
708
1147
|
* or the current one, where 1.37.0 and 1.38.0 wrote it (its partition key unescaped, its sort key escaped).
|
|
709
1148
|
* Under a partition whose text didn't change, the current sort key is where the row belongs.
|
|
710
1149
|
*/
|
|
711
|
-
const oldPosition = (pk, pkNow, skOther, sk, storedAt
|
|
712
|
-
|
|
713
|
-
|
|
1150
|
+
const oldPosition = (pk, pkNow, skOther, sk, storedAt, otherKind) => {
|
|
1151
|
+
if (storedAt.has(positionOf(pk, skOther)))
|
|
1152
|
+
return { pk, sk: skOther };
|
|
1153
|
+
if (storedAt.has(positionOf(pk, sk)))
|
|
1154
|
+
return { pk, sk: pk === pkNow ? skOther : sk };
|
|
1155
|
+
// A sort key holding a numeric composite's other kind's text. Looked for only for a row at
|
|
1156
|
+
// neither key: one at its current key under the other kind's text too would have been read
|
|
1157
|
+
// back as a second element composing that key, which the decomposition refuses.
|
|
1158
|
+
return { pk, sk: otherKind(pk) ?? skOther };
|
|
1159
|
+
};
|
|
1160
|
+
// ---------------------------------------------------------------------------
|
|
1161
|
+
// Which rows of its partition are the aggregate's (DESIGN.md §7 "Which rows in its partition
|
|
1162
|
+
// are an aggregate's")
|
|
1163
|
+
// ---------------------------------------------------------------------------
|
|
1164
|
+
/** Every entity type a node of the aggregate's rows carries. */
|
|
1165
|
+
const nodeTypes = (() => {
|
|
1166
|
+
const types = new Set();
|
|
1167
|
+
const walk = (node) => {
|
|
1168
|
+
types.add(node.entityType);
|
|
1169
|
+
for (const child of node.children)
|
|
1170
|
+
walk(child);
|
|
1171
|
+
};
|
|
1172
|
+
walk(rootNode);
|
|
1173
|
+
return [...types];
|
|
1174
|
+
})();
|
|
1175
|
+
/** The fixed text every partition key the aggregate composes begins with. */
|
|
1176
|
+
const partitionHead = composeCollectionKey(config.schema, config.collection.name, []);
|
|
1177
|
+
/**
|
|
1178
|
+
* `ownsRows`: every row of the aggregate's types in its partition is its own, so `update` deletes
|
|
1179
|
+
* the rows of them it reads beyond the ones its value keys, and `rekey` reports them.
|
|
1180
|
+
*/
|
|
1181
|
+
const ownsRows = config.ownsRows === true;
|
|
1182
|
+
const ownedTypes = new Set(nodeTypes);
|
|
1183
|
+
/**
|
|
1184
|
+
* Each node a row can be handed to, as `assembleNode` hands rows: its entity type and its static
|
|
1185
|
+
* discriminator (an enclosing sub-aggregate's merged in at resolve time). With the transaction
|
|
1186
|
+
* group its rows are written in and the discriminator values its sort key holds.
|
|
1187
|
+
*/
|
|
1188
|
+
const nodeSlots = (() => {
|
|
1189
|
+
const slots = [{ node: rootNode, group: "root", keyDiscriminators: { current: [], other: () => [] } }];
|
|
1190
|
+
const visit = (node, parentGroup, parent) => {
|
|
1191
|
+
if (node.cardinality === "one" && node.children.length > 0) {
|
|
1192
|
+
const ownName = node.fieldName ?? node.entityType;
|
|
1193
|
+
const group = parentGroup === "root" ? ownName : `${parentGroup}.${ownName}`;
|
|
1194
|
+
const own = ownDiscriminatorValues(node, config.schema);
|
|
1195
|
+
const values = {
|
|
1196
|
+
current: [...parent.current, ...own.current],
|
|
1197
|
+
other: () => [...parent.other(), ...own.other()],
|
|
1198
|
+
};
|
|
1199
|
+
slots.push({ node, group, keyDiscriminators: values });
|
|
1200
|
+
for (const child of node.children)
|
|
1201
|
+
visit(child, group, values);
|
|
1202
|
+
return;
|
|
1203
|
+
}
|
|
1204
|
+
if (node.cardinality === "one") {
|
|
1205
|
+
const own = ownDiscriminatorValues(node, config.schema);
|
|
1206
|
+
slots.push({
|
|
1207
|
+
node,
|
|
1208
|
+
group: parentGroup,
|
|
1209
|
+
keyDiscriminators: {
|
|
1210
|
+
current: [...parent.current, ...own.current],
|
|
1211
|
+
other: () => [...parent.other(), ...own.other()],
|
|
1212
|
+
},
|
|
1213
|
+
});
|
|
1214
|
+
return;
|
|
1215
|
+
}
|
|
1216
|
+
slots.push({ node, group: parentGroup, keyDiscriminators: parent });
|
|
1217
|
+
};
|
|
1218
|
+
for (const child of rootNode.children)
|
|
1219
|
+
visit(child, "root", { current: [], other: () => [] });
|
|
1220
|
+
return slots;
|
|
1221
|
+
})();
|
|
1222
|
+
/** The nodes `item` is handed to by its entity type and static discriminator. */
|
|
1223
|
+
const slotsOf = (item) => nodeSlots.filter(({ node }) => item.__edd_e__ === node.entityType &&
|
|
1224
|
+
Object.entries(node.discriminator ?? {}).every(([attr, value]) => typeof value === "function" || (Object.hasOwn(item, attr) && item[attr] === value)));
|
|
1225
|
+
/**
|
|
1226
|
+
* `update`'s cleanup with `ownsRows` (DESIGN.md §7 "Which rows in its partition are an
|
|
1227
|
+
* aggregate's"): the rows read of each changed node, keyed where the new value writes nothing and
|
|
1228
|
+
* the update's groups delete nothing (`written`, `deleted`). A node changed when the update writes
|
|
1229
|
+
* its group (`writtenGroups`) and its items of the old value and of the new one differ by the
|
|
1230
|
+
* comparison that decides that ({@link sameItems}: types and attributes in order, not keys). A row
|
|
1231
|
+
* is a node's as assembly hands it ({@link slotsOf}); one handed to two nodes is left. Each row
|
|
1232
|
+
* once.
|
|
1233
|
+
*/
|
|
1234
|
+
const ownedRowsLeft = (allItems, pkValue, oldGroups, newGroups, writtenGroups, written, deleted) => {
|
|
1235
|
+
const inWrittenGroup = new Set();
|
|
1236
|
+
const byNode = (groups) => {
|
|
1237
|
+
const items = new Map();
|
|
1238
|
+
for (const group of groups) {
|
|
1239
|
+
for (const item of group.items) {
|
|
1240
|
+
if (writtenGroups.has(group.name))
|
|
1241
|
+
inWrittenGroup.add(item.node);
|
|
1242
|
+
const list = items.get(item.node) ?? [];
|
|
1243
|
+
list.push(item);
|
|
1244
|
+
items.set(item.node, list);
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
return items;
|
|
1248
|
+
};
|
|
1249
|
+
const before = byNode(oldGroups);
|
|
1250
|
+
const after = byNode(newGroups);
|
|
1251
|
+
const changed = new Set(nodeSlots
|
|
1252
|
+
.map(({ node }) => node)
|
|
1253
|
+
.filter((node) => inWrittenGroup.has(node) && !sameItems(before.get(node) ?? [], after.get(node) ?? [])));
|
|
1254
|
+
if (changed.size === 0)
|
|
1255
|
+
return [];
|
|
1256
|
+
const taken = new Set(deleted);
|
|
1257
|
+
const left = [];
|
|
1258
|
+
for (const item of allItems) {
|
|
1259
|
+
const sk = String(item.sk);
|
|
1260
|
+
if (item[config.pk.field] !== pkValue || written.has(sk) || taken.has(sk))
|
|
1261
|
+
continue;
|
|
1262
|
+
const slots = slotsOf(item);
|
|
1263
|
+
if (slots.length !== 1 || !changed.has(slots[0].node))
|
|
1264
|
+
continue;
|
|
1265
|
+
taken.add(sk);
|
|
1266
|
+
left.push({ pk: pkValue, sk, entityType: String(item.__edd_e__) });
|
|
1267
|
+
}
|
|
1268
|
+
return left;
|
|
1269
|
+
};
|
|
1270
|
+
/**
|
|
1271
|
+
* The attributes the aggregate writes on its rows, for another aggregate declaring `ownsRows` to
|
|
1272
|
+
* check at bind (DESIGN.md §7 "Which rows in its partition are an aggregate's"), as each row holds
|
|
1273
|
+
* them after the last write of each: its partition key, `sk` and the collection index's sort key
|
|
1274
|
+
* on every row, its list keys on its root row, its timestamps, written last, and its rows' own
|
|
1275
|
+
* attributes (their fields, discriminators and context, or what a custom `decompose` returns):
|
|
1276
|
+
* any name holding any text, but the ones the library writes after them.
|
|
1277
|
+
*/
|
|
1278
|
+
const attributeWriters = (() => {
|
|
1279
|
+
const table = config.table.Tag;
|
|
1280
|
+
const labelled = (type) => ({
|
|
1281
|
+
type,
|
|
1282
|
+
label: composeKey(config.schema, type, []),
|
|
1283
|
+
});
|
|
1284
|
+
const all = nodeTypes.map(labelled);
|
|
1285
|
+
const root = labelled(config.root.entityType);
|
|
1286
|
+
const mirror = config.collection.index !== undefined && config.collection.sk !== undefined
|
|
1287
|
+
? config.collection.sk.field
|
|
1288
|
+
: undefined;
|
|
1289
|
+
const writers = [
|
|
1290
|
+
{
|
|
1291
|
+
field: config.pk.field,
|
|
1292
|
+
head: partitionHead,
|
|
1293
|
+
exact: config.pk.composite.length === 0,
|
|
1294
|
+
types: all,
|
|
1295
|
+
table,
|
|
1296
|
+
channel: "its partition key",
|
|
1297
|
+
},
|
|
1298
|
+
...all.map((type) => ({
|
|
1299
|
+
field: "sk",
|
|
1300
|
+
head: type.label,
|
|
1301
|
+
types: [type],
|
|
1302
|
+
table,
|
|
1303
|
+
channel: "its sort key",
|
|
1304
|
+
})),
|
|
1305
|
+
];
|
|
1306
|
+
if (mirror !== undefined) {
|
|
1307
|
+
writers.push({
|
|
1308
|
+
field: mirror,
|
|
1309
|
+
head: partitionHead,
|
|
1310
|
+
types: [root],
|
|
1311
|
+
table,
|
|
1312
|
+
channel: "its collection index's sort key",
|
|
1313
|
+
});
|
|
1314
|
+
for (const type of all) {
|
|
1315
|
+
writers.push({
|
|
1316
|
+
field: mirror,
|
|
1317
|
+
head: type.label,
|
|
1318
|
+
types: [type],
|
|
1319
|
+
table,
|
|
1320
|
+
channel: "its collection index's sort key",
|
|
1321
|
+
});
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
if (config.list !== undefined) {
|
|
1325
|
+
const head = composeCollectionKey(config.schema, config.list.name, []);
|
|
1326
|
+
for (const field of [config.list.pk.field, config.list.sk.field]) {
|
|
1327
|
+
writers.push({ field, head, types: [root], table, channel: "its list index's keys" });
|
|
1328
|
+
}
|
|
1329
|
+
}
|
|
1330
|
+
// Its timestamps, written after everything else: one named as a key replaces it.
|
|
1331
|
+
for (const name of systemAttrs) {
|
|
1332
|
+
writers.push({ field: name, head: undefined, types: all, table, channel: `its "${name}"` });
|
|
1333
|
+
}
|
|
1334
|
+
// Its rows' own attributes. Whatever a schema declares, these are any name holding any text, but
|
|
1335
|
+
// the ones the library writes after them.
|
|
1336
|
+
const library = [config.pk.field, "sk", "__edd_e__", ...(mirror === undefined ? [] : [mirror])];
|
|
1337
|
+
writers.push({
|
|
1338
|
+
field: undefined,
|
|
1339
|
+
except: library,
|
|
1340
|
+
head: undefined,
|
|
1341
|
+
types: all,
|
|
1342
|
+
table,
|
|
1343
|
+
channel: "its rows' own attributes",
|
|
1344
|
+
});
|
|
1345
|
+
return withTypeOverwrites(writers);
|
|
1346
|
+
})();
|
|
1347
|
+
/** What `DynamoClient.make` checks an aggregate declaring `ownsRows` against. */
|
|
1348
|
+
const ownership = {
|
|
1349
|
+
pkField: config.pk.field,
|
|
1350
|
+
pkComposite: config.pk.composite,
|
|
1351
|
+
partitionHead,
|
|
1352
|
+
schema: config.schema,
|
|
1353
|
+
table: config.table.Tag,
|
|
1354
|
+
types: nodeTypes.map((type) => ({ type, label: composeKey(config.schema, type, []) })),
|
|
1355
|
+
declared: [
|
|
1356
|
+
...Object.entries((config.table.entities ?? {})),
|
|
1357
|
+
...Object.entries((config.table.aggregates ?? {})),
|
|
1358
|
+
].map(([name, member]) => ({ name, member })),
|
|
1359
|
+
};
|
|
714
1360
|
/**
|
|
715
1361
|
* `rekey`'s view of where the aggregate's rows are stored (#183, DESIGN.md §7 "`rekey`"): for
|
|
716
1362
|
* each decomposed item, its current key and its old one — the partition the row was found in
|
|
@@ -722,14 +1368,33 @@ const makeAggregate = (schema, config) => {
|
|
|
722
1368
|
for (const item of allItems) {
|
|
723
1369
|
storedAt.set(positionOf(String(item[config.pk.field]), String(item.sk)), item);
|
|
724
1370
|
}
|
|
1371
|
+
/** The sort keys stored in a partition, other than `sk` ({@link oldPosition}). */
|
|
1372
|
+
const partitions = new Map();
|
|
1373
|
+
const sortKeysIn = (pk, sk) => {
|
|
1374
|
+
let held = partitions.get(pk);
|
|
1375
|
+
if (held === undefined) {
|
|
1376
|
+
held = kindTargets(allItems
|
|
1377
|
+
.filter((item) => String(item[config.pk.field]) === pk)
|
|
1378
|
+
.map((item) => String(item.sk)));
|
|
1379
|
+
partitions.set(pk, held);
|
|
1380
|
+
}
|
|
1381
|
+
const inPartition = held;
|
|
1382
|
+
return {
|
|
1383
|
+
has: (text) => text !== sk && inPartition.has(text),
|
|
1384
|
+
hasPrefix: inPartition.hasPrefix,
|
|
1385
|
+
};
|
|
1386
|
+
};
|
|
725
1387
|
const rows = groups.flatMap((group, g) => group.items.map((item, i) => {
|
|
726
1388
|
const built = composed[g].items[i];
|
|
727
1389
|
const sk = built.sk?.S ?? "";
|
|
728
1390
|
return {
|
|
729
1391
|
group: group.name,
|
|
1392
|
+
item,
|
|
730
1393
|
built,
|
|
1394
|
+
/** An element of a `many` edge with a custom `decompose`: its row moves as stored. */
|
|
1395
|
+
custom: item.node.decompose !== undefined,
|
|
731
1396
|
current: { pk: pkValue, sk },
|
|
732
|
-
old: oldPosition(from ?? pkValue, pkValue, otherSortKey(config.schema, item, sk), sk, storedAt),
|
|
1397
|
+
old: oldPosition(from ?? pkValue, pkValue, otherSortKey(config.schema, item, sk), sk, storedAt, (pk) => item.otherKindSortKey?.(sortKeysIn(pk, sk))),
|
|
733
1398
|
};
|
|
734
1399
|
}));
|
|
735
1400
|
const placements = placeRows(rows.map((row) => ({
|
|
@@ -753,7 +1418,8 @@ const makeAggregate = (schema, config) => {
|
|
|
753
1418
|
});
|
|
754
1419
|
}
|
|
755
1420
|
// 1. Assemble current state
|
|
756
|
-
const current = yield* assembleAggregate(
|
|
1421
|
+
const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
|
|
1422
|
+
const now = yield* DateTime.now;
|
|
757
1423
|
// 2. Apply mutation — provide optics context for composable updates
|
|
758
1424
|
const state = toPlainState(current);
|
|
759
1425
|
const updated = mutationFn({
|
|
@@ -762,12 +1428,15 @@ const makeAggregate = (schema, config) => {
|
|
|
762
1428
|
optic: opticRoot,
|
|
763
1429
|
current: current,
|
|
764
1430
|
});
|
|
765
|
-
// 3. Validate the mutated state
|
|
766
|
-
//
|
|
767
|
-
//
|
|
768
|
-
//
|
|
769
|
-
//
|
|
770
|
-
|
|
1431
|
+
// 3. Validate the mutated state — its tolerant transforms take the domain
|
|
1432
|
+
// values the mutation yields as what they are, for every field (root +
|
|
1433
|
+
// nested edges), so update no longer trips the "Expected string, got
|
|
1434
|
+
// DateTime" decode that a strict `*FromString` schema would raise (#72
|
|
1435
|
+
// update path), and a transformation with one type on both sides isn't
|
|
1436
|
+
// applied again to a value it already made.
|
|
1437
|
+
// A row the mutation added doesn't need the dates the library stamps.
|
|
1438
|
+
const written = fillStamps(rootNode, updated, now, "required");
|
|
1439
|
+
const decoded = yield* Schema.decodeUnknownEffect(mutatedStateSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
|
|
771
1440
|
entityType: aggregateName,
|
|
772
1441
|
operation: "aggregate.update",
|
|
773
1442
|
cause,
|
|
@@ -776,7 +1445,7 @@ const makeAggregate = (schema, config) => {
|
|
|
776
1445
|
const assembledNew = { ...decoded };
|
|
777
1446
|
// 4. Decompose both old and new
|
|
778
1447
|
const oldGroups = yield* decomposeAggregate(assembledOld, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
779
|
-
const newGroups = yield* decomposeAggregate(assembledNew, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
1448
|
+
const newGroups = yield* decomposeAggregate(assembledNew, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: true });
|
|
780
1449
|
// 5. Diff at the ITEM (primary-key) level, not just the group level.
|
|
781
1450
|
// A `many`-edge element — and a cleared `one` edge — lives in its PARENT's
|
|
782
1451
|
// transaction group, so removing it SHRINKS a group rather than dropping a
|
|
@@ -796,20 +1465,30 @@ const makeAggregate = (schema, config) => {
|
|
|
796
1465
|
}
|
|
797
1466
|
}
|
|
798
1467
|
// 6. Build the full new + old DynamoDB item sets (with composed keys). The
|
|
799
|
-
// collection SK
|
|
800
|
-
//
|
|
801
|
-
//
|
|
1468
|
+
// collection SK and list keys are mirror attributes, never the (pk, sk)
|
|
1469
|
+
// identity used to PUT or DELETE, and the old set is read only for its
|
|
1470
|
+
// (pk, sk) delete keys, so it composes neither and is never stamped.
|
|
802
1471
|
// Rewritten rows are stamped `updated`; their stored `created` is read
|
|
803
1472
|
// back off the fetched partition and re-emitted verbatim, since these are
|
|
804
|
-
// PUTs and would otherwise clobber it.
|
|
805
|
-
|
|
806
|
-
const now = yield* DateTime.now;
|
|
807
|
-
const oldDynamo = buildDynamoItems(oldGroups, config, pkValue, KeyComposer.extractKeyComposites(config.schema, {}, config.collection.sk?.composite ?? [], keyRecord(assembledOld)), keyRecord);
|
|
1473
|
+
// PUTs and would otherwise clobber it.
|
|
1474
|
+
const oldDynamo = buildDynamoItems(oldGroups, config, pkValue, undefined, keyRecord);
|
|
808
1475
|
const skOf = (item) => item.sk?.S ?? "";
|
|
809
1476
|
const existingCreated = new Map(readExistingCreated(allItems));
|
|
1477
|
+
// Each row's declared `updated` as the mutation found it: if it changed it, it's the caller's.
|
|
1478
|
+
const updatedBefore = new Map();
|
|
1479
|
+
if (stampFields?.updatedAt) {
|
|
1480
|
+
for (const group of oldGroups) {
|
|
1481
|
+
for (const item of group.items) {
|
|
1482
|
+
updatedBefore.set(composeKey(config.schema, item.entityType, [...item.skComposites]), item.attributes[stampFields.updatedAt]);
|
|
1483
|
+
}
|
|
1484
|
+
}
|
|
1485
|
+
}
|
|
810
1486
|
// Packed AFTER the group diff above compared the decomposed values, so
|
|
811
1487
|
// an unchanged packed value is never rewritten (#147).
|
|
812
|
-
const
|
|
1488
|
+
const newPacked = yield* packAggregateGroups(newGroups, packedByType, aggregateName, "update");
|
|
1489
|
+
const newDynamo = yield* composeOrFail("update", () => buildDynamoItems(newPacked, config, pkValue, assembledNew, keyRecord, stampFor(now, existingCreated, undefined, updatedBefore)));
|
|
1490
|
+
yield* refuseOtherKindKeys(newGroups, "aggregate.update");
|
|
1491
|
+
yield* refuseNotReadBack(newDynamo, key, "aggregate.update", storedAsGivenIn(newGroups));
|
|
813
1492
|
const newItemsByGroup = new Map(newDynamo.map((g) => [g.group, g.items]));
|
|
814
1493
|
const oldItemsByGroup = new Map(oldDynamo.map((g) => [g.group, g.items]));
|
|
815
1494
|
// Every sk that survives anywhere in the new decomposition — an old item is
|
|
@@ -842,13 +1521,91 @@ const makeAggregate = (schema, config) => {
|
|
|
842
1521
|
continue;
|
|
843
1522
|
groupWrites.push({ group: name, puts, deletes });
|
|
844
1523
|
}
|
|
1524
|
+
// With `ownsRows`, every row of its types in the partition is the aggregate's (DESIGN.md §7
|
|
1525
|
+
// "Which rows in its partition are an aggregate's"). After the update's groups, the rows read
|
|
1526
|
+
// of each node whose decomposition changed that the new value doesn't write are deleted too
|
|
1527
|
+
// (`ownedRowsLeft`): a node's rows are what its decomposition writes.
|
|
1528
|
+
const cleanup = ownsRows
|
|
1529
|
+
? ownedRowsLeft(allItems, pkValue, oldGroups, newGroups, new Set(groupWrites.map(({ group }) => group)), survivingSks, groupWrites.flatMap(({ deletes }) => deletes.map((item) => skOf(item))))
|
|
1530
|
+
: [];
|
|
845
1531
|
if (groupWrites.length > 0) {
|
|
846
1532
|
yield* writeTransactionGroups(client, tableConfig.name, groupWrites, aggregateName, groupKeys);
|
|
847
1533
|
}
|
|
848
|
-
|
|
1534
|
+
if (cleanup.length > 0) {
|
|
1535
|
+
yield* deleteOwnedRows(client, tableConfig.name, config.pk.field, cleanup);
|
|
1536
|
+
}
|
|
1537
|
+
if (!returnsStamps) {
|
|
1538
|
+
return decoded;
|
|
1539
|
+
}
|
|
1540
|
+
// A stamp the domain object holds: what's returned is what's stored, as `get` would read it,
|
|
1541
|
+
// and no read is needed to know that. The partition as read, with these writes applied.
|
|
1542
|
+
const stored = new Map(allItems.map((item) => [String(item.sk), item]));
|
|
1543
|
+
for (const { sk } of cleanup)
|
|
1544
|
+
stored.delete(sk);
|
|
1545
|
+
for (const { deletes, puts } of groupWrites) {
|
|
1546
|
+
for (const item of deletes)
|
|
1547
|
+
stored.delete(String(item.sk.S));
|
|
1548
|
+
const written = puts.map((item) => fromAttributeMap(item));
|
|
1549
|
+
yield* unpackAggregateItems(written, dispatchByType, aggregateName);
|
|
1550
|
+
for (const item of written)
|
|
1551
|
+
stored.set(String(item.sk), item);
|
|
1552
|
+
}
|
|
1553
|
+
return (yield* assembleAggregate(assembly, rootNode, [...stored.values()], contextFields, key, aggregateName, systemAttrs));
|
|
849
1554
|
});
|
|
850
1555
|
/** How many times `rekey` reads an aggregate again after a write changed it in between. */
|
|
851
1556
|
const REKEY_ATTEMPTS = 3;
|
|
1557
|
+
/**
|
|
1558
|
+
* Every attribute a row of each entity type can hold, the table key aside: its node's own fields
|
|
1559
|
+
* (an edge field is its own rows'), the context fields and discriminators a row beneath the root
|
|
1560
|
+
* carries, the index keys, the timestamps and `__edd_e__`. A row `rekey` moves is guarded on each
|
|
1561
|
+
* one it didn't have still being absent, so a write that adds one cancels the move.
|
|
1562
|
+
*/
|
|
1563
|
+
const writableAttributes = (() => {
|
|
1564
|
+
const shared = [
|
|
1565
|
+
"__edd_e__",
|
|
1566
|
+
...indexFields,
|
|
1567
|
+
...[timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null),
|
|
1568
|
+
];
|
|
1569
|
+
const byType = new Map();
|
|
1570
|
+
const walk = (node) => {
|
|
1571
|
+
const names = byType.get(node.entityType) ?? new Set(shared);
|
|
1572
|
+
const edges = new Set(node.children.map((child) => child.fieldName));
|
|
1573
|
+
for (const field of Object.keys(node.ownFields ?? {})) {
|
|
1574
|
+
if (!edges.has(field))
|
|
1575
|
+
names.add(field);
|
|
1576
|
+
}
|
|
1577
|
+
if (node.cardinality !== "root") {
|
|
1578
|
+
for (const field of contextFields)
|
|
1579
|
+
names.add(field);
|
|
1580
|
+
for (const [field, value] of Object.entries(node.discriminator ?? {})) {
|
|
1581
|
+
if (typeof value !== "function")
|
|
1582
|
+
names.add(field);
|
|
1583
|
+
}
|
|
1584
|
+
}
|
|
1585
|
+
byType.set(node.entityType, names);
|
|
1586
|
+
for (const child of node.children)
|
|
1587
|
+
walk(child);
|
|
1588
|
+
};
|
|
1589
|
+
walk(rootNode);
|
|
1590
|
+
return new Map([...byType].map(([entityType, names]) => [entityType, [...names].sort()]));
|
|
1591
|
+
})();
|
|
1592
|
+
/**
|
|
1593
|
+
* The entity types the library stamps an `updatedAt` on, every row of every node holding them. A
|
|
1594
|
+
* node declaring a field of that name other than a date holds the caller's value there
|
|
1595
|
+
* (`rowStampsOf`), which a write of the library leaves as it was, so it proves nothing of the row.
|
|
1596
|
+
*/
|
|
1597
|
+
const stampsUpdated = (() => {
|
|
1598
|
+
const stamped = new Set();
|
|
1599
|
+
const unstamped = new Set();
|
|
1600
|
+
const walk = (node) => {
|
|
1601
|
+
const updated = node.rowStamps?.updatedAt ?? null;
|
|
1602
|
+
(updated === null ? unstamped : stamped).add(node.entityType);
|
|
1603
|
+
for (const child of node.children)
|
|
1604
|
+
walk(child);
|
|
1605
|
+
};
|
|
1606
|
+
walk(rootNode);
|
|
1607
|
+
return new Set([...stamped].filter((entityType) => !unstamped.has(entityType)));
|
|
1608
|
+
})();
|
|
852
1609
|
/**
|
|
853
1610
|
* `rekey`'s move of the aggregate at `key` (#183, DESIGN.md §7 "`rekey`"): read from the
|
|
854
1611
|
* partition its root was found in and its current one, and placed ({@link locateRows}). Each row
|
|
@@ -856,11 +1613,16 @@ const makeAggregate = (schema, config) => {
|
|
|
856
1613
|
* its `created` and `updated`, beside a Delete of the old row — and a row at its current key
|
|
857
1614
|
* whose list or collection index key holds other text has those keys rewritten. Nothing else is
|
|
858
1615
|
* written, and every write is conditional: the Put only where nothing is, the Delete and the
|
|
859
|
-
* rewrite only while the row is as read
|
|
860
|
-
*
|
|
861
|
-
*
|
|
862
|
-
*
|
|
863
|
-
*
|
|
1616
|
+
* rewrite only while the row is as read, whole, with each attribute its entity type can hold and
|
|
1617
|
+
* it didn't still absent (`wholeRowGuard`; a row too wide for that, on its `updatedAt` when the
|
|
1618
|
+
* library stamps one on it, `preferredGuard`, or else as `unprovable` decides: under `"report"` an
|
|
1619
|
+
* aggregate nothing of which has moved is left as it is, every row, and each such row is reported
|
|
1620
|
+
* `unguarded`, dry run or not; one already part-moved is finished under the strongest guard that
|
|
1621
|
+
* fits, as 1.39.0 finished it). Rows whose keys chain move in order, the one whose current key is
|
|
1622
|
+
* free first, so no write lands on a row still to move, and the root moves last, so a move cut
|
|
1623
|
+
* short is found by the next run. A write that loses to a concurrent one reads the aggregate
|
|
1624
|
+
* again; a row stored under both keys leaves the aggregate as it is, reported. A dry run writes
|
|
1625
|
+
* nothing.
|
|
864
1626
|
*/
|
|
865
1627
|
const rekeyCore = (key, dryRun,
|
|
866
1628
|
/** The old partition the aggregate's root was found in, when it isn't the current one. */
|
|
@@ -869,7 +1631,9 @@ const makeAggregate = (schema, config) => {
|
|
|
869
1631
|
* Leave the current partition unread: a dry run's, while another aggregate still to move
|
|
870
1632
|
* holds it, whose rows this one's move would find gone by then.
|
|
871
1633
|
*/
|
|
872
|
-
fromOnly
|
|
1634
|
+
fromOnly,
|
|
1635
|
+
/** What a row too wide to guard whole, with no `updatedAt` to stand in, gets. */
|
|
1636
|
+
unprovable) => Effect.gen(function* () {
|
|
873
1637
|
let movedRows = 0;
|
|
874
1638
|
let rewrittenRows = 0;
|
|
875
1639
|
for (let attempt = 0; attempt < REKEY_ATTEMPTS; attempt++) {
|
|
@@ -902,11 +1666,10 @@ const makeAggregate = (schema, config) => {
|
|
|
902
1666
|
if (atFrom.some((item) => !held.has(String(item.sk))))
|
|
903
1667
|
continue;
|
|
904
1668
|
}
|
|
905
|
-
const current = yield* assembleAggregate(
|
|
1669
|
+
const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
|
|
906
1670
|
const assembled = { ...current };
|
|
907
1671
|
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
908
|
-
const
|
|
909
|
-
const rows = locateRows(groups, buildDynamoItems(groups, config, pkValue, rootComposites, keyRecord), allItems, pkValue, from);
|
|
1672
|
+
const rows = locateRows(groups, buildDynamoItems(groups, config, pkValue, undefined, keyRecord), allItems, pkValue, from);
|
|
910
1673
|
const doubled = rows.filter((row) => row.placement === "both" || row.placement === "ambiguous");
|
|
911
1674
|
if (doubled.length > 0) {
|
|
912
1675
|
// In one partition, a move during the read shows a row at both keys too: it's
|
|
@@ -934,6 +1697,46 @@ const makeAggregate = (schema, config) => {
|
|
|
934
1697
|
})),
|
|
935
1698
|
};
|
|
936
1699
|
}
|
|
1700
|
+
// With `ownsRows`, every row of its types it reads is the aggregate's (DESIGN.md §7 "Which
|
|
1701
|
+
// rows in its partition are an aggregate's"), and it moves exactly what it moves without the
|
|
1702
|
+
// option: the rows its value decomposes to. Where any other row of its types would go can't
|
|
1703
|
+
// be told from what's stored, so it isn't moved. One whose own partition key changes would
|
|
1704
|
+
// be left behind in the old partition: the aggregate is left as it is, reported `failed`.
|
|
1705
|
+
// Otherwise the row stays where the aggregate reads it, counted `unrecognizedKey`. Without
|
|
1706
|
+
// `ownsRows`, nothing here applies.
|
|
1707
|
+
const placed = new Set();
|
|
1708
|
+
for (const row of rows) {
|
|
1709
|
+
if (row.placement === "old")
|
|
1710
|
+
placed.add(positionOf(row.old.pk, row.old.sk));
|
|
1711
|
+
if (row.placement === "current")
|
|
1712
|
+
placed.add(positionOf(row.current.pk, row.current.sk));
|
|
1713
|
+
}
|
|
1714
|
+
const unplaced = [];
|
|
1715
|
+
for (const item of ownsRows ? allItems : []) {
|
|
1716
|
+
if (!ownedTypes.has(String(item.__edd_e__)))
|
|
1717
|
+
continue;
|
|
1718
|
+
const at = { pk: String(item[config.pk.field]), sk: String(item.sk) };
|
|
1719
|
+
if (!placed.has(positionOf(at.pk, at.sk)))
|
|
1720
|
+
unplaced.push(at);
|
|
1721
|
+
}
|
|
1722
|
+
const stranded = unplaced.filter((at) => at.pk !== pkValue);
|
|
1723
|
+
if (stranded.length > 0) {
|
|
1724
|
+
return {
|
|
1725
|
+
conflicts: stranded.map((at) => ({
|
|
1726
|
+
member: aggregateName,
|
|
1727
|
+
kind: "aggregate",
|
|
1728
|
+
reason: "failed",
|
|
1729
|
+
key: { [config.pk.field]: at.pk, sk: at.sk },
|
|
1730
|
+
target: undefined,
|
|
1731
|
+
message: "The aggregate owns its rows (`ownsRows`), and this one isn't a row its value " +
|
|
1732
|
+
"decomposes to, so where it goes can't be told. Moving the rest would leave it in " +
|
|
1733
|
+
"the old partition: the aggregate is left as it is.",
|
|
1734
|
+
})),
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
const left = unplaced.length > 0 ? { skipped: { unrecognizedKey: unplaced.length } } : {};
|
|
1738
|
+
const tally = (rows) => ({ ...done(rows), ...left });
|
|
1739
|
+
const counted = rows.length;
|
|
937
1740
|
// Each row's write keeps the `created` and `updated` of the row it moves.
|
|
938
1741
|
const createdField = stampFields?.createdAt ?? null;
|
|
939
1742
|
const updatedField = stampFields?.updatedAt ?? null;
|
|
@@ -950,19 +1753,72 @@ const makeAggregate = (schema, config) => {
|
|
|
950
1753
|
keptUpdated.set(row.current.sk, was[updatedField]);
|
|
951
1754
|
}
|
|
952
1755
|
}
|
|
953
|
-
const
|
|
1756
|
+
const packedGroups = yield* packAggregateGroups(groups, packedByType, aggregateName, "update");
|
|
1757
|
+
const rekeyedAt = yield* DateTime.now;
|
|
1758
|
+
const built = (yield* composeOrFail("rekey", () => buildDynamoItems(packedGroups, config, pkValue, assembled, keyRecord, stampFor(rekeyedAt, keptCreated, keptUpdated)))).flatMap((group) => group.items);
|
|
954
1759
|
const storedAt = new Map(stored.map((item) => [
|
|
955
1760
|
positionOf(item[config.pk.field]?.S ?? "", item.sk?.S ?? ""),
|
|
956
1761
|
item,
|
|
957
1762
|
]));
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
1763
|
+
// An aggregate is left as it is, reported, only while nothing of it has moved. One already
|
|
1764
|
+
// part-moved, in this run or a run cut short, is finished under the strongest guard that
|
|
1765
|
+
// fits, as 1.39.0 finished it: left across two keys, a read under either misses rows.
|
|
1766
|
+
const partMoved = movedRows > 0 ||
|
|
1767
|
+
rows.some((row) => row.placement === "current" &&
|
|
1768
|
+
positionOf(row.old.pk, row.old.sk) !== positionOf(row.current.pk, row.current.sk));
|
|
1769
|
+
const unprovableHere = partMoved ? "strongest" : unprovable;
|
|
1770
|
+
// The row as read, whole, with every attribute its entity type can hold and it didn't
|
|
1771
|
+
// still absent: 1.39.0's guard with those appended. A row too wide for that is guarded on
|
|
1772
|
+
// its `updatedAt` when the library stamps one on it, held or absent (`preferredGuard`),
|
|
1773
|
+
// with what else fits; otherwise `unprovableHere` decides, and `undefined` is a row
|
|
1774
|
+
// reported.
|
|
1775
|
+
const guardOf = (at, r) => {
|
|
1776
|
+
const read = storedAt.get(positionOf(at.pk, at.sk)) ?? {};
|
|
1777
|
+
const entityType = built[r].__edd_e__?.S ?? "";
|
|
1778
|
+
const absent = writableAttributes.get(entityType) ?? [];
|
|
1779
|
+
const prefer = updatedField === null ? [] : [updatedField];
|
|
1780
|
+
const whole = wholeRowGuard(read, config.pk.field, prefer, [], absent);
|
|
1781
|
+
if (whole !== undefined)
|
|
1782
|
+
return whole;
|
|
1783
|
+
if (updatedField !== null && stampsUpdated.has(entityType)) {
|
|
1784
|
+
return preferredGuard(read, config.pk.field, prefer, absent);
|
|
1785
|
+
}
|
|
1786
|
+
switch (unprovableHere) {
|
|
1787
|
+
case "report":
|
|
1788
|
+
return undefined;
|
|
1789
|
+
case "strongest":
|
|
1790
|
+
return asReadGuard(read, config.pk.field, prefer);
|
|
1791
|
+
}
|
|
1792
|
+
};
|
|
961
1793
|
const keyOf = (at) => toAttributeMap({ [config.pk.field]: at.pk, sk: at.sk });
|
|
1794
|
+
// A custom `decompose`'s row is written as stored, its keys and its collection sort key
|
|
1795
|
+
// copy replaced: decomposing the value read back needn't give the attributes it holds (one
|
|
1796
|
+
// renaming a transformed field would store it decoded once more on every run).
|
|
1797
|
+
const mirror = config.collection.index !== undefined && config.collection.sk !== undefined
|
|
1798
|
+
? config.collection.sk.field
|
|
1799
|
+
: undefined;
|
|
1800
|
+
const itemOf = (r) => {
|
|
1801
|
+
const row = rows[r];
|
|
1802
|
+
if (!row.custom)
|
|
1803
|
+
return built[r];
|
|
1804
|
+
const at = row.placement === "old" ? row.old : row.current;
|
|
1805
|
+
return {
|
|
1806
|
+
...storedAt.get(positionOf(at.pk, at.sk)),
|
|
1807
|
+
[config.pk.field]: { S: row.current.pk },
|
|
1808
|
+
sk: { S: row.current.sk },
|
|
1809
|
+
...(mirror !== undefined && { [mirror]: { S: row.current.sk } }),
|
|
1810
|
+
};
|
|
1811
|
+
};
|
|
962
1812
|
const moves = [];
|
|
963
1813
|
const rewrites = [];
|
|
1814
|
+
const unguarded = [];
|
|
964
1815
|
for (const [r, row] of rows.entries()) {
|
|
965
1816
|
if (row.placement === "old") {
|
|
1817
|
+
const guard = guardOf(row.old, r);
|
|
1818
|
+
if (guard === undefined) {
|
|
1819
|
+
unguarded.push({ from: row.old, to: row.current });
|
|
1820
|
+
continue;
|
|
1821
|
+
}
|
|
966
1822
|
moves.push({
|
|
967
1823
|
from: row.old,
|
|
968
1824
|
to: row.current,
|
|
@@ -970,13 +1826,17 @@ const makeAggregate = (schema, config) => {
|
|
|
970
1826
|
{
|
|
971
1827
|
Put: {
|
|
972
1828
|
TableName: tableConfig.name,
|
|
973
|
-
Item:
|
|
1829
|
+
Item: itemOf(r),
|
|
974
1830
|
ConditionExpression: "attribute_not_exists(#pk)",
|
|
975
1831
|
ExpressionAttributeNames: { "#pk": config.pk.field },
|
|
976
1832
|
},
|
|
977
1833
|
},
|
|
978
1834
|
{
|
|
979
|
-
Delete: {
|
|
1835
|
+
Delete: {
|
|
1836
|
+
TableName: tableConfig.name,
|
|
1837
|
+
Key: keyOf(row.old),
|
|
1838
|
+
...guard,
|
|
1839
|
+
},
|
|
980
1840
|
},
|
|
981
1841
|
],
|
|
982
1842
|
});
|
|
@@ -984,15 +1844,20 @@ const makeAggregate = (schema, config) => {
|
|
|
984
1844
|
}
|
|
985
1845
|
if (row.placement !== "current" || row.atCurrent === undefined)
|
|
986
1846
|
continue;
|
|
987
|
-
const
|
|
1847
|
+
const item = itemOf(r);
|
|
1848
|
+
const stale = staleIndexFields(item, row.atCurrent);
|
|
988
1849
|
if (stale.length === 0)
|
|
989
1850
|
continue;
|
|
990
|
-
const guard = guardOf(row.current);
|
|
1851
|
+
const guard = guardOf(row.current, r);
|
|
1852
|
+
if (guard === undefined) {
|
|
1853
|
+
unguarded.push({ from: row.current, to: row.current });
|
|
1854
|
+
continue;
|
|
1855
|
+
}
|
|
991
1856
|
const names = { ...guard.ExpressionAttributeNames };
|
|
992
1857
|
const values = { ...guard.ExpressionAttributeValues };
|
|
993
1858
|
const sets = stale.map((field, i) => {
|
|
994
1859
|
names[`#x${i}`] = field;
|
|
995
|
-
values[`:x${i}`] =
|
|
1860
|
+
values[`:x${i}`] = item[field];
|
|
996
1861
|
return `#x${i} = :x${i}`;
|
|
997
1862
|
});
|
|
998
1863
|
rewrites.push([
|
|
@@ -1008,17 +1873,35 @@ const makeAggregate = (schema, config) => {
|
|
|
1008
1873
|
},
|
|
1009
1874
|
]);
|
|
1010
1875
|
}
|
|
1876
|
+
// Nothing of it has moved (`unprovableHere`): an unguarded row leaves the aggregate as is.
|
|
1877
|
+
if (unguarded.length > 0) {
|
|
1878
|
+
return {
|
|
1879
|
+
...(movedRows > 0 && { moved: { aggregate: movedRows } }),
|
|
1880
|
+
...(rewrittenRows > 0 && { indexKeysRewritten: rewrittenRows }),
|
|
1881
|
+
...left,
|
|
1882
|
+
conflicts: unguarded.map((row) => ({
|
|
1883
|
+
member: aggregateName,
|
|
1884
|
+
kind: "aggregate",
|
|
1885
|
+
reason: "unguarded",
|
|
1886
|
+
key: { [config.pk.field]: row.from.pk, sk: row.from.sk },
|
|
1887
|
+
target: { [config.pk.field]: row.to.pk, sk: row.to.sk },
|
|
1888
|
+
message: `${Rekey.UNGUARDED_MESSAGE} Its aggregate's other rows are left with it.`,
|
|
1889
|
+
})),
|
|
1890
|
+
};
|
|
1891
|
+
}
|
|
1011
1892
|
if (moves.length === 0 && rewrites.length === 0)
|
|
1012
|
-
return
|
|
1893
|
+
return tally(counted);
|
|
1013
1894
|
if (dryRun) {
|
|
1014
1895
|
movedRows += moves.length;
|
|
1015
1896
|
rewrittenRows += rewrites.length;
|
|
1016
|
-
return
|
|
1897
|
+
return tally(counted);
|
|
1017
1898
|
}
|
|
1018
1899
|
// In waves: a row moves once no row still to move is stored at its
|
|
1019
1900
|
// current key, and the root once nothing else is left: while it's under the old partition
|
|
1020
1901
|
// the next run finds the aggregate there. Each move's Put and Delete share a transaction;
|
|
1021
|
-
//
|
|
1902
|
+
// a transaction takes the units in order while it is within DynamoDB's limits on one
|
|
1903
|
+
// (`packRequests`: 100 actions, 4 MB of item size, 16 MB of body), and at least one.
|
|
1904
|
+
const shape = transactWriteShape(yield* Capacity.requestFields);
|
|
1022
1905
|
const units = rewrites.map((items) => ({ kind: "rewrite", items }));
|
|
1023
1906
|
let pending = moves;
|
|
1024
1907
|
let lost = false;
|
|
@@ -1032,13 +1915,8 @@ const makeAggregate = (schema, config) => {
|
|
|
1032
1915
|
break;
|
|
1033
1916
|
pending = pending.filter((move) => !wave.includes(move));
|
|
1034
1917
|
units.push(...wave.map((move) => ({ kind: "move", items: move.items })));
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
let size = 0;
|
|
1038
|
-
while (units.length > 0 && size + units[0].items.length <= TRANSACT_LIMIT) {
|
|
1039
|
-
size += units[0].items.length;
|
|
1040
|
-
chunk.push(units.shift());
|
|
1041
|
-
}
|
|
1918
|
+
const chunks = packRequests(units.splice(0), (unit) => transactWriteUnit(unit.items), shape);
|
|
1919
|
+
for (const chunk of chunks) {
|
|
1042
1920
|
const written = yield* client
|
|
1043
1921
|
.transactWriteItems({ TransactItems: chunk.flatMap((unit) => unit.items) })
|
|
1044
1922
|
.pipe(Effect.as(true), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
|
|
@@ -1060,9 +1938,9 @@ const makeAggregate = (schema, config) => {
|
|
|
1060
1938
|
if (lost)
|
|
1061
1939
|
continue;
|
|
1062
1940
|
if (pending.length === 0)
|
|
1063
|
-
return
|
|
1941
|
+
return tally(counted);
|
|
1064
1942
|
return {
|
|
1065
|
-
...
|
|
1943
|
+
...tally(counted - pending.length),
|
|
1066
1944
|
conflicts: pending.map((move) => ({
|
|
1067
1945
|
member: aggregateName,
|
|
1068
1946
|
kind: "aggregate",
|
|
@@ -1119,11 +1997,24 @@ const makeAggregate = (schema, config) => {
|
|
|
1119
1997
|
return undefined;
|
|
1120
1998
|
}
|
|
1121
1999
|
};
|
|
2000
|
+
/**
|
|
2001
|
+
* Is `pk` a partition key a root row's values have composed: under each setting's text, and with
|
|
2002
|
+
* a numeric composite as either kind (`CompositeCodec.kindReadingOf`), the other kind read from
|
|
2003
|
+
* the digits the row stored. The current text comes first, and a root under it composes nothing
|
|
2004
|
+
* more.
|
|
2005
|
+
*/
|
|
2006
|
+
const holdsPartition = (row, key, pk) => [
|
|
2007
|
+
config.schema,
|
|
2008
|
+
KeyText136.schema136(config.schema),
|
|
2009
|
+
KeyText136.schema137(config.schema),
|
|
2010
|
+
KeyText136.schemaEscaped(config.schema),
|
|
2011
|
+
].some((under) => kindReadingOf(keyRecord(key), config.pk.composite, (field) => row[field]?.N, ({ record }) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, record)), pk) !== undefined);
|
|
1122
2012
|
/**
|
|
1123
2013
|
* The root of another aggregate at `pk`, stored there under text its values no longer compose:
|
|
1124
2014
|
* it moves first, or this move's rows would land in its partition.
|
|
1125
2015
|
*/
|
|
1126
|
-
const staleRootAt = (tableName, pk) => Effect.map(rootItemAt(tableName, pk), ({ Item }) => Item === undefined ||
|
|
2016
|
+
const staleRootAt = (tableName, pk) => Effect.map(rootItemAt(tableName, pk), ({ Item }) => Item === undefined ||
|
|
2017
|
+
partitionUnder(config.schema, rootKeyAsRead(fromAttributeMap(Item))) === pk
|
|
1127
2018
|
? undefined
|
|
1128
2019
|
: Item);
|
|
1129
2020
|
/**
|
|
@@ -1153,6 +2044,10 @@ const makeAggregate = (schema, config) => {
|
|
|
1153
2044
|
* or be on its way to it (a run cut short moves the root last), in any order the scan met them,
|
|
1154
2045
|
* and a dry run decides the same. Its values don't say whose it is unless the aggregate's context
|
|
1155
2046
|
* holds them, so with no root at all there's no aggregate to move it with, and it's reported.
|
|
2047
|
+
*
|
|
2048
|
+
* A run that hasn't read the whole table can't say there's no root: a root at its old key, on a
|
|
2049
|
+
* page this run didn't read, names this partition only when the scan reaches it. So it reports
|
|
2050
|
+
* the row as unjudged, and a run over the whole table judges it.
|
|
1156
2051
|
*/
|
|
1157
2052
|
const rekeyFinish = (ctx) => Effect.gen(function* () {
|
|
1158
2053
|
const { rooted, rootless } = rekeyRunOf(ctx);
|
|
@@ -1169,7 +2064,9 @@ const makeAggregate = (schema, config) => {
|
|
|
1169
2064
|
if (Item !== undefined)
|
|
1170
2065
|
left++;
|
|
1171
2066
|
}
|
|
1172
|
-
|
|
2067
|
+
if (left === 0)
|
|
2068
|
+
return {};
|
|
2069
|
+
return { skipped: ctx.sawWholeTable() ? { unrecognizedKey: left } : { rootNotSeen: left } };
|
|
1173
2070
|
});
|
|
1174
2071
|
const rekeyRow = (row, ctx, depth) => Effect.gen(function* () {
|
|
1175
2072
|
const pk = row[config.pk.field]?.S;
|
|
@@ -1179,16 +2076,10 @@ const makeAggregate = (schema, config) => {
|
|
|
1179
2076
|
if (row.sk?.S !== rekeyRootSk || row.__edd_e__?.S !== config.root.entityType) {
|
|
1180
2077
|
return yield* rekeyRowBelowRoot(row, pk, ctx);
|
|
1181
2078
|
}
|
|
1182
|
-
const key = fromAttributeMap(row);
|
|
2079
|
+
const key = rootKeyAsRead(fromAttributeMap(row));
|
|
1183
2080
|
const current = partitionUnder(config.schema, key);
|
|
1184
2081
|
// Under none of the keys its values have had: nothing here can place it.
|
|
1185
|
-
if (current === undefined ||
|
|
1186
|
-
![
|
|
1187
|
-
current,
|
|
1188
|
-
partitionUnder(KeyText136.schema136(config.schema), key),
|
|
1189
|
-
partitionUnder(KeyText136.schema137(config.schema), key),
|
|
1190
|
-
partitionUnder(KeyText136.schemaEscaped(config.schema), key),
|
|
1191
|
-
].includes(pk)) {
|
|
2082
|
+
if (current === undefined || !holdsPartition(row, key, pk)) {
|
|
1192
2083
|
return { skipped: { unrecognizedKey: 1 } };
|
|
1193
2084
|
}
|
|
1194
2085
|
const { rooted } = rekeyRunOf(ctx);
|
|
@@ -1229,7 +2120,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1229
2120
|
fromOnly = ctx.dryRun;
|
|
1230
2121
|
}
|
|
1231
2122
|
}
|
|
1232
|
-
const moved = yield* rekeyCore(key, ctx.dryRun, from, fromOnly).pipe(Effect.catch((error) => {
|
|
2123
|
+
const moved = yield* rekeyCore(key, ctx.dryRun, from, fromOnly, Rekey.unprovableRow(ctx)).pipe(Effect.catch((error) => {
|
|
1233
2124
|
if (Rekey.isDynamoClientError(error))
|
|
1234
2125
|
return Effect.fail(error);
|
|
1235
2126
|
const assembly = error._tag === "AggregateAssemblyError" ? error.reason : undefined;
|
|
@@ -1239,6 +2130,13 @@ const makeAggregate = (schema, config) => {
|
|
|
1239
2130
|
// A root under both partition keys (its sort key is fixed, so one
|
|
1240
2131
|
// partition holds one): neither copy is judged.
|
|
1241
2132
|
const both = assembly === "Multiple root items found";
|
|
2133
|
+
// What went wrong, as the error says it: a tagged error's own message is empty.
|
|
2134
|
+
const detail = error._tag === "AggregateAssemblyError" ||
|
|
2135
|
+
error._tag === "AggregateDecompositionError"
|
|
2136
|
+
? error.reason
|
|
2137
|
+
: error._tag === "ValidationError"
|
|
2138
|
+
? String(error.cause ?? error.message)
|
|
2139
|
+
: error.message;
|
|
1242
2140
|
return Effect.succeed({
|
|
1243
2141
|
conflicts: [
|
|
1244
2142
|
{
|
|
@@ -1249,7 +2147,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1249
2147
|
target: { [config.pk.field]: current, sk: rekeyRootSk },
|
|
1250
2148
|
message: both
|
|
1251
2149
|
? "The aggregate's root is also stored under its current key."
|
|
1252
|
-
: `${error._tag}: ${
|
|
2150
|
+
: `${error._tag}: ${detail}`,
|
|
1253
2151
|
},
|
|
1254
2152
|
],
|
|
1255
2153
|
});
|
|
@@ -1268,6 +2166,9 @@ const makeAggregate = (schema, config) => {
|
|
|
1268
2166
|
_tag: "Aggregate",
|
|
1269
2167
|
_tableTag: config.table.Tag,
|
|
1270
2168
|
_packedByType: packedByType,
|
|
2169
|
+
_ownsRows: ownsRows,
|
|
2170
|
+
_attributeWriters: attributeWriters,
|
|
2171
|
+
_ownership: ownership,
|
|
1271
2172
|
schema,
|
|
1272
2173
|
pkField: config.pk.field,
|
|
1273
2174
|
collection: {
|
|
@@ -1294,38 +2195,40 @@ const makeAggregate = (schema, config) => {
|
|
|
1294
2195
|
key,
|
|
1295
2196
|
});
|
|
1296
2197
|
}
|
|
1297
|
-
const result = yield* assembleAggregate(
|
|
2198
|
+
const result = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
|
|
1298
2199
|
return result;
|
|
1299
2200
|
}),
|
|
1300
2201
|
create: (input) => Effect.gen(function* () {
|
|
1301
2202
|
const client = yield* Capacity.client;
|
|
1302
2203
|
const tableConfig = yield* config.table.Tag;
|
|
1303
2204
|
// 1. Hydrate refs from edges
|
|
1304
|
-
const hydrated = yield* hydrateAggregateRefs(
|
|
2205
|
+
const hydrated = yield* hydrateAggregateRefs(
|
|
2206
|
+
// What `create`'s type takes (`CreateArgument`) is judged here, at run time.
|
|
2207
|
+
input, config.edges, schemaFields, aggregateName);
|
|
1305
2208
|
// 2. Validate via schema decode (decodeSchema substitutes nested edge
|
|
1306
2209
|
// self-date/Redacted leaves — Option A — and is identical to `schema`
|
|
1307
|
-
// when no edge needs it).
|
|
1308
|
-
|
|
2210
|
+
// when no edge needs it). A date the library stamps is stamped now,
|
|
2211
|
+
// over what the input holds for it unless the root declares it
|
|
2212
|
+
// optional, so what's composed and returned is what's stored.
|
|
2213
|
+
const now = yield* DateTime.now;
|
|
2214
|
+
const written = fillStamps(rootNode, hydrated, now, "declared");
|
|
2215
|
+
const decoded = yield* Schema.decodeUnknownEffect(writeSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
|
|
1309
2216
|
entityType: aggregateName,
|
|
1310
2217
|
operation: "aggregate.create",
|
|
1311
2218
|
cause,
|
|
1312
2219
|
})));
|
|
1313
2220
|
const assembled = { ...decoded };
|
|
1314
2221
|
// 3. Compose PK
|
|
1315
|
-
const
|
|
1316
|
-
const pkValue = composeCollectionKey(config.schema, config.collection.name, composites);
|
|
2222
|
+
const pkValue = yield* composeOrFail("create", () => collectionPkOf(assembled));
|
|
1317
2223
|
// 4. Decompose into items grouped by sub-aggregate transaction boundaries
|
|
1318
|
-
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
1319
|
-
// 5.
|
|
1320
|
-
// form — `update` already did (see `newDynamo` / `oldDynamo` below), so
|
|
1321
|
-
// leaving `create` raw made the two write paths mirror the collection SK
|
|
1322
|
-
// differently for a transformed composite.
|
|
1323
|
-
const collectionSkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.collection.sk?.composite ?? [], keyRecord(assembled));
|
|
1324
|
-
// 6. Build DynamoDB items with composed keys (create only ever PUTs).
|
|
2224
|
+
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: false });
|
|
2225
|
+
// 5. Build DynamoDB items with composed keys (create only ever PUTs).
|
|
1325
2226
|
// Every row is new, so `created` has nothing to carry forward.
|
|
1326
|
-
const
|
|
1327
|
-
const dynamoGroups =
|
|
1328
|
-
|
|
2227
|
+
const packedGroups = yield* packAggregateGroups(groups, packedByType, aggregateName, "create");
|
|
2228
|
+
const dynamoGroups = yield* composeOrFail("create", () => buildDynamoItems(packedGroups, config, pkValue, assembled, keyRecord, stampFor(now, EMPTY_CREATED)));
|
|
2229
|
+
yield* refuseOtherKindKeys(groups, "aggregate.create");
|
|
2230
|
+
yield* refuseNotReadBack(dynamoGroups, assembled, "aggregate.create", storedAsGivenIn(groups));
|
|
2231
|
+
// 6. Write via sub-aggregate transactions. The root item goes first in
|
|
1329
2232
|
// the first transaction, guarded by `attribute_not_exists` (#134):
|
|
1330
2233
|
// an existing aggregate cancels it before any edge or sub-aggregate
|
|
1331
2234
|
// row is written. Rows below the root need no guard of their own —
|
|
@@ -1354,7 +2257,13 @@ const makeAggregate = (schema, config) => {
|
|
|
1354
2257
|
(diagnosis, original) => new DynamoValidationError({
|
|
1355
2258
|
operation: "Query",
|
|
1356
2259
|
cause: assemblyReadCause("delete", diagnosis, original),
|
|
1357
|
-
}))
|
|
2260
|
+
})).pipe(
|
|
2261
|
+
// Nor a key with no value: nothing to read, reported as a key that finds nothing.
|
|
2262
|
+
Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
|
|
2263
|
+
aggregate: aggregateName,
|
|
2264
|
+
reason: String(error.cause?.message ?? error.cause),
|
|
2265
|
+
key,
|
|
2266
|
+
}))));
|
|
1358
2267
|
if (allItems.length === 0) {
|
|
1359
2268
|
return yield* new AggregateAssemblyError({
|
|
1360
2269
|
aggregate: aggregateName,
|
|
@@ -1396,7 +2305,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1396
2305
|
// DOMAIN record, so it goes through the same key form the write side
|
|
1397
2306
|
// used — otherwise `list` composes a key `create` never wrote and
|
|
1398
2307
|
// silently returns nothing (#111).
|
|
1399
|
-
const listPkComposites =
|
|
2308
|
+
const listPkComposites = yield* composeOrFail("list", () => keyCompositesOrThrow(aggregateName, "its list partition key", config.schema, listConfig.pk.composite, keyRecord(filter ?? {})));
|
|
1400
2309
|
// Build SK prefix from contiguous filter values matching SK composites.
|
|
1401
2310
|
// `keyValueText`, NOT `String(v)` — the write side encodes
|
|
1402
2311
|
// numerics, so `String(5)` would look for `5` where `0000000000000005`
|
|
@@ -1456,15 +2365,25 @@ const makeAggregate = (schema, config) => {
|
|
|
1456
2365
|
nextKey = undefined;
|
|
1457
2366
|
}
|
|
1458
2367
|
else {
|
|
2368
|
+
// `!== undefined`, as above: an empty string is a cursor no list
|
|
2369
|
+
// returned, not a way of saying "from the start".
|
|
2370
|
+
const startKey = options?.cursor === undefined ? undefined : decodeKeyCursor(options.cursor);
|
|
2371
|
+
if (options?.cursor !== undefined && startKey === undefined) {
|
|
2372
|
+
return yield* new ValidationError({
|
|
2373
|
+
entityType: aggregateName,
|
|
2374
|
+
operation: "list",
|
|
2375
|
+
cause: `[EDD-9094] Aggregate "${aggregateName}": the cursor is not one a list returned. ` +
|
|
2376
|
+
"A cursor is opaque: pass back the text of a previous `list` result's `cursor`, " +
|
|
2377
|
+
"unchanged, to the same list. Nothing was sent.",
|
|
2378
|
+
});
|
|
2379
|
+
}
|
|
1459
2380
|
const result = yield* queryListPartition(client, tableConfig, listConfig, config.schema, {
|
|
1460
2381
|
pkValue: composeCollectionKey(config.schema, listConfig.name, listPkComposites),
|
|
1461
2382
|
skValues,
|
|
1462
2383
|
skComplete,
|
|
1463
2384
|
limit,
|
|
1464
2385
|
pageSize,
|
|
1465
|
-
startKey
|
|
1466
|
-
? JSON.parse(atob(options.cursor))
|
|
1467
|
-
: undefined,
|
|
2386
|
+
startKey,
|
|
1468
2387
|
filter: rootFilter,
|
|
1469
2388
|
accept: options?.filterBy,
|
|
1470
2389
|
reverse: options?.reverse === true,
|
|
@@ -1476,21 +2395,23 @@ const makeAggregate = (schema, config) => {
|
|
|
1476
2395
|
// Extract PK composite values from each root item and assemble
|
|
1477
2396
|
const aggregates = [];
|
|
1478
2397
|
for (const rootItem of rootItems) {
|
|
1479
|
-
const
|
|
2398
|
+
const stored = {};
|
|
1480
2399
|
for (const composite of config.pk.composite) {
|
|
1481
|
-
|
|
2400
|
+
stored[composite] = rootItem[composite];
|
|
1482
2401
|
}
|
|
2402
|
+
// The key the root's values compose as a read takes them, as `create` composed it.
|
|
2403
|
+
const key = rootKeyAsRead(stored);
|
|
1483
2404
|
const assembled = yield* Effect.gen(function* () {
|
|
1484
2405
|
const { allItems } = yield* fetchPartition(key, "list");
|
|
1485
2406
|
if (allItems.length === 0)
|
|
1486
2407
|
return undefined;
|
|
1487
|
-
const result = yield* assembleAggregate(
|
|
2408
|
+
const result = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
|
|
1488
2409
|
return result;
|
|
1489
2410
|
});
|
|
1490
2411
|
if (assembled !== undefined)
|
|
1491
2412
|
aggregates.push(assembled);
|
|
1492
2413
|
}
|
|
1493
|
-
const cursor = nextKey ? Option.some(
|
|
2414
|
+
const cursor = nextKey ? Option.some(encodeKeyCursor(nextKey)) : Option.none();
|
|
1494
2415
|
return { data: aggregates, cursor };
|
|
1495
2416
|
}),
|
|
1496
2417
|
}));
|
|
@@ -1555,6 +2476,14 @@ const deepEqual = (a, b) => {
|
|
|
1555
2476
|
}
|
|
1556
2477
|
if (Array.isArray(a) || Array.isArray(b))
|
|
1557
2478
|
return false;
|
|
2479
|
+
// A set has no own keys: compared below, any two would be equal, and a change to one
|
|
2480
|
+
// would never be written. Members are strings, numbers or binary values, by identity.
|
|
2481
|
+
if (a instanceof Set || b instanceof Set) {
|
|
2482
|
+
return (a instanceof Set &&
|
|
2483
|
+
b instanceof Set &&
|
|
2484
|
+
a.size === b.size &&
|
|
2485
|
+
[...a].every((member) => b.has(member)));
|
|
2486
|
+
}
|
|
1558
2487
|
const aObj = a;
|
|
1559
2488
|
const bObj = b;
|
|
1560
2489
|
const aKeys = Object.keys(aObj);
|
|
@@ -1563,11 +2492,13 @@ const deepEqual = (a, b) => {
|
|
|
1563
2492
|
return false;
|
|
1564
2493
|
return aKeys.every((k) => deepEqual(aObj[k], bObj[k]));
|
|
1565
2494
|
};
|
|
1566
|
-
const deepEqualGroups = (a, b) =>
|
|
1567
|
-
|
|
2495
|
+
const deepEqualGroups = (a, b) => sameItems(a.items, b.items);
|
|
2496
|
+
/** Whether two decompositions are one: the same items, in order, of the same types and attributes. */
|
|
2497
|
+
const sameItems = (a, b) => {
|
|
2498
|
+
if (a.length !== b.length)
|
|
1568
2499
|
return false;
|
|
1569
|
-
return a.
|
|
1570
|
-
const other = b
|
|
2500
|
+
return a.every((item, i) => {
|
|
2501
|
+
const other = b[i];
|
|
1571
2502
|
if (item.entityType !== other.entityType)
|
|
1572
2503
|
return false;
|
|
1573
2504
|
return deepEqual(item.attributes, other.attributes);
|
|
@@ -1648,6 +2579,7 @@ const resolveNode = (args) => {
|
|
|
1648
2579
|
edges: {},
|
|
1649
2580
|
discriminator: mergedDisc,
|
|
1650
2581
|
ownDiscriminator: edge.discriminator,
|
|
2582
|
+
ownFields: valueFields,
|
|
1651
2583
|
attrEncoders: buildAttrEncoders(valueFields, resolveRef),
|
|
1652
2584
|
...edgeStorage(edgePackedFields(field, edge.entity, valueFields, edge.discriminator, undefined), edge.entity, valueFields),
|
|
1653
2585
|
}));
|
|
@@ -1662,6 +2594,11 @@ const resolveNode = (args) => {
|
|
|
1662
2594
|
// entity's model, which is what such an element IS.
|
|
1663
2595
|
const entityFields = fieldsOf(edge.entity?.model);
|
|
1664
2596
|
const elementFields = manyElementFields(parentFields, field) ?? entityFields;
|
|
2597
|
+
const parentField = parentFields?.[field];
|
|
2598
|
+
const arrayElement = parentField === undefined ? undefined : extractArrayElement(parentField);
|
|
2599
|
+
const keyedValue = parentField === undefined || arrayElement !== undefined
|
|
2600
|
+
? undefined
|
|
2601
|
+
: extractKeyedValue(parentField);
|
|
1665
2602
|
children.push(resolveNode({
|
|
1666
2603
|
fieldName: field,
|
|
1667
2604
|
entityType: edge.entityType,
|
|
@@ -1670,7 +2607,11 @@ const resolveNode = (args) => {
|
|
|
1670
2607
|
discriminator,
|
|
1671
2608
|
assemble: edge.assemble,
|
|
1672
2609
|
decompose: edge.decompose,
|
|
1673
|
-
|
|
2610
|
+
decomposeInput: edge.decompose === undefined
|
|
2611
|
+
? undefined
|
|
2612
|
+
: storedFormFirst(field, parentFields?.[field], resolveRef),
|
|
2613
|
+
ownFields: elementFields,
|
|
2614
|
+
attrEncoders: buildAttrEncoders(elementFields, resolveRef, keyedValue !== undefined && edge.entity === undefined),
|
|
1674
2615
|
// Sort-key composites keep reading the pre-#133 encoding (the entity
|
|
1675
2616
|
// model's top-level transforms), so no stored key is re-spelled.
|
|
1676
2617
|
keyAttrEncoders: buildKeyAttrEncoders(entityFields),
|
|
@@ -1711,16 +2652,19 @@ const resolveNode = (args) => {
|
|
|
1711
2652
|
}
|
|
1712
2653
|
}
|
|
1713
2654
|
}
|
|
2655
|
+
const ownFields = args.ownFields ?? parentFields;
|
|
1714
2656
|
return {
|
|
1715
2657
|
fieldName,
|
|
1716
2658
|
entityType,
|
|
1717
2659
|
cardinality,
|
|
2660
|
+
ownFields,
|
|
1718
2661
|
// Absent optionals stay absent under `exactOptionalPropertyTypes`.
|
|
1719
2662
|
...(discriminator !== undefined && { discriminator }),
|
|
1720
2663
|
...(ownDiscriminator !== undefined && { ownDiscriminator }),
|
|
1721
2664
|
children,
|
|
1722
2665
|
...(assemble !== undefined && { assemble }),
|
|
1723
2666
|
...(decompose !== undefined && { decompose }),
|
|
2667
|
+
...(args.decomposeInput !== undefined && { decomposeInput: args.decomposeInput }),
|
|
1724
2668
|
...(skComposite !== undefined && { skComposite }),
|
|
1725
2669
|
...(refIdentifierField !== undefined && { refIdentifierField }),
|
|
1726
2670
|
...(args.packed !== undefined && { packed: args.packed }),
|
|
@@ -1847,14 +2791,12 @@ stored) => Effect.gen(function* () {
|
|
|
1847
2791
|
} while (exclusiveStartKey !== undefined);
|
|
1848
2792
|
return allItems;
|
|
1849
2793
|
});
|
|
1850
|
-
|
|
1851
|
-
// Internal: Assembly algorithm
|
|
1852
|
-
// ---------------------------------------------------------------------------
|
|
1853
|
-
const assembleAggregate = (decodeSchema, rootNode, allItems, _contextFields, key, aggregateName,
|
|
2794
|
+
const assembleAggregate = (assembly, rootNode, allItems, _contextFields, key, aggregateName,
|
|
1854
2795
|
/** Library-managed attribute names (system timestamps) to drop before decode. */
|
|
1855
2796
|
systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
2797
|
+
const reached = assemblyWalk(rootNode, allItems, (node, item) => takesRow(node, item.__edd_e__, (attr) => item[attr]));
|
|
1856
2798
|
// Find the root item
|
|
1857
|
-
const rootItems =
|
|
2799
|
+
const rootItems = reached.get(rootNode) ?? [];
|
|
1858
2800
|
if (rootItems.length === 0) {
|
|
1859
2801
|
return yield* new AggregateAssemblyError({
|
|
1860
2802
|
aggregate: aggregateName,
|
|
@@ -1873,7 +2815,7 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
|
1873
2815
|
// Assemble edge values from the item collection
|
|
1874
2816
|
const edgeValues = {};
|
|
1875
2817
|
for (const child of rootNode.children) {
|
|
1876
|
-
const assembled = yield* assembleNode(child,
|
|
2818
|
+
const assembled = yield* assembleNode(child, reached, key, aggregateName, systemAttrs);
|
|
1877
2819
|
if (child.fieldName !== null && assembled !== undefined) {
|
|
1878
2820
|
edgeValues[child.fieldName] = assembled;
|
|
1879
2821
|
}
|
|
@@ -1897,7 +2839,7 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
|
1897
2839
|
"gsi5sk",
|
|
1898
2840
|
"lsi1sk",
|
|
1899
2841
|
"lsi2sk",
|
|
1900
|
-
...systemAttrs,
|
|
2842
|
+
...stampsToStrip(rootNode, systemAttrs),
|
|
1901
2843
|
]);
|
|
1902
2844
|
for (const [fieldKey, value] of Object.entries(rootItem)) {
|
|
1903
2845
|
if (metaFields.has(fieldKey))
|
|
@@ -1911,30 +2853,50 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
|
1911
2853
|
// Decode through `decodeSchema` — a tolerant clone of the aggregate schema
|
|
1912
2854
|
// that lifts every date / Redacted leaf (root + nested edges) from the stored
|
|
1913
2855
|
// wire form to its domain value in a single pass (#72 + Option A).
|
|
1914
|
-
const
|
|
1915
|
-
|
|
1916
|
-
operation: "aggregate.assemble",
|
|
1917
|
-
cause,
|
|
1918
|
-
})));
|
|
2856
|
+
const toValidationError = (cause) => new ValidationError({ entityType: aggregateName, operation: "aggregate.assemble", cause });
|
|
2857
|
+
const decoded = yield* Schema.decodeUnknownEffect(assembly.schema)(assembled).pipe(Effect.mapError(toValidationError), failingAsBefore(() => issueDecoding(assembly.before(), assembled), toValidationError));
|
|
1919
2858
|
return decoded;
|
|
1920
2859
|
});
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
|
|
1924
|
-
|
|
2860
|
+
/**
|
|
2861
|
+
* Whether assembly hands a row to `node`: the row's entity type is the node's, and so is each of
|
|
2862
|
+
* the node's static discriminator values (a computed one, a function, isn't matched). A node's
|
|
2863
|
+
* discriminator already holds every enclosing one (`resolveNode`). `valueOf` reads an attribute of
|
|
2864
|
+
* the row as a read has it.
|
|
2865
|
+
*/
|
|
2866
|
+
const takesRow = (node, entityType, valueOf) => {
|
|
2867
|
+
if (entityType !== node.entityType)
|
|
2868
|
+
return false;
|
|
2869
|
+
for (const [attr, value] of Object.entries(node.discriminator ?? {})) {
|
|
2870
|
+
if (typeof value === "function")
|
|
2871
|
+
continue;
|
|
2872
|
+
if (valueOf(attr) !== value)
|
|
1925
2873
|
return false;
|
|
1926
|
-
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
|
|
1932
|
-
|
|
1933
|
-
|
|
1934
|
-
|
|
1935
|
-
|
|
1936
|
-
|
|
1937
|
-
|
|
2874
|
+
}
|
|
2875
|
+
return true;
|
|
2876
|
+
};
|
|
2877
|
+
/**
|
|
2878
|
+
* Assembly's walk over an aggregate's rows: each node a read reaches, with the rows it takes
|
|
2879
|
+
* (`takesRow`). A node with edges (the root, a sub-aggregate) leads to them only through its one
|
|
2880
|
+
* row: one that takes none is absent, and one that takes more can't be assembled, so a read hands
|
|
2881
|
+
* nothing to the nodes under it. Assembly reads each node's rows off this walk, and the write
|
|
2882
|
+
* check (`EDD-9128`) judges a row only by the nodes it reaches, so the two never disagree on which
|
|
2883
|
+
* node a row is.
|
|
2884
|
+
*/
|
|
2885
|
+
const assemblyWalk = (rootNode, rows, takes) => {
|
|
2886
|
+
const reached = new Map();
|
|
2887
|
+
const visit = (node) => {
|
|
2888
|
+
const taken = rows.filter((row) => takes(node, row));
|
|
2889
|
+
reached.set(node, taken);
|
|
2890
|
+
if (node.children.length > 0 && taken.length !== 1)
|
|
2891
|
+
return;
|
|
2892
|
+
for (const child of node.children)
|
|
2893
|
+
visit(child);
|
|
2894
|
+
};
|
|
2895
|
+
visit(rootNode);
|
|
2896
|
+
return reached;
|
|
2897
|
+
};
|
|
2898
|
+
const assembleNode = (node, reached, key, aggregateName, systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
2899
|
+
const matchingItems = reached.get(node) ?? [];
|
|
1938
2900
|
if (node.cardinality === "one") {
|
|
1939
2901
|
// One-to-one: sub-aggregate root or simple one edge
|
|
1940
2902
|
if (node.children.length > 0) {
|
|
@@ -1951,12 +2913,10 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
|
|
|
1951
2913
|
}
|
|
1952
2914
|
const subRootItem = matchingItems[0];
|
|
1953
2915
|
const edgeValues = {};
|
|
2916
|
+
// Its one row leads to its edges (`assemblyWalk`). Each child's discriminator already holds
|
|
2917
|
+
// this node's (`resolveNode`).
|
|
1954
2918
|
for (const child of node.children) {
|
|
1955
|
-
|
|
1956
|
-
const childNode = node.discriminator
|
|
1957
|
-
? { ...child, discriminator: { ...node.discriminator, ...child.discriminator } }
|
|
1958
|
-
: child;
|
|
1959
|
-
const assembled = yield* assembleNode(childNode, allItems, key, aggregateName, systemAttrs);
|
|
2919
|
+
const assembled = yield* assembleNode(child, reached, key, aggregateName, systemAttrs);
|
|
1960
2920
|
if (child.fieldName !== null && assembled !== undefined) {
|
|
1961
2921
|
edgeValues[child.fieldName] = assembled;
|
|
1962
2922
|
}
|
|
@@ -1964,6 +2924,7 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
|
|
|
1964
2924
|
// Build sub-aggregate result: sub-root fields + assembled edges
|
|
1965
2925
|
const subFields = {};
|
|
1966
2926
|
const edgeFieldNames = new Set(node.children.map((c) => c.fieldName).filter(Boolean));
|
|
2927
|
+
const stripped = stampsToStrip(node, systemAttrs);
|
|
1967
2928
|
for (const [fieldKey, value] of Object.entries(subRootItem)) {
|
|
1968
2929
|
// Skip DynamoDB metadata, discriminator attributes, and edge fields
|
|
1969
2930
|
if (fieldKey === "__edd_e__")
|
|
@@ -1972,7 +2933,7 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
|
|
|
1972
2933
|
continue;
|
|
1973
2934
|
if (fieldKey.startsWith("gsi") || fieldKey.startsWith("lsi"))
|
|
1974
2935
|
continue;
|
|
1975
|
-
if (
|
|
2936
|
+
if (stripped.has(fieldKey))
|
|
1976
2937
|
continue;
|
|
1977
2938
|
if (edgeFieldNames.has(fieldKey))
|
|
1978
2939
|
continue;
|
|
@@ -1989,10 +2950,10 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
|
|
|
1989
2950
|
return undefined;
|
|
1990
2951
|
// Return the item (stripped of DynamoDB metadata)
|
|
1991
2952
|
const item = matchingItems[0];
|
|
1992
|
-
return stripMetadata(item, systemAttrs);
|
|
2953
|
+
return stripMetadata(item, stampsToStrip(node, systemAttrs));
|
|
1993
2954
|
}
|
|
1994
2955
|
// Many edge: collect all matching items
|
|
1995
|
-
const stripped = matchingItems.map((item) => stripMetadata(item, systemAttrs));
|
|
2956
|
+
const stripped = matchingItems.map((item) => stripMetadata(item, stampsToStrip(node, systemAttrs)));
|
|
1996
2957
|
if (node.assemble) {
|
|
1997
2958
|
return node.assemble(stripped);
|
|
1998
2959
|
}
|
|
@@ -2002,6 +2963,14 @@ const assembleNode = (node, allItems, key, aggregateName, systemAttrs = EMPTY_AT
|
|
|
2002
2963
|
// Internal: Strip DynamoDB metadata from items
|
|
2003
2964
|
// ---------------------------------------------------------------------------
|
|
2004
2965
|
const EMPTY_ATTRS = new Set();
|
|
2966
|
+
/** The timestamps a node's rows hold beside its value: those its value doesn't declare. */
|
|
2967
|
+
const stampsToStrip = (node, systemAttrs) => {
|
|
2968
|
+
const own = node.ownFields;
|
|
2969
|
+
if (own === undefined)
|
|
2970
|
+
return systemAttrs;
|
|
2971
|
+
const kept = [...systemAttrs].filter((name) => !(name in own));
|
|
2972
|
+
return kept.length === systemAttrs.size ? systemAttrs : new Set(kept);
|
|
2973
|
+
};
|
|
2005
2974
|
const stripMetadata = (item, systemAttrs = EMPTY_ATTRS) => {
|
|
2006
2975
|
const result = {};
|
|
2007
2976
|
for (const [key, value] of Object.entries(item)) {
|
|
@@ -2017,14 +2986,45 @@ const stripMetadata = (item, systemAttrs = EMPTY_ATTRS) => {
|
|
|
2017
2986
|
}
|
|
2018
2987
|
return result;
|
|
2019
2988
|
};
|
|
2989
|
+
/** An object as given, to name it in an error, whatever its `toString` (a JSON body's may be text). */
|
|
2990
|
+
const describeObject = (value) => {
|
|
2991
|
+
try {
|
|
2992
|
+
const json = JSON.stringify(value);
|
|
2993
|
+
if (json !== undefined)
|
|
2994
|
+
return json;
|
|
2995
|
+
}
|
|
2996
|
+
catch {
|
|
2997
|
+
// A cycle, or a `toJSON` that throws: named by its kind below.
|
|
2998
|
+
}
|
|
2999
|
+
return Object.prototype.toString.call(value);
|
|
3000
|
+
};
|
|
3001
|
+
/** An id as given, to name it in an error. */
|
|
3002
|
+
const describeId = (id) => typeof id === "string"
|
|
3003
|
+
? JSON.stringify(id)
|
|
3004
|
+
: typeof id === "bigint"
|
|
3005
|
+
? `${id}n`
|
|
3006
|
+
: id instanceof Date
|
|
3007
|
+
? `a Date (${Number.isNaN(id.getTime()) ? "invalid" : id.toISOString()})`
|
|
3008
|
+
: typeof id === "object" && id !== null
|
|
3009
|
+
? `an object (${describeObject(id)})`
|
|
3010
|
+
: typeof id === "function"
|
|
3011
|
+
? "a function"
|
|
3012
|
+
: String(id);
|
|
3013
|
+
/** An id as `RefNotFound` names it. */
|
|
3014
|
+
const refIdText = (id) => typeof id === "string" ? id : id instanceof Date ? id.toISOString() : String(id);
|
|
2020
3015
|
/**
|
|
2021
3016
|
* Walk the input recursively following graph edges, collect ref IDs,
|
|
2022
3017
|
* fetch referenced entities, and replace IDs with hydrated domain data.
|
|
3018
|
+
*
|
|
3019
|
+
* Every id is judged before anything is fetched: an id of an entity no one id names
|
|
3020
|
+
* (`EDD-9129`), then an id that is no value of the entity's key composite, or one `put` refuses as
|
|
3021
|
+
* DynamoDB can't store it (`EDD-9131`), then one with no key text (`EDD-9096`). Each is then fetched by the key `Entity.put` wrote for it,
|
|
3022
|
+
* composed as `Batch.get` composes an entity's own `get` (`composePrimaryKeyOrFail`), once per key.
|
|
2023
3023
|
*/
|
|
2024
|
-
const hydrateAggregateRefs = (input, edges, aggregateName) => Effect.gen(function* () {
|
|
3024
|
+
const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen(function* () {
|
|
2025
3025
|
// Collect all ref IDs from the entire input hierarchy
|
|
2026
3026
|
const refRequests = [];
|
|
2027
|
-
collectRefIdsFromEdges(refRequests, input, edges, []);
|
|
3027
|
+
collectRefIdsFromEdges(refRequests, input, edges, fields, [], "");
|
|
2028
3028
|
if (refRequests.length === 0)
|
|
2029
3029
|
return input;
|
|
2030
3030
|
// Group by entity type for efficient fetching
|
|
@@ -2039,57 +3039,150 @@ const hydrateAggregateRefs = (input, edges, aggregateName) => Effect.gen(functio
|
|
|
2039
3039
|
byEntityType.set(key, { entity: req.entity, reqs: [req] });
|
|
2040
3040
|
}
|
|
2041
3041
|
}
|
|
2042
|
-
//
|
|
2043
|
-
|
|
3042
|
+
// An entity no one id names (its key has two composites, or none): nothing to fetch it by.
|
|
3043
|
+
// 1.39.0 fetched under its identifier (or `id`), which no key composes from alone, and died.
|
|
2044
3044
|
for (const [entityType, { entity, reqs }] of byEntityType) {
|
|
2045
|
-
|
|
2046
|
-
|
|
2047
|
-
|
|
2048
|
-
const
|
|
2049
|
-
|
|
2050
|
-
|
|
2051
|
-
|
|
2052
|
-
|
|
2053
|
-
|
|
2054
|
-
|
|
2055
|
-
|
|
2056
|
-
|
|
2057
|
-
|
|
2058
|
-
|
|
3045
|
+
if (refKeyComposite(entity) !== undefined)
|
|
3046
|
+
continue;
|
|
3047
|
+
const composites = refKeyComposites(entity);
|
|
3048
|
+
const named = [...new Set(reqs.map((req) => req.fieldName))];
|
|
3049
|
+
return yield* new ValidationError({
|
|
3050
|
+
entityType: aggregateName,
|
|
3051
|
+
operation: "aggregate.create",
|
|
3052
|
+
cause: new Error(`[EDD-9129] Aggregate "${aggregateName}": ${named.map((name) => `"${name}"`).join(", ")} ` +
|
|
3053
|
+
`${named.length === 1 ? "is" : "are"} given an id of entity "${entityType}", whose ` +
|
|
3054
|
+
`primary key is composed from ${composites.length === 0
|
|
3055
|
+
? "no attribute"
|
|
3056
|
+
: composites.map((name) => `"${name}"`).join(", ")}, so no one id names one item to fetch. Give "${named[0]}" whole, or key that entity ` +
|
|
3057
|
+
`by one attribute to fetch it by id. Nothing was fetched or written.`),
|
|
3058
|
+
});
|
|
3059
|
+
}
|
|
3060
|
+
// `RefEntity` is the pure structural bound (no `get` — issue #66): aggregate
|
|
3061
|
+
// edges can be authored from AWS-free `@effect-dynamodb/schema` definitions,
|
|
3062
|
+
// which carry no runtime `.get`/operations. Ref hydration is a runtime
|
|
3063
|
+
// operation, so promote a pure edge target to a full operational Entity (a
|
|
3064
|
+
// thin op-attach over its retained `_data`); runtime-authored targets already
|
|
3065
|
+
// carry `.get` and pass through untouched. Mirrors `DynamoClient.make()`'s
|
|
3066
|
+
// entity binding. Promoted once per distinct edge entity type per hydrate (issue #71).
|
|
3067
|
+
const runtimeEntities = new Map();
|
|
3068
|
+
for (const [entityType, { entity }] of byEntityType) {
|
|
3069
|
+
runtimeEntities.set(entityType, (typeof entity.get === "function"
|
|
2059
3070
|
? entity
|
|
2060
|
-
: entityFromDefinition(entity));
|
|
2061
|
-
|
|
2062
|
-
|
|
3071
|
+
: entityFromDefinition(entity)));
|
|
3072
|
+
}
|
|
3073
|
+
// An id that is no value of the key composite names no item: up to 1.39.0 a string was
|
|
3074
|
+
// fetched under a key no `put` writes (`lineid_5` for a number), and anything else was dropped.
|
|
3075
|
+
// Nor does one `put` refuses: one that doesn't encode as the attribute is stored (an infinite
|
|
3076
|
+
// number through a digits-only string codec), or one DynamoDB can't store (an infinite number,
|
|
3077
|
+
// at any depth of a struct, an `Option` or a `Result`), whose key text can name an item of
|
|
3078
|
+
// another value (`{ a: Infinity }` and `{ a: 5 }` compose one key), fetched in its place.
|
|
3079
|
+
// An id given more than once is judged once: one composing the key text of an id already
|
|
3080
|
+
// judged, and equal to it as a value of the key composite (`Schema.toEquivalence`), so three
|
|
3081
|
+
// ISO strings of one instant, each decoded to a `Date` of its own, are judged once. The key
|
|
3082
|
+
// text alone isn't enough: `{ a: Infinity }` composes the key of `{ a: 5 }`, and is refused.
|
|
3083
|
+
// An id whose key isn't composed here is judged, and fails composing below.
|
|
3084
|
+
const judged = new Map();
|
|
3085
|
+
const composed = new Map();
|
|
3086
|
+
for (const req of refRequests) {
|
|
3087
|
+
const composite = refKeyComposite(req.entity);
|
|
3088
|
+
if (Option.isNone(req.id)) {
|
|
3089
|
+
return yield* new ValidationError({
|
|
3090
|
+
entityType: aggregateName,
|
|
3091
|
+
operation: "aggregate.create",
|
|
3092
|
+
cause: new Error(`[EDD-9131] Aggregate "${aggregateName}": "${req.at}" is given ${describeId(req.given)}, ` +
|
|
3093
|
+
`which is no value of "${composite}", the attribute entity ` +
|
|
3094
|
+
`"${req.entity.entityType}" is keyed by, so it names no item to fetch. Give an id of ` +
|
|
3095
|
+
`that attribute's type. Nothing was fetched or written.`),
|
|
3096
|
+
});
|
|
3097
|
+
}
|
|
3098
|
+
const runtimeEntity = runtimeEntities.get(req.entity.entityType);
|
|
3099
|
+
const key = yield* Effect.exit(composePrimaryKeyOrFail(runtimeEntity, { [composite]: req.id.value }, "aggregate.create"));
|
|
3100
|
+
if (Exit.isSuccess(key)) {
|
|
3101
|
+
const keyText = `${req.entity.entityType}:${JSON.stringify(Object.values(key.value))}`;
|
|
3102
|
+
composed.set(req, keyText);
|
|
3103
|
+
const same = judged.get(keyText) ?? [];
|
|
3104
|
+
judged.set(keyText, same);
|
|
3105
|
+
const equivalent = idEquivalence(req.entity);
|
|
3106
|
+
const value = req.id.value;
|
|
3107
|
+
if (same.some((other) => equivalent(other, value)))
|
|
3108
|
+
continue;
|
|
3109
|
+
same.push(value);
|
|
3110
|
+
}
|
|
3111
|
+
const unstorable = yield* runtimeEntity._unstorableKey({ [composite]: req.id.value }).pipe(Effect.mapError((refused) => new ValidationError({
|
|
3112
|
+
entityType: aggregateName,
|
|
3113
|
+
operation: "aggregate.create",
|
|
3114
|
+
cause: new Error(`[EDD-9131] Aggregate "${aggregateName}": "${req.at}" is given ` +
|
|
3115
|
+
`${describeId(req.given)}, which no item of entity "${req.entity.entityType}" ` +
|
|
3116
|
+
`can be keyed by: \`put\` refuses it, as it doesn't encode as "${composite}" ` +
|
|
3117
|
+
`is stored. Give an id that does. Nothing was fetched or written.`, { cause: refused }),
|
|
3118
|
+
})));
|
|
3119
|
+
if (unstorable !== undefined) {
|
|
3120
|
+
return yield* new ValidationError({
|
|
3121
|
+
entityType: aggregateName,
|
|
3122
|
+
operation: "aggregate.create",
|
|
3123
|
+
cause: new Error(`[EDD-9131] Aggregate "${aggregateName}": "${req.at}" is given ${describeId(req.given)}, ` +
|
|
3124
|
+
`which no item of entity "${req.entity.entityType}" can be keyed by: \`put\` ` +
|
|
3125
|
+
`refuses it, as DynamoDB can't store it (${unstorable.describe()}). Give an id ` +
|
|
3126
|
+
`DynamoDB can store. Nothing was fetched or written.`),
|
|
3127
|
+
});
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
// Each id's key, composed before anything is fetched: one with no key text (`NaN`,
|
|
3131
|
+
// `EDD-9096`) fails here. An id fetched twice, or two ids composing one key (`"L"` and `"l"`
|
|
3132
|
+
// under lowercase casing), is fetched once: `BatchGetItem` refuses a repeated key.
|
|
3133
|
+
const fetches = [];
|
|
3134
|
+
const lookupKeys = new Map();
|
|
3135
|
+
for (const [entityType, { entity, reqs }] of byEntityType) {
|
|
3136
|
+
const runtimeEntity = runtimeEntities.get(entityType);
|
|
3137
|
+
const composite = refKeyComposite(entity);
|
|
3138
|
+
const ops = [];
|
|
3139
|
+
const seen = new Set();
|
|
3140
|
+
for (const req of reqs) {
|
|
3141
|
+
// Composed while judging the id, unless that failed: then composing fails here.
|
|
3142
|
+
let lookupKey = composed.get(req);
|
|
3143
|
+
if (lookupKey === undefined) {
|
|
3144
|
+
const key = yield* composePrimaryKeyOrFail(runtimeEntity, { [composite]: Option.getOrThrow(req.id) }, "aggregate.create");
|
|
3145
|
+
lookupKey = `${entityType}:${JSON.stringify(Object.values(key))}`;
|
|
3146
|
+
}
|
|
3147
|
+
lookupKeys.set(req, lookupKey);
|
|
3148
|
+
if (!seen.has(lookupKey)) {
|
|
3149
|
+
seen.add(lookupKey);
|
|
3150
|
+
ops.push({ lookupKey, req });
|
|
3151
|
+
}
|
|
3152
|
+
}
|
|
3153
|
+
fetches.push({ entityType, runtimeEntity, ops });
|
|
3154
|
+
}
|
|
3155
|
+
// Batch-fetch all refs — one Batch.get call per entity type
|
|
3156
|
+
const hydratedLookup = new Map();
|
|
3157
|
+
for (const { entityType, runtimeEntity, ops } of fetches) {
|
|
3158
|
+
const composite = refKeyComposite(runtimeEntity);
|
|
3159
|
+
// Build EntityGet intermediates for batch fetching: `Batch.get` composes each key as the
|
|
3160
|
+
// entity's own `get` does, the key `Entity.put` wrote.
|
|
3161
|
+
const getOps = ops.map(({ req }) => runtimeEntity.get({ [composite]: Option.getOrThrow(req.id) }));
|
|
2063
3162
|
const results = yield* Batch.get(getOps);
|
|
2064
3163
|
// Map results back to lookup, failing on missing refs.
|
|
2065
|
-
for (let i = 0; i <
|
|
2066
|
-
const
|
|
3164
|
+
for (let i = 0; i < ops.length; i++) {
|
|
3165
|
+
const { lookupKey, req } = ops[i];
|
|
2067
3166
|
const result = results[i];
|
|
2068
3167
|
if (result == null) {
|
|
2069
3168
|
return yield* new RefNotFound({
|
|
2070
3169
|
entity: aggregateName,
|
|
2071
|
-
field:
|
|
3170
|
+
field: req.fieldName,
|
|
2072
3171
|
refEntity: entityType,
|
|
2073
|
-
refId:
|
|
3172
|
+
refId: refIdText(req.given),
|
|
2074
3173
|
});
|
|
2075
3174
|
}
|
|
2076
|
-
// `Batch.get` returns the
|
|
2077
|
-
//
|
|
2078
|
-
//
|
|
2079
|
-
|
|
2080
|
-
// class expecting the wire form. Re-encode through the ref's substituted
|
|
2081
|
-
// `recordSchema` so the spliced value is wire-form and decoded exactly once
|
|
2082
|
-
// (issue #72) — this also keeps it marshall-safe for decompose.
|
|
2083
|
-
const wire = yield* Schema.encodeUnknownEffect(runtimeEntity.schemas.recordSchema)(result).pipe(Effect.mapError((cause) => new ValidationError({
|
|
2084
|
-
entityType: aggregateName,
|
|
2085
|
-
operation: "aggregate.hydrateRefs.encode",
|
|
2086
|
-
cause,
|
|
2087
|
-
})));
|
|
2088
|
-
hydratedLookup.set(`${entityType}:${id}`, wire);
|
|
3175
|
+
// `Batch.get` returns the decoded record: domain values, as a caller holds, and
|
|
3176
|
+
// `writeSchema` takes them as that. Encoded here, a field with one type on both
|
|
3177
|
+
// sides of a transformation would be taken for a domain value and encoded twice.
|
|
3178
|
+
hydratedLookup.set(lookupKey, result);
|
|
2089
3179
|
}
|
|
2090
3180
|
}
|
|
2091
3181
|
// Walk the input again and replace IDs with hydrated data
|
|
2092
|
-
const result = replaceRefIds(input, refRequests,
|
|
3182
|
+
const result = replaceRefIds(input, refRequests, (req) => {
|
|
3183
|
+
const lookupKey = lookupKeys.get(req);
|
|
3184
|
+
return lookupKey === undefined ? undefined : hydratedLookup.get(lookupKey);
|
|
3185
|
+
});
|
|
2093
3186
|
renameInputFields(result, edges);
|
|
2094
3187
|
return result;
|
|
2095
3188
|
});
|
|
@@ -2115,82 +3208,118 @@ const renameInputFields = (data, edges) => {
|
|
|
2115
3208
|
}
|
|
2116
3209
|
}
|
|
2117
3210
|
};
|
|
3211
|
+
/** An id given for an edge's entity: the id as given, and as a value of its key composite. */
|
|
3212
|
+
const refId = (entity, given) => ({ given, id: refIdValue(entity, given) });
|
|
3213
|
+
const idEquivalences = new WeakMap();
|
|
3214
|
+
/**
|
|
3215
|
+
* Whether two ids of `entity` are one value of its key composite (`refIdField`), by the field's
|
|
3216
|
+
* own equivalence (`Schema.toEquivalence`: two `Date`s of one instant are one); `Equal.equals`
|
|
3217
|
+
* where the field can't be read or derives none.
|
|
3218
|
+
*/
|
|
3219
|
+
const idEquivalence = (entity) => {
|
|
3220
|
+
const field = refIdField(entity);
|
|
3221
|
+
if (field === undefined)
|
|
3222
|
+
return Equal.equals;
|
|
3223
|
+
const cached = idEquivalences.get(field);
|
|
3224
|
+
if (cached !== undefined)
|
|
3225
|
+
return cached;
|
|
3226
|
+
let equivalent;
|
|
3227
|
+
try {
|
|
3228
|
+
equivalent = Schema.toEquivalence(field);
|
|
3229
|
+
}
|
|
3230
|
+
catch {
|
|
3231
|
+
equivalent = Equal.equals;
|
|
3232
|
+
}
|
|
3233
|
+
idEquivalences.set(field, equivalent);
|
|
3234
|
+
return equivalent;
|
|
3235
|
+
};
|
|
2118
3236
|
/**
|
|
2119
3237
|
* Recursively walk input following graph edges to collect ref ID references.
|
|
2120
3238
|
* Edge-driven: entity lookup comes from the edge directly, not from a refs bag.
|
|
3239
|
+
*
|
|
3240
|
+
* An id is anything given where the input takes one (`null` and `undefined` give none), judged
|
|
3241
|
+
* by `hydrateAggregateRefs` before anything is fetched. Up to 1.39.0 only a string was taken,
|
|
3242
|
+
* so a number or bigint id was dropped, and an optional edge was created without it.
|
|
2121
3243
|
*/
|
|
2122
|
-
const collectRefIdsFromEdges = (result, input, edges,
|
|
3244
|
+
const collectRefIdsFromEdges = (result, input, edges,
|
|
3245
|
+
/** The fields of the schema `input` is a value of: a `many` element's schema is read off it. */
|
|
3246
|
+
fields, path,
|
|
3247
|
+
/** Where `input` is, to name an id in an error: `""` at the root, `"sub."` under `sub`. */
|
|
3248
|
+
at) => {
|
|
2123
3249
|
for (const [edgeName, edge] of Object.entries(edges)) {
|
|
2124
3250
|
if (!("_tag" in edge))
|
|
2125
3251
|
continue;
|
|
2126
|
-
if (edge._tag === "RefEdge") {
|
|
2127
|
-
// RefEdge → ${field}Id in input
|
|
3252
|
+
if (edge._tag === "RefEdge" || (edge._tag === "OneEdge" && edge.entity)) {
|
|
3253
|
+
// RefEdge, and OneEdge with an entity → ${field}Id in input, where it holds an id `create`
|
|
3254
|
+
// fetches (`holdsRefId`): a string as on 1.39.0, an id of another type only where the model's
|
|
3255
|
+
// field is the entity's own model, its id isn't declared, and the entity isn't given whole.
|
|
3256
|
+
const entity = edge.entity;
|
|
2128
3257
|
const idFieldName = `${edgeName}Id`;
|
|
2129
|
-
const idValue = input
|
|
2130
|
-
if (
|
|
3258
|
+
const idValue = given(input, idFieldName);
|
|
3259
|
+
if (holdsRefId(fields, edgeName, entity, input)) {
|
|
2131
3260
|
result.push({
|
|
2132
|
-
entity
|
|
2133
|
-
|
|
2134
|
-
path: [...path],
|
|
2135
|
-
fieldName: edgeName,
|
|
2136
|
-
idFieldName,
|
|
2137
|
-
});
|
|
2138
|
-
}
|
|
2139
|
-
}
|
|
2140
|
-
else if (edge._tag === "OneEdge" && edge.entity) {
|
|
2141
|
-
// OneEdge with entity → ${field}Id in input
|
|
2142
|
-
const idFieldName = `${edgeName}Id`;
|
|
2143
|
-
const idValue = input[idFieldName];
|
|
2144
|
-
if (typeof idValue === "string") {
|
|
2145
|
-
result.push({
|
|
2146
|
-
entity: edge.entity,
|
|
2147
|
-
id: idValue,
|
|
3261
|
+
entity,
|
|
3262
|
+
...refId(entity, idValue),
|
|
2148
3263
|
path: [...path],
|
|
2149
3264
|
fieldName: edgeName,
|
|
2150
3265
|
idFieldName,
|
|
3266
|
+
at: `${at}${idFieldName}`,
|
|
2151
3267
|
});
|
|
2152
3268
|
}
|
|
2153
3269
|
}
|
|
2154
3270
|
else if (edge._tag === "BoundSubAggregate") {
|
|
2155
3271
|
const bound = edge;
|
|
2156
|
-
const subInput = input
|
|
3272
|
+
const subInput = given(input, edgeName);
|
|
2157
3273
|
if (subInput != null && typeof subInput === "object") {
|
|
2158
|
-
collectRefIdsFromEdges(result, subInput, bound.aggregate.edges, [
|
|
2159
|
-
...path,
|
|
2160
|
-
edgeName,
|
|
2161
|
-
]);
|
|
3274
|
+
collectRefIdsFromEdges(result, subInput, bound.aggregate.edges, fieldsOf(bound.aggregate.schema), [...path, edgeName], `${at}${edgeName}.`);
|
|
2162
3275
|
}
|
|
2163
3276
|
}
|
|
2164
3277
|
else if (edge._tag === "ManyEdge" && edge.entity) {
|
|
2165
3278
|
// ManyEdge with entity → walk array elements for ref IDs
|
|
3279
|
+
const entity = edge.entity;
|
|
2166
3280
|
const inputKey = edge.inputField ?? edgeName;
|
|
2167
|
-
const arr = input
|
|
3281
|
+
const arr = given(input, inputKey);
|
|
2168
3282
|
if (Array.isArray(arr)) {
|
|
2169
|
-
const entityFieldName = deriveEntityFieldName(
|
|
3283
|
+
const entityFieldName = deriveEntityFieldName(entity);
|
|
3284
|
+
const element = manyElementSchema(fields, edgeName);
|
|
3285
|
+
const entityElement = isEntityElement(element, entity);
|
|
2170
3286
|
for (let i = 0; i < arr.length; i++) {
|
|
2171
3287
|
const elem = arr[i];
|
|
2172
|
-
if (
|
|
2173
|
-
|
|
3288
|
+
if (elem == null)
|
|
3289
|
+
continue;
|
|
3290
|
+
const asId = refId(entity, elem);
|
|
3291
|
+
if (entityElement
|
|
3292
|
+
? Option.isSome(asId.id) || typeof elem !== "object"
|
|
3293
|
+
: typeof elem === "string") {
|
|
3294
|
+
// Element IS the ref ID. Where the element is the entity (`Array<Umpire>`), an id of
|
|
3295
|
+
// the entity's key composite, or a scalar given for one, which names no item. Any
|
|
3296
|
+
// other element, a string, as on 1.39.0.
|
|
2174
3297
|
result.push({
|
|
2175
|
-
entity
|
|
2176
|
-
|
|
3298
|
+
entity,
|
|
3299
|
+
...asId,
|
|
2177
3300
|
path: [...path, inputKey, String(i)],
|
|
2178
3301
|
fieldName: edgeName,
|
|
2179
3302
|
idFieldName: String(i),
|
|
3303
|
+
at: `${at}${inputKey}[${i}]`,
|
|
2180
3304
|
});
|
|
2181
3305
|
}
|
|
2182
|
-
else if (
|
|
2183
|
-
|
|
3306
|
+
else if (typeof elem === "object" &&
|
|
3307
|
+
elementHoldsRef(element, entity, elem)) {
|
|
3308
|
+
// Element wraps the entity, given as `${field}Id`, where it holds an id `create`
|
|
3309
|
+
// fetches (`elementHoldsRef`, the rule a `one` edge's id follows): a string as on
|
|
3310
|
+
// 1.39.0, an id of another type only where the element's field of the entity's name is
|
|
3311
|
+
// the entity's own model, its id isn't declared, and the entity isn't given whole.
|
|
2184
3312
|
const elemObj = elem;
|
|
2185
3313
|
const idFieldName = `${entityFieldName}Id`;
|
|
2186
|
-
const idValue = elemObj
|
|
2187
|
-
if (
|
|
3314
|
+
const idValue = given(elemObj, idFieldName);
|
|
3315
|
+
if (idValue != null) {
|
|
2188
3316
|
result.push({
|
|
2189
|
-
entity
|
|
2190
|
-
|
|
3317
|
+
entity,
|
|
3318
|
+
...refId(entity, idValue),
|
|
2191
3319
|
path: [...path, inputKey, String(i)],
|
|
2192
3320
|
fieldName: entityFieldName,
|
|
2193
3321
|
idFieldName,
|
|
3322
|
+
at: `${at}${inputKey}[${i}].${idFieldName}`,
|
|
2194
3323
|
});
|
|
2195
3324
|
}
|
|
2196
3325
|
}
|
|
@@ -2256,21 +3385,23 @@ const replaceRefIds = (input, refRequests, lookup) => {
|
|
|
2256
3385
|
// Deep clone the input for mutation
|
|
2257
3386
|
const result = cloneInput(input);
|
|
2258
3387
|
for (const req of refRequests) {
|
|
2259
|
-
const
|
|
2260
|
-
const data = lookup.get(lookupKey);
|
|
3388
|
+
const data = lookup(req);
|
|
2261
3389
|
if (!data)
|
|
2262
3390
|
continue;
|
|
3391
|
+
// For ManyEdge elements that are direct IDs (element IS the ref), the target is the array
|
|
3392
|
+
// itself: the path ends at the element, which may be an object (a `Date` id).
|
|
3393
|
+
const isElementId = /^\d+$/.test(req.idFieldName);
|
|
3394
|
+
const segments = isElementId ? req.path.slice(0, -1) : req.path;
|
|
2263
3395
|
// Navigate to the target location in the result
|
|
2264
3396
|
let target = result;
|
|
2265
|
-
for (const segment of
|
|
3397
|
+
for (const segment of segments) {
|
|
2266
3398
|
const next = target[segment];
|
|
2267
3399
|
if (next == null || typeof next !== "object")
|
|
2268
3400
|
break;
|
|
2269
3401
|
target = next;
|
|
2270
3402
|
}
|
|
2271
|
-
//
|
|
2272
|
-
|
|
2273
|
-
if (Array.isArray(target) && /^\d+$/.test(req.idFieldName)) {
|
|
3403
|
+
// Replace the element at the index
|
|
3404
|
+
if (Array.isArray(target) && isElementId) {
|
|
2274
3405
|
target[Number(req.idFieldName)] = data;
|
|
2275
3406
|
}
|
|
2276
3407
|
else {
|
|
@@ -2281,15 +3412,24 @@ const replaceRefIds = (input, refRequests, lookup) => {
|
|
|
2281
3412
|
}
|
|
2282
3413
|
return result;
|
|
2283
3414
|
};
|
|
3415
|
+
/** Each field a decomposition stored as given, once, as `"field" of "member"` (`EDD-9127`). */
|
|
3416
|
+
const storedAsGivenIn = (groups) => [
|
|
3417
|
+
...new Set(groups.flatMap((group) => group.items.flatMap((item) => item.storedAsGiven.map((field) => `"${field}" of "${item.member}"`)))),
|
|
3418
|
+
];
|
|
2284
3419
|
/**
|
|
2285
3420
|
* Decompose an assembled domain object into DynamoDB items grouped by
|
|
2286
3421
|
* sub-aggregate transaction boundaries.
|
|
2287
3422
|
*/
|
|
2288
|
-
const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggregateName, schema
|
|
3423
|
+
const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggregateName, schema,
|
|
3424
|
+
/**
|
|
3425
|
+
* A write's own value (`create`'s input, the state `update`'s mutation returned), before it was
|
|
3426
|
+
* decoded: a custom `decompose` is handed it read as on 1.39.0. Undefined for what was read.
|
|
3427
|
+
*/
|
|
3428
|
+
written) => Effect.gen(function* () {
|
|
2289
3429
|
const items = [];
|
|
2290
|
-
const encodeWith = (set, field, value) => {
|
|
3430
|
+
const encodeWith = (set, field, value, asGiven) => {
|
|
2291
3431
|
const encode = set[field];
|
|
2292
|
-
return encode && value != null ? encode(value) : value;
|
|
3432
|
+
return encode && value != null ? encode(value, asGiven) : value;
|
|
2293
3433
|
};
|
|
2294
3434
|
// Extract context values from the root, encoded for DynamoDB storage.
|
|
2295
3435
|
// Domain Date/DateTime objects must be encoded before toAttributeMap() marshalling,
|
|
@@ -2304,10 +3444,12 @@ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggreg
|
|
|
2304
3444
|
const edgeFieldNames = new Set(rootNode.children.map((c) => c.fieldName).filter(Boolean));
|
|
2305
3445
|
const rootAttrs = {};
|
|
2306
3446
|
const rootKeyAttrs = {};
|
|
3447
|
+
// A context field is a root field, so this names it too.
|
|
3448
|
+
const rootAsGiven = [];
|
|
2307
3449
|
for (const [key, value] of Object.entries(assembled)) {
|
|
2308
3450
|
if (edgeFieldNames.has(key))
|
|
2309
3451
|
continue;
|
|
2310
|
-
rootAttrs[key] = encodeWith(encoders.stored, key, value);
|
|
3452
|
+
rootAttrs[key] = encodeWith(encoders.stored, key, value, () => rootAsGiven.push(key));
|
|
2311
3453
|
rootKeyAttrs[key] = encodeWith(encoders.key, key, value);
|
|
2312
3454
|
}
|
|
2313
3455
|
items.push({
|
|
@@ -2318,11 +3460,14 @@ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggreg
|
|
|
2318
3460
|
skComposites: [],
|
|
2319
3461
|
skCompositesOther: () => [],
|
|
2320
3462
|
member: rootNode.entityType,
|
|
3463
|
+
rowStamps: rootNode.rowStamps,
|
|
3464
|
+
storedAsGiven: rootAsGiven,
|
|
3465
|
+
node: rootNode,
|
|
2321
3466
|
});
|
|
2322
3467
|
// Decompose each edge
|
|
2323
3468
|
for (const child of rootNode.children) {
|
|
2324
3469
|
const fieldValue = assembled[child.fieldName];
|
|
2325
|
-
yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], other: () => [] }, aggregateName, schema);
|
|
3470
|
+
yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], other: () => [] }, aggregateName, schema, writtenField(written, child.fieldName));
|
|
2326
3471
|
}
|
|
2327
3472
|
// Two items composing the same sort key are two writes to one row. DynamoDB
|
|
2328
3473
|
// rejects the whole TransactWriteItems with a ValidationException ("Transaction
|
|
@@ -2367,6 +3512,305 @@ const mergeContextValues = (attrs, contextValues) => {
|
|
|
2367
3512
|
attrs[key] = value;
|
|
2368
3513
|
}
|
|
2369
3514
|
};
|
|
3515
|
+
/**
|
|
3516
|
+
* Whether two keys beginning with these fixed texts can be one text: the texts are equal, or one
|
|
3517
|
+
* continues the other after a `#`. A composite value is taken to be any text (with `escapeKeys`
|
|
3518
|
+
* off one may hold `#`), so this never misses a key that can be the other's.
|
|
3519
|
+
*/
|
|
3520
|
+
const headsOverlap = (a, b) => a === b || a.startsWith(`${b}#`) || b.startsWith(`${a}#`);
|
|
3521
|
+
/**
|
|
3522
|
+
* Whether a writer's text can be the aggregate's partition key: any text can, and composed text
|
|
3523
|
+
* can when it and the key can be one text ({@link headsOverlap}). The aggregate's partition key is
|
|
3524
|
+
* its head continued after `#` when it has composites, and exactly its head when it has none (a
|
|
3525
|
+
* singleton): text that continues its own head can be that only when its head and a `#` begin it.
|
|
3526
|
+
*/
|
|
3527
|
+
const canBePartitionKey = (writer, ownership) => {
|
|
3528
|
+
const head = writer.head;
|
|
3529
|
+
if (head === undefined)
|
|
3530
|
+
return true;
|
|
3531
|
+
const partition = ownership.partitionHead;
|
|
3532
|
+
if (ownership.pkComposite.length === 0) {
|
|
3533
|
+
const equal = head === partition;
|
|
3534
|
+
const continued = partition.startsWith(`${head}#`);
|
|
3535
|
+
return writer.exact === true ? equal : writer.exact === false ? continued : equal || continued;
|
|
3536
|
+
}
|
|
3537
|
+
return writer.exact === true ? head.startsWith(`${partition}#`) : headsOverlap(head, partition);
|
|
3538
|
+
};
|
|
3539
|
+
/**
|
|
3540
|
+
* Whether a row of `theirs` can be taken for a row of `ours`: it can carry any type, it's the same
|
|
3541
|
+
* type, or keys of the two can be one text, each cased as its member's keys are. A bind-time
|
|
3542
|
+
* comparison only: ownership and assembly match `__edd_e__` exactly.
|
|
3543
|
+
*/
|
|
3544
|
+
const typesCollide = (theirs, ours) => theirs.any !== undefined || theirs.type === ours.type || headsOverlap(theirs.label, ours.label);
|
|
3545
|
+
/**
|
|
3546
|
+
* A member's writers, every row type of them made any when one stores an attribute under
|
|
3547
|
+
* `__edd_e__` other than the library's marker, or any attribute: its rows can carry any type. An
|
|
3548
|
+
* aggregate's timestamp so named does, since it's written last. An entity can't (`EDD-9140`).
|
|
3549
|
+
*/
|
|
3550
|
+
const withTypeOverwrites = (writers) => {
|
|
3551
|
+
const marker = writers.find((writer) => writer.field === "__edd_e__" ||
|
|
3552
|
+
(writer.field === undefined && writer.except?.includes("__edd_e__") !== true));
|
|
3553
|
+
if (marker === undefined)
|
|
3554
|
+
return writers;
|
|
3555
|
+
const any = { via: `${marker.channel}, stored under "__edd_e__"` };
|
|
3556
|
+
return writers.map((writer) => ({
|
|
3557
|
+
...writer,
|
|
3558
|
+
types: writer.types.map((type) => ({ ...type, any })),
|
|
3559
|
+
}));
|
|
3560
|
+
};
|
|
3561
|
+
/**
|
|
3562
|
+
* The attributes an entity writes (DESIGN.md §7 "Which rows in its partition are an aggregate's"),
|
|
3563
|
+
* as each row holds them after the last write of each:
|
|
3564
|
+
* - its primary key on every row it writes under it: live rows, version snapshots, soft-delete
|
|
3565
|
+
* tombstones, time-series events, projection tombstones and outbox items;
|
|
3566
|
+
* - each secondary index's partition key on its live rows, and each vector index's partition;
|
|
3567
|
+
* - its unique sentinels, under their own key, with back-pointers to the owning row's key;
|
|
3568
|
+
* - any sort key, its timestamps, `deletedAt`, and the attributes a projection writes on its
|
|
3569
|
+
* tombstones and outbox items, as any text;
|
|
3570
|
+
* - its model attributes, on its rows and kept on its projection tombstones: any name holding any
|
|
3571
|
+
* text, but `__edd_e__` and its table key attributes, which it writes after them (`EDD-9109` and
|
|
3572
|
+
* `EDD-9140` refuse a model attribute stored under them).
|
|
3573
|
+
* None of its rows is an aggregate node's: it composes each composite with its field's name
|
|
3574
|
+
* (`id_p`), which an aggregate never does, and its primary key has at least one. An entity whose
|
|
3575
|
+
* keys can't be read is taken to write any attribute.
|
|
3576
|
+
*/
|
|
3577
|
+
const entityWriters = (entity) => {
|
|
3578
|
+
const e = entity;
|
|
3579
|
+
const type = e.entityType;
|
|
3580
|
+
const table = e._tableTag;
|
|
3581
|
+
try {
|
|
3582
|
+
const schema = e._schema;
|
|
3583
|
+
const typed = (name, casing) => ({
|
|
3584
|
+
type: name,
|
|
3585
|
+
label: composeKey(schema, name, [], { casing }),
|
|
3586
|
+
});
|
|
3587
|
+
const labelOf = (index) => {
|
|
3588
|
+
const collection = index.collection;
|
|
3589
|
+
return collection === undefined
|
|
3590
|
+
? type
|
|
3591
|
+
: Array.isArray(collection)
|
|
3592
|
+
? collection[0]
|
|
3593
|
+
: collection;
|
|
3594
|
+
};
|
|
3595
|
+
// A partition key with composites, or a shard, continues its head after `#`.
|
|
3596
|
+
const exactOf = (index) => index.pk.composite.length > 0 || index.shards !== undefined ? false : undefined;
|
|
3597
|
+
const primary = e.indexes.primary;
|
|
3598
|
+
const tableKeys = [
|
|
3599
|
+
primary.pk.field,
|
|
3600
|
+
...(primary.sk?.field === undefined ? [] : [primary.sk.field]),
|
|
3601
|
+
];
|
|
3602
|
+
const stamps = [e.systemFields?.createdAt, e.systemFields?.updatedAt].filter((name) => typeof name === "string");
|
|
3603
|
+
const writers = [];
|
|
3604
|
+
const anyText = (fields, types, on, channel) => {
|
|
3605
|
+
for (const field of fields) {
|
|
3606
|
+
writers.push({ field, head: undefined, types, table: on, channel: channel(field) });
|
|
3607
|
+
}
|
|
3608
|
+
};
|
|
3609
|
+
const projectionTypes = [];
|
|
3610
|
+
for (const [name, index] of Object.entries(e.indexes)) {
|
|
3611
|
+
const head = composeKey(schema, labelOf(index), [], { casing: index.casing });
|
|
3612
|
+
const exact = exactOf(index);
|
|
3613
|
+
const own = typed(type, index.casing);
|
|
3614
|
+
if (name !== "primary") {
|
|
3615
|
+
// A half on a table key attribute holds the primary key's text (an inverted index): two
|
|
3616
|
+
// halves of one entity share an attribute only with the same fields (`EDD-9106`).
|
|
3617
|
+
if (!tableKeys.includes(index.pk.field)) {
|
|
3618
|
+
writers.push({
|
|
3619
|
+
field: index.pk.field,
|
|
3620
|
+
head,
|
|
3621
|
+
exact,
|
|
3622
|
+
types: [own],
|
|
3623
|
+
table,
|
|
3624
|
+
channel: `its index "${name}"`,
|
|
3625
|
+
});
|
|
3626
|
+
}
|
|
3627
|
+
if (index.sk?.field !== undefined && !tableKeys.includes(index.sk.field)) {
|
|
3628
|
+
writers.push({
|
|
3629
|
+
field: index.sk.field,
|
|
3630
|
+
head: undefined,
|
|
3631
|
+
types: [own],
|
|
3632
|
+
table,
|
|
3633
|
+
channel: `its index "${name}"'s sort key`,
|
|
3634
|
+
});
|
|
3635
|
+
}
|
|
3636
|
+
continue;
|
|
3637
|
+
}
|
|
3638
|
+
// Its live rows, version snapshots, soft-delete tombstones, time-series events and projection
|
|
3639
|
+
// rows. None is an aggregate node's row: an entity composes each composite with its field's
|
|
3640
|
+
// name (`id_p`), which an aggregate never does, and its primary key has at least one.
|
|
3641
|
+
const tombstone = e._projectionTombstones !== undefined ? typed(`${type}#tombstone`, index.casing) : undefined;
|
|
3642
|
+
const outboxConfigs = e._projectionOutboxes ?? [];
|
|
3643
|
+
const outboxHere = outboxConfigs.some((outbox) => outbox.table === undefined)
|
|
3644
|
+
? typed(`${type}#outbox`, index.casing)
|
|
3645
|
+
: undefined;
|
|
3646
|
+
if (tombstone !== undefined)
|
|
3647
|
+
projectionTypes.push(tombstone);
|
|
3648
|
+
const rows = [
|
|
3649
|
+
own,
|
|
3650
|
+
...(tombstone === undefined ? [] : [tombstone]),
|
|
3651
|
+
...(outboxHere === undefined ? [] : [outboxHere]),
|
|
3652
|
+
];
|
|
3653
|
+
writers.push({
|
|
3654
|
+
field: index.pk.field,
|
|
3655
|
+
head,
|
|
3656
|
+
exact,
|
|
3657
|
+
types: rows,
|
|
3658
|
+
table,
|
|
3659
|
+
channel: "its primary key",
|
|
3660
|
+
});
|
|
3661
|
+
if (index.sk?.field !== undefined) {
|
|
3662
|
+
writers.push({
|
|
3663
|
+
field: index.sk.field,
|
|
3664
|
+
head: undefined,
|
|
3665
|
+
types: rows,
|
|
3666
|
+
table,
|
|
3667
|
+
channel: "its sort key",
|
|
3668
|
+
});
|
|
3669
|
+
}
|
|
3670
|
+
if (e.softDelete !== undefined && e.softDelete !== false) {
|
|
3671
|
+
anyText(["deletedAt"], [own], table, () => "its soft-delete tombstones' `deletedAt`");
|
|
3672
|
+
}
|
|
3673
|
+
if (tombstone !== undefined) {
|
|
3674
|
+
anyText(["__edd_removed__", KEY_TEXT], [tombstone], table, (field) => `its projection tombstones' "${field}"`);
|
|
3675
|
+
}
|
|
3676
|
+
for (const constraint of Object.keys(e.unique ?? {})) {
|
|
3677
|
+
const sentinel = composeUniqueKey(schema, type, constraint, [], {
|
|
3678
|
+
casing: index.casing,
|
|
3679
|
+
}).sk;
|
|
3680
|
+
const rowType = { type: `${type}._unique.${constraint}`, label: sentinel };
|
|
3681
|
+
const channel = `its unique constraint "${constraint}"`;
|
|
3682
|
+
writers.push({
|
|
3683
|
+
field: index.pk.field,
|
|
3684
|
+
head: sentinel,
|
|
3685
|
+
exact: false,
|
|
3686
|
+
types: [rowType],
|
|
3687
|
+
table,
|
|
3688
|
+
channel,
|
|
3689
|
+
});
|
|
3690
|
+
if (index.sk?.field !== undefined) {
|
|
3691
|
+
writers.push({
|
|
3692
|
+
field: index.sk.field,
|
|
3693
|
+
head: sentinel,
|
|
3694
|
+
exact: true,
|
|
3695
|
+
types: [rowType],
|
|
3696
|
+
table,
|
|
3697
|
+
channel,
|
|
3698
|
+
});
|
|
3699
|
+
}
|
|
3700
|
+
// Written after the sentinel's key: one named as a key attribute replaces it.
|
|
3701
|
+
writers.push({
|
|
3702
|
+
field: "_entity_pk",
|
|
3703
|
+
head,
|
|
3704
|
+
exact,
|
|
3705
|
+
types: [rowType],
|
|
3706
|
+
table,
|
|
3707
|
+
channel: `${channel}'s back-pointer "_entity_pk"`,
|
|
3708
|
+
});
|
|
3709
|
+
anyText(["_entity_sk"], [rowType], table, () => `${channel}'s back-pointer "_entity_sk"`);
|
|
3710
|
+
}
|
|
3711
|
+
// Each projection's outbox items: under the row's partition key, on the row table or another.
|
|
3712
|
+
const outboxes = outboxConfigs.map((outbox) => outbox.table === undefined
|
|
3713
|
+
? { on: table, pk: index.pk.field, sk: index.sk?.field, index: outbox.index }
|
|
3714
|
+
: { on: outbox.table.Tag, pk: outbox.pk, sk: outbox.sk, index: outbox.index });
|
|
3715
|
+
for (const outbox of outboxes) {
|
|
3716
|
+
const outboxType = typed(`${type}#outbox`, index.casing);
|
|
3717
|
+
const channel = "its projection outbox";
|
|
3718
|
+
for (const field of [outbox.pk, OUTBOX_ROW_PK]) {
|
|
3719
|
+
writers.push({ field, head, exact, types: [outboxType], table: outbox.on, channel });
|
|
3720
|
+
}
|
|
3721
|
+
anyText([
|
|
3722
|
+
...(outbox.sk === undefined ? [] : [outbox.sk]),
|
|
3723
|
+
OUTBOX_ROW_SK,
|
|
3724
|
+
"effect",
|
|
3725
|
+
"source",
|
|
3726
|
+
"streamId",
|
|
3727
|
+
"eventType",
|
|
3728
|
+
KEY_TEXT,
|
|
3729
|
+
OUTBOX_CLAIM,
|
|
3730
|
+
OUTBOX_CLAIMED_UNTIL,
|
|
3731
|
+
...(outbox.index === undefined ? [] : [outbox.index.pk, outbox.index.sk]),
|
|
3732
|
+
], [outboxType], outbox.on, (field) => `${channel}'s "${field}"`);
|
|
3733
|
+
}
|
|
3734
|
+
}
|
|
3735
|
+
for (const [name, vector] of Object.entries(e._vectorIndexes ?? {})) {
|
|
3736
|
+
writers.push({
|
|
3737
|
+
field: vector.partitionField,
|
|
3738
|
+
head: vector.compose === undefined
|
|
3739
|
+
? composeKey(schema, type, [], { casing: vector.casing })
|
|
3740
|
+
: undefined,
|
|
3741
|
+
types: [typed(type)],
|
|
3742
|
+
table,
|
|
3743
|
+
channel: `its vector index "${name}"`,
|
|
3744
|
+
});
|
|
3745
|
+
}
|
|
3746
|
+
anyText([...stamps, INCARNATION_TOKEN], [typed(type)], table, (field) => `its "${field}"`);
|
|
3747
|
+
// Its model attributes: on its rows, and kept on its projection tombstones. Whatever its model
|
|
3748
|
+
// declares, these are any name holding any text, but the ones it writes after them.
|
|
3749
|
+
writers.push({
|
|
3750
|
+
field: undefined,
|
|
3751
|
+
except: ["__edd_e__", ...tableKeys],
|
|
3752
|
+
head: undefined,
|
|
3753
|
+
types: [typed(type), ...projectionTypes],
|
|
3754
|
+
table,
|
|
3755
|
+
channel: "its model attributes",
|
|
3756
|
+
});
|
|
3757
|
+
return withTypeOverwrites(writers);
|
|
3758
|
+
}
|
|
3759
|
+
catch {
|
|
3760
|
+
return [
|
|
3761
|
+
{
|
|
3762
|
+
field: undefined,
|
|
3763
|
+
head: undefined,
|
|
3764
|
+
types: [{ type, label: type, any: { via: "its keys can't be read" } }],
|
|
3765
|
+
table,
|
|
3766
|
+
channel: "its keys, which can't be read",
|
|
3767
|
+
},
|
|
3768
|
+
];
|
|
3769
|
+
}
|
|
3770
|
+
};
|
|
3771
|
+
/**
|
|
3772
|
+
* The first member that can write a row of one of the aggregate's types into its partition, if
|
|
3773
|
+
* any (DESIGN.md §7 "Which rows in its partition are an aggregate's"): `DynamoClient.make` refuses
|
|
3774
|
+
* an aggregate declaring `ownsRows` for it (`EDD-9130`). A member can when one of its attribute
|
|
3775
|
+
* writers ({@link entityWriters}, an aggregate's own) writes the aggregate's `pk.field` on the same
|
|
3776
|
+
* physical table (`sameTable`), with text that can be the aggregate's partition key
|
|
3777
|
+
* ({@link canBePartitionKey}), on a row whose type collides with one of the aggregate's
|
|
3778
|
+
* ({@link typesCollide}). The aggregate itself isn't one.
|
|
3779
|
+
*/
|
|
3780
|
+
export const ownershipConflict = (aggregate, members, sameTable) => {
|
|
3781
|
+
const ownership = aggregate._ownership;
|
|
3782
|
+
if (ownership === undefined)
|
|
3783
|
+
return undefined;
|
|
3784
|
+
const seen = new Set([aggregate]);
|
|
3785
|
+
for (const { name, member } of [...ownership.declared, ...members]) {
|
|
3786
|
+
if (member === null || typeof member !== "object" || seen.has(member))
|
|
3787
|
+
continue;
|
|
3788
|
+
seen.add(member);
|
|
3789
|
+
const writers = member
|
|
3790
|
+
._attributeWriters ??
|
|
3791
|
+
(member._tag === "Entity" ? entityWriters(member) : []);
|
|
3792
|
+
for (const writer of writers) {
|
|
3793
|
+
if (!sameTable(writer.table))
|
|
3794
|
+
continue;
|
|
3795
|
+
if (writer.field === undefined
|
|
3796
|
+
? writer.except?.includes(ownership.pkField) === true
|
|
3797
|
+
: writer.field !== ownership.pkField) {
|
|
3798
|
+
continue;
|
|
3799
|
+
}
|
|
3800
|
+
if (!canBePartitionKey(writer, ownership))
|
|
3801
|
+
continue;
|
|
3802
|
+
for (const theirs of writer.types) {
|
|
3803
|
+
const ours = ownership.types.find((type) => typesCollide(theirs, type));
|
|
3804
|
+
if (ours === undefined)
|
|
3805
|
+
continue;
|
|
3806
|
+
return theirs.any === undefined
|
|
3807
|
+
? { member: name, type: theirs.type, channel: writer.channel }
|
|
3808
|
+
: { member: name, type: ours.type, channel: `${writer.channel}; ${theirs.any.via}` };
|
|
3809
|
+
}
|
|
3810
|
+
}
|
|
3811
|
+
}
|
|
3812
|
+
return undefined;
|
|
3813
|
+
};
|
|
2370
3814
|
/** A sort key value in the text of the setting `schema` isn't using. */
|
|
2371
3815
|
const otherKeyText = (schema, value) => KeyComposer.keyValueText(schema.escapeKeys === true ? KeyText136.schema136(schema) : KeyText136.schemaEscaped(schema), value, schema.casing);
|
|
2372
3816
|
/** A decomposed row's sort key under the other setting; `sk`, if a value has no text there. */
|
|
@@ -2395,7 +3839,9 @@ const ownDiscriminatorValues = (node, schema) => {
|
|
|
2395
3839
|
*/
|
|
2396
3840
|
const decomposeNode = (items, node, value, contextValues, parentGroup,
|
|
2397
3841
|
/** The parent's discriminator values, in today's text and in 1.36's (#171). */
|
|
2398
|
-
parentDiscriminators, aggregateName, schema
|
|
3842
|
+
parentDiscriminators, aggregateName, schema,
|
|
3843
|
+
/** The caller's own value here, on a write (see {@link Written}). */
|
|
3844
|
+
written) => Effect.gen(function* () {
|
|
2399
3845
|
// Optional edges may have null/undefined values — skip decomposition
|
|
2400
3846
|
if (value == null)
|
|
2401
3847
|
return;
|
|
@@ -2423,7 +3869,7 @@ parentDiscriminators, aggregateName, schema) => Effect.gen(function* () {
|
|
|
2423
3869
|
subRootAttrs[key] = val;
|
|
2424
3870
|
}
|
|
2425
3871
|
// Serialize this node's own date fields to their wire primitive (#72).
|
|
2426
|
-
applyNodeAttrEncoders(subRootAttrs, node.attrEncoders);
|
|
3872
|
+
const storedAsGiven = applyNodeAttrEncoders(subRootAttrs, node.attrEncoders);
|
|
2427
3873
|
// Inject context and discriminator
|
|
2428
3874
|
mergeContextValues(subRootAttrs, contextValues.stored);
|
|
2429
3875
|
if (node.discriminator) {
|
|
@@ -2439,18 +3885,21 @@ parentDiscriminators, aggregateName, schema) => Effect.gen(function* () {
|
|
|
2439
3885
|
skComposites: discValues.current,
|
|
2440
3886
|
skCompositesOther: discValues.other,
|
|
2441
3887
|
member: node.fieldName ?? node.entityType,
|
|
3888
|
+
rowStamps: node.rowStamps,
|
|
3889
|
+
storedAsGiven,
|
|
3890
|
+
node,
|
|
2442
3891
|
});
|
|
2443
3892
|
// Decompose children within this sub-aggregate
|
|
2444
3893
|
for (const child of node.children) {
|
|
2445
3894
|
const childValue = subValue[child.fieldName];
|
|
2446
|
-
yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, schema);
|
|
3895
|
+
yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, schema, writtenField(written, child.fieldName));
|
|
2447
3896
|
}
|
|
2448
3897
|
}
|
|
2449
3898
|
else if (node.cardinality === "one") {
|
|
2450
3899
|
// Simple one-to-one edge (no children)
|
|
2451
3900
|
const attrs = { ...value };
|
|
2452
3901
|
// Serialize this edge entity's own date fields to their wire primitive (#72).
|
|
2453
|
-
applyNodeAttrEncoders(attrs, node.attrEncoders);
|
|
3902
|
+
const storedAsGiven = applyNodeAttrEncoders(attrs, node.attrEncoders);
|
|
2454
3903
|
mergeContextValues(attrs, contextValues.stored);
|
|
2455
3904
|
if (node.discriminator) {
|
|
2456
3905
|
for (const [k, v] of Object.entries(node.discriminator)) {
|
|
@@ -2467,12 +3916,18 @@ parentDiscriminators, aggregateName, schema) => Effect.gen(function* () {
|
|
|
2467
3916
|
skComposites: [...parentDiscriminators.current, ...own.current],
|
|
2468
3917
|
skCompositesOther: () => [...parentDiscriminators.other(), ...own.other()],
|
|
2469
3918
|
member: node.fieldName ?? node.entityType,
|
|
3919
|
+
rowStamps: node.rowStamps,
|
|
3920
|
+
storedAsGiven,
|
|
3921
|
+
node,
|
|
2470
3922
|
});
|
|
2471
3923
|
}
|
|
2472
3924
|
else {
|
|
2473
3925
|
// Many edge
|
|
3926
|
+
const handed = written === undefined || node.decomposeInput === undefined
|
|
3927
|
+
? value
|
|
3928
|
+
: Option.getOrElse(node.decomposeInput(written), () => value);
|
|
2474
3929
|
const arrayItems = node.decompose
|
|
2475
|
-
? node.decompose(
|
|
3930
|
+
? node.decompose(handed)
|
|
2476
3931
|
: Array.isArray(value)
|
|
2477
3932
|
? value
|
|
2478
3933
|
: [];
|
|
@@ -2490,7 +3945,7 @@ parentDiscriminators, aggregateName, schema) => Effect.gen(function* () {
|
|
|
2490
3945
|
// The element's attributes in their STORED form — every nested date,
|
|
2491
3946
|
// transformed scalar and hydrated ref encoded (#72, #133).
|
|
2492
3947
|
const attrs = { ...elem };
|
|
2493
|
-
applyNodeAttrEncoders(attrs, node.attrEncoders);
|
|
3948
|
+
const storedAsGiven = applyNodeAttrEncoders(attrs, node.attrEncoders);
|
|
2494
3949
|
withContext(attrs, contextValues.stored);
|
|
2495
3950
|
// The sort key is read from the element as the pre-#133 encoders left
|
|
2496
3951
|
// it, NOT from `attrs`: encoding a ref's nested `NumberFromString` turns
|
|
@@ -2512,7 +3967,48 @@ parentDiscriminators, aggregateName, schema) => Effect.gen(function* () {
|
|
|
2512
3967
|
...parentDiscriminators.other(),
|
|
2513
3968
|
...values.map((value) => otherKeyText(schema, value)),
|
|
2514
3969
|
],
|
|
3970
|
+
otherKindSortKey: (targets) => {
|
|
3971
|
+
const slots = values.map((_, i) => String(i));
|
|
3972
|
+
const settings = [
|
|
3973
|
+
[
|
|
3974
|
+
() => parentDiscriminators.current,
|
|
3975
|
+
(value) => KeyComposer.keyValueText(schema, value, schema.casing),
|
|
3976
|
+
],
|
|
3977
|
+
[() => parentDiscriminators.other(), (value) => otherKeyText(schema, value)],
|
|
3978
|
+
];
|
|
3979
|
+
for (const [parents, text] of settings) {
|
|
3980
|
+
const sortKey = (record) => composeKey(schema, node.entityType, [
|
|
3981
|
+
...parents(),
|
|
3982
|
+
...slots.map((slot) => text(record[slot])),
|
|
3983
|
+
]);
|
|
3984
|
+
const reading = kindReadingOf({ ...values }, slots, () => undefined, ({ record }) => sortKey(record), targets);
|
|
3985
|
+
if (reading !== undefined && reading.asOther.size > 0)
|
|
3986
|
+
return sortKey(reading.record);
|
|
3987
|
+
}
|
|
3988
|
+
return undefined;
|
|
3989
|
+
},
|
|
3990
|
+
skTextFor: (taker, path) => {
|
|
3991
|
+
try {
|
|
3992
|
+
let from = keyAttrs;
|
|
3993
|
+
if (taker !== node) {
|
|
3994
|
+
from = { ...elem };
|
|
3995
|
+
applyNodeAttrEncoders(from, taker.keyAttrEncoders);
|
|
3996
|
+
mergeContextValues(from, contextValues.key);
|
|
3997
|
+
}
|
|
3998
|
+
const value = readCompositePath(from, path);
|
|
3999
|
+
return value == null || !isScalarComposite(value)
|
|
4000
|
+
? undefined
|
|
4001
|
+
: KeyComposer.keyValueText(schema, value, schema.casing);
|
|
4002
|
+
}
|
|
4003
|
+
catch {
|
|
4004
|
+
// What `taker` can't compose a key from isn't a key it writes.
|
|
4005
|
+
return undefined;
|
|
4006
|
+
}
|
|
4007
|
+
},
|
|
2515
4008
|
member: node.fieldName ?? node.entityType,
|
|
4009
|
+
rowStamps: node.rowStamps,
|
|
4010
|
+
storedAsGiven,
|
|
4011
|
+
node,
|
|
2516
4012
|
});
|
|
2517
4013
|
}
|
|
2518
4014
|
}
|
|
@@ -2598,7 +4094,8 @@ const manyEdgeSkComposites = (node, attrs, aggregateName) => Effect.gen(function
|
|
|
2598
4094
|
`attribute itself by dotted path (e.g. "umpire.id", not "umpire").`,
|
|
2599
4095
|
});
|
|
2600
4096
|
}
|
|
2601
|
-
|
|
4097
|
+
// A number its field stores as a string holds its `NaN` in key form, as the root's key does.
|
|
4098
|
+
return values.map((value, i) => storedNaNKeyForm(fieldAtPath(node.ownFields, declared[i]), value));
|
|
2602
4099
|
});
|
|
2603
4100
|
/**
|
|
2604
4101
|
* Extract ref identifier values from an item's attributes for use as SK composites.
|
|
@@ -2651,7 +4148,86 @@ const hashToShard = (value, cardinality) => {
|
|
|
2651
4148
|
}
|
|
2652
4149
|
return Math.abs(hash) % cardinality;
|
|
2653
4150
|
};
|
|
4151
|
+
/**
|
|
4152
|
+
* A `many` value's rows, each through `fill`, put back in the shape the value has. A custom
|
|
4153
|
+
* `decompose` says what the rows are, and only its `assemble` can put them back: with no `assemble`,
|
|
4154
|
+
* a value that isn't an array has no way back, so its rows can't be filled. This runs before the
|
|
4155
|
+
* input is decoded, so a value they can't take apart or put back is left for the schema to report.
|
|
4156
|
+
*/
|
|
4157
|
+
const fillRows = (child, value, fill) => {
|
|
4158
|
+
const filledOf = (rows) => {
|
|
4159
|
+
const filled = rows.map(fill);
|
|
4160
|
+
return filled.some((row, i) => row !== rows[i]) ? filled : undefined;
|
|
4161
|
+
};
|
|
4162
|
+
if (child.decompose !== undefined && child.assemble !== undefined) {
|
|
4163
|
+
try {
|
|
4164
|
+
const filled = value === undefined ? undefined : filledOf(child.decompose(value));
|
|
4165
|
+
return filled === undefined ? value : child.assemble(filled);
|
|
4166
|
+
}
|
|
4167
|
+
catch {
|
|
4168
|
+
return value;
|
|
4169
|
+
}
|
|
4170
|
+
}
|
|
4171
|
+
return Array.isArray(value) ? (filledOf(value) ?? value) : value;
|
|
4172
|
+
};
|
|
4173
|
+
/**
|
|
4174
|
+
* `value` with the dates its rows declare, walking the graph. `"declared"` (`create`) stamps every one
|
|
4175
|
+
* the input lacks, and one it holds unless the root declares that date `Schema.optional` (`replaces`):
|
|
4176
|
+
* up to 1.39.0 the input had to hold a date the root required, which the stamp then replaced, so a
|
|
4177
|
+
* value there is a placeholder; 1.39.0 stamped one the root declares `Schema.optionalKey` over a value
|
|
4178
|
+
* passed, and one it declares `Schema.optional` was the caller's to store. `"required"`
|
|
4179
|
+
* (`update`) fills only one the mutated state lacks and a schema requires; one it doesn't require a
|
|
4180
|
+
* rewrite stamps anyway: a mutation that changes nothing still has nothing to write. A value with
|
|
4181
|
+
* nothing to add comes back as it is.
|
|
4182
|
+
*/
|
|
4183
|
+
const fillStamps = (node, value, now, which) => {
|
|
4184
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
4185
|
+
return value;
|
|
4186
|
+
const given = value;
|
|
4187
|
+
const added = {};
|
|
4188
|
+
const row = node.rowStamps;
|
|
4189
|
+
const fill = (name, declared, required, replaces, encoding) => {
|
|
4190
|
+
if (name === null || (given[name] !== undefined && (which === "required" || !replaces)))
|
|
4191
|
+
return;
|
|
4192
|
+
if (which === "declared" ? declared : required) {
|
|
4193
|
+
added[name] = generateTimestampPrimitive(now, encoding);
|
|
4194
|
+
}
|
|
4195
|
+
};
|
|
4196
|
+
if (row !== undefined) {
|
|
4197
|
+
fill(row.createdAt, row.createdDeclared, row.createdRequired, row.createdReplaces, row.createdEncoding);
|
|
4198
|
+
fill(row.updatedAt, row.updatedDeclared, row.updatedRequired, row.updatedReplaces, row.updatedEncoding);
|
|
4199
|
+
}
|
|
4200
|
+
for (const child of node.children) {
|
|
4201
|
+
const current = given[child.fieldName];
|
|
4202
|
+
const next = child.cardinality === "many"
|
|
4203
|
+
? fillRows(child, current, (row) => fillStamps(child, row, now, which))
|
|
4204
|
+
: fillStamps(child, current, now, which);
|
|
4205
|
+
if (next !== current)
|
|
4206
|
+
added[child.fieldName] = next;
|
|
4207
|
+
}
|
|
4208
|
+
return Object.keys(added).length === 0 ? value : { ...given, ...added };
|
|
4209
|
+
};
|
|
4210
|
+
/**
|
|
4211
|
+
* A key's composites, in key text. One with no value has no key text, so this throws: `[EDD-9123]`,
|
|
4212
|
+
* a `KeyValueError` that `composeKeysOrFail` makes a `ValidationError` before anything is written.
|
|
4213
|
+
* Only for a key the aggregate can't do without: a list's keys are sparse (`buildDynamoItems`).
|
|
4214
|
+
*/
|
|
4215
|
+
const keyCompositesOrThrow = (aggregateName, key, schema, composite, record) => {
|
|
4216
|
+
const absent = composite.filter((attr) => record[attr] === undefined || record[attr] === null);
|
|
4217
|
+
if (absent.length > 0) {
|
|
4218
|
+
const names = absent.map((attr) => `"${attr}"`).join(", ");
|
|
4219
|
+
throw new KeyValueError({
|
|
4220
|
+
value: undefined,
|
|
4221
|
+
reason: `no value for ${names}`,
|
|
4222
|
+
message: `[EDD-9123] Aggregate "${aggregateName}": ${key} is composed from ${names}, which has no ` +
|
|
4223
|
+
`value here. An aggregate can't be read without this key, so nothing was sent. Supply it, ` +
|
|
4224
|
+
`or compose the key from a field that always has one.`,
|
|
4225
|
+
});
|
|
4226
|
+
}
|
|
4227
|
+
return KeyComposer.extractKeyComposites(schema, {}, composite, record);
|
|
4228
|
+
};
|
|
2654
4229
|
const EMPTY_CREATED = new Map();
|
|
4230
|
+
const hasKeyValue = (value) => value !== undefined && value !== null;
|
|
2655
4231
|
/**
|
|
2656
4232
|
* Convert decomposed items into DynamoDB attribute maps with composed keys.
|
|
2657
4233
|
*
|
|
@@ -2661,7 +4237,12 @@ const EMPTY_CREATED = new Map();
|
|
|
2661
4237
|
* on every comparison and silently collapse the diff into a full-partition
|
|
2662
4238
|
* rewrite on every update (#98).
|
|
2663
4239
|
*/
|
|
2664
|
-
const buildDynamoItems = (groups, config, pkValue,
|
|
4240
|
+
const buildDynamoItems = (groups, config, pkValue,
|
|
4241
|
+
/**
|
|
4242
|
+
* The root's value, the collection sort key's composites read from. Undefined: the caller wants
|
|
4243
|
+
* each row's identity (`pk`, `sk`) only, and neither that key nor the list keys are composed.
|
|
4244
|
+
*/
|
|
4245
|
+
rootValue,
|
|
2665
4246
|
/**
|
|
2666
4247
|
* The aggregate's composite key-form normaliser. Required, not optional: the
|
|
2667
4248
|
* list-GSI keys composed below have to be spelled exactly as `Aggregate.list`
|
|
@@ -2678,49 +4259,70 @@ keyRecord, stamp) => groups.map((group) => ({
|
|
|
2678
4259
|
attrs[config.pk.field] = pkValue;
|
|
2679
4260
|
// SK: entity-type specific
|
|
2680
4261
|
attrs.sk = composeKey(config.schema, item.entityType, [...item.skComposites]);
|
|
4262
|
+
// System timestamps. Written last, so a generated value wins over the same-named field
|
|
4263
|
+
// propagated onto edge items via `context`; known first, so a key over one holds what the row
|
|
4264
|
+
// holds. A date the row declares holds what the row does: on `create` the stamp `fillStamps`
|
|
4265
|
+
// put there, on `update` a value the mutation changed, and `created` stays what's stored
|
|
4266
|
+
// whatever the mutation did to it.
|
|
4267
|
+
const stamped = {};
|
|
4268
|
+
const row = item.rowStamps;
|
|
4269
|
+
if (stamp && row !== undefined) {
|
|
4270
|
+
const { existingCreated, now } = stamp;
|
|
4271
|
+
const sk = attrs.sk;
|
|
4272
|
+
if (row.createdAt !== null) {
|
|
4273
|
+
const held = row.createdDeclared ? item.attributes[row.createdAt] : undefined;
|
|
4274
|
+
stamped[row.createdAt] =
|
|
4275
|
+
existingCreated.get(sk) ?? held ?? generateTimestampPrimitive(now, row.createdStored);
|
|
4276
|
+
}
|
|
4277
|
+
if (row.updatedAt !== null) {
|
|
4278
|
+
const held = row.updatedDeclared ? item.attributes[row.updatedAt] : undefined;
|
|
4279
|
+
const before = stamp.updatedBefore;
|
|
4280
|
+
const supplied = held !== undefined && !(before?.has(sk) && deepEqual(before.get(sk), held));
|
|
4281
|
+
stamped[row.updatedAt] =
|
|
4282
|
+
stamp.existingUpdated?.get(sk) ??
|
|
4283
|
+
(supplied ? held : generateTimestampPrimitive(now, row.updatedStored));
|
|
4284
|
+
}
|
|
4285
|
+
}
|
|
2681
4286
|
// Collection SK mirror — only written when an index is actually provisioned.
|
|
2682
4287
|
// Root items get the collection key; every other item's value is a verbatim copy
|
|
2683
4288
|
// of its own `sk`. With no index there is nothing to sort, so the attribute is
|
|
2684
4289
|
// omitted entirely rather than duplicating `sk` on every item.
|
|
2685
4290
|
const isRootItem = item.entityType === config.root.entityType && item.skComposites.length === 0;
|
|
2686
4291
|
const collectionSk = config.collection.sk;
|
|
2687
|
-
if (
|
|
4292
|
+
if (rootValue !== undefined &&
|
|
4293
|
+
config.collection.index !== undefined &&
|
|
4294
|
+
collectionSk !== undefined) {
|
|
2688
4295
|
attrs[collectionSk.field] = isRootItem
|
|
2689
|
-
? composeCollectionKey(config.schema, config.collection.name,
|
|
4296
|
+
? composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(config.root.entityType, "its collection sort key", config.schema, collectionSk.composite, keyRecord({ ...rootValue, ...stamped })))
|
|
2690
4297
|
: composeKey(config.schema, item.entityType, [...item.skComposites]);
|
|
2691
4298
|
}
|
|
2692
|
-
// List collection GSI keys (root items only)
|
|
2693
|
-
|
|
2694
|
-
|
|
2695
|
-
|
|
2696
|
-
|
|
2697
|
-
|
|
2698
|
-
|
|
2699
|
-
|
|
2700
|
-
|
|
2701
|
-
|
|
2702
|
-
|
|
2703
|
-
|
|
2704
|
-
|
|
2705
|
-
|
|
2706
|
-
|
|
2707
|
-
|
|
2708
|
-
|
|
2709
|
-
|
|
2710
|
-
|
|
2711
|
-
|
|
2712
|
-
|
|
2713
|
-
|
|
2714
|
-
const
|
|
2715
|
-
attrs[
|
|
2716
|
-
}
|
|
2717
|
-
if (fields.updatedAt !== null) {
|
|
2718
|
-
attrs[fields.updatedAt] =
|
|
2719
|
-
stamp.existingUpdated?.get(sk) ??
|
|
2720
|
-
generateTimestampPrimitive(now, fields.updatedEncoding);
|
|
4299
|
+
// List collection GSI keys (root items only). Sparse, as an entity index is: a row with no
|
|
4300
|
+
// value for a composite isn't in the list, whole index or nothing, and a later write that
|
|
4301
|
+
// gives it one puts it there. Every aggregate write is a whole-row Put, so leaving both
|
|
4302
|
+
// attributes off is also what takes it out.
|
|
4303
|
+
if (rootValue !== undefined && isRootItem && config.list) {
|
|
4304
|
+
const listKeyValues = keyRecord({
|
|
4305
|
+
...(item.keyAttributes ?? item.attributes),
|
|
4306
|
+
...stamped,
|
|
4307
|
+
});
|
|
4308
|
+
const listComposites = [...config.list.pk.composite, ...config.list.sk.composite];
|
|
4309
|
+
if (listComposites.every((attr) => hasKeyValue(listKeyValues[attr]))) {
|
|
4310
|
+
const listPkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.list.pk.composite, listKeyValues);
|
|
4311
|
+
if (config.list.cardinality) {
|
|
4312
|
+
const shard = hashToShard(pkValue, config.list.cardinality);
|
|
4313
|
+
attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, [
|
|
4314
|
+
...listPkComposites,
|
|
4315
|
+
String(shard),
|
|
4316
|
+
]);
|
|
4317
|
+
}
|
|
4318
|
+
else {
|
|
4319
|
+
attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, listPkComposites);
|
|
4320
|
+
}
|
|
4321
|
+
const listSkComposites = KeyComposer.extractKeyComposites(config.schema, {}, config.list.sk.composite, listKeyValues);
|
|
4322
|
+
attrs[config.list.sk.field] = composeCollectionKey(config.schema, config.list.name, listSkComposites);
|
|
2721
4323
|
}
|
|
2722
4324
|
}
|
|
2723
|
-
return toAttributeMap(attrs);
|
|
4325
|
+
return toAttributeMap({ ...attrs, ...stamped });
|
|
2724
4326
|
}),
|
|
2725
4327
|
}));
|
|
2726
4328
|
function writeTransactionGroups(client, tableName, groups, aggregateName, keys, rootGuard) {
|
|
@@ -2828,11 +4430,50 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
|
|
|
2828
4430
|
}
|
|
2829
4431
|
});
|
|
2830
4432
|
}
|
|
2831
|
-
|
|
2832
|
-
|
|
2833
|
-
|
|
2834
|
-
|
|
2835
|
-
|
|
4433
|
+
/**
|
|
4434
|
+
* `update`'s cleanup Deletes with `ownsRows` (DESIGN.md §7 "Which rows in its partition are an
|
|
4435
|
+
* aggregate's"), sent after the update's groups have committed, up to {@link TRANSACT_WRITE_ITEMS_LIMIT} to a
|
|
4436
|
+
* request: Deletes of keys already stored reach no other limit of a transaction. Each holds while
|
|
4437
|
+
* its row is gone or still of the type read, so a row another write removed in between is fine,
|
|
4438
|
+
* and one replaced with a row of another type is left. A cancelled request is sent once more
|
|
4439
|
+
* without the Deletes whose condition failed; the mutation isn't run again and nothing is read
|
|
4440
|
+
* again. A failure is reported as a later group's is: the update's groups have committed, and the
|
|
4441
|
+
* rows it didn't delete stay until the next update of their node.
|
|
4442
|
+
*/
|
|
4443
|
+
const deleteOwnedRows = (client, tableName, pkField, rows) => Effect.gen(function* () {
|
|
4444
|
+
const deleteOf = (row) => ({
|
|
4445
|
+
Delete: {
|
|
4446
|
+
TableName: tableName,
|
|
4447
|
+
Key: toAttributeMap({ [pkField]: row.pk, sk: row.sk }),
|
|
4448
|
+
ConditionExpression: "attribute_not_exists(#pk) OR #e = :e",
|
|
4449
|
+
ExpressionAttributeNames: { "#pk": pkField, "#e": "__edd_e__" },
|
|
4450
|
+
ExpressionAttributeValues: { ":e": { S: row.entityType } },
|
|
4451
|
+
},
|
|
4452
|
+
});
|
|
4453
|
+
for (let start = 0; start < rows.length; start += TRANSACT_WRITE_ITEMS_LIMIT) {
|
|
4454
|
+
const chunk = rows.slice(start, start + TRANSACT_WRITE_ITEMS_LIMIT);
|
|
4455
|
+
const reasons = yield* client
|
|
4456
|
+
.transactWriteItems({ TransactItems: chunk.map((row) => deleteOf(row)) })
|
|
4457
|
+
.pipe(Effect.as(undefined), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
|
|
4458
|
+
? Effect.succeed(error.cause.CancellationReasons ?? [])
|
|
4459
|
+
: Effect.fail(error)));
|
|
4460
|
+
if (reasons === undefined)
|
|
4461
|
+
continue;
|
|
4462
|
+
const rest = chunk.filter((_, i) => reasons[i]?.Code !== "ConditionalCheckFailed");
|
|
4463
|
+
if (rest.length === 0)
|
|
4464
|
+
continue;
|
|
4465
|
+
yield* client.transactWriteItems({ TransactItems: rest.map((row) => deleteOf(row)) }).pipe(Effect.mapError((error) => isAwsTransactionCancelled(error.cause)
|
|
4466
|
+
? new TransactionCancelled({
|
|
4467
|
+
operation: "TransactWriteItems",
|
|
4468
|
+
reasons: (error.cause.CancellationReasons ?? []).map((r) => ({
|
|
4469
|
+
code: r?.Code,
|
|
4470
|
+
message: r?.Message,
|
|
4471
|
+
})),
|
|
4472
|
+
cause: error.cause,
|
|
4473
|
+
})
|
|
4474
|
+
: error));
|
|
4475
|
+
}
|
|
4476
|
+
});
|
|
2836
4477
|
/**
|
|
2837
4478
|
* Place an aggregate's rows from the keys that hold a row (#171). Each row has
|
|
2838
4479
|
* a `current` and an `old` position. Off doesn't escape sort key text,
|
|
@@ -2898,7 +4539,8 @@ const deleteAllItems = (client, tableName, allItems, pkField) => Effect.gen(func
|
|
|
2898
4539
|
// Chunk into batches of 25 (DynamoDB batchWriteItem limit). Items DynamoDB
|
|
2899
4540
|
// leaves unprocessed (throttling) are retried with exponential backoff, as
|
|
2900
4541
|
// `Batch.write` retries them; a bounded number of retries, then a clear
|
|
2901
|
-
// failure — never a silent partial delete (#134).
|
|
4542
|
+
// failure — never a silent partial delete (#134). By count alone: 25 stored keys (at most
|
|
4543
|
+
// 2048 + 1024 bytes each, so at most about 0.5 MB as JSON) can't reach the 16 MB request limit.
|
|
2902
4544
|
for (let i = 0; i < deleteRequests.length; i += 25) {
|
|
2903
4545
|
let pending = deleteRequests.slice(i, i + 25);
|
|
2904
4546
|
let retries = 0;
|