effect-dynamodb 1.40.0 → 1.41.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/README.md +1 -1
- package/dist/Aggregate.d.ts +19 -1
- package/dist/Aggregate.d.ts.map +1 -1
- package/dist/Aggregate.js +2387 -456
- package/dist/Aggregate.js.map +1 -1
- package/dist/Collection.d.ts.map +1 -1
- package/dist/Collection.js +4 -4
- package/dist/Collection.js.map +1 -1
- package/dist/DynamoClient.d.ts +25 -16
- package/dist/DynamoClient.d.ts.map +1 -1
- package/dist/DynamoClient.js +131 -69
- package/dist/DynamoClient.js.map +1 -1
- package/dist/Entity.d.ts +164 -24
- package/dist/Entity.d.ts.map +1 -1
- package/dist/Entity.js +4276 -860
- package/dist/Entity.js.map +1 -1
- package/dist/EventStore.d.ts.map +1 -1
- package/dist/EventStore.js +189 -85
- package/dist/EventStore.js.map +1 -1
- package/dist/Expression.d.ts.map +1 -1
- package/dist/Expression.js +40 -24
- package/dist/Expression.js.map +1 -1
- package/dist/Marshaller.d.ts +38 -7
- package/dist/Marshaller.d.ts.map +1 -1
- package/dist/Marshaller.js +265 -62
- package/dist/Marshaller.js.map +1 -1
- package/dist/Query.d.ts +80 -5
- package/dist/Query.d.ts.map +1 -1
- package/dist/Query.js +214 -13
- package/dist/Query.js.map +1 -1
- package/dist/Table.d.ts +275 -14
- package/dist/Table.d.ts.map +1 -1
- package/dist/Table.js +30 -2
- package/dist/Table.js.map +1 -1
- package/dist/Transaction.d.ts.map +1 -1
- package/dist/Transaction.js +60 -3
- package/dist/Transaction.js.map +1 -1
- package/dist/VectorSearchEmulation.d.ts.map +1 -1
- package/dist/VectorSearchEmulation.js +4 -3
- package/dist/VectorSearchEmulation.js.map +1 -1
- package/dist/change-feed/DynamoStreamsClient.d.ts +8 -6
- package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
- package/dist/change-feed/DynamoStreamsClient.js +11 -7
- package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/BoundCrud.d.ts +39 -1
- package/dist/internal/BoundCrud.d.ts.map +1 -1
- package/dist/internal/BoundCrud.js +25 -0
- package/dist/internal/BoundCrud.js.map +1 -1
- package/dist/internal/BoundQuery.d.ts +46 -3
- package/dist/internal/BoundQuery.d.ts.map +1 -1
- package/dist/internal/BoundQuery.js +383 -28
- package/dist/internal/BoundQuery.js.map +1 -1
- package/dist/internal/BoundVectorQuery.d.ts +6 -0
- package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
- package/dist/internal/BoundVectorQuery.js +6 -4
- package/dist/internal/BoundVectorQuery.js.map +1 -1
- package/dist/internal/Capacity.d.ts +2 -1
- package/dist/internal/Capacity.d.ts.map +1 -1
- package/dist/internal/Capacity.js +89 -12
- package/dist/internal/Capacity.js.map +1 -1
- package/dist/internal/ClientOptions.d.ts +72 -0
- package/dist/internal/ClientOptions.d.ts.map +1 -1
- package/dist/internal/ClientOptions.js +212 -1
- package/dist/internal/ClientOptions.js.map +1 -1
- package/dist/internal/ConditionHolds.d.ts +29 -0
- package/dist/internal/ConditionHolds.d.ts.map +1 -0
- package/dist/internal/ConditionHolds.js +453 -0
- package/dist/internal/ConditionHolds.js.map +1 -0
- package/dist/internal/Digest.d.ts +20 -0
- package/dist/internal/Digest.d.ts.map +1 -0
- package/dist/internal/Digest.js +106 -0
- package/dist/internal/Digest.js.map +1 -0
- package/dist/internal/DynamoArithmetic.d.ts +33 -0
- package/dist/internal/DynamoArithmetic.d.ts.map +1 -0
- package/dist/internal/DynamoArithmetic.js +112 -0
- package/dist/internal/DynamoArithmetic.js.map +1 -0
- package/dist/internal/EntityCombinators.d.ts +2 -2
- package/dist/internal/EntityCombinators.d.ts.map +1 -1
- package/dist/internal/EntityCombinators.js.map +1 -1
- package/dist/internal/EntityOps.d.ts +58 -7
- package/dist/internal/EntityOps.d.ts.map +1 -1
- package/dist/internal/EntityOps.js.map +1 -1
- package/dist/internal/EventProjection.d.ts +3 -1
- package/dist/internal/EventProjection.d.ts.map +1 -1
- package/dist/internal/EventProjection.js +9 -0
- package/dist/internal/EventProjection.js.map +1 -1
- package/dist/internal/Expr.d.ts +72 -2
- package/dist/internal/Expr.d.ts.map +1 -1
- package/dist/internal/Expr.js +211 -3
- package/dist/internal/Expr.js.map +1 -1
- package/dist/internal/ExpressionLimits.d.ts.map +1 -1
- package/dist/internal/ExpressionLimits.js +10 -6
- package/dist/internal/ExpressionLimits.js.map +1 -1
- package/dist/internal/FormGuard.d.ts +52 -0
- package/dist/internal/FormGuard.d.ts.map +1 -0
- package/dist/internal/FormGuard.js +83 -0
- package/dist/internal/FormGuard.js.map +1 -0
- package/dist/internal/Hydrate.d.ts.map +1 -1
- package/dist/internal/Hydrate.js +2 -1
- package/dist/internal/Hydrate.js.map +1 -1
- package/dist/internal/InputForm.d.ts +24 -0
- package/dist/internal/InputForm.d.ts.map +1 -0
- package/dist/internal/InputForm.js +44 -0
- package/dist/internal/InputForm.js.map +1 -0
- package/dist/internal/InsertStatement.d.ts +15 -0
- package/dist/internal/InsertStatement.d.ts.map +1 -0
- package/dist/internal/InsertStatement.js +18 -0
- package/dist/internal/InsertStatement.js.map +1 -0
- package/dist/internal/MultiProjection.d.ts.map +1 -1
- package/dist/internal/MultiProjection.js +9 -9
- package/dist/internal/MultiProjection.js.map +1 -1
- package/dist/internal/OperandReaders.d.ts +36 -0
- package/dist/internal/OperandReaders.d.ts.map +1 -0
- package/dist/internal/OperandReaders.js +176 -0
- package/dist/internal/OperandReaders.js.map +1 -0
- package/dist/internal/Packed.d.ts.map +1 -1
- package/dist/internal/Packed.js +11 -10
- package/dist/internal/Packed.js.map +1 -1
- package/dist/internal/PathBuilder.d.ts +49 -11
- package/dist/internal/PathBuilder.d.ts.map +1 -1
- package/dist/internal/PathBuilder.js +88 -24
- package/dist/internal/PathBuilder.js.map +1 -1
- package/dist/internal/ProjectionEngine.d.ts +135 -16
- package/dist/internal/ProjectionEngine.d.ts.map +1 -1
- package/dist/internal/ProjectionEngine.js +961 -126
- package/dist/internal/ProjectionEngine.js.map +1 -1
- package/dist/internal/Rekey.d.ts +167 -21
- package/dist/internal/Rekey.d.ts.map +1 -1
- package/dist/internal/Rekey.js +1283 -64
- package/dist/internal/Rekey.js.map +1 -1
- package/dist/internal/ReturnedItem.d.ts +23 -0
- package/dist/internal/ReturnedItem.d.ts.map +1 -0
- package/dist/internal/ReturnedItem.js +39 -0
- package/dist/internal/ReturnedItem.js.map +1 -0
- package/dist/internal/RoundTrip.d.ts +17 -8
- package/dist/internal/RoundTrip.d.ts.map +1 -1
- package/dist/internal/RoundTrip.js +41 -14
- package/dist/internal/RoundTrip.js.map +1 -1
- package/dist/internal/TransactPlan.d.ts.map +1 -1
- package/dist/internal/TransactPlan.js +4 -0
- package/dist/internal/TransactPlan.js.map +1 -1
- package/dist/internal/TransactWriteOps.d.ts +2 -1
- package/dist/internal/TransactWriteOps.d.ts.map +1 -1
- package/dist/internal/TransactWriteOps.js +22 -5
- package/dist/internal/TransactWriteOps.js.map +1 -1
- package/dist/internal/TransactableOps.d.ts +116 -5
- package/dist/internal/TransactableOps.d.ts.map +1 -1
- package/dist/internal/TransactableOps.js +318 -25
- package/dist/internal/TransactableOps.js.map +1 -1
- package/dist/internal/WriteDiagnosis.d.ts +35 -0
- package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
- package/dist/internal/WriteDiagnosis.js +133 -4
- package/dist/internal/WriteDiagnosis.js.map +1 -1
- package/package.json +5 -5
package/dist/Aggregate.js
CHANGED
|
@@ -13,36 +13,43 @@ import * as DynamoModel from "@effect-dynamodb/schema/DynamoModel.js";
|
|
|
13
13
|
import { composeCollectionKey, composeKey, composeUniqueKey, KEY_DELIMITER, } from "@effect-dynamodb/schema/DynamoSchema.js";
|
|
14
14
|
import { AggregateAssemblyError, AggregateDecompositionError, AggregateTransactionOverflow, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, RefNotFound, TRANSACT_WRITE_ITEMS_LIMIT, TransactionCancelled, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
|
|
15
15
|
import { fieldAtPath, kindReadingOf, kindTargets, makeCompositeKeyForm, readBackAs, readBackUnsure, readsBackOtherwise, refuseInexact, storedNaNKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
|
|
16
|
-
import { buildDateTransform, containsWireTransform, matchDateRepresentation, optionalField, resolveSystemFields, substituteSchemaDeep, validateNoTransformOverride, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
|
|
16
|
+
import { buildDateTransform, containedKindOf, containedOperand, containsWireTransform, matchDateRepresentation, optionalField, refHeldTarget, resolveSystemFields, substituteSchemaDeep, validateNoTransformOverride, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
|
|
17
17
|
import { failingAsBefore, issueDecoding } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
|
|
18
18
|
import { readingInstances } from "@effect-dynamodb/schema/internal/InstanceReads.js";
|
|
19
|
+
import { keyReadings } from "@effect-dynamodb/schema/internal/KeyReadings.js";
|
|
19
20
|
import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
|
|
21
|
+
import { lostIn } from "@effect-dynamodb/schema/internal/LostValues.js";
|
|
20
22
|
import { KeyValueError } from "@effect-dynamodb/schema/internal/NumericKey.js";
|
|
23
|
+
import { declaredCopy, givenEntry, given as givenValue, hasOwnName, ownValue, setOwn, } from "@effect-dynamodb/schema/internal/OwnNames.js";
|
|
21
24
|
import { isDispatchEligible } from "@effect-dynamodb/schema/internal/PackedCodec.js";
|
|
22
|
-
import { extractArrayElement, extractKeyedValue, getSchemaFields, hasEncodingTransformation, holdsCustomDeclaration, refuseUnreadable, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
|
|
25
|
+
import { extractArrayElement, extractKeyedValue, getSchemaFields, hasEncodingTransformation, holdsCustomDeclaration, holdsUntyped, refuseUnreadable, storedBelowFields, } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
|
|
23
26
|
import { refuseAggregateKeyInTableKey } from "@effect-dynamodb/schema/internal/SharedKeyAttribute.js";
|
|
27
|
+
import { isZoneInstance, zoneEntriesWritten } from "@effect-dynamodb/schema/internal/StoredForm.js";
|
|
28
|
+
import { givenZoneReading } from "@effect-dynamodb/schema/internal/ZoneKeyText.js";
|
|
24
29
|
import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
|
|
25
|
-
import { DateTime, Effect, Equal, Exit, Option, Schema, SchemaAST, } from "effect";
|
|
30
|
+
import { BigDecimal, Cause, Chunk, DateTime, Effect, Equal, Exit, HashMap, HashSet, Option, Redacted, Result, Schema, SchemaAST, } from "effect";
|
|
26
31
|
import * as Batch from "./Batch.js";
|
|
27
32
|
import { fromDefinition as entityFromDefinition } from "./Entity.js";
|
|
33
|
+
import { entityNaming } from "./internal/BoundQuery.js";
|
|
28
34
|
import * as Capacity from "./internal/Capacity.js";
|
|
29
35
|
import { decodeKeyCursor, encodeKeyCursor } from "./internal/Cursor.js";
|
|
36
|
+
import { digest } from "./internal/Digest.js";
|
|
30
37
|
import { compileExpr, createConditionOps, emptyPartProblem, isEmptyExpr, parseSimpleShorthand, } from "./internal/Expr.js";
|
|
31
38
|
import { asReadGuard, preferredGuard, wholeRowGuard, } from "./internal/ExpressionLimits.js";
|
|
32
39
|
import { packRequests, transactWriteShape, transactWriteUnit } from "./internal/ItemSize.js";
|
|
33
40
|
import { hasStoredForm, packItemSync, unpackItemSync, withRegistry } from "./internal/Packed.js";
|
|
34
|
-
import {
|
|
41
|
+
import { pathBuilderOf } from "./internal/PathBuilder.js";
|
|
35
42
|
import * as Rekey from "./internal/Rekey.js";
|
|
36
43
|
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";
|
|
44
|
+
import { composePrimaryKeyOrFail, generateTimestampPrimitive, INCARNATION_TOKEN, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_READ_MODEL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, outboxMarkInUse, ROW_TOKEN, rowTokened, rowTokenInUse, } from "./internal/TransactableOps.js";
|
|
38
45
|
import { diagnosedValidationError, diagnoseFailure, explainDiagnosis, mergeKeyAttributes, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
|
|
39
|
-
import { fromAttributeMap, toAttributeMap, toAttributeValue, } from "./Marshaller.js";
|
|
40
|
-
import { resolvePrimaryKey } from "./Table.js";
|
|
46
|
+
import { fromAttributeMap, isCachedNormal, toAttributeMap, toAttributeValue, unstorableIn, } from "./Marshaller.js";
|
|
47
|
+
import { addTableKeyAttributes, resolvePrimaryKey } from "./Table.js";
|
|
41
48
|
// Internal modules (decomposed from Aggregate.ts)
|
|
42
49
|
export { isManyEdge, isOneEdge, isRefEdge, many, one, ref, } from "@effect-dynamodb/schema/internal/AggregateEdges.js";
|
|
43
50
|
export { deriveAggregateSchemas, deriveElementInputSchema, deriveEntityFieldName, extractArrayElement, getSchemaFields, isFieldOptional, isSchemaMatchingEntity, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
44
51
|
import { makeCursor, } from "@effect-dynamodb/schema/internal/AggregateCursor.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";
|
|
52
|
+
import { declaredValueNames, deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, manyEdgePaths, manyElementFields, manyElementSchema, readRowOf, readTakesOff, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseAggregateProtoName, refuseManySortKeysOverMovingValue, resolveAggregateStamps, rowKeysOn, subAggregateRowKind, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
46
53
|
// ---------------------------------------------------------------------------
|
|
47
54
|
// TypeId
|
|
48
55
|
// ---------------------------------------------------------------------------
|
|
@@ -61,6 +68,9 @@ export function make(schema, config) {
|
|
|
61
68
|
// Sub-aggregate form
|
|
62
69
|
return makeSubAggregate(schema, config);
|
|
63
70
|
}
|
|
71
|
+
// A sub-aggregate's rows are written where an aggregate places it, so whether every write
|
|
72
|
+
// stores a name is decided there: the aggregate holding it walks into it (#239).
|
|
73
|
+
refuseAggregateProtoName(config.root.entityType, schema, config.edges);
|
|
64
74
|
// Top-level form
|
|
65
75
|
return makeAggregate(schema, config);
|
|
66
76
|
}
|
|
@@ -137,7 +147,7 @@ const isMixedDateUnion = (ast) => {
|
|
|
137
147
|
const dateAttrEncoder = (fieldSchema, options) => {
|
|
138
148
|
if (options?.mixedUnions !== true && isMixedDateUnion(fieldSchema.ast))
|
|
139
149
|
return undefined;
|
|
140
|
-
const encodings = storedDateEncodings(fieldSchema);
|
|
150
|
+
const encodings = storedDateEncodings(fieldSchema, options?.keyText === true);
|
|
141
151
|
const last = encodings.at(-1);
|
|
142
152
|
if (!last)
|
|
143
153
|
return undefined;
|
|
@@ -157,15 +167,27 @@ const dateAttrEncoder = (fieldSchema, options) => {
|
|
|
157
167
|
};
|
|
158
168
|
/**
|
|
159
169
|
* 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,
|
|
161
|
-
*
|
|
162
|
-
*
|
|
163
|
-
*
|
|
170
|
+
* the field's own annotation, or under `Schema.optional` its value's, as an entity's write reads it,
|
|
171
|
+
* else those its schema's dates imply. A stamp in a field a row declares is stored the same way
|
|
172
|
+
* (`rowStampsOf`).
|
|
173
|
+
*
|
|
174
|
+
* `keyText`: the encodings key text is composed from, read off the field as declared, so an
|
|
175
|
+
* annotation inside `Schema.optional`'s union isn't seen there and such a field's key text is its
|
|
176
|
+
* date's default, ISO text, as 1.39.0 and 1.40.0 composed it (they stored its values that way too,
|
|
177
|
+
* #241). A key never moves with a stored form.
|
|
164
178
|
*/
|
|
165
|
-
const storedDateEncodings = (fieldSchema) => {
|
|
166
|
-
const explicit = DynamoModel.getEncoding(fieldSchema)
|
|
179
|
+
const storedDateEncodings = (fieldSchema, keyText = false) => {
|
|
180
|
+
const explicit = DynamoModel.getEncoding(fieldSchema) ??
|
|
181
|
+
(keyText ? undefined : encodingUnderOptional(fieldSchema));
|
|
167
182
|
return explicit ? [explicit] : inferDateEncodings(fieldSchema.ast);
|
|
168
183
|
};
|
|
184
|
+
/** The encoding annotated on the value of a `Schema.optional` field, if that value is one schema. */
|
|
185
|
+
const encodingUnderOptional = (fieldSchema) => {
|
|
186
|
+
const optional = optionalField(fieldSchema);
|
|
187
|
+
return optional === undefined || optional.union !== undefined
|
|
188
|
+
? undefined
|
|
189
|
+
: DynamoModel.getEncoding(optional.inner);
|
|
190
|
+
};
|
|
169
191
|
/** Whether a value is a date field's stored form: one its date encodings decode. */
|
|
170
192
|
const storedDateForm = (fieldSchema) => {
|
|
171
193
|
const decoders = storedDateEncodings(fieldSchema).map((encoding) => Schema.decodeUnknownOption(buildDateTransform(encoding)));
|
|
@@ -247,7 +269,7 @@ const storedFormFirst = (field, fieldSchema, resolveRef) => {
|
|
|
247
269
|
const which = written.update ? "update" : "create";
|
|
248
270
|
const read = readers[which] ?? reader(written.update);
|
|
249
271
|
readers[which] = read;
|
|
250
|
-
return Option.map(read(written.present ? { [field]: written.value } : {}), (asRead) => asRead
|
|
272
|
+
return Option.map(read(written.present ? { [field]: written.value } : {}), (asRead) => ownValue(asRead, field));
|
|
251
273
|
};
|
|
252
274
|
};
|
|
253
275
|
/**
|
|
@@ -307,12 +329,12 @@ storedDates = false) => {
|
|
|
307
329
|
// it reads back. Elsewhere a value the encoding doesn't take fails the write, as on 1.39.0.
|
|
308
330
|
const date = dateAttrEncoder(fieldSchema);
|
|
309
331
|
if (date && !storedDates) {
|
|
310
|
-
encoders
|
|
332
|
+
setOwn(encoders, field, date);
|
|
311
333
|
continue;
|
|
312
334
|
}
|
|
313
335
|
if (date) {
|
|
314
336
|
const stored = storedDateForm(fieldSchema);
|
|
315
|
-
encoders
|
|
337
|
+
setOwn(encoders, field, (value, asGiven) => {
|
|
316
338
|
try {
|
|
317
339
|
return date(value);
|
|
318
340
|
}
|
|
@@ -321,7 +343,7 @@ storedDates = false) => {
|
|
|
321
343
|
asGiven?.();
|
|
322
344
|
return value;
|
|
323
345
|
}
|
|
324
|
-
};
|
|
346
|
+
});
|
|
325
347
|
continue;
|
|
326
348
|
}
|
|
327
349
|
// 3. Nothing anywhere in the value has a wire form distinct from its domain form.
|
|
@@ -336,10 +358,12 @@ storedDates = false) => {
|
|
|
336
358
|
tolerantTransforms: true,
|
|
337
359
|
resolveRef,
|
|
338
360
|
}));
|
|
361
|
+
// What the field encodes to: `undefined` where it encodes to no key. A key the struct left
|
|
362
|
+
// out is not read off the result's prototype (`__proto__`, `toString`, …).
|
|
339
363
|
return (value) => {
|
|
340
364
|
const encoded = encode({ [field]: value });
|
|
341
365
|
return Option.isSome(encoded)
|
|
342
|
-
? Option.some(encoded.value
|
|
366
|
+
? Option.some(ownValue(encoded.value, field))
|
|
343
367
|
: Option.none();
|
|
344
368
|
};
|
|
345
369
|
};
|
|
@@ -349,10 +373,10 @@ storedDates = false) => {
|
|
|
349
373
|
// is the first's; this only keeps such a value from being marshalled as it is.
|
|
350
374
|
const encodeAsRead = encoderOver({ decodeOnly: true });
|
|
351
375
|
const own = ownAttrEncoder(fieldSchema);
|
|
352
|
-
encoders
|
|
376
|
+
setOwn(encoders, field, (value, asGiven) => encodeSubstituted(value).pipe(Option.orElse(() => encodeAsRead(value)), Option.orElse(() => own(value)), Option.getOrElse(() => {
|
|
353
377
|
asGiven?.();
|
|
354
378
|
return value;
|
|
355
|
-
}));
|
|
379
|
+
})));
|
|
356
380
|
}
|
|
357
381
|
return encoders;
|
|
358
382
|
};
|
|
@@ -376,28 +400,353 @@ const buildKeyAttrEncoders = (fields) => {
|
|
|
376
400
|
return encoders;
|
|
377
401
|
for (const field of Object.keys(fields)) {
|
|
378
402
|
const fieldSchema = fields[field];
|
|
379
|
-
const date = dateAttrEncoder(fieldSchema, { mixedUnions: true });
|
|
403
|
+
const date = dateAttrEncoder(fieldSchema, { mixedUnions: true, keyText: true });
|
|
380
404
|
if (date) {
|
|
381
405
|
// Before, a value this encoder rejects (the `5` of a mixed date union)
|
|
382
406
|
// threw and failed the write, so there is no stored key to stay
|
|
383
407
|
// byte-identical with: compose from the value as it is.
|
|
384
|
-
encoders
|
|
408
|
+
setOwn(encoders, field, (value) => {
|
|
385
409
|
try {
|
|
386
410
|
return date(value);
|
|
387
411
|
}
|
|
388
412
|
catch {
|
|
389
413
|
return value;
|
|
390
414
|
}
|
|
391
|
-
};
|
|
415
|
+
});
|
|
392
416
|
}
|
|
393
417
|
else if (hasEncodingTransformation(fieldSchema)) {
|
|
394
418
|
// A key composed from a value no encoder takes is composed from the value as it is.
|
|
395
419
|
const own = ownAttrEncoder(fieldSchema);
|
|
396
|
-
encoders
|
|
420
|
+
setOwn(encoders, field, (value) => Option.getOrElse(own(value), () => value));
|
|
397
421
|
}
|
|
398
422
|
}
|
|
399
423
|
return encoders;
|
|
400
424
|
};
|
|
425
|
+
/**
|
|
426
|
+
* @internal The one decision of which declared sort key composites of an `entity:` `many` edge
|
|
427
|
+
* escapeKeys moves (#241, DESIGN.md §11 "An `entity:` edge's sort key"). Through 1.40.0 such an
|
|
428
|
+
* edge composed a composite from the entity's encoding of the field the composite starts at (`n`
|
|
429
|
+
* of `n`, `f` of `f.n`) wherever the entity's model encodes that field for keys
|
|
430
|
+
* ({@link buildKeyAttrEncoders}: a field whose schema, optional or not, is a transformation, such
|
|
431
|
+
* as a codec, a date stored as a number or a `Schema.Class`), and from the value elsewhere, as a
|
|
432
|
+
* plain edge composes every composite. These are the composites named here. Under `escapeKeys:
|
|
433
|
+
* true` they are composed from the value; their text changes where the encoded value's text
|
|
434
|
+
* differs from the value's (`5` stored `"5"` composes `5`, the value `0000000000000005`), and a
|
|
435
|
+
* composite not named here never changes. The composer reads it, and `update` and `rekey`, which
|
|
436
|
+
* compose a row's text under the other composition to find and move the rows stored under 1.40.0's
|
|
437
|
+
* text, read the encoders resolved from it.
|
|
438
|
+
*/
|
|
439
|
+
export const entityEdgeEncodedComposites = (entityModel, composites) => {
|
|
440
|
+
if (entityModel === undefined || composites === undefined)
|
|
441
|
+
return [];
|
|
442
|
+
const encoders = buildKeyAttrEncoders(fieldsOf(entityModel));
|
|
443
|
+
return composites.filter((path) => Object.hasOwn(encoders, path.split(".")[0]));
|
|
444
|
+
};
|
|
445
|
+
/**
|
|
446
|
+
* Whether two values are one value (#241), as `create`'s judgement of a value given (`EDD-9159`),
|
|
447
|
+
* `update`'s test of a stale context copy and the copies an `update` hands back compare them. Strict:
|
|
448
|
+
* a value is one only where a read returning one of them returns the other.
|
|
449
|
+
*
|
|
450
|
+
* - A number by `Object.is` (`NaN` is `NaN`, `-0` is not `0`); a `bigint` only beside a `bigint`.
|
|
451
|
+
* - A `BigDecimal` by its digits and its scale (`1.5` is not `1.50`).
|
|
452
|
+
* - A `Date` or `DateTime` by its instant (and a zoned `DateTime` by its zone too); bytes by their
|
|
453
|
+
* bytes; a `Redacted` by the value it holds.
|
|
454
|
+
* - A set (and a `HashSet`) by its members, a map (and a `HashMap`) by its entries, whatever their
|
|
455
|
+
* order; an `Option` by its value; an array (and a `Chunk`) by its elements in order.
|
|
456
|
+
* - Anything else by its prototype and its own fields (a field holding `undefined`, which DynamoDB
|
|
457
|
+
* can't store, as no field), so a class instance is one only with one of its class.
|
|
458
|
+
*
|
|
459
|
+
* Never `Equal.equals`: a `BigDecimal` caches its normalized form on the instance compared, so
|
|
460
|
+
* comparing would add a property to the value the caller gave.
|
|
461
|
+
*/
|
|
462
|
+
const sameValue = (a, b) => {
|
|
463
|
+
if (typeof a === "number" && typeof b === "number")
|
|
464
|
+
return Object.is(a, b);
|
|
465
|
+
if (a === b)
|
|
466
|
+
return true;
|
|
467
|
+
if (a === null || b === null || typeof a !== "object" || typeof b !== "object")
|
|
468
|
+
return false;
|
|
469
|
+
if (DateTime.isDateTime(a) || DateTime.isDateTime(b)) {
|
|
470
|
+
if (!DateTime.isDateTime(a) || !DateTime.isDateTime(b))
|
|
471
|
+
return false;
|
|
472
|
+
if (DateTime.toEpochMillis(a) !== DateTime.toEpochMillis(b))
|
|
473
|
+
return false;
|
|
474
|
+
if (DateTime.isZoned(a) !== DateTime.isZoned(b))
|
|
475
|
+
return false;
|
|
476
|
+
return (!DateTime.isZoned(a) ||
|
|
477
|
+
DateTime.zoneToString(a.zone) === DateTime.zoneToString(b.zone));
|
|
478
|
+
}
|
|
479
|
+
if (a instanceof Date || b instanceof Date) {
|
|
480
|
+
if (!(a instanceof Date) || !(b instanceof Date))
|
|
481
|
+
return false;
|
|
482
|
+
return Object.is(a.getTime(), b.getTime());
|
|
483
|
+
}
|
|
484
|
+
if (a instanceof Uint8Array || b instanceof Uint8Array) {
|
|
485
|
+
if (!(a instanceof Uint8Array) || !(b instanceof Uint8Array))
|
|
486
|
+
return false;
|
|
487
|
+
return a.length === b.length && a.every((byte, i) => byte === b[i]);
|
|
488
|
+
}
|
|
489
|
+
if (BigDecimal.isBigDecimal(a) || BigDecimal.isBigDecimal(b)) {
|
|
490
|
+
if (!BigDecimal.isBigDecimal(a) || !BigDecimal.isBigDecimal(b))
|
|
491
|
+
return false;
|
|
492
|
+
return a.value === b.value && a.scale === b.scale;
|
|
493
|
+
}
|
|
494
|
+
if (Redacted.isRedacted(a) || Redacted.isRedacted(b)) {
|
|
495
|
+
if (!Redacted.isRedacted(a) || !Redacted.isRedacted(b))
|
|
496
|
+
return false;
|
|
497
|
+
return sameValue(Redacted.value(a), Redacted.value(b));
|
|
498
|
+
}
|
|
499
|
+
const asSet = (x) => x instanceof Set ? [...x] : HashSet.isHashSet(x) ? [...x] : undefined;
|
|
500
|
+
const [setA, setB] = [asSet(a), asSet(b)];
|
|
501
|
+
if (setA !== undefined || setB !== undefined) {
|
|
502
|
+
if (setA === undefined || setB === undefined || setA.length !== setB.length)
|
|
503
|
+
return false;
|
|
504
|
+
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
|
|
505
|
+
return false;
|
|
506
|
+
return setA.every((member) => setB.some((other) => sameValue(member, other)));
|
|
507
|
+
}
|
|
508
|
+
const asMap = (x) => x instanceof Map ? [...x] : HashMap.isHashMap(x) ? [...x] : undefined;
|
|
509
|
+
const [mapA, mapB] = [asMap(a), asMap(b)];
|
|
510
|
+
if (mapA !== undefined || mapB !== undefined) {
|
|
511
|
+
if (mapA === undefined || mapB === undefined || mapA.length !== mapB.length)
|
|
512
|
+
return false;
|
|
513
|
+
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
|
|
514
|
+
return false;
|
|
515
|
+
return mapA.every(([key, value]) => mapB.some(([k, v]) => sameValue(key, k) && sameValue(value, v)));
|
|
516
|
+
}
|
|
517
|
+
if (Option.isOption(a) || Option.isOption(b)) {
|
|
518
|
+
if (!Option.isOption(a) || !Option.isOption(b))
|
|
519
|
+
return false;
|
|
520
|
+
if (Option.isNone(a) || Option.isNone(b))
|
|
521
|
+
return Option.isNone(a) && Option.isNone(b);
|
|
522
|
+
return sameValue(a.value, b.value);
|
|
523
|
+
}
|
|
524
|
+
if (Chunk.isChunk(a) || Chunk.isChunk(b)) {
|
|
525
|
+
if (!Chunk.isChunk(a) || !Chunk.isChunk(b))
|
|
526
|
+
return false;
|
|
527
|
+
return sameValue(Chunk.toReadonlyArray(a), Chunk.toReadonlyArray(b));
|
|
528
|
+
}
|
|
529
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
530
|
+
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
|
|
531
|
+
return false;
|
|
532
|
+
return a.every((element, i) => sameValue(element, b[i]));
|
|
533
|
+
}
|
|
534
|
+
if (Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
|
|
535
|
+
return false;
|
|
536
|
+
const keys = (x) => Object.keys(x).filter((key) => x[key] !== undefined);
|
|
537
|
+
const [aKeys, bKeys] = [keys(a), keys(b)];
|
|
538
|
+
return (aKeys.length === bKeys.length &&
|
|
539
|
+
aKeys.every((key) => Object.hasOwn(b, key) &&
|
|
540
|
+
sameValue(a[key], b[key])));
|
|
541
|
+
};
|
|
542
|
+
/**
|
|
543
|
+
* A value as a refusal shows it (#241), so two that differ show differently: text quoted, a number
|
|
544
|
+
* bare, a `bigint` as `5n`, a `Date` and a `DateTime` with their instant (and zone), a set and a map
|
|
545
|
+
* with their members, bytes as bytes, an `Option` as `Option.some(…)`, a `BigDecimal` with every
|
|
546
|
+
* digit of its scale, a class instance with its class's name, `undefined` as `undefined`. A
|
|
547
|
+
* `Redacted` never shows what it holds.
|
|
548
|
+
*/
|
|
549
|
+
const rendered = (value, depth = 0) => {
|
|
550
|
+
if (depth > 6)
|
|
551
|
+
return "…";
|
|
552
|
+
const inner = (x) => rendered(x, depth + 1);
|
|
553
|
+
switch (typeof value) {
|
|
554
|
+
case "string":
|
|
555
|
+
return JSON.stringify(value);
|
|
556
|
+
case "number":
|
|
557
|
+
return Object.is(value, -0) ? "-0" : String(value);
|
|
558
|
+
case "bigint":
|
|
559
|
+
return `${value}n`;
|
|
560
|
+
case "undefined":
|
|
561
|
+
return "undefined";
|
|
562
|
+
case "function":
|
|
563
|
+
return "a function";
|
|
564
|
+
case "symbol":
|
|
565
|
+
return String(value);
|
|
566
|
+
case "boolean":
|
|
567
|
+
return String(value);
|
|
568
|
+
}
|
|
569
|
+
if (value === null)
|
|
570
|
+
return "null";
|
|
571
|
+
if (DateTime.isDateTime(value)) {
|
|
572
|
+
return DateTime.isZoned(value)
|
|
573
|
+
? `DateTime.Zoned(${DateTime.formatIsoZoned(value)})`
|
|
574
|
+
: `DateTime.Utc(${DateTime.formatIso(value)})`;
|
|
575
|
+
}
|
|
576
|
+
if (value instanceof Date) {
|
|
577
|
+
return `Date(${Number.isNaN(value.getTime()) ? "invalid" : value.toISOString()})`;
|
|
578
|
+
}
|
|
579
|
+
if (value instanceof Uint8Array)
|
|
580
|
+
return `Uint8Array [${[...value].join(", ")}]`;
|
|
581
|
+
if (BigDecimal.isBigDecimal(value))
|
|
582
|
+
return `BigDecimal(${decimalText(value)})`;
|
|
583
|
+
// Never the value it holds: a refusal's message may be logged.
|
|
584
|
+
if (Redacted.isRedacted(value))
|
|
585
|
+
return "a Redacted value";
|
|
586
|
+
if (value instanceof Set) {
|
|
587
|
+
return `Set {${[...value]
|
|
588
|
+
.map(inner)
|
|
589
|
+
.sort()
|
|
590
|
+
.map((member) => ` ${member}`)
|
|
591
|
+
.join(",")} }`;
|
|
592
|
+
}
|
|
593
|
+
if (value instanceof Map) {
|
|
594
|
+
return `Map {${[...value].map(([k, v]) => ` ${inner(k)} => ${inner(v)}`).join(",")} }`;
|
|
595
|
+
}
|
|
596
|
+
if (Option.isOption(value)) {
|
|
597
|
+
return Option.isNone(value) ? "Option.none()" : `Option.some(${inner(value.value)})`;
|
|
598
|
+
}
|
|
599
|
+
if (Array.isArray(value))
|
|
600
|
+
return `[${value.map(inner).join(", ")}]`;
|
|
601
|
+
const proto = Object.getPrototypeOf(value);
|
|
602
|
+
const entries = Object.entries(value).filter(([, v]) => v !== undefined);
|
|
603
|
+
const body = `{${entries.map(([k, v]) => ` ${JSON.stringify(k)}: ${inner(v)}`).join(",")} }`;
|
|
604
|
+
const name = proto === null || proto === Object.prototype ? undefined : proto.constructor?.name;
|
|
605
|
+
return name === undefined || name === "" ? body : `${name} ${body}`;
|
|
606
|
+
};
|
|
607
|
+
/** A `BigDecimal` as decimal text with every digit of its scale (`1.50`), without normalizing it. */
|
|
608
|
+
const decimalText = (d) => {
|
|
609
|
+
const sign = d.value < 0n ? "-" : "";
|
|
610
|
+
const digits = (d.value < 0n ? -d.value : d.value).toString();
|
|
611
|
+
if (d.scale <= 0)
|
|
612
|
+
return `${sign}${digits}${"0".repeat(-d.scale)}`;
|
|
613
|
+
const padded = digits.padStart(d.scale + 1, "0");
|
|
614
|
+
return `${sign}${padded.slice(0, -d.scale)}.${padded.slice(-d.scale)}`;
|
|
615
|
+
};
|
|
616
|
+
/** The {@link Placed} of a value of `schema`. */
|
|
617
|
+
const placedFields = (schema) => {
|
|
618
|
+
if (schema === undefined)
|
|
619
|
+
return undefined;
|
|
620
|
+
const value = unwrapOptionalField(DynamoModel.isConfiguredModel(schema) ? schema.model : schema);
|
|
621
|
+
if (SchemaAST.isUnion(value.ast)) {
|
|
622
|
+
const members = value.members;
|
|
623
|
+
if (!Array.isArray(members))
|
|
624
|
+
return undefined;
|
|
625
|
+
const held = members.filter((member) => !SchemaAST.isNull(member.ast) && !SchemaAST.isUndefined(member.ast));
|
|
626
|
+
return held.length === 1 ? placedFields(held[0]) : undefined;
|
|
627
|
+
}
|
|
628
|
+
if (SchemaAST.isUnknown(value.ast) || SchemaAST.isAny(value.ast))
|
|
629
|
+
return "any";
|
|
630
|
+
const fields = getSchemaFields(value);
|
|
631
|
+
if (fields === undefined)
|
|
632
|
+
return undefined;
|
|
633
|
+
const stored = SchemaAST.toEncoded(value.ast);
|
|
634
|
+
if (!SchemaAST.isObjects(stored))
|
|
635
|
+
return undefined;
|
|
636
|
+
const domain = Object.keys(fields);
|
|
637
|
+
const names = stored.propertySignatures.map((property) => property.name);
|
|
638
|
+
return names.length === domain.length && names.every((name, i) => name === domain[i])
|
|
639
|
+
? fields
|
|
640
|
+
: undefined;
|
|
641
|
+
};
|
|
642
|
+
/** A schema's decode as a read takes it: tolerant, absent reads as the value it stands for. */
|
|
643
|
+
const readsAs = (schema, resolveRef) => {
|
|
644
|
+
const decode = Schema.decodeUnknownResult(readingInstances(substituteSchemaDeep(schema, {
|
|
645
|
+
tolerantTransforms: true,
|
|
646
|
+
decodeOnly: true,
|
|
647
|
+
resolveRef,
|
|
648
|
+
absentReads: true,
|
|
649
|
+
})));
|
|
650
|
+
return (value) => {
|
|
651
|
+
try {
|
|
652
|
+
const result = decode(value);
|
|
653
|
+
return Result.isSuccess(result)
|
|
654
|
+
? { ok: result.success }
|
|
655
|
+
: { fails: issueText(result.failure) };
|
|
656
|
+
}
|
|
657
|
+
catch (defect) {
|
|
658
|
+
return { fails: issueText(defect) };
|
|
659
|
+
}
|
|
660
|
+
};
|
|
661
|
+
};
|
|
662
|
+
/** `EDD-9159`'s reason for a value given at `name` of `member`'s value (#241). */
|
|
663
|
+
const givenOverRowReason = (member, name, givenValue, what, read) => {
|
|
664
|
+
const returned = "read" in read ? read.read : undefined;
|
|
665
|
+
const reads = "fails" in read
|
|
666
|
+
? `fails there (${read.fails})`
|
|
667
|
+
: returned === undefined
|
|
668
|
+
? "returns nothing for it"
|
|
669
|
+
: `returns ${capped(rendered(returned))} for it`;
|
|
670
|
+
return (`[EDD-9159] "${member}" gives "${name}" the value ${capped(rendered(givenValue))} at the top ` +
|
|
671
|
+
`of its value, which is also ${what}. The library writes its own value there, and a read of ` +
|
|
672
|
+
`"${member}" ${reads}, so the value would not read back as given. ` +
|
|
673
|
+
("fails" in read
|
|
674
|
+
? `Name it something else, or declare "${name}" so a read of "${member}" takes the library's value.`
|
|
675
|
+
: returned === undefined
|
|
676
|
+
? "Leave it out of the value, or name it something else."
|
|
677
|
+
: `Give it ${capped(rendered(returned))}, leave it out of the value, or name it something else.`));
|
|
678
|
+
};
|
|
679
|
+
/**
|
|
680
|
+
* `EDD-9159`'s reason for a name `member`'s value gives nothing at, where the library writes its own
|
|
681
|
+
* value and a read of the member fails there (#241): no value given there reads back.
|
|
682
|
+
*/
|
|
683
|
+
const unreadOverRowReason = (member, name, what, fails) => `[EDD-9159] "${member}" gives "${name}" no value, and "${name}" is also ${what}. The library ` +
|
|
684
|
+
`writes its own value there, and a read of "${member}" fails there (${capped(fails)}), so the ` +
|
|
685
|
+
`row would not read back. Declare "${name}" in "${member}"'s value so it reads the library's ` +
|
|
686
|
+
"value, or name it something else.";
|
|
687
|
+
/**
|
|
688
|
+
* `EDD-9159`'s reason for a custom `decompose`'s rows that give nothing where the library writes the
|
|
689
|
+
* root's `context` values, a read of which fails (#241).
|
|
690
|
+
*/
|
|
691
|
+
const customUnreadReason = (member, context, fails) => `[EDD-9159] "${member}"'s rows hold the root's ${context.map((name) => `"${name}"`).join(", ")}, ` +
|
|
692
|
+
`which the aggregate copies onto every row beneath the root, and a read of "${member}" with ` +
|
|
693
|
+
`them fails (${capped(fails)}), so its rows would not read back. Declare them in its elements ` +
|
|
694
|
+
"so they read the root's values, or name the elements' fields something else.";
|
|
695
|
+
/** `EDD-9159`'s reason for a row of a custom `decompose` the library writes over (#241). */
|
|
696
|
+
const customOverRowReason = (member, name, own, what, asReturned, read) => `[EDD-9159] "${member}"'s rows give "${name}" the value ${capped(rendered(own))}, which is ` +
|
|
697
|
+
`also ${what}. The library writes its own value there, and a read of "${member}" ` +
|
|
698
|
+
("fails" in read
|
|
699
|
+
? `fails (${read.fails})`
|
|
700
|
+
: `returns ${capped(rendered(read.read))}, not ${capped(rendered(asReturned))}`) +
|
|
701
|
+
", so the value would not read back as given. Leave it out of the rows, or name it something else.";
|
|
702
|
+
/** A rendering, cut short. */
|
|
703
|
+
const capped = (text) => (text.length > 300 ? `${text.slice(0, 300)}…` : text);
|
|
704
|
+
/** A read's failure, on one line. */
|
|
705
|
+
const issueText = (issue) => {
|
|
706
|
+
const text = String(issue?.message ?? issue)
|
|
707
|
+
.replace(/\s+/g, " ")
|
|
708
|
+
.trim();
|
|
709
|
+
return text.length > 300 ? `${text.slice(0, 300)}…` : text;
|
|
710
|
+
};
|
|
711
|
+
/**
|
|
712
|
+
* The encoder of a `many` edge's element as a whole (#241): one whose schema shows no fields of
|
|
713
|
+
* its own, a union (a member renaming a field among them) or a transformation of the whole element
|
|
714
|
+
* (`Schema.encodeKeys`, a struct decoded to another), so no encoder of {@link buildAttrEncoders}
|
|
715
|
+
* reaches what it transforms. Up to 1.40.0 such an element was stored as the domain value it held
|
|
716
|
+
* (`text` where its schema stores `line`), with only the encoders of the edge entity's fields, by
|
|
717
|
+
* name. This is the encoder {@link buildAttrEncoders} gives a field holding the element, so the
|
|
718
|
+
* element is encoded exactly once, through the schema a read decodes it with, as every other
|
|
719
|
+
* attribute is. A row stored as the domain value still reads, through the same tolerant decode.
|
|
720
|
+
*
|
|
721
|
+
* None for an element that shows its fields (each has its own encoder), an opaque ref (encoded as the
|
|
722
|
+
* entity's model), one with nothing to encode, and an edge with a custom `decompose`, whose rows are
|
|
723
|
+
* what it returns, not elements of the schema.
|
|
724
|
+
*/
|
|
725
|
+
const wholeElementEncoder = (edgeName, element, decompose, resolveRef) => {
|
|
726
|
+
if (element === undefined || decompose !== undefined)
|
|
727
|
+
return undefined;
|
|
728
|
+
if (getSchemaFields(element) !== undefined || isOpaqueRefField(element))
|
|
729
|
+
return undefined;
|
|
730
|
+
return buildAttrEncoders({ [edgeName]: element }, resolveRef)[edgeName];
|
|
731
|
+
};
|
|
732
|
+
/**
|
|
733
|
+
* A `many` element's attributes in their stored form, and the fields stored as given. Exactly one
|
|
734
|
+
* encoding: the element's as a whole where {@link wholeElementEncoder} gave the node one and it
|
|
735
|
+
* takes the element, else the per-field encoders, as every element was stored up to 1.40.0.
|
|
736
|
+
*/
|
|
737
|
+
const storedElement = (elem, node) => {
|
|
738
|
+
if (node.elementEncoder !== undefined) {
|
|
739
|
+
let refused = false;
|
|
740
|
+
const encoded = node.elementEncoder(elem, () => {
|
|
741
|
+
refused = true;
|
|
742
|
+
});
|
|
743
|
+
if (!refused && encoded !== null && typeof encoded === "object" && !Array.isArray(encoded)) {
|
|
744
|
+
return { attrs: { ...encoded }, storedAsGiven: [] };
|
|
745
|
+
}
|
|
746
|
+
}
|
|
747
|
+
const attrs = rowValues(node, elem);
|
|
748
|
+
return { attrs, storedAsGiven: applyNodeAttrEncoders(attrs, node.attrEncoders) };
|
|
749
|
+
};
|
|
401
750
|
/**
|
|
402
751
|
* A schema's declared fields, if it exposes them (Schema.Struct / Schema.Class).
|
|
403
752
|
*
|
|
@@ -413,6 +762,50 @@ const fieldsOf = (schema) => {
|
|
|
413
762
|
const source = DynamoModel.isConfiguredModel(schema) ? schema.model : schema;
|
|
414
763
|
return source?.fields;
|
|
415
764
|
};
|
|
765
|
+
/** The schema of an edge entity's model, a `DynamoModel.configure` wrapper unwrapped. */
|
|
766
|
+
const modelOf = (model) => model === undefined
|
|
767
|
+
? undefined
|
|
768
|
+
: (DynamoModel.isConfiguredModel(model) ? model.model : model);
|
|
769
|
+
/**
|
|
770
|
+
* The attribute names a value of `schema` can be stored under, for a node whose value exposes no
|
|
771
|
+
* `.fields` (#240): an object's properties, on its type side and its encoded side, every member of
|
|
772
|
+
* a union, what a declaration (an annotated class) is built from, a suspended schema's body once.
|
|
773
|
+
* Read by `rekey`'s guard, which holds each one a row didn't have still absent.
|
|
774
|
+
*/
|
|
775
|
+
const storedFieldNames = (schema) => {
|
|
776
|
+
const names = new Set();
|
|
777
|
+
const seen = new Set();
|
|
778
|
+
const walk = (ast) => {
|
|
779
|
+
if (seen.has(ast))
|
|
780
|
+
return;
|
|
781
|
+
seen.add(ast);
|
|
782
|
+
switch (ast._tag) {
|
|
783
|
+
case "Objects":
|
|
784
|
+
for (const property of ast.propertySignatures) {
|
|
785
|
+
if (typeof property.name === "string")
|
|
786
|
+
names.add(property.name);
|
|
787
|
+
}
|
|
788
|
+
walk(SchemaAST.toEncoded(ast));
|
|
789
|
+
return;
|
|
790
|
+
case "Union":
|
|
791
|
+
for (const member of ast.types)
|
|
792
|
+
walk(member);
|
|
793
|
+
return;
|
|
794
|
+
case "Suspend":
|
|
795
|
+
walk(ast.thunk());
|
|
796
|
+
return;
|
|
797
|
+
case "Declaration":
|
|
798
|
+
for (const parameter of ast.typeParameters)
|
|
799
|
+
walk(parameter);
|
|
800
|
+
walk(SchemaAST.toEncoded(ast));
|
|
801
|
+
return;
|
|
802
|
+
default:
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
};
|
|
806
|
+
walk(schema.ast);
|
|
807
|
+
return [...names].sort();
|
|
808
|
+
};
|
|
416
809
|
/** The value schema of a struct field, with any `optionalKey` / `optional` wrapper removed. */
|
|
417
810
|
const unwrapOptionalField = (field) => optionalField(field)?.inner ?? field;
|
|
418
811
|
/**
|
|
@@ -490,34 +883,58 @@ const unwrapEntityModel = (model) => DynamoModel.isConfiguredModel(model) ? mode
|
|
|
490
883
|
*/
|
|
491
884
|
const collectRefTargets = (rootFields, rootEdges) => {
|
|
492
885
|
const targets = new Map();
|
|
493
|
-
|
|
886
|
+
// What a ref holds is what a read of its entity returns (`refHeldTarget`, #241), the one decision
|
|
887
|
+
// an entity's `refs` take too.
|
|
888
|
+
//
|
|
889
|
+
// `heldOnly`: registered only where the read holds less than the target (`refHeldTarget` decides
|
|
890
|
+
// another schema), so a declaration 1.40.0 left unregistered decodes as it did everywhere else.
|
|
891
|
+
const register = (field, model, heldOnly) => {
|
|
494
892
|
if (field !== undefined && model !== undefined && !targets.has(field)) {
|
|
495
|
-
|
|
893
|
+
const target = unwrapEntityModel(model);
|
|
894
|
+
const held = refHeldTarget(target);
|
|
895
|
+
if (!heldOnly || held !== target)
|
|
896
|
+
targets.set(field, held);
|
|
496
897
|
}
|
|
497
898
|
};
|
|
899
|
+
// A ref the walker CAN see into keeps its own class, except where that class holds a hidden field a
|
|
900
|
+
// read can't do without: the walker would demand it of a hydrated value that has none (1.40.0
|
|
901
|
+
// refused every such create), so the field is re-pointed at what a read of it holds. Anywhere
|
|
902
|
+
// else `refHeldTarget` returns the class itself and nothing is registered.
|
|
903
|
+
const registerHeld = (field) => {
|
|
904
|
+
if (field === undefined || targets.has(field))
|
|
905
|
+
return;
|
|
906
|
+
const inner = unwrapOptionalField(field);
|
|
907
|
+
if (getSchemaFields(inner) === undefined)
|
|
908
|
+
return;
|
|
909
|
+
const held = refHeldTarget(inner);
|
|
910
|
+
if (held !== inner)
|
|
911
|
+
targets.set(field, held);
|
|
912
|
+
};
|
|
498
913
|
const registerNested = (entity) => {
|
|
499
914
|
if (entity?.model === undefined)
|
|
500
915
|
return;
|
|
501
916
|
const entityFields = getSchemaFields(unwrapEntityModel(entity.model));
|
|
502
917
|
for (const nested of entity._data?.resolvedRefs ?? []) {
|
|
503
|
-
register(entityFields
|
|
918
|
+
register(ownValue(entityFields, nested.fieldName), nested.refEntity?.model, false);
|
|
504
919
|
}
|
|
505
920
|
};
|
|
506
|
-
const walk = (fields, edges, isRoot) => {
|
|
921
|
+
const walk = (fields, edges, isRoot, heldOnly) => {
|
|
507
922
|
for (const [edgeName, edge] of Object.entries(edges)) {
|
|
508
923
|
if (!("_tag" in edge))
|
|
509
924
|
continue;
|
|
510
925
|
if (edge._tag === "RefEdge" || edge._tag === "OneEdge") {
|
|
511
926
|
const entity = edge.entity;
|
|
512
|
-
const field = fields
|
|
927
|
+
const field = ownValue(fields, edgeName);
|
|
513
928
|
if (field !== undefined && (isRoot || isOpaqueRefField(field))) {
|
|
514
|
-
register(field, entity?.model);
|
|
929
|
+
register(field, entity?.model, heldOnly);
|
|
515
930
|
}
|
|
931
|
+
else if (entity !== undefined)
|
|
932
|
+
registerHeld(field);
|
|
516
933
|
registerNested(entity);
|
|
517
934
|
}
|
|
518
935
|
else if (edge._tag === "ManyEdge") {
|
|
519
936
|
const entity = edge.entity;
|
|
520
|
-
const arrayField = fields
|
|
937
|
+
const arrayField = ownValue(fields, edgeName);
|
|
521
938
|
const element = arrayField === undefined ? undefined : extractArrayElement(arrayField);
|
|
522
939
|
if (arrayField !== undefined && element !== undefined && isOpaqueRefField(element)) {
|
|
523
940
|
// The element IS an opaque ref (`Schema.Array(Player.pipe(DynamoModel.ref))`):
|
|
@@ -525,26 +942,49 @@ const collectRefTargets = (rootFields, rootEdges) => {
|
|
|
525
942
|
// walker re-applies the field's optionality around the target.
|
|
526
943
|
const model = entity?.model;
|
|
527
944
|
if (model !== undefined && !targets.has(arrayField)) {
|
|
528
|
-
|
|
945
|
+
const target = unwrapEntityModel(model);
|
|
946
|
+
const held = refHeldTarget(target);
|
|
947
|
+
if (!heldOnly || held !== target) {
|
|
948
|
+
targets.set(arrayField, Schema.Array(held));
|
|
949
|
+
}
|
|
950
|
+
}
|
|
951
|
+
}
|
|
952
|
+
else if (edge.entity !== undefined &&
|
|
953
|
+
arrayField !== undefined &&
|
|
954
|
+
isEntityElement(element, edge.entity)) {
|
|
955
|
+
// The element IS the entity's class, which the walker sees into (`Array<Umpire>`): as
|
|
956
|
+
// `registerHeld`, re-pointed only where its read holds less than the class.
|
|
957
|
+
const held = refHeldTarget(element);
|
|
958
|
+
if (held !== element && !targets.has(arrayField)) {
|
|
959
|
+
targets.set(arrayField, Schema.Array(held));
|
|
529
960
|
}
|
|
530
961
|
}
|
|
531
962
|
else if (edge.entity !== undefined) {
|
|
532
963
|
// The element WRAPS the ref (`PlayerSheet { player }`), found by name as
|
|
533
964
|
// hydration finds it.
|
|
534
|
-
const refField = manyElementFields(fields, edgeName)
|
|
965
|
+
const refField = ownValue(manyElementFields(fields, edgeName), deriveEntityFieldName(edge.entity));
|
|
535
966
|
if (refField !== undefined && isOpaqueRefField(refField)) {
|
|
536
|
-
register(refField, entity?.model);
|
|
967
|
+
register(refField, entity?.model, heldOnly);
|
|
537
968
|
}
|
|
969
|
+
else
|
|
970
|
+
registerHeld(refField);
|
|
538
971
|
}
|
|
539
972
|
registerNested(entity);
|
|
540
973
|
}
|
|
541
974
|
else if (edge._tag === "BoundSubAggregate") {
|
|
542
975
|
const bound = edge;
|
|
543
|
-
walk(fieldsOf(bound.aggregate.schema), bound.aggregate.edges, false);
|
|
976
|
+
walk(fieldsOf(bound.aggregate.schema), bound.aggregate.edges, false, heldOnly);
|
|
977
|
+
// The enclosing model's own declaration of the sub-aggregate's value, which assembly decodes
|
|
978
|
+
// the value with too, where it isn't the sub-aggregate's schema. 1.40.0 registered none of
|
|
979
|
+
// its refs, so only a ref whose read holds less than its target is.
|
|
980
|
+
const declared = fields?.[edgeName];
|
|
981
|
+
const declaredFields = declared === undefined ? undefined : getSchemaFields(unwrapOptionalField(declared));
|
|
982
|
+
if (declaredFields !== undefined)
|
|
983
|
+
walk(declaredFields, bound.aggregate.edges, false, true);
|
|
544
984
|
}
|
|
545
985
|
}
|
|
546
986
|
};
|
|
547
|
-
walk(rootFields, rootEdges, true);
|
|
987
|
+
walk(rootFields, rootEdges, true, false);
|
|
548
988
|
return targets;
|
|
549
989
|
};
|
|
550
990
|
/**
|
|
@@ -559,8 +999,8 @@ const applyNodeAttrEncoders = (attrs, encoders) => {
|
|
|
559
999
|
if (!encoders)
|
|
560
1000
|
return asGiven;
|
|
561
1001
|
for (const [field, encode] of Object.entries(encoders)) {
|
|
562
|
-
if (field
|
|
563
|
-
attrs
|
|
1002
|
+
if (hasOwnName(attrs, field) && attrs[field] != null) {
|
|
1003
|
+
setOwn(attrs, field, encode(attrs[field], () => asGiven.push(field)));
|
|
564
1004
|
}
|
|
565
1005
|
}
|
|
566
1006
|
return asGiven;
|
|
@@ -621,23 +1061,26 @@ const makeAggregate = (schema, config) => {
|
|
|
621
1061
|
refuseAggregateKeyOverMovingValue(aggregateName, config.timestamps, schemaFields, config.pk.composite);
|
|
622
1062
|
// The form a stamp is stored in: on a row declaring its field, the form the row stores any value of
|
|
623
1063
|
// 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
|
-
|
|
626
|
-
|
|
627
|
-
|
|
1064
|
+
// own encoding. A row that doesn't declare it holds what the root's would. With `keyText`, the form
|
|
1065
|
+
// a key over it reads it in, as `buildKeyAttrEncoders` does.
|
|
1066
|
+
const storedIn = (fields, name, declared, encoding, keyText = false) => {
|
|
1067
|
+
const field = declared && name !== null ? ownValue(fields, name) : undefined;
|
|
1068
|
+
return ((field === undefined ? undefined : storedDateEncodings(field, keyText).at(-1)) ?? encoding);
|
|
628
1069
|
};
|
|
629
1070
|
const stampFields = timestampFields.createdAt !== null || timestampFields.updatedAt !== null
|
|
630
1071
|
? {
|
|
631
1072
|
createdAt: timestampFields.createdAt,
|
|
632
1073
|
createdEncoding: storedIn(schemaFields, timestampFields.createdAt, timestampFields.createdAtCollision, timestampFields.createdAtEncoding),
|
|
1074
|
+
createdKey: storedIn(schemaFields, timestampFields.createdAt, timestampFields.createdAtCollision, timestampFields.createdAtEncoding, true),
|
|
633
1075
|
updatedAt: timestampFields.updatedAt,
|
|
634
1076
|
updatedEncoding: storedIn(schemaFields, timestampFields.updatedAt, timestampFields.updatedAtCollision, timestampFields.updatedAtEncoding),
|
|
1077
|
+
updatedKey: storedIn(schemaFields, timestampFields.updatedAt, timestampFields.updatedAtCollision, timestampFields.updatedAtEncoding, true),
|
|
635
1078
|
}
|
|
636
1079
|
: undefined;
|
|
637
1080
|
// What the read path may drop before decoding: each node drops those its rows
|
|
638
1081
|
// don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object.
|
|
639
1082
|
const systemAttrs = new Set([timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null));
|
|
640
|
-
const requiredIn = (fields, name) => name !== null && fields
|
|
1083
|
+
const requiredIn = (fields, name) => name !== null && ownValue(fields, name) !== undefined && !isFieldOptional(fields[name]);
|
|
641
1084
|
// On `create`, a stamp replaces a value the input holds, as on 1.39.0, except under a date the root
|
|
642
1085
|
// declares `Schema.optional`: 1.39.0 left that field the caller's and stored a value passed for it.
|
|
643
1086
|
// That is 1.39.0's verdict, the resolver's over the root's fields as declared: `Schema.optional`'s
|
|
@@ -662,6 +1105,9 @@ const makeAggregate = (schema, config) => {
|
|
|
662
1105
|
createdStored: own.createdAtCollision
|
|
663
1106
|
? storedIn(fields, own.createdAt, true, own.createdAtEncoding)
|
|
664
1107
|
: stampFields.createdEncoding,
|
|
1108
|
+
createdKey: own.createdAtCollision
|
|
1109
|
+
? storedIn(fields, own.createdAt, true, own.createdAtEncoding, true)
|
|
1110
|
+
: stampFields.createdKey,
|
|
665
1111
|
createdDeclared: own.createdAtCollision,
|
|
666
1112
|
createdRequired: own.createdAtCollision && requiredIn(fields, own.createdAt),
|
|
667
1113
|
createdReplaces,
|
|
@@ -670,6 +1116,9 @@ const makeAggregate = (schema, config) => {
|
|
|
670
1116
|
updatedStored: own.updatedAtCollision
|
|
671
1117
|
? storedIn(fields, own.updatedAt, true, own.updatedAtEncoding)
|
|
672
1118
|
: stampFields.updatedEncoding,
|
|
1119
|
+
updatedKey: own.updatedAtCollision
|
|
1120
|
+
? storedIn(fields, own.updatedAt, true, own.updatedAtEncoding, true)
|
|
1121
|
+
: stampFields.updatedKey,
|
|
673
1122
|
updatedDeclared: own.updatedAtCollision,
|
|
674
1123
|
updatedRequired: own.updatedAtCollision && requiredIn(fields, own.updatedAt),
|
|
675
1124
|
updatedReplaces,
|
|
@@ -692,6 +1141,10 @@ const makeAggregate = (schema, config) => {
|
|
|
692
1141
|
edges: config.edges,
|
|
693
1142
|
parentFields: schemaFields,
|
|
694
1143
|
resolveRef,
|
|
1144
|
+
escapeKeys: config.schema.escapeKeys === true,
|
|
1145
|
+
rowKeys: config,
|
|
1146
|
+
readRow: readRowOf("root", config, declaredValueNames.own(schemaFields, config.edges)),
|
|
1147
|
+
placed: placedFields(schema),
|
|
695
1148
|
}));
|
|
696
1149
|
// Rows that hold a stamp in the domain object: what `update` returns has to say what it wrote.
|
|
697
1150
|
const declaresStamp = (node) => node.rowStamps?.createdDeclared === true ||
|
|
@@ -709,6 +1162,41 @@ const makeAggregate = (schema, config) => {
|
|
|
709
1162
|
const attrEncoders = buildAttrEncoders(schemaFields, resolveRef);
|
|
710
1163
|
const keyAttrEncoders = buildKeyAttrEncoders(schemaFields);
|
|
711
1164
|
const rootEncoders = { stored: attrEncoders, key: keyAttrEncoders };
|
|
1165
|
+
/**
|
|
1166
|
+
* What the root row stores for a value of a top-level field (#242): its encoder's form, and for
|
|
1167
|
+
* `contains` an element of what it stores (`containedOperand`: a list's element, a set's member,
|
|
1168
|
+
* a substring of text). A top-level field is the attribute itself, so its stored form is the
|
|
1169
|
+
* schema's. The value itself where the field has no encoder or it doesn't take the value, or
|
|
1170
|
+
* what it gives DynamoDB can't store, and at a nested path (the encoders are per attribute). A
|
|
1171
|
+
* list filter's operand that is one of Effect's instances or a `Date` is sent in this form
|
|
1172
|
+
* (`operandsAsStored`).
|
|
1173
|
+
*/
|
|
1174
|
+
const rootStoredFormAt = (segments, value, kind) => {
|
|
1175
|
+
const name = String(segments[0]);
|
|
1176
|
+
const encode = segments.length === 1 ? attrEncoders[name] : undefined;
|
|
1177
|
+
const field = schemaFields?.[name];
|
|
1178
|
+
if (encode === undefined || field === undefined)
|
|
1179
|
+
return value;
|
|
1180
|
+
const storedOf = (given) => {
|
|
1181
|
+
let asGiven = false;
|
|
1182
|
+
try {
|
|
1183
|
+
const stored = encode(given, () => {
|
|
1184
|
+
asGiven = true;
|
|
1185
|
+
});
|
|
1186
|
+
return asGiven || unstorableIn({ stored }) !== undefined ? undefined : { stored };
|
|
1187
|
+
}
|
|
1188
|
+
catch {
|
|
1189
|
+
return undefined;
|
|
1190
|
+
}
|
|
1191
|
+
};
|
|
1192
|
+
const stored = kind === "value"
|
|
1193
|
+
? storedOf(value)
|
|
1194
|
+
: containedOperand(containedKindOf(field), storedOf, (element) => {
|
|
1195
|
+
const list = storedOf([element])?.stored;
|
|
1196
|
+
return Array.isArray(list) && list.length === 1 ? { stored: list[0] } : undefined;
|
|
1197
|
+
})(value);
|
|
1198
|
+
return stored === undefined ? value : stored.stored;
|
|
1199
|
+
};
|
|
712
1200
|
// Decode schema for read/assemble + input validation. Mirrors the raw `schema`
|
|
713
1201
|
// but recursively substitutes EVERY date / Redacted / transformed leaf — root
|
|
714
1202
|
// and nested — with a TOLERANT transform. This is the single decode path for
|
|
@@ -783,6 +1271,15 @@ const makeAggregate = (schema, config) => {
|
|
|
783
1271
|
`\`collection.index\` naming the GSI partitioned by "${config.pk.field}".`);
|
|
784
1272
|
}
|
|
785
1273
|
}
|
|
1274
|
+
// Its key attributes are the table's, registered on it or not: the library adds none of its own
|
|
1275
|
+
// under their names (`Table.tableKeyAttributes`, #237).
|
|
1276
|
+
addTableKeyAttributes(config.table.Tag, [
|
|
1277
|
+
config.pk.field,
|
|
1278
|
+
tablePrimary?.pk ?? config.pk.field,
|
|
1279
|
+
tablePrimary?.sk ?? "sk",
|
|
1280
|
+
...(config.collection.sk === undefined ? [] : [config.collection.sk.field]),
|
|
1281
|
+
...(config.list ? [config.list.pk.field, config.list.sk.field] : []),
|
|
1282
|
+
]);
|
|
786
1283
|
refuseAggregateKeyInTableKey(aggregateName, [config.pk.field, "sk", tablePrimary?.pk, tablePrimary?.sk], [
|
|
787
1284
|
...(config.collection.index === undefined || config.collection.sk === undefined
|
|
788
1285
|
? []
|
|
@@ -808,7 +1305,7 @@ const makeAggregate = (schema, config) => {
|
|
|
808
1305
|
const map = new Map();
|
|
809
1306
|
for (const item of allItems) {
|
|
810
1307
|
const sk = item.sk;
|
|
811
|
-
const prior = item
|
|
1308
|
+
const prior = ownValue(item, createdField);
|
|
812
1309
|
if (typeof sk === "string" && prior !== undefined)
|
|
813
1310
|
map.set(sk, prior);
|
|
814
1311
|
}
|
|
@@ -819,7 +1316,9 @@ const makeAggregate = (schema, config) => {
|
|
|
819
1316
|
/** Compose keys and marshal rows: a value it can't place is a `ValidationError`, not a defect. */
|
|
820
1317
|
const composeOrFail = (operation, compose) => marshalOrFail(aggregateName, `aggregate.${operation}`, compose);
|
|
821
1318
|
/** The partition key `record` composes. Throws what {@link composeOrFail} turns into its failure. */
|
|
822
|
-
const collectionPkOf = (record
|
|
1319
|
+
const collectionPkOf = (record,
|
|
1320
|
+
/** `create`'s own schema: its partition key is the write's own (`EDD-9162`). */
|
|
1321
|
+
under = config.schema) => composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(aggregateName, AGGREGATE_KEY.partition, under, config.pk.composite, keyRecord(record)));
|
|
823
1322
|
// Build optics at construction time (once per aggregate definition)
|
|
824
1323
|
const classToPlain = Schema.toIso(schema);
|
|
825
1324
|
const opticRoot = Schema.toIsoFocus(schema);
|
|
@@ -869,8 +1368,9 @@ const makeAggregate = (schema, config) => {
|
|
|
869
1368
|
const keyRecord = (record) => {
|
|
870
1369
|
const composites = {};
|
|
871
1370
|
for (const attr of compositeAttrs) {
|
|
872
|
-
|
|
873
|
-
|
|
1371
|
+
const entry = givenEntry(record, attr);
|
|
1372
|
+
if (entry !== undefined)
|
|
1373
|
+
setOwn(composites, attr, entry.value);
|
|
874
1374
|
}
|
|
875
1375
|
return toCompositeKeyRecord(compositeKeyForm, composites);
|
|
876
1376
|
};
|
|
@@ -893,9 +1393,9 @@ const makeAggregate = (schema, config) => {
|
|
|
893
1393
|
const decodeRootKey = (() => {
|
|
894
1394
|
const fields = {};
|
|
895
1395
|
for (const attr of config.pk.composite) {
|
|
896
|
-
const field = schemaFields
|
|
1396
|
+
const field = ownValue(schemaFields, attr);
|
|
897
1397
|
if (field !== undefined)
|
|
898
|
-
fields
|
|
1398
|
+
setOwn(fields, attr, field);
|
|
899
1399
|
}
|
|
900
1400
|
return Schema.decodeUnknownOption(substituteSchemaDeep(Schema.Struct(fields), {
|
|
901
1401
|
tolerantTransforms: true,
|
|
@@ -912,8 +1412,8 @@ const makeAggregate = (schema, config) => {
|
|
|
912
1412
|
const rootKeyAsRead = (row) => {
|
|
913
1413
|
const composites = {};
|
|
914
1414
|
for (const attr of config.pk.composite) {
|
|
915
|
-
if (attr
|
|
916
|
-
composites
|
|
1415
|
+
if (hasOwnName(row, attr))
|
|
1416
|
+
setOwn(composites, attr, row[attr]);
|
|
917
1417
|
}
|
|
918
1418
|
const read = decodeRootKey(composites);
|
|
919
1419
|
return Option.isSome(read) ? { ...row, ...read.value } : row;
|
|
@@ -929,10 +1429,36 @@ const makeAggregate = (schema, config) => {
|
|
|
929
1429
|
const from = rekeyRead?.from;
|
|
930
1430
|
const allItems = from === undefined
|
|
931
1431
|
? yield* read(pkValue)
|
|
932
|
-
: [...(yield* read(from)), ...(
|
|
1432
|
+
: [...(yield* read(from)), ...(yield* read(pkValue))];
|
|
933
1433
|
return { client, tableConfig, pkValue, allItems };
|
|
934
1434
|
});
|
|
935
1435
|
const holdsCustom = holdsCustomDeclaration(schema.ast);
|
|
1436
|
+
const holdsUntypedValue = holdsUntyped(schema.ast);
|
|
1437
|
+
/**
|
|
1438
|
+
* Refuses a write whose rows hold, where no schema types a value, a part DynamoDB doesn't store
|
|
1439
|
+
* (`EDD-9161`): a `Date` is written as an empty map and reads back as `{}`. Only an aggregate whose
|
|
1440
|
+
* model holds such a position pays for the walk. Run before anything is marshalled: a part behind
|
|
1441
|
+
* a getter is marked here, and judged as the marshaller calls the getter.
|
|
1442
|
+
*/
|
|
1443
|
+
const refuseLost = (groups, operation) => {
|
|
1444
|
+
if (!holdsUntypedValue)
|
|
1445
|
+
return Effect.void;
|
|
1446
|
+
for (const group of groups) {
|
|
1447
|
+
for (const item of group.items) {
|
|
1448
|
+
for (const [attr, value] of Object.entries(item.attributes)) {
|
|
1449
|
+
const lost = lostIn(value);
|
|
1450
|
+
if (lost === undefined)
|
|
1451
|
+
continue;
|
|
1452
|
+
return Effect.fail(new ValidationError({
|
|
1453
|
+
entityType: aggregateName,
|
|
1454
|
+
operation,
|
|
1455
|
+
cause: notReadBack(`Field "${attr}" of "${item.member}"`, lost, attr),
|
|
1456
|
+
}));
|
|
1457
|
+
}
|
|
1458
|
+
}
|
|
1459
|
+
}
|
|
1460
|
+
return Effect.void;
|
|
1461
|
+
};
|
|
936
1462
|
/**
|
|
937
1463
|
* Refuses the rows of a write that wouldn't read back: the rows it's about to write, through the read
|
|
938
1464
|
* path a `get` takes. Only two kinds of write pay for it: one of an aggregate holding a custom
|
|
@@ -1043,7 +1569,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1043
1569
|
const into = `edge "${node.fieldName}"'s sort key`;
|
|
1044
1570
|
const fields = node.ownFields;
|
|
1045
1571
|
return composites.flatMap((path) => {
|
|
1046
|
-
const top = fields
|
|
1572
|
+
const top = ownValue(fields, path.slice(0, path.indexOf(".")));
|
|
1047
1573
|
const leaf = fieldAtPath(fields, path);
|
|
1048
1574
|
return fields !== undefined &&
|
|
1049
1575
|
top !== undefined &&
|
|
@@ -1079,6 +1605,270 @@ const makeAggregate = (schema, config) => {
|
|
|
1079
1605
|
walk(rootNode);
|
|
1080
1606
|
return byNode;
|
|
1081
1607
|
})();
|
|
1608
|
+
/** Each key attribute the library writes on a row, by what it holds (`EDD-9159` names it). */
|
|
1609
|
+
const keyWhat = new Map(rowKeysOn("root", config));
|
|
1610
|
+
const whatIs = (name) => keyWhat.get(name) ?? "a context attribute the aggregate copies onto its rows";
|
|
1611
|
+
// A read's decode of one name of a member's value, through the field's schema (`Struct({ name:
|
|
1612
|
+
// field })`, as assembly substitutes it), and of a whole value: one each, built on first use.
|
|
1613
|
+
const nameReads = new Map();
|
|
1614
|
+
const nameRead = (name, field) => {
|
|
1615
|
+
const byName = nameReads.get(field) ?? new Map();
|
|
1616
|
+
nameReads.set(field, byName);
|
|
1617
|
+
let read = byName.get(name);
|
|
1618
|
+
if (read === undefined) {
|
|
1619
|
+
read = readsAs(Schema.Struct({ [name]: field }), resolveRef);
|
|
1620
|
+
byName.set(name, read);
|
|
1621
|
+
}
|
|
1622
|
+
return read;
|
|
1623
|
+
};
|
|
1624
|
+
const wholeReads = new Map();
|
|
1625
|
+
const wholeRead = (schema) => {
|
|
1626
|
+
let read = wholeReads.get(schema);
|
|
1627
|
+
if (read === undefined) {
|
|
1628
|
+
read = readsAs(schema, resolveRef);
|
|
1629
|
+
wholeReads.set(schema, read);
|
|
1630
|
+
}
|
|
1631
|
+
return read;
|
|
1632
|
+
};
|
|
1633
|
+
/** `holder`'s own `name`, `undefined` when it holds none. */
|
|
1634
|
+
const ownAt = (holder, name) => holder !== null && typeof holder === "object" && Object.hasOwn(holder, name)
|
|
1635
|
+
? holder[name]
|
|
1636
|
+
: undefined;
|
|
1637
|
+
/**
|
|
1638
|
+
* What a read of `node`'s row returns at `name` (#241): `value` is the row as a read hands its
|
|
1639
|
+
* value over (`rowValueAsRead`), decoded as assembly decodes it: by the field's schema where the
|
|
1640
|
+
* member's places the name (`placedFields`), as it is where the member keeps what it's given, and
|
|
1641
|
+
* otherwise by the whole value's schema. `undefined` where none of these reads it.
|
|
1642
|
+
*/
|
|
1643
|
+
const readAt = (node, value, name) => {
|
|
1644
|
+
const placed = node.placed;
|
|
1645
|
+
if (placed === "any")
|
|
1646
|
+
return { read: ownAt(value, name) };
|
|
1647
|
+
if (placed !== undefined) {
|
|
1648
|
+
if (!Object.hasOwn(placed, name))
|
|
1649
|
+
return undefined;
|
|
1650
|
+
const read = nameRead(name, placed[name])(Object.hasOwn(value, name) ? { [name]: value[name] } : {});
|
|
1651
|
+
return "fails" in read ? read : { read: ownAt(read.ok, name) };
|
|
1652
|
+
}
|
|
1653
|
+
if (node.valueReadSchema === undefined)
|
|
1654
|
+
return undefined;
|
|
1655
|
+
const read = wholeRead(node.valueReadSchema)(value);
|
|
1656
|
+
return "fails" in read ? read : { read: ownAt(read.ok, name) };
|
|
1657
|
+
};
|
|
1658
|
+
/**
|
|
1659
|
+
* Whether a read of `node`'s value can only be made whole (#241): the root, or a sub-aggregate with
|
|
1660
|
+
* edges of its own, whose schema can't place each name of its row (a union, `Schema.suspend`).
|
|
1661
|
+
* Assembly reads such a value from its row and its edges' rows together, as a `get` does
|
|
1662
|
+
* ({@link nodeReadOf}).
|
|
1663
|
+
*/
|
|
1664
|
+
const readWhole = (node) => node.placed === undefined && (node === rootNode || node.children.length > 0);
|
|
1665
|
+
/**
|
|
1666
|
+
* What a `get` reads of `node`'s value from `rows`, as assembly reads it (#241): the root's value
|
|
1667
|
+
* is the whole aggregate's, read as `get` reads it; a sub-aggregate's is its row and its edges'
|
|
1668
|
+
* rows put together ({@link assembleNode}) and decoded by the field holding it.
|
|
1669
|
+
*/
|
|
1670
|
+
const nodeReadOf = (node, rows) => Effect.map(Effect.exit(node === rootNode
|
|
1671
|
+
? assembleAggregate(assembly, rootNode, rows, contextFields, {}, aggregateName, systemAttrs)
|
|
1672
|
+
: Effect.flatMap(assembleNode(node, assemblyWalk(rootNode, rows, (each, row) => takesRow(each, row.__edd_e__, (attr) => row[attr])), {}, aggregateName, systemAttrs), (raw) => Effect.succeed(nameRead(node.fieldName, node.fieldSchema)(raw === undefined ? {} : { [node.fieldName]: raw })))), (exit) => {
|
|
1673
|
+
if (Exit.isFailure(exit))
|
|
1674
|
+
return { fails: issueText(Cause.squash(exit.cause)) };
|
|
1675
|
+
const read = exit.value;
|
|
1676
|
+
if (node === rootNode)
|
|
1677
|
+
return { read };
|
|
1678
|
+
const named = read;
|
|
1679
|
+
return "fails" in named ? named : { read: ownAt(named.ok, node.fieldName) };
|
|
1680
|
+
});
|
|
1681
|
+
/**
|
|
1682
|
+
* The names `create` judges on `item`'s row: each the library writes there (`written`: its key
|
|
1683
|
+
* attributes, and on a row beneath the root each context attribute) where a read of the member
|
|
1684
|
+
* reads it ({@link readAt}). One the caller's input gives a value at the top of the row's value
|
|
1685
|
+
* (`item.input`, read with `given`, so a function is none) is judged against that value. One it
|
|
1686
|
+
* gives none, where the member's schema places the name, is judged only by whether the read
|
|
1687
|
+
* succeeds: what the library writes there is the member's value of it, and a row whose read fails
|
|
1688
|
+
* reads back as nothing (1.40.0 stored it). A context name the member declares with the root's
|
|
1689
|
+
* own schema reads as the root's does, so it's left out. A discriminator is the library's to fill.
|
|
1690
|
+
*/
|
|
1691
|
+
const judgedNames = (item, written) => {
|
|
1692
|
+
const { node, input } = item;
|
|
1693
|
+
if (input === null || typeof input !== "object")
|
|
1694
|
+
return [];
|
|
1695
|
+
const whole = readWhole(node);
|
|
1696
|
+
return [...new Set(written)].flatMap((name) => {
|
|
1697
|
+
if (node.discriminator !== undefined && Object.hasOwn(node.discriminator, name))
|
|
1698
|
+
return [];
|
|
1699
|
+
const placed = node.placed;
|
|
1700
|
+
if (given(input, name) !== undefined) {
|
|
1701
|
+
if (placed === "any")
|
|
1702
|
+
return [{ name, given: true }];
|
|
1703
|
+
if (placed !== undefined)
|
|
1704
|
+
return Object.hasOwn(placed, name) ? [{ name, given: true }] : [];
|
|
1705
|
+
return (node.valueReadSchema !== undefined || whole) &&
|
|
1706
|
+
ownAt(item.value, name) !== undefined
|
|
1707
|
+
? [{ name, given: true }]
|
|
1708
|
+
: [];
|
|
1709
|
+
}
|
|
1710
|
+
// A sub-aggregate its schema can't place reads every name it's given none of as a whole.
|
|
1711
|
+
if (whole)
|
|
1712
|
+
return node === rootNode ? [] : [{ name, given: false }];
|
|
1713
|
+
if (placed === undefined || placed === "any" || !Object.hasOwn(placed, name))
|
|
1714
|
+
return [];
|
|
1715
|
+
const rootField = schemaFields?.[name];
|
|
1716
|
+
if (rootField !== undefined &&
|
|
1717
|
+
unwrapOptionalField(placed[name]) === unwrapOptionalField(rootField)) {
|
|
1718
|
+
return [];
|
|
1719
|
+
}
|
|
1720
|
+
return [{ name, given: false }];
|
|
1721
|
+
});
|
|
1722
|
+
};
|
|
1723
|
+
/**
|
|
1724
|
+
* `[EDD-9159]`, on `create` only (#241): a value the caller gives where the library writes its
|
|
1725
|
+
* own, which a `get` right after wouldn't return. Each row as the write builds it (`built`, in the
|
|
1726
|
+
* order of `groups`) is read as a `get` reads it: unmarshalled, its packed attributes unpacked,
|
|
1727
|
+
* taken as its member's value (`rowValueAsRead`) and decoded by the member's schema
|
|
1728
|
+
* ({@link readAt}). The value read is compared with the value given, decoded (`item.value`), in
|
|
1729
|
+
* domain terms ({@link sameValue}): equal, the row is written as on 1.40.0; different, or a read
|
|
1730
|
+
* that fails there, and the `create` is refused, nothing sent, the message showing both. A `many`
|
|
1731
|
+
* edge with a custom `decompose` or `assemble` is read whole, through it: refused where its read
|
|
1732
|
+
* with the library's values differs from its read with the values its rows held. Nothing is read
|
|
1733
|
+
* for a `create` giving no such value.
|
|
1734
|
+
*/
|
|
1735
|
+
const refuseGivenOverRows = (groups, built) => {
|
|
1736
|
+
const judged = [];
|
|
1737
|
+
const custom = new Map();
|
|
1738
|
+
groups.forEach((group, g) => {
|
|
1739
|
+
group.items.forEach((item, i) => {
|
|
1740
|
+
const written = [
|
|
1741
|
+
...built[g].written[i],
|
|
1742
|
+
...(item.node.cardinality === "root" ? [] : contextFields),
|
|
1743
|
+
];
|
|
1744
|
+
if (item.node.decompose !== undefined || item.node.assemble !== undefined) {
|
|
1745
|
+
const rows = custom.get(item.node) ?? [];
|
|
1746
|
+
rows.push({ g, i, item, written });
|
|
1747
|
+
custom.set(item.node, rows);
|
|
1748
|
+
return;
|
|
1749
|
+
}
|
|
1750
|
+
const names = judgedNames(item, written);
|
|
1751
|
+
if (names.length > 0)
|
|
1752
|
+
judged.push({ g, i, item, names });
|
|
1753
|
+
});
|
|
1754
|
+
});
|
|
1755
|
+
const customOwn = [...custom.values()].some((rows) => rows.some(({ item, written }) => written.some((name) => Object.hasOwn(item.own, name))));
|
|
1756
|
+
if (judged.length === 0 && !customOwn && (custom.size === 0 || contextFields.length === 0)) {
|
|
1757
|
+
return Effect.void;
|
|
1758
|
+
}
|
|
1759
|
+
return Effect.gen(function* () {
|
|
1760
|
+
// Every row built, as a read hands it over: unmarshalled, its packed attributes unpacked.
|
|
1761
|
+
const rows = built.map((group) => group.items.map((item) => fromAttributeMap(item)));
|
|
1762
|
+
yield* unpackAggregateItems(rows.flat(), dispatchByType, aggregateName);
|
|
1763
|
+
const all = rows.flat();
|
|
1764
|
+
const wholeReads = new Map();
|
|
1765
|
+
for (const { g, i, item, names } of judged) {
|
|
1766
|
+
const row = rows[g][i];
|
|
1767
|
+
const value = rowValueAsRead(item.node, row, systemAttrs);
|
|
1768
|
+
let whole;
|
|
1769
|
+
if (readWhole(item.node)) {
|
|
1770
|
+
whole = wholeReads.get(item.node);
|
|
1771
|
+
if (whole === undefined) {
|
|
1772
|
+
whole = yield* nodeReadOf(item.node, all);
|
|
1773
|
+
wholeReads.set(item.node, whole);
|
|
1774
|
+
}
|
|
1775
|
+
}
|
|
1776
|
+
for (const { name, given: isGiven } of names) {
|
|
1777
|
+
const read = whole === undefined
|
|
1778
|
+
? readAt(item.node, value, name)
|
|
1779
|
+
: "fails" in whole
|
|
1780
|
+
? whole
|
|
1781
|
+
: { read: ownAt(whole.read, name) };
|
|
1782
|
+
if (read === undefined)
|
|
1783
|
+
continue;
|
|
1784
|
+
if (!isGiven) {
|
|
1785
|
+
if ("read" in read)
|
|
1786
|
+
continue;
|
|
1787
|
+
if (whole !== undefined) {
|
|
1788
|
+
// Read whole, the failure is the library's value's only if the read without it holds.
|
|
1789
|
+
const { [name]: _, ...bare } = row;
|
|
1790
|
+
const without = yield* nodeReadOf(item.node, all.map((each) => (each === row ? bare : each)));
|
|
1791
|
+
if ("fails" in without)
|
|
1792
|
+
continue;
|
|
1793
|
+
}
|
|
1794
|
+
return yield* new AggregateDecompositionError({
|
|
1795
|
+
aggregate: aggregateName,
|
|
1796
|
+
member: item.member,
|
|
1797
|
+
reason: unreadOverRowReason(item.member, name, whatIs(name), read.fails),
|
|
1798
|
+
});
|
|
1799
|
+
}
|
|
1800
|
+
if ("read" in read && sameValue(ownAt(item.value, name), read.read))
|
|
1801
|
+
continue;
|
|
1802
|
+
return yield* new AggregateDecompositionError({
|
|
1803
|
+
aggregate: aggregateName,
|
|
1804
|
+
member: item.member,
|
|
1805
|
+
reason: givenOverRowReason(item.member, name, given(item.input, name), whatIs(name), read),
|
|
1806
|
+
});
|
|
1807
|
+
}
|
|
1808
|
+
}
|
|
1809
|
+
for (const [node, entries] of custom) {
|
|
1810
|
+
if (node.fieldName === null || node.fieldSchema === undefined)
|
|
1811
|
+
continue;
|
|
1812
|
+
const field = node.fieldName;
|
|
1813
|
+
// The rows as the custom `decompose` returned them: each value the library wrote over one
|
|
1814
|
+
// of theirs put back, as a read would hand it over.
|
|
1815
|
+
const overwritten = [];
|
|
1816
|
+
const actual = entries.map(({ g, i }) => rows[g][i]);
|
|
1817
|
+
const asReturned = entries.map(({ g, i, item, written }) => {
|
|
1818
|
+
const row = { ...rows[g][i] };
|
|
1819
|
+
for (const name of new Set(written)) {
|
|
1820
|
+
if (!Object.hasOwn(item.own, name))
|
|
1821
|
+
continue;
|
|
1822
|
+
let own;
|
|
1823
|
+
try {
|
|
1824
|
+
own = asRead(item.own[name]);
|
|
1825
|
+
}
|
|
1826
|
+
catch {
|
|
1827
|
+
continue;
|
|
1828
|
+
}
|
|
1829
|
+
if (sameValue(own, row[name]))
|
|
1830
|
+
continue;
|
|
1831
|
+
overwritten.push({ item, name, own });
|
|
1832
|
+
row[name] = own;
|
|
1833
|
+
}
|
|
1834
|
+
return row;
|
|
1835
|
+
});
|
|
1836
|
+
const readOf = (edgeRows) => Effect.map(Effect.exit(assembleNode(node, new Map([[node, edgeRows]]), {}, aggregateName, systemAttrs)), (exit) => {
|
|
1837
|
+
if (Exit.isFailure(exit))
|
|
1838
|
+
return { fails: issueText(Cause.squash(exit.cause)) };
|
|
1839
|
+
const read = nameRead(field, node.fieldSchema)(exit.value === undefined ? {} : { [field]: exit.value });
|
|
1840
|
+
return "fails" in read ? read : { read: ownAt(read.ok, field) };
|
|
1841
|
+
});
|
|
1842
|
+
if (overwritten.length === 0) {
|
|
1843
|
+
// Nothing given where the library writes: its rows read back unless a read of them fails
|
|
1844
|
+
// over what it writes there (a context copy the elements declare in another form).
|
|
1845
|
+
if (contextFields.length === 0)
|
|
1846
|
+
continue;
|
|
1847
|
+
const read = yield* readOf(actual);
|
|
1848
|
+
if ("read" in read)
|
|
1849
|
+
continue;
|
|
1850
|
+
const { item } = entries[0];
|
|
1851
|
+
return yield* new AggregateDecompositionError({
|
|
1852
|
+
aggregate: aggregateName,
|
|
1853
|
+
member: item.member,
|
|
1854
|
+
reason: customUnreadReason(item.member, contextFields, read.fails),
|
|
1855
|
+
});
|
|
1856
|
+
}
|
|
1857
|
+
const was = yield* readOf(asReturned);
|
|
1858
|
+
if ("fails" in was)
|
|
1859
|
+
continue;
|
|
1860
|
+
const now = yield* readOf(actual);
|
|
1861
|
+
if ("read" in now && sameValue(was.read, now.read))
|
|
1862
|
+
continue;
|
|
1863
|
+
const { item, name, own } = overwritten[0];
|
|
1864
|
+
return yield* new AggregateDecompositionError({
|
|
1865
|
+
aggregate: aggregateName,
|
|
1866
|
+
member: item.member,
|
|
1867
|
+
reason: customOverRowReason(item.member, name, own, whatIs(name), was.read, now),
|
|
1868
|
+
});
|
|
1869
|
+
}
|
|
1870
|
+
});
|
|
1871
|
+
};
|
|
1082
1872
|
/**
|
|
1083
1873
|
* Refuses a write storing, for a key composite whose numeric kinds can't be read at load, a value
|
|
1084
1874
|
* that reads back otherwise: a stored row would compose other key text (`EDD-9128`). `groups` is
|
|
@@ -1093,7 +1883,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1093
1883
|
// An attribute as a read has it: a discriminator is matched against what's read back.
|
|
1094
1884
|
(node, item) => takesRow(node, item.entityType, (attr) => {
|
|
1095
1885
|
try {
|
|
1096
|
-
return asRead(item.attributes
|
|
1886
|
+
return asRead(ownValue(item.attributes, attr));
|
|
1097
1887
|
}
|
|
1098
1888
|
catch {
|
|
1099
1889
|
return undefined;
|
|
@@ -1126,7 +1916,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1126
1916
|
}), rekeyRead);
|
|
1127
1917
|
const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps);
|
|
1128
1918
|
/** A stored row's position: its partition and sort key. */
|
|
1129
|
-
const positionOf = (pk, sk) =>
|
|
1919
|
+
const positionOf = (pk, sk) => Rekey.identity(pk, sk);
|
|
1130
1920
|
/**
|
|
1131
1921
|
* Attributes holding index keys the aggregate composes: the collection SK mirror, the list
|
|
1132
1922
|
* keys. Never a table key attribute, which `make` refuses (`EDD-9112`).
|
|
@@ -1140,16 +1930,21 @@ const makeAggregate = (schema, config) => {
|
|
|
1140
1930
|
/** Index key attributes of `composed` whose text the row stored as `stored` doesn't hold. */
|
|
1141
1931
|
const staleIndexFields = (composed, stored) => indexFields.filter((field) => {
|
|
1142
1932
|
const text = composed[field]?.S;
|
|
1143
|
-
return text !== undefined && text !== stored
|
|
1933
|
+
return text !== undefined && text !== ownValue(stored, field);
|
|
1144
1934
|
});
|
|
1145
1935
|
/**
|
|
1146
1936
|
* Where a row may be under the partition's old text: at the sort key the other setting composes,
|
|
1147
|
-
*
|
|
1148
|
-
*
|
|
1937
|
+
* at the one the other composition of an `entity:` edge's sort key composes (`skElse`, #241), or
|
|
1938
|
+
* the current one, where 1.37.0 and 1.38.0 wrote it (its partition key unescaped, its sort key
|
|
1939
|
+
* escaped). Under a partition whose text didn't change, the current sort key is where the row
|
|
1940
|
+
* belongs.
|
|
1149
1941
|
*/
|
|
1150
|
-
const oldPosition = (pk, pkNow, skOther, sk, storedAt, otherKind) => {
|
|
1942
|
+
const oldPosition = (pk, pkNow, skOther, skElse, sk, storedAt, otherKind) => {
|
|
1151
1943
|
if (storedAt.has(positionOf(pk, skOther)))
|
|
1152
1944
|
return { pk, sk: skOther };
|
|
1945
|
+
if (skElse !== undefined && skElse !== sk && storedAt.has(positionOf(pk, skElse))) {
|
|
1946
|
+
return { pk, sk: skElse };
|
|
1947
|
+
}
|
|
1153
1948
|
if (storedAt.has(positionOf(pk, sk)))
|
|
1154
1949
|
return { pk, sk: pk === pkNow ? skOther : sk };
|
|
1155
1950
|
// A sort key holding a numeric composite's other kind's text. Looked for only for a row at
|
|
@@ -1179,15 +1974,24 @@ const makeAggregate = (schema, config) => {
|
|
|
1179
1974
|
* the rows of them it reads beyond the ones its value keys, and `rekey` reports them.
|
|
1180
1975
|
*/
|
|
1181
1976
|
const ownsRows = config.ownsRows === true;
|
|
1977
|
+
/** The aggregate's entity types: `delete` deletes only the rows of these, option or not. */
|
|
1182
1978
|
const ownedTypes = new Set(nodeTypes);
|
|
1183
1979
|
/**
|
|
1184
1980
|
* Each node a row can be handed to, as `assembleNode` hands rows: its entity type and its static
|
|
1185
1981
|
* discriminator (an enclosing sub-aggregate's merged in at resolve time). With the transaction
|
|
1186
|
-
* group its rows are written in
|
|
1982
|
+
* group its rows are written in, the discriminator values its sort key holds, and those values as
|
|
1983
|
+
* declared (`keyEntries`, which `EDD-9162` judges).
|
|
1187
1984
|
*/
|
|
1188
1985
|
const nodeSlots = (() => {
|
|
1189
|
-
const slots = [
|
|
1190
|
-
|
|
1986
|
+
const slots = [
|
|
1987
|
+
{
|
|
1988
|
+
node: rootNode,
|
|
1989
|
+
group: "root",
|
|
1990
|
+
keyDiscriminators: { current: [], other: () => [] },
|
|
1991
|
+
keyEntries: [],
|
|
1992
|
+
},
|
|
1993
|
+
];
|
|
1994
|
+
const visit = (node, parentGroup, parent, parentEntries) => {
|
|
1191
1995
|
if (node.cardinality === "one" && node.children.length > 0) {
|
|
1192
1996
|
const ownName = node.fieldName ?? node.entityType;
|
|
1193
1997
|
const group = parentGroup === "root" ? ownName : `${parentGroup}.${ownName}`;
|
|
@@ -1196,9 +2000,10 @@ const makeAggregate = (schema, config) => {
|
|
|
1196
2000
|
current: [...parent.current, ...own.current],
|
|
1197
2001
|
other: () => [...parent.other(), ...own.other()],
|
|
1198
2002
|
};
|
|
1199
|
-
|
|
2003
|
+
const keyEntries = [...parentEntries, ...ownDiscriminatorEntries(node)];
|
|
2004
|
+
slots.push({ node, group, keyDiscriminators: values, keyEntries });
|
|
1200
2005
|
for (const child of node.children)
|
|
1201
|
-
visit(child, group, values);
|
|
2006
|
+
visit(child, group, values, keyEntries);
|
|
1202
2007
|
return;
|
|
1203
2008
|
}
|
|
1204
2009
|
if (node.cardinality === "one") {
|
|
@@ -1210,15 +2015,65 @@ const makeAggregate = (schema, config) => {
|
|
|
1210
2015
|
current: [...parent.current, ...own.current],
|
|
1211
2016
|
other: () => [...parent.other(), ...own.other()],
|
|
1212
2017
|
},
|
|
2018
|
+
keyEntries: [...parentEntries, ...ownDiscriminatorEntries(node)],
|
|
1213
2019
|
});
|
|
1214
2020
|
return;
|
|
1215
2021
|
}
|
|
1216
|
-
slots.push({ node, group: parentGroup, keyDiscriminators: parent });
|
|
2022
|
+
slots.push({ node, group: parentGroup, keyDiscriminators: parent, keyEntries: parentEntries });
|
|
1217
2023
|
};
|
|
1218
|
-
for (const child of rootNode.children)
|
|
1219
|
-
visit(child, "root", { current: [], other: () => [] });
|
|
2024
|
+
for (const child of rootNode.children) {
|
|
2025
|
+
visit(child, "root", { current: [], other: () => [] }, []);
|
|
2026
|
+
}
|
|
1220
2027
|
return slots;
|
|
1221
2028
|
})();
|
|
2029
|
+
/** The static discriminator values each node's sort key composes (`EDD-9162` judges them). */
|
|
2030
|
+
const keyEntriesOf = new Map(nodeSlots.map(({ node, keyEntries }) => [node, keyEntries]));
|
|
2031
|
+
/**
|
|
2032
|
+
* The keys a write composes its own values into (#242, `EDD-9162`), as an entity's write does: where
|
|
2033
|
+
* the partition key (`create`'s), `buildDynamoItems` or a row's sort key composes a key from an
|
|
2034
|
+
* object composing `[object Object]`, which every such object composes alike, the write is refused
|
|
2035
|
+
* there. Aggregates written with different values would share one partition, or one list or
|
|
2036
|
+
* collection key, or a row would be keyed by a text no read finds again. A key the write doesn't
|
|
2037
|
+
* compose refuses nothing: a list key missing a value. A `many` element's sort key already refuses
|
|
2038
|
+
* every object (`manyEdgeSkComposites`).
|
|
2039
|
+
*
|
|
2040
|
+
* `read`, on an `update`, is the aggregate as read: a root composite equal to the one the root read
|
|
2041
|
+
* holds is the key that row is stored under, composed again, as an entity update's own key record
|
|
2042
|
+
* is, so an aggregate an earlier release wrote can still be updated. A `get`, `list` or `delete`
|
|
2043
|
+
* composes the text as it always did.
|
|
2044
|
+
*/
|
|
2045
|
+
const ownKeys = (read) => {
|
|
2046
|
+
// A record whose key form fails has no key to keep.
|
|
2047
|
+
const formOf = (record) => {
|
|
2048
|
+
if (record === undefined)
|
|
2049
|
+
return undefined;
|
|
2050
|
+
try {
|
|
2051
|
+
return keyRecord(record);
|
|
2052
|
+
}
|
|
2053
|
+
catch {
|
|
2054
|
+
return undefined;
|
|
2055
|
+
}
|
|
2056
|
+
};
|
|
2057
|
+
return {
|
|
2058
|
+
schema: {
|
|
2059
|
+
...config.schema,
|
|
2060
|
+
objectKeys: (site) => {
|
|
2061
|
+
if (site.key instanceof DiscriminatorKey) {
|
|
2062
|
+
return `Discriminator "${site.attr}" of "${site.key.member}" is composed into its sort key`;
|
|
2063
|
+
}
|
|
2064
|
+
if (read !== undefined && site.attr !== undefined) {
|
|
2065
|
+
const asRead = formOf(site.key === AGGREGATE_KEY.listPartition || site.key === AGGREGATE_KEY.listSort
|
|
2066
|
+
? read.rootKey
|
|
2067
|
+
: read.rootValue);
|
|
2068
|
+
if (asRead !== undefined && deepEqual(asRead[site.attr], site.value))
|
|
2069
|
+
return undefined;
|
|
2070
|
+
}
|
|
2071
|
+
return `Field "${site.attr}" of "${rootNode.entityType}" is composed into ${site.key.into}`;
|
|
2072
|
+
},
|
|
2073
|
+
},
|
|
2074
|
+
discriminators: (node) => keyEntriesOf.get(node) ?? [],
|
|
2075
|
+
};
|
|
2076
|
+
};
|
|
1222
2077
|
/** The nodes `item` is handed to by its entity type and static discriminator. */
|
|
1223
2078
|
const slotsOf = (item) => nodeSlots.filter(({ node }) => item.__edd_e__ === node.entityType &&
|
|
1224
2079
|
Object.entries(node.discriminator ?? {}).every(([attr, value]) => typeof value === "function" || (Object.hasOwn(item, attr) && item[attr] === value)));
|
|
@@ -1357,6 +2212,42 @@ const makeAggregate = (schema, config) => {
|
|
|
1357
2212
|
...Object.entries((config.table.aggregates ?? {})),
|
|
1358
2213
|
].map(([name, member]) => ({ name, member })),
|
|
1359
2214
|
};
|
|
2215
|
+
/**
|
|
2216
|
+
* Whether `stored`, a row read from the partition, is provably not `item`'s: a `many` element's
|
|
2217
|
+
* row holding other values for what its sort key is composed from (its declared `sk.composite`,
|
|
2218
|
+
* else its refs' identifiers, and its node's discriminators). Values neither side holds, or one
|
|
2219
|
+
* the marshaller refuses, prove nothing. Any other row's sort key is its node's alone.
|
|
2220
|
+
*/
|
|
2221
|
+
const otherElement = (item, stored) => {
|
|
2222
|
+
const node = item.node;
|
|
2223
|
+
if (node.cardinality !== "many")
|
|
2224
|
+
return false;
|
|
2225
|
+
const text = (value) => {
|
|
2226
|
+
if (value === undefined || value === null)
|
|
2227
|
+
return undefined;
|
|
2228
|
+
try {
|
|
2229
|
+
return Rekey.canonicalValue(toAttributeValue(value));
|
|
2230
|
+
}
|
|
2231
|
+
catch {
|
|
2232
|
+
return undefined;
|
|
2233
|
+
}
|
|
2234
|
+
};
|
|
2235
|
+
const differs = (ours, theirs) => {
|
|
2236
|
+
const a = text(ours);
|
|
2237
|
+
const b = text(theirs);
|
|
2238
|
+
return a !== undefined && b !== undefined && a !== b;
|
|
2239
|
+
};
|
|
2240
|
+
for (const [field, value] of Object.entries(node.discriminator ?? {})) {
|
|
2241
|
+
if (typeof value !== "function" && differs(item.attributes[field], stored[field]))
|
|
2242
|
+
return true;
|
|
2243
|
+
}
|
|
2244
|
+
if (node.skComposite === undefined) {
|
|
2245
|
+
const ours = extractRefIdentifiers(item.attributes, node.refIdentifierField);
|
|
2246
|
+
const theirs = extractRefIdentifiers(stored, node.refIdentifierField);
|
|
2247
|
+
return ours.length === theirs.length && ours.some((id, i) => differs(id, theirs[i]));
|
|
2248
|
+
}
|
|
2249
|
+
return node.skComposite.some((path) => differs(readCompositePath(item.attributes, path), readCompositePath(stored, path)));
|
|
2250
|
+
};
|
|
1360
2251
|
/**
|
|
1361
2252
|
* `rekey`'s view of where the aggregate's rows are stored (#183, DESIGN.md §7 "`rekey`"): for
|
|
1362
2253
|
* each decomposed item, its current key and its old one — the partition the row was found in
|
|
@@ -1394,20 +2285,166 @@ const makeAggregate = (schema, config) => {
|
|
|
1394
2285
|
/** An element of a `many` edge with a custom `decompose`: its row moves as stored. */
|
|
1395
2286
|
custom: item.node.decompose !== undefined,
|
|
1396
2287
|
current: { pk: pkValue, sk },
|
|
1397
|
-
old: oldPosition(from ?? pkValue, pkValue, otherSortKey(config.schema, item, sk), sk, storedAt, (pk) => item.otherKindSortKey?.(sortKeysIn(pk, sk))),
|
|
2288
|
+
old: oldPosition(from ?? pkValue, pkValue, otherSortKey(config.schema, item, sk), otherCompositionSortKey(config.schema, item), sk, storedAt, (pk) => item.otherKindSortKey?.(sortKeysIn(pk, sk))),
|
|
1398
2289
|
};
|
|
1399
2290
|
}));
|
|
1400
2291
|
const placements = placeRows(rows.map((row) => ({
|
|
1401
2292
|
current: positionOf(row.current.pk, row.current.sk),
|
|
1402
2293
|
old: positionOf(row.old.pk, row.old.sk),
|
|
1403
2294
|
})), (position) => storedAt.has(position));
|
|
2295
|
+
// Another aggregate sharing the partition can hold a key of the chain (#240): its row reads,
|
|
2296
|
+
// by the keys alone, as this one's under both keys, or can't be told apart. There, a key holds
|
|
2297
|
+
// the row only if the row stored there holds the values its sort key is composed from
|
|
2298
|
+
// ({@link otherElement}); a row stored under neither by that test keeps what the keys said.
|
|
2299
|
+
const refined = placements.map((placement, r) => {
|
|
2300
|
+
if (placement !== "both" && placement !== "ambiguous")
|
|
2301
|
+
return placement;
|
|
2302
|
+
const row = rows[r];
|
|
2303
|
+
const holds = (at) => {
|
|
2304
|
+
const there = storedAt.get(positionOf(at.pk, at.sk));
|
|
2305
|
+
return there !== undefined && !otherElement(row.item, there);
|
|
2306
|
+
};
|
|
2307
|
+
const atOld = holds(row.old);
|
|
2308
|
+
const atCurrent = holds(row.current);
|
|
2309
|
+
if (atOld && atCurrent)
|
|
2310
|
+
return "both";
|
|
2311
|
+
if (atOld)
|
|
2312
|
+
return "old";
|
|
2313
|
+
if (atCurrent)
|
|
2314
|
+
return "current";
|
|
2315
|
+
return placement;
|
|
2316
|
+
});
|
|
1404
2317
|
return rows.map((row, r) => ({
|
|
1405
2318
|
...row,
|
|
1406
|
-
placement:
|
|
2319
|
+
placement: refined[r],
|
|
1407
2320
|
atCurrent: storedAt.get(positionOf(row.current.pk, row.current.sk)),
|
|
1408
2321
|
atOld: storedAt.get(positionOf(row.old.pk, row.old.sk)),
|
|
1409
2322
|
}));
|
|
1410
2323
|
};
|
|
2324
|
+
/** A context attribute's copy on a row, decoded as a read of the root decodes the root's own. */
|
|
2325
|
+
const contextCopyRead = (name, row) => {
|
|
2326
|
+
const field = schemaFields?.[name];
|
|
2327
|
+
const held = Object.hasOwn(row, name) ? row[name] : undefined;
|
|
2328
|
+
if (field === undefined)
|
|
2329
|
+
return { read: held };
|
|
2330
|
+
const read = nameRead(name, field)(held === undefined ? {} : { [name]: held });
|
|
2331
|
+
return "fails" in read ? read : { read: ownAt(read.ok, name) };
|
|
2332
|
+
};
|
|
2333
|
+
/**
|
|
2334
|
+
* The context attributes a write stores on a row of `node` as the root's copy (#241): each one
|
|
2335
|
+
* `context` names, except an attribute the library manages on that row whatever `context` says,
|
|
2336
|
+
* which a write puts there after the copy: a key attribute (`__edd_e__`, the partition key
|
|
2337
|
+
* attribute, `sk`, an index key the aggregate composes), a timestamp it stamps, or a discriminator
|
|
2338
|
+
* of the node. The root's own row holds the values, not copies. Decided from the definition, once
|
|
2339
|
+
* per node: `update`'s repair of a stale copy ({@link staleContextGroups}) and the copies its
|
|
2340
|
+
* result holds ({@link withStoredContextCopies}) both read it.
|
|
2341
|
+
*/
|
|
2342
|
+
const contextCopies = new Map();
|
|
2343
|
+
const libraryManaged = new Set([
|
|
2344
|
+
"__edd_e__",
|
|
2345
|
+
config.pk.field,
|
|
2346
|
+
"sk",
|
|
2347
|
+
...indexFields,
|
|
2348
|
+
...systemAttrs,
|
|
2349
|
+
]);
|
|
2350
|
+
const contextCopiesOn = (node) => {
|
|
2351
|
+
let names = contextCopies.get(node);
|
|
2352
|
+
if (names === undefined) {
|
|
2353
|
+
names =
|
|
2354
|
+
node === rootNode
|
|
2355
|
+
? []
|
|
2356
|
+
: contextFields.filter((name) => !libraryManaged.has(name) &&
|
|
2357
|
+
!(node.discriminator !== undefined &&
|
|
2358
|
+
Object.hasOwn(node.discriminator, name) &&
|
|
2359
|
+
typeof node.discriminator[name] !== "function"));
|
|
2360
|
+
contextCopies.set(node, names);
|
|
2361
|
+
}
|
|
2362
|
+
return names;
|
|
2363
|
+
};
|
|
2364
|
+
/**
|
|
2365
|
+
* `update`'s result (#241): 1.40.0's, the mutated state as decoded, with one change: where a
|
|
2366
|
+
* member value holds a copy of a context attribute ({@link contextCopiesOn}), the copy is what its
|
|
2367
|
+
* row holds once the write is done ({@link contextCopiesAsStored}). Nothing else differs: element
|
|
2368
|
+
* order, own properties (an explicit `undefined` included), classes and every other value are the
|
|
2369
|
+
* mutation's.
|
|
2370
|
+
*/
|
|
2371
|
+
const withStoredContextCopies = (decoded, rowAt) => {
|
|
2372
|
+
if (contextFields.length === 0)
|
|
2373
|
+
return decoded;
|
|
2374
|
+
const stored = contextValuesOf(decoded, contextFields, rootEncoders).stored;
|
|
2375
|
+
return contextCopiesAsStored(rootNode, decoded, stored, rowAt, contextCopiesOn, resolveRef);
|
|
2376
|
+
};
|
|
2377
|
+
/**
|
|
2378
|
+
* The groups holding a row read whose copy of a context attribute ({@link contextCopiesOn}) isn't
|
|
2379
|
+
* the root's value (#241), compared in domain terms: as stored by this release or as an earlier
|
|
2380
|
+
* one stored it, one value is one value, so rows a release wrote in another form (a date
|
|
2381
|
+
* `Schema.optional` held as ISO text) are not stale. A copy stored exactly as the root row stores
|
|
2382
|
+
* its own is the root's without decoding. A row is a group's as assembly hands it over
|
|
2383
|
+
* ({@link slotsOf}). An aggregate no write left half-written has none.
|
|
2384
|
+
*/
|
|
2385
|
+
const staleContextGroups = (allItems, root) => {
|
|
2386
|
+
const stale = new Set();
|
|
2387
|
+
if (contextFields.length === 0)
|
|
2388
|
+
return stale;
|
|
2389
|
+
const rootRow = allItems.find((row) => slotsOf(row).some(({ node }) => node === rootNode));
|
|
2390
|
+
for (const row of allItems) {
|
|
2391
|
+
for (const { node, group } of slotsOf(row)) {
|
|
2392
|
+
if (node === rootNode || stale.has(group))
|
|
2393
|
+
continue;
|
|
2394
|
+
const fresh = contextCopiesOn(node).every((name) => {
|
|
2395
|
+
if (rootRow !== undefined && sameValue(ownAt(row, name), ownAt(rootRow, name))) {
|
|
2396
|
+
return true;
|
|
2397
|
+
}
|
|
2398
|
+
const read = contextCopyRead(name, row);
|
|
2399
|
+
return "read" in read && sameValue(read.read, ownAt(root, name));
|
|
2400
|
+
});
|
|
2401
|
+
if (!fresh)
|
|
2402
|
+
stale.add(group);
|
|
2403
|
+
}
|
|
2404
|
+
}
|
|
2405
|
+
return stale;
|
|
2406
|
+
};
|
|
2407
|
+
/**
|
|
2408
|
+
* `[EDD-9160]` (#241): an update about to write a group one of whose values was read from a row
|
|
2409
|
+
* stored under a sort key other than the one this configuration composes for that value, through
|
|
2410
|
+
* the function the write itself keys rows with ({@link sortKeyOf}). Each value's row is the one a
|
|
2411
|
+
* read took it from ({@link rowsReadAt}). Such a row was written under the other `escapeKeys`
|
|
2412
|
+
* setting (`$`, `#` or another escaped character, a number other than a non-negative integer
|
|
2413
|
+
* below 1e16, an `entity:` edge's composite its model encodes), which `rekey` moves. Written, the
|
|
2414
|
+
* group's rows go under this setting's text beside them, and every element reads twice (up to
|
|
2415
|
+
* 1.40.0 the update wrote them). Refused before anything is written. A row the update moves itself
|
|
2416
|
+
* (an `entity:` edge's under 1.40.0's composition, `moved`) is not one, and a value whose row is
|
|
2417
|
+
* at the key composed now, whatever the setting, sends what it did.
|
|
2418
|
+
*/
|
|
2419
|
+
const refuseOtherSettingRows = (oldGroups, written, readAt, moved) => {
|
|
2420
|
+
for (const group of oldGroups) {
|
|
2421
|
+
if (!written(group.name))
|
|
2422
|
+
continue;
|
|
2423
|
+
for (const item of group.items) {
|
|
2424
|
+
if (item.path === undefined)
|
|
2425
|
+
continue;
|
|
2426
|
+
const row = readAt.get(JSON.stringify(item.path));
|
|
2427
|
+
const stored = row?.sk;
|
|
2428
|
+
const sk = sortKeyOf(config.schema, item);
|
|
2429
|
+
if (typeof stored !== "string" || sk === undefined || stored === sk)
|
|
2430
|
+
continue;
|
|
2431
|
+
if (moved.get(group.name)?.includes(stored) === true)
|
|
2432
|
+
continue;
|
|
2433
|
+
return Effect.fail(new ValidationError({
|
|
2434
|
+
entityType: aggregateName,
|
|
2435
|
+
operation: "aggregate.update",
|
|
2436
|
+
cause: new Error(`[EDD-9160] Aggregate "${aggregateName}": a row of "${item.member}" is stored under ` +
|
|
2437
|
+
`the sort key ${JSON.stringify(stored)}, and this schema ` +
|
|
2438
|
+
`(\`escapeKeys: ${config.schema.escapeKeys === true}\`) keys it ` +
|
|
2439
|
+
`${JSON.stringify(sk)}: the row was written under the other \`escapeKeys\` ` +
|
|
2440
|
+
"setting. Writing it would store the row a second time, and every read would " +
|
|
2441
|
+
"hand it back twice. Run `rekey` on the table (`db.tables.<Table>.rekey()`) to " +
|
|
2442
|
+
"move the aggregate's rows to this setting's text first. Nothing was written."),
|
|
2443
|
+
}));
|
|
2444
|
+
}
|
|
2445
|
+
}
|
|
2446
|
+
return Effect.void;
|
|
2447
|
+
};
|
|
1411
2448
|
const updateCore = (key, mutationFn) => Effect.gen(function* () {
|
|
1412
2449
|
const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "update");
|
|
1413
2450
|
if (allItems.length === 0) {
|
|
@@ -1443,9 +2480,11 @@ const makeAggregate = (schema, config) => {
|
|
|
1443
2480
|
})));
|
|
1444
2481
|
const assembledOld = { ...current };
|
|
1445
2482
|
const assembledNew = { ...decoded };
|
|
1446
|
-
// 4. Decompose both old and new
|
|
1447
|
-
|
|
1448
|
-
|
|
2483
|
+
// 4. Decompose both old and new. Two items composing one sort key are judged below, over the
|
|
2484
|
+
// groups this write sends: rows stored under two keys can compose one now (#241), and a
|
|
2485
|
+
// group the write leaves alone keeps them.
|
|
2486
|
+
const oldGroups = yield* decomposeAggregate(assembledOld, rootNode, contextFields, rootEncoders, aggregateName, config.schema, undefined, "keep");
|
|
2487
|
+
const newGroups = yield* decomposeAggregate(assembledNew, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: true }, "keep");
|
|
1449
2488
|
// 5. Diff at the ITEM (primary-key) level, not just the group level.
|
|
1450
2489
|
// A `many`-edge element — and a cleared `one` edge — lives in its PARENT's
|
|
1451
2490
|
// transaction group, so removing it SHRINKS a group rather than dropping a
|
|
@@ -1464,6 +2503,26 @@ const makeAggregate = (schema, config) => {
|
|
|
1464
2503
|
break;
|
|
1465
2504
|
}
|
|
1466
2505
|
}
|
|
2506
|
+
// A group whose rows read hold a copy of a context attribute other than the root's value is
|
|
2507
|
+
// written too (#241): an earlier write failing partway left them behind its root, and a read
|
|
2508
|
+
// hands that copy back. A group whose copies are the root's stays unwritten.
|
|
2509
|
+
const stale = contextChanged ? new Set() : staleContextGroups(allItems, assembledOld);
|
|
2510
|
+
/** Whether the write sends group `name`: the diff below writes exactly these. */
|
|
2511
|
+
const groupChanged = (name) => {
|
|
2512
|
+
const oldGroup = oldGroupMap.get(name);
|
|
2513
|
+
const newGroup = newGroupMap.get(name);
|
|
2514
|
+
return (contextChanged ||
|
|
2515
|
+
stale.has(name) ||
|
|
2516
|
+
oldGroup === undefined ||
|
|
2517
|
+
newGroup === undefined ||
|
|
2518
|
+
!deepEqualGroups(oldGroup, newGroup));
|
|
2519
|
+
};
|
|
2520
|
+
const readRows = new Map();
|
|
2521
|
+
for (const item of allItems) {
|
|
2522
|
+
if (typeof item.sk === "string")
|
|
2523
|
+
readRows.set(item.sk, item);
|
|
2524
|
+
}
|
|
2525
|
+
yield* refuseSharedSortKeys(newGroups.flatMap((group) => group.items), config.schema, aggregateName, (item) => groupChanged(item.transactionGroup), doubledKeys(newGroups.flatMap((group) => group.items), config.schema, (sk) => readRows.get(sk)));
|
|
1467
2526
|
// 6. Build the full new + old DynamoDB item sets (with composed keys). The
|
|
1468
2527
|
// collection SK and list keys are mirror attributes, never the (pk, sk)
|
|
1469
2528
|
// identity used to PUT or DELETE, and the old set is read only for its
|
|
@@ -1471,24 +2530,86 @@ const makeAggregate = (schema, config) => {
|
|
|
1471
2530
|
// Rewritten rows are stamped `updated`; their stored `created` is read
|
|
1472
2531
|
// back off the fetched partition and re-emitted verbatim, since these are
|
|
1473
2532
|
// PUTs and would otherwise clobber it.
|
|
1474
|
-
|
|
2533
|
+
// Built as the new set is, so what can't be stored fails the update rather than dying.
|
|
2534
|
+
const oldDynamo = yield* composeOrFail("update", () => buildDynamoItems(oldGroups, config, pkValue, undefined, keyRecord));
|
|
1475
2535
|
const skOf = (item) => item.sk?.S ?? "";
|
|
1476
2536
|
const existingCreated = new Map(readExistingCreated(allItems));
|
|
2537
|
+
// Under `escapeKeys: true`, the rows read under the sort key text 1.40.0 composed for an
|
|
2538
|
+
// element of an `entity:` edge (#241, DESIGN.md §11 "An `entity:` edge's sort key"), by the
|
|
2539
|
+
// group that writes the element: its write deletes them in the same transaction, and the
|
|
2540
|
+
// element's row keeps what such a row keeps across an update (its `created`, carried as a
|
|
2541
|
+
// row at the element's key would be). A text an element composes now is that element's row.
|
|
2542
|
+
const previousRows = new Map();
|
|
2543
|
+
// A key two rows read compose now, with the one of them the new value holds there (#241):
|
|
2544
|
+
// what the update carries of a row (`created`, the `updated` the mutation found) is that one's.
|
|
2545
|
+
const survivors = new Map();
|
|
2546
|
+
if (config.schema.escapeKeys === true) {
|
|
2547
|
+
const read = new Map();
|
|
2548
|
+
for (const item of allItems) {
|
|
2549
|
+
if (typeof item.sk === "string")
|
|
2550
|
+
read.set(item.sk, item);
|
|
2551
|
+
}
|
|
2552
|
+
const composedNow = new Set(oldDynamo.flatMap((group) => group.items.map(skOf)));
|
|
2553
|
+
const movedTo = new Map();
|
|
2554
|
+
oldGroups.forEach((group, g) => {
|
|
2555
|
+
group.items.forEach((item, i) => {
|
|
2556
|
+
const from = otherCompositionSortKey(config.schema, item);
|
|
2557
|
+
if (from === undefined || composedNow.has(from))
|
|
2558
|
+
return;
|
|
2559
|
+
if (read.get(from)?.__edd_e__ !== item.entityType)
|
|
2560
|
+
return;
|
|
2561
|
+
const to = skOf(oldDynamo[g].items[i]);
|
|
2562
|
+
previousRows.set(group.name, [...(previousRows.get(group.name) ?? []), from]);
|
|
2563
|
+
movedTo.set(to, [...(movedTo.get(to) ?? []), { item, from }]);
|
|
2564
|
+
});
|
|
2565
|
+
});
|
|
2566
|
+
for (const [to, moved] of movedTo) {
|
|
2567
|
+
// Two rows read whose values compose one key: the one the new value holds, if one is,
|
|
2568
|
+
// identified by what identifies a row, its key in the text it's stored under (its entity
|
|
2569
|
+
// type, discriminators and element key, through the key form), never by what it holds,
|
|
2570
|
+
// which the update may change.
|
|
2571
|
+
const kept = moved.length === 1
|
|
2572
|
+
? moved
|
|
2573
|
+
: moved.filter(({ from }) => newGroups.some((group) => group.items.some((other) => sortKeyOf(config.schema, other) === to &&
|
|
2574
|
+
otherCompositionSortKey(config.schema, other) === from)));
|
|
2575
|
+
if (moved.length > 1)
|
|
2576
|
+
survivors.set(to, kept.length === 1 ? kept[0].item : undefined);
|
|
2577
|
+
if (existingCreated.has(to) || kept.length !== 1)
|
|
2578
|
+
continue;
|
|
2579
|
+
const created = existingCreated.get(kept[0].from);
|
|
2580
|
+
if (created !== undefined)
|
|
2581
|
+
existingCreated.set(to, created);
|
|
2582
|
+
}
|
|
2583
|
+
}
|
|
1477
2584
|
// Each row's declared `updated` as the mutation found it: if it changed it, it's the caller's.
|
|
1478
2585
|
const updatedBefore = new Map();
|
|
1479
2586
|
if (stampFields?.updatedAt) {
|
|
1480
2587
|
for (const group of oldGroups) {
|
|
1481
2588
|
for (const item of group.items) {
|
|
1482
|
-
|
|
2589
|
+
const sk = composeKey(config.schema, item.entityType, [...item.skComposites]);
|
|
2590
|
+
if (survivors.has(sk) && survivors.get(sk) !== item)
|
|
2591
|
+
continue;
|
|
2592
|
+
updatedBefore.set(sk, ownValue(item.attributes, stampFields.updatedAt));
|
|
1483
2593
|
}
|
|
1484
2594
|
}
|
|
1485
2595
|
}
|
|
2596
|
+
// Ahead of anything marshalled: a part behind a getter is judged as it's marshalled.
|
|
2597
|
+
yield* refuseLost(newGroups, "aggregate.update");
|
|
1486
2598
|
// Packed AFTER the group diff above compared the decomposed values, so
|
|
1487
2599
|
// an unchanged packed value is never rewritten (#147).
|
|
1488
2600
|
const newPacked = yield* packAggregateGroups(newGroups, packedByType, aggregateName, "update");
|
|
1489
|
-
const
|
|
2601
|
+
const rootRead = oldGroups
|
|
2602
|
+
.flatMap((group) => group.items)
|
|
2603
|
+
.find((item) => item.node === rootNode);
|
|
2604
|
+
const newDynamo = yield* composeOrFail("update", () => buildDynamoItems(newPacked, config, pkValue, assembledNew, keyRecord, stampFor(now, existingCreated, undefined, updatedBefore), ownKeys({
|
|
2605
|
+
rootValue: assembledOld,
|
|
2606
|
+
rootKey: rootRead === undefined ? undefined : (rootRead.keyAttributes ?? rootRead.attributes),
|
|
2607
|
+
})));
|
|
1490
2608
|
yield* refuseOtherKindKeys(newGroups, "aggregate.update");
|
|
1491
2609
|
yield* refuseNotReadBack(newDynamo, key, "aggregate.update", storedAsGivenIn(newGroups));
|
|
2610
|
+
// The row each value of the state was read from (#241).
|
|
2611
|
+
const readAt = rowsReadAt(rootNode, allItems, systemAttrs);
|
|
2612
|
+
yield* refuseOtherSettingRows(oldGroups, groupChanged, readAt, previousRows);
|
|
1492
2613
|
const newItemsByGroup = new Map(newDynamo.map((g) => [g.group, g.items]));
|
|
1493
2614
|
const oldItemsByGroup = new Map(oldDynamo.map((g) => [g.group, g.items]));
|
|
1494
2615
|
// Every sk that survives anywhere in the new decomposition — an old item is
|
|
@@ -1502,24 +2623,29 @@ const makeAggregate = (schema, config) => {
|
|
|
1502
2623
|
const groupWrites = [];
|
|
1503
2624
|
const groupNames = new Set([...newGroupMap.keys(), ...oldGroupMap.keys()]);
|
|
1504
2625
|
for (const name of groupNames) {
|
|
1505
|
-
|
|
1506
|
-
const newGroup = newGroupMap.get(name);
|
|
1507
|
-
const changed = contextChanged ||
|
|
1508
|
-
oldGroup === undefined ||
|
|
1509
|
-
newGroup === undefined ||
|
|
1510
|
-
!deepEqualGroups(oldGroup, newGroup);
|
|
1511
|
-
if (!changed)
|
|
2626
|
+
if (!groupChanged(name))
|
|
1512
2627
|
continue;
|
|
1513
2628
|
const puts = newItemsByGroup.get(name) ?? [];
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
.map((item) => (
|
|
1517
|
-
|
|
1518
|
-
|
|
2629
|
+
// Each row once: two old items can compose one key (rows stored under two keys, #241).
|
|
2630
|
+
const deleteSks = new Set((oldItemsByGroup.get(name) ?? [])
|
|
2631
|
+
.map((item) => skOf(item))
|
|
2632
|
+
.filter((sk) => !survivingSks.has(sk)));
|
|
2633
|
+
// A row read under the text 1.40.0 composed goes in the same transaction (#241).
|
|
2634
|
+
const previous = (previousRows.get(name) ?? []).filter((sk) => !survivingSks.has(sk));
|
|
2635
|
+
for (const sk of previous)
|
|
2636
|
+
deleteSks.add(sk);
|
|
2637
|
+
const deletes = [...deleteSks].map((sk) => ({
|
|
2638
|
+
[config.pk.field]: { S: pkValue },
|
|
2639
|
+
sk: { S: sk },
|
|
1519
2640
|
}));
|
|
1520
2641
|
if (puts.length === 0 && deletes.length === 0)
|
|
1521
2642
|
continue;
|
|
1522
|
-
groupWrites.push({
|
|
2643
|
+
groupWrites.push({
|
|
2644
|
+
group: name,
|
|
2645
|
+
puts,
|
|
2646
|
+
deletes,
|
|
2647
|
+
...(previous.length > 0 && { previous: previous.length }),
|
|
2648
|
+
});
|
|
1523
2649
|
}
|
|
1524
2650
|
// With `ownsRows`, every row of its types in the partition is the aggregate's (DESIGN.md §7
|
|
1525
2651
|
// "Which rows in its partition are an aggregate's"). After the update's groups, the rows read
|
|
@@ -1535,10 +2661,33 @@ const makeAggregate = (schema, config) => {
|
|
|
1535
2661
|
yield* deleteOwnedRows(client, tableConfig.name, config.pk.field, cleanup);
|
|
1536
2662
|
}
|
|
1537
2663
|
if (!returnsStamps) {
|
|
1538
|
-
|
|
2664
|
+
// 1.40.0's result, the mutated state as decoded, with one change (#241): a member value's
|
|
2665
|
+
// copy of a context attribute is what its row now holds: the root's, on a row the write
|
|
2666
|
+
// sent; what it held when read, on one it didn't.
|
|
2667
|
+
const rowsNow = new Map();
|
|
2668
|
+
for (const group of newGroups) {
|
|
2669
|
+
const sent = groupChanged(group.name);
|
|
2670
|
+
for (const item of group.items) {
|
|
2671
|
+
if (item.path === undefined)
|
|
2672
|
+
continue;
|
|
2673
|
+
let now;
|
|
2674
|
+
if (sent)
|
|
2675
|
+
now = { written: true };
|
|
2676
|
+
else {
|
|
2677
|
+
// A group the write didn't send holds the values it was read as, each on its row.
|
|
2678
|
+
const row = readAt.get(JSON.stringify(item.path));
|
|
2679
|
+
if (row !== undefined)
|
|
2680
|
+
now = { row };
|
|
2681
|
+
}
|
|
2682
|
+
if (now !== undefined)
|
|
2683
|
+
rowsNow.set(JSON.stringify(item.path), now);
|
|
2684
|
+
}
|
|
2685
|
+
}
|
|
2686
|
+
return withStoredContextCopies(decoded, (path) => rowsNow.get(JSON.stringify(path)));
|
|
1539
2687
|
}
|
|
1540
2688
|
// 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
|
|
2689
|
+
// and no read is needed to know that. The partition as read, with these writes applied, as
|
|
2690
|
+
// 1.40.0 assembled it.
|
|
1542
2691
|
const stored = new Map(allItems.map((item) => [String(item.sk), item]));
|
|
1543
2692
|
for (const { sk } of cleanup)
|
|
1544
2693
|
stored.delete(sk);
|
|
@@ -1570,7 +2719,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1570
2719
|
const walk = (node) => {
|
|
1571
2720
|
const names = byType.get(node.entityType) ?? new Set(shared);
|
|
1572
2721
|
const edges = new Set(node.children.map((child) => child.fieldName));
|
|
1573
|
-
for (const field of Object.keys(node.ownFields ?? {})) {
|
|
2722
|
+
for (const field of [...Object.keys(node.ownFields ?? {}), ...(node.storedNames ?? [])]) {
|
|
1574
2723
|
if (!edges.has(field))
|
|
1575
2724
|
names.add(field);
|
|
1576
2725
|
}
|
|
@@ -1621,34 +2770,55 @@ const makeAggregate = (schema, config) => {
|
|
|
1621
2770
|
* fits, as 1.39.0 finished it). Rows whose keys chain move in order, the one whose current key is
|
|
1622
2771
|
* free first, so no write lands on a row still to move, and the root moves last, so a move cut
|
|
1623
2772
|
* 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
|
|
1625
|
-
*
|
|
2773
|
+
* again; a row stored under both keys leaves the aggregate as it is, reported, as does one whose
|
|
2774
|
+
* current key holds a row that isn't its own and stays there once what holds it is judged (#240).
|
|
2775
|
+
* A dry run writes nothing: it plans each write the run would send (`plan`), and reads its plan.
|
|
1626
2776
|
*/
|
|
1627
|
-
const rekeyCore = (key,
|
|
2777
|
+
const rekeyCore = (key, ctx,
|
|
1628
2778
|
/** The old partition the aggregate's root was found in, when it isn't the current one. */
|
|
1629
|
-
from
|
|
1630
|
-
|
|
1631
|
-
|
|
1632
|
-
* holds it, whose rows this one's move would find gone by then.
|
|
1633
|
-
*/
|
|
1634
|
-
fromOnly,
|
|
1635
|
-
/** What a row too wide to guard whole, with no `updatedAt` to stand in, gets. */
|
|
1636
|
-
unprovable) => Effect.gen(function* () {
|
|
2779
|
+
from) => Effect.gen(function* () {
|
|
2780
|
+
/** What a row too wide to guard whole, with no `updatedAt` to stand in, gets. */
|
|
2781
|
+
const unprovable = Rekey.unprovableRow(ctx);
|
|
1637
2782
|
let movedRows = 0;
|
|
1638
2783
|
let rewrittenRows = 0;
|
|
2784
|
+
// Rows moved under a guard that can miss a write ({@link Table.RekeyGuardGaps}).
|
|
2785
|
+
let gaps = {};
|
|
2786
|
+
// Whether the aggregates holding this one's current keys have been judged first.
|
|
2787
|
+
let yielded = false;
|
|
2788
|
+
// The aggregate left as it is, reported: with what it moved before it found that.
|
|
2789
|
+
const leftAsIs = (conflicts) => ({
|
|
2790
|
+
...(movedRows > 0 && { moved: { aggregate: movedRows } }),
|
|
2791
|
+
...(rewrittenRows > 0 && { indexKeysRewritten: rewrittenRows }),
|
|
2792
|
+
...gaps,
|
|
2793
|
+
conflicts,
|
|
2794
|
+
});
|
|
1639
2795
|
for (let attempt = 0; attempt < REKEY_ATTEMPTS; attempt++) {
|
|
1640
|
-
const
|
|
1641
|
-
const
|
|
1642
|
-
|
|
1643
|
-
|
|
1644
|
-
|
|
1645
|
-
|
|
2796
|
+
const read = [];
|
|
2797
|
+
const fetched = yield* fetchPartition(key, "rekey", { stored: read, from });
|
|
2798
|
+
const { client, tableConfig, pkValue } = fetched;
|
|
2799
|
+
// The rows under the old partition are the aggregate's only while its root is there. Once
|
|
2800
|
+
// the root has left — moved by a run started at the same time — another aggregate's move
|
|
2801
|
+
// can bring its rows there (the old partition is where its values compose a key now): they
|
|
2802
|
+
// are that aggregate's, not this one's, and this one is read from its current partition
|
|
2803
|
+
// alone (#240).
|
|
2804
|
+
const rootAtFrom = from !== undefined &&
|
|
2805
|
+
read.some((item) => item[config.pk.field]?.S === from &&
|
|
2806
|
+
item.sk?.S === rekeyRootSk &&
|
|
2807
|
+
item.__edd_e__?.S === config.root.entityType &&
|
|
2808
|
+
partitionUnder(config.schema, rootKeyAsRead(fromAttributeMap(item))) ===
|
|
2809
|
+
partitionUnder(config.schema, key));
|
|
2810
|
+
const at = rootAtFrom ? from : undefined;
|
|
2811
|
+
const allItems = at === from
|
|
2812
|
+
? fetched.allItems
|
|
2813
|
+
: fetched.allItems.filter((item) => item[config.pk.field] !== from);
|
|
2814
|
+
const stored = at === from ? read : read.filter((item) => item[config.pk.field]?.S !== from);
|
|
1646
2815
|
const done = (rows) => {
|
|
1647
2816
|
const unchanged = Math.max(0, rows - movedRows - rewrittenRows);
|
|
1648
2817
|
return {
|
|
1649
2818
|
...(unchanged > 0 && { unchanged }),
|
|
1650
2819
|
...(movedRows > 0 && { moved: { aggregate: movedRows } }),
|
|
1651
2820
|
...(rewrittenRows > 0 && { indexKeysRewritten: rewrittenRows }),
|
|
2821
|
+
...gaps,
|
|
1652
2822
|
};
|
|
1653
2823
|
};
|
|
1654
2824
|
// Gone since the scan read it: deleted by a write.
|
|
@@ -1657,24 +2827,66 @@ const makeAggregate = (schema, config) => {
|
|
|
1657
2827
|
// A write moving the aggregate between the reads of its two partitions shows its
|
|
1658
2828
|
// rows under both, and they can't be assembled or placed: with rows in both, read
|
|
1659
2829
|
// again, and while a row read under the old partition has gone from it, retry.
|
|
1660
|
-
const atFrom = allItems.filter((item) => item[config.pk.field] ===
|
|
1661
|
-
if (
|
|
1662
|
-
const again = yield* fetchPartition(key, "rekey", { from
|
|
2830
|
+
const atFrom = allItems.filter((item) => item[config.pk.field] === at);
|
|
2831
|
+
if (at !== undefined && atFrom.length > 0 && atFrom.length < allItems.length) {
|
|
2832
|
+
const again = yield* fetchPartition(key, "rekey", { from: at });
|
|
1663
2833
|
const held = new Set(again.allItems
|
|
1664
|
-
.filter((item) => item[config.pk.field] ===
|
|
2834
|
+
.filter((item) => item[config.pk.field] === at)
|
|
1665
2835
|
.map((item) => String(item.sk)));
|
|
1666
2836
|
if (atFrom.some((item) => !held.has(String(item.sk))))
|
|
1667
2837
|
continue;
|
|
1668
2838
|
}
|
|
1669
2839
|
const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
|
|
1670
2840
|
const assembled = { ...current };
|
|
1671
|
-
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
1672
|
-
|
|
1673
|
-
|
|
1674
|
-
|
|
2841
|
+
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema, undefined, "keep");
|
|
2842
|
+
// Two rows of one element that differ (#241): reported, naming both, and the aggregate left
|
|
2843
|
+
// as it is. Any other key two items compose fails it as before.
|
|
2844
|
+
const decomposed = groups.flatMap((group) => group.items);
|
|
2845
|
+
const rowAtSk = new Map();
|
|
2846
|
+
for (const item of allItems) {
|
|
2847
|
+
if (item[config.pk.field] === pkValue)
|
|
2848
|
+
rowAtSk.set(String(item.sk), item);
|
|
2849
|
+
}
|
|
2850
|
+
const doubled = doubledKeys(decomposed, config.schema, (sk) => rowAtSk.get(sk));
|
|
2851
|
+
if (doubled.size > 0) {
|
|
2852
|
+
// A write moving the group during the read shows its rows under both texts too: only
|
|
2853
|
+
// while the row under 1.40.0's is still there.
|
|
2854
|
+
const held = yield* Effect.forEach([...doubled.values()], (sk) => client
|
|
2855
|
+
.getItem({
|
|
2856
|
+
TableName: tableConfig.name,
|
|
2857
|
+
Key: toAttributeMap({ [config.pk.field]: pkValue, sk }),
|
|
2858
|
+
ConsistentRead: true,
|
|
2859
|
+
})
|
|
2860
|
+
.pipe(Effect.map(({ Item }) => Item !== undefined)));
|
|
2861
|
+
if (held.some((still) => !still))
|
|
2862
|
+
continue;
|
|
2863
|
+
return leftAsIs([...doubled].map(([to, from]) => ({
|
|
2864
|
+
member: aggregateName,
|
|
2865
|
+
kind: "aggregate",
|
|
2866
|
+
reason: "bothKeys",
|
|
2867
|
+
key: { [config.pk.field]: pkValue, sk: from },
|
|
2868
|
+
target: { [config.pk.field]: pkValue, sk: to },
|
|
2869
|
+
message: "Two rows of one element, one under the key text 1.40.0 composed and one under " +
|
|
2870
|
+
"this release's, hold different values, as a 1.40.0 writer leaves a group this " +
|
|
2871
|
+
"release keyed, so which is the element can't be told: the aggregate is left as it " +
|
|
2872
|
+
"is. Update it stating the elements the group should hold, one for each key.",
|
|
2873
|
+
})));
|
|
2874
|
+
}
|
|
2875
|
+
yield* refuseSharedSortKeys(decomposed, config.schema, aggregateName);
|
|
2876
|
+
const rows = locateRows(groups, buildDynamoItems(groups, config, pkValue, undefined, keyRecord), allItems, pkValue, at);
|
|
2877
|
+
// A row under 1.40.0's text that is a copy of the element's row under this release's
|
|
2878
|
+
// (#241): deleted, as the move of a row whose key is already held by itself.
|
|
2879
|
+
const copies = new Set(rows.flatMap((row, r) => row.placement === "both" &&
|
|
2880
|
+
row.atOld !== undefined &&
|
|
2881
|
+
row.atCurrent !== undefined &&
|
|
2882
|
+
copiesOfOneElement(row.item.node, row.atOld, row.atCurrent, systemAttrs)
|
|
2883
|
+
? [r]
|
|
2884
|
+
: []));
|
|
2885
|
+
const bothKeys = rows.filter((row, r) => (row.placement === "both" && !copies.has(r)) || row.placement === "ambiguous");
|
|
2886
|
+
if (bothKeys.length > 0) {
|
|
1675
2887
|
// In one partition, a move during the read shows a row at both keys too: it's
|
|
1676
2888
|
// only under both while it's still under its old key.
|
|
1677
|
-
const held = yield* Effect.forEach(
|
|
2889
|
+
const held = yield* Effect.forEach(bothKeys, (row) => client
|
|
1678
2890
|
.getItem({
|
|
1679
2891
|
TableName: tableConfig.name,
|
|
1680
2892
|
Key: toAttributeMap({ [config.pk.field]: row.old.pk, sk: row.old.sk }),
|
|
@@ -1683,19 +2895,58 @@ const makeAggregate = (schema, config) => {
|
|
|
1683
2895
|
.pipe(Effect.map(({ Item }) => Item !== undefined)));
|
|
1684
2896
|
if (held.some((still) => !still))
|
|
1685
2897
|
continue;
|
|
1686
|
-
return {
|
|
1687
|
-
|
|
1688
|
-
|
|
1689
|
-
|
|
1690
|
-
|
|
1691
|
-
|
|
1692
|
-
|
|
1693
|
-
|
|
1694
|
-
|
|
1695
|
-
|
|
1696
|
-
|
|
1697
|
-
|
|
1698
|
-
|
|
2898
|
+
return leftAsIs(bothKeys.map((row) => ({
|
|
2899
|
+
member: aggregateName,
|
|
2900
|
+
kind: "aggregate",
|
|
2901
|
+
reason: "bothKeys",
|
|
2902
|
+
key: { [config.pk.field]: row.old.pk, sk: row.old.sk },
|
|
2903
|
+
target: { [config.pk.field]: row.current.pk, sk: row.current.sk },
|
|
2904
|
+
message: row.placement === "both"
|
|
2905
|
+
? "The row is also stored under its current key: the aggregate is left as it is."
|
|
2906
|
+
: "Its rows' keys overlap across key text, and which row is stored under which " +
|
|
2907
|
+
"key can't be told from the keys held: the aggregate is left as it is.",
|
|
2908
|
+
})));
|
|
2909
|
+
}
|
|
2910
|
+
// A row whose current key holds another's row (another aggregate's, sharing the partition,
|
|
2911
|
+
// #240) moves once that row has: what holds it is judged first, as the scan would judge it
|
|
2912
|
+
// (`yieldTo`), and the aggregate read again. A row still there, or one held by what waits
|
|
2913
|
+
// on this aggregate in turn, leaves the aggregate as it is, reported.
|
|
2914
|
+
const sources = new Set(rows.flatMap((row) => row.placement === "old" ? [positionOf(row.old.pk, row.old.sk)] : []));
|
|
2915
|
+
const blocked = rows.filter((row) => row.placement === "old" &&
|
|
2916
|
+
row.atCurrent !== undefined &&
|
|
2917
|
+
!sources.has(positionOf(row.current.pk, row.current.sk)));
|
|
2918
|
+
if (blocked.length > 0) {
|
|
2919
|
+
let waited = false;
|
|
2920
|
+
let loop = false;
|
|
2921
|
+
if (!yielded) {
|
|
2922
|
+
yielded = true;
|
|
2923
|
+
const raw = new Map(stored.map((item) => [
|
|
2924
|
+
positionOf(item[config.pk.field]?.S ?? "", item.sk?.S ?? ""),
|
|
2925
|
+
item,
|
|
2926
|
+
]));
|
|
2927
|
+
for (const row of blocked) {
|
|
2928
|
+
const there = raw.get(positionOf(row.current.pk, row.current.sk));
|
|
2929
|
+
if (there === undefined)
|
|
2930
|
+
continue;
|
|
2931
|
+
const judged = yield* ctx.yieldTo(there, stored);
|
|
2932
|
+
if (judged === "loop")
|
|
2933
|
+
loop = true;
|
|
2934
|
+
if (judged === "settled")
|
|
2935
|
+
waited = true;
|
|
2936
|
+
}
|
|
2937
|
+
}
|
|
2938
|
+
if (waited && !loop)
|
|
2939
|
+
continue;
|
|
2940
|
+
return leftAsIs(blocked.map((row) => ({
|
|
2941
|
+
member: aggregateName,
|
|
2942
|
+
kind: "aggregate",
|
|
2943
|
+
reason: loop ? "contended" : "taken",
|
|
2944
|
+
key: { [config.pk.field]: row.old.pk, sk: row.old.sk },
|
|
2945
|
+
target: { [config.pk.field]: row.current.pk, sk: row.current.sk },
|
|
2946
|
+
message: loop
|
|
2947
|
+
? Rekey.LOOP_MESSAGE
|
|
2948
|
+
: "Another row is stored where this one belongs: the aggregate is left as it is.",
|
|
2949
|
+
})));
|
|
1699
2950
|
}
|
|
1700
2951
|
// With `ownsRows`, every row of its types it reads is the aggregate's (DESIGN.md §7 "Which
|
|
1701
2952
|
// rows in its partition are an aggregate's"), and it moves exactly what it moves without the
|
|
@@ -1721,22 +2972,23 @@ const makeAggregate = (schema, config) => {
|
|
|
1721
2972
|
}
|
|
1722
2973
|
const stranded = unplaced.filter((at) => at.pk !== pkValue);
|
|
1723
2974
|
if (stranded.length > 0) {
|
|
1724
|
-
return {
|
|
1725
|
-
|
|
1726
|
-
|
|
1727
|
-
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
})),
|
|
1735
|
-
};
|
|
2975
|
+
return leftAsIs(stranded.map((at) => ({
|
|
2976
|
+
member: aggregateName,
|
|
2977
|
+
kind: "aggregate",
|
|
2978
|
+
reason: "failed",
|
|
2979
|
+
key: { [config.pk.field]: at.pk, sk: at.sk },
|
|
2980
|
+
target: undefined,
|
|
2981
|
+
message: "The aggregate owns its rows (`ownsRows`), and this one isn't a row its value " +
|
|
2982
|
+
"decomposes to, so where it goes can't be told. Moving the rest would leave it in " +
|
|
2983
|
+
"the old partition: the aggregate is left as it is.",
|
|
2984
|
+
})));
|
|
1736
2985
|
}
|
|
1737
2986
|
const left = unplaced.length > 0 ? { skipped: { unrecognizedKey: unplaced.length } } : {};
|
|
1738
2987
|
const tally = (rows) => ({ ...done(rows), ...left });
|
|
1739
|
-
|
|
2988
|
+
// A row at its current key that this run put there (another aggregate holding it moved it)
|
|
2989
|
+
// was counted where it moved: not again here as unchanged.
|
|
2990
|
+
const counted = rows.filter((row) => row.placement !== "current" ||
|
|
2991
|
+
!ctx.placed(toAttributeMap({ [config.pk.field]: row.current.pk, sk: row.current.sk }))).length;
|
|
1740
2992
|
// Each row's write keeps the `created` and `updated` of the row it moves.
|
|
1741
2993
|
const createdField = stampFields?.createdAt ?? null;
|
|
1742
2994
|
const updatedField = stampFields?.updatedAt ?? null;
|
|
@@ -1746,11 +2998,11 @@ const makeAggregate = (schema, config) => {
|
|
|
1746
2998
|
const was = row.placement === "old" ? row.atOld : row.atCurrent;
|
|
1747
2999
|
if (was === undefined)
|
|
1748
3000
|
continue;
|
|
1749
|
-
if (createdField !== null && was
|
|
1750
|
-
keptCreated.set(row.current.sk, was
|
|
3001
|
+
if (createdField !== null && ownValue(was, createdField) !== undefined) {
|
|
3002
|
+
keptCreated.set(row.current.sk, ownValue(was, createdField));
|
|
1751
3003
|
}
|
|
1752
|
-
if (updatedField !== null && was
|
|
1753
|
-
keptUpdated.set(row.current.sk, was
|
|
3004
|
+
if (updatedField !== null && ownValue(was, updatedField) !== undefined) {
|
|
3005
|
+
keptUpdated.set(row.current.sk, ownValue(was, updatedField));
|
|
1754
3006
|
}
|
|
1755
3007
|
}
|
|
1756
3008
|
const packedGroups = yield* packAggregateGroups(groups, packedByType, aggregateName, "update");
|
|
@@ -1772,6 +3024,8 @@ const makeAggregate = (schema, config) => {
|
|
|
1772
3024
|
// its `updatedAt` when the library stamps one on it, held or absent (`preferredGuard`),
|
|
1773
3025
|
// with what else fits; otherwise `unprovableHere` decides, and `undefined` is a row
|
|
1774
3026
|
// reported.
|
|
3027
|
+
// What a move under each guard can miss ({@link Table.RekeyGuardGaps}), by position.
|
|
3028
|
+
const gapAt = new Map();
|
|
1775
3029
|
const guardOf = (at, r) => {
|
|
1776
3030
|
const read = storedAt.get(positionOf(at.pk, at.sk)) ?? {};
|
|
1777
3031
|
const entityType = built[r].__edd_e__?.S ?? "";
|
|
@@ -1781,12 +3035,14 @@ const makeAggregate = (schema, config) => {
|
|
|
1781
3035
|
if (whole !== undefined)
|
|
1782
3036
|
return whole;
|
|
1783
3037
|
if (updatedField !== null && stampsUpdated.has(entityType)) {
|
|
3038
|
+
gapAt.set(positionOf(at.pk, at.sk), "stamp");
|
|
1784
3039
|
return preferredGuard(read, config.pk.field, prefer, absent);
|
|
1785
3040
|
}
|
|
1786
3041
|
switch (unprovableHere) {
|
|
1787
3042
|
case "report":
|
|
1788
3043
|
return undefined;
|
|
1789
3044
|
case "strongest":
|
|
3045
|
+
gapAt.set(positionOf(at.pk, at.sk), "strongest");
|
|
1790
3046
|
return asReadGuard(read, config.pk.field, prefer);
|
|
1791
3047
|
}
|
|
1792
3048
|
};
|
|
@@ -1813,6 +3069,19 @@ const makeAggregate = (schema, config) => {
|
|
|
1813
3069
|
const rewrites = [];
|
|
1814
3070
|
const unguarded = [];
|
|
1815
3071
|
for (const [r, row] of rows.entries()) {
|
|
3072
|
+
if (copies.has(r)) {
|
|
3073
|
+
const guard = guardOf(row.old, r);
|
|
3074
|
+
if (guard === undefined) {
|
|
3075
|
+
unguarded.push({ from: row.old, to: row.current });
|
|
3076
|
+
continue;
|
|
3077
|
+
}
|
|
3078
|
+
moves.push({
|
|
3079
|
+
from: row.old,
|
|
3080
|
+
to: row.current,
|
|
3081
|
+
items: [{ Delete: { TableName: tableConfig.name, Key: keyOf(row.old), ...guard } }],
|
|
3082
|
+
});
|
|
3083
|
+
continue;
|
|
3084
|
+
}
|
|
1816
3085
|
if (row.placement === "old") {
|
|
1817
3086
|
const guard = guardOf(row.old, r);
|
|
1818
3087
|
if (guard === undefined) {
|
|
@@ -1822,6 +3091,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1822
3091
|
moves.push({
|
|
1823
3092
|
from: row.old,
|
|
1824
3093
|
to: row.current,
|
|
3094
|
+
gap: gapAt.get(positionOf(row.old.pk, row.old.sk)),
|
|
1825
3095
|
items: [
|
|
1826
3096
|
{
|
|
1827
3097
|
Put: {
|
|
@@ -1876,26 +3146,19 @@ const makeAggregate = (schema, config) => {
|
|
|
1876
3146
|
// Nothing of it has moved (`unprovableHere`): an unguarded row leaves the aggregate as is.
|
|
1877
3147
|
if (unguarded.length > 0) {
|
|
1878
3148
|
return {
|
|
1879
|
-
...(movedRows > 0 && { moved: { aggregate: movedRows } }),
|
|
1880
|
-
...(rewrittenRows > 0 && { indexKeysRewritten: rewrittenRows }),
|
|
1881
3149
|
...left,
|
|
1882
|
-
|
|
3150
|
+
...leftAsIs(unguarded.map((row) => ({
|
|
1883
3151
|
member: aggregateName,
|
|
1884
3152
|
kind: "aggregate",
|
|
1885
3153
|
reason: "unguarded",
|
|
1886
3154
|
key: { [config.pk.field]: row.from.pk, sk: row.from.sk },
|
|
1887
3155
|
target: { [config.pk.field]: row.to.pk, sk: row.to.sk },
|
|
1888
3156
|
message: `${Rekey.UNGUARDED_MESSAGE} Its aggregate's other rows are left with it.`,
|
|
1889
|
-
})),
|
|
3157
|
+
}))),
|
|
1890
3158
|
};
|
|
1891
3159
|
}
|
|
1892
3160
|
if (moves.length === 0 && rewrites.length === 0)
|
|
1893
3161
|
return tally(counted);
|
|
1894
|
-
if (dryRun) {
|
|
1895
|
-
movedRows += moves.length;
|
|
1896
|
-
rewrittenRows += rewrites.length;
|
|
1897
|
-
return tally(counted);
|
|
1898
|
-
}
|
|
1899
3162
|
// In waves: a row moves once no row still to move is stored at its
|
|
1900
3163
|
// current key, and the root once nothing else is left: while it's under the old partition
|
|
1901
3164
|
// the next run finds the aggregate there. Each move's Put and Delete share a transaction;
|
|
@@ -1914,21 +3177,36 @@ const makeAggregate = (schema, config) => {
|
|
|
1914
3177
|
if (wave.length === 0 && units.length === 0)
|
|
1915
3178
|
break;
|
|
1916
3179
|
pending = pending.filter((move) => !wave.includes(move));
|
|
1917
|
-
units.push(...wave.map((move) => ({
|
|
3180
|
+
units.push(...wave.map((move) => ({
|
|
3181
|
+
kind: "move",
|
|
3182
|
+
items: move.items,
|
|
3183
|
+
gap: move.gap,
|
|
3184
|
+
from: move.from,
|
|
3185
|
+
to: move.to,
|
|
3186
|
+
})));
|
|
1918
3187
|
const chunks = packRequests(units.splice(0), (unit) => transactWriteUnit(unit.items), shape);
|
|
1919
3188
|
for (const chunk of chunks) {
|
|
1920
|
-
const
|
|
1921
|
-
|
|
1922
|
-
|
|
1923
|
-
?
|
|
1924
|
-
: Effect.
|
|
3189
|
+
const items = chunk.flatMap((unit) => unit.items);
|
|
3190
|
+
// A dry run plans the write, as the run would send it (`plan`), and reads its plan.
|
|
3191
|
+
const written = ctx.dryRun
|
|
3192
|
+
? ctx.plan(items)
|
|
3193
|
+
: yield* client.transactWriteItems({ TransactItems: items }).pipe(Effect.as(true), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
|
|
3194
|
+
? Effect.succeed(false)
|
|
3195
|
+
: Effect.fail(error)));
|
|
1925
3196
|
if (!written) {
|
|
1926
3197
|
lost = true;
|
|
1927
3198
|
break;
|
|
1928
3199
|
}
|
|
1929
3200
|
for (const unit of chunk) {
|
|
1930
|
-
if (unit.kind === "move")
|
|
3201
|
+
if (unit.kind === "move") {
|
|
1931
3202
|
movedRows++;
|
|
3203
|
+
gaps = Rekey.mergeTallies(gaps, Rekey.guardGap(ctx, unit.gap, {
|
|
3204
|
+
member: aggregateName,
|
|
3205
|
+
kind: "aggregate",
|
|
3206
|
+
key: { [config.pk.field]: unit.from.pk, sk: unit.from.sk },
|
|
3207
|
+
target: { [config.pk.field]: unit.to.pk, sk: unit.to.sk },
|
|
3208
|
+
}));
|
|
3209
|
+
}
|
|
1932
3210
|
else
|
|
1933
3211
|
rewrittenRows++;
|
|
1934
3212
|
}
|
|
@@ -1954,6 +3232,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1954
3232
|
return {
|
|
1955
3233
|
...(movedRows > 0 && { moved: { aggregate: movedRows } }),
|
|
1956
3234
|
...(rewrittenRows > 0 && { indexKeysRewritten: rewrittenRows }),
|
|
3235
|
+
...gaps,
|
|
1957
3236
|
conflicts: [
|
|
1958
3237
|
{
|
|
1959
3238
|
member: aggregateName,
|
|
@@ -1982,7 +3261,7 @@ const makeAggregate = (schema, config) => {
|
|
|
1982
3261
|
})();
|
|
1983
3262
|
const rekeyPrefix = composeCollectionKey(config.schema, config.collection.name, []);
|
|
1984
3263
|
const rekeyRootSk = composeKey(config.schema, config.root.entityType, []);
|
|
1985
|
-
const rekeyUnit = (pk) =>
|
|
3264
|
+
const rekeyUnit = (pk) => Rekey.identity("aggregate", aggregateName, pk);
|
|
1986
3265
|
const rootItemAt = (tableName, pk) => Effect.flatMap(Capacity.client, (client) => client.getItem({
|
|
1987
3266
|
TableName: tableName,
|
|
1988
3267
|
Key: toAttributeMap({ [config.pk.field]: pk, sk: rekeyRootSk }),
|
|
@@ -2003,12 +3282,20 @@ const makeAggregate = (schema, config) => {
|
|
|
2003
3282
|
* the digits the row stored. The current text comes first, and a root under it composes nothing
|
|
2004
3283
|
* more.
|
|
2005
3284
|
*/
|
|
2006
|
-
const holdsPartition = (row, key, pk) =>
|
|
2007
|
-
|
|
2008
|
-
|
|
2009
|
-
|
|
2010
|
-
|
|
2011
|
-
|
|
3285
|
+
const holdsPartition = (row, key, pk) => {
|
|
3286
|
+
const record = keyRecord(key);
|
|
3287
|
+
// Its zones under the names they were given, as 1.38.0 to 1.40.0 keyed them on Effect 4.1.3: a
|
|
3288
|
+
// rekey-only reading (`givenZoneReading`).
|
|
3289
|
+
const readings = keyReadings(record, [
|
|
3290
|
+
givenZoneReading(record, fromAttributeMap(row)),
|
|
3291
|
+
]);
|
|
3292
|
+
return [
|
|
3293
|
+
config.schema,
|
|
3294
|
+
KeyText136.schema136(config.schema),
|
|
3295
|
+
KeyText136.schema137(config.schema),
|
|
3296
|
+
KeyText136.schemaEscaped(config.schema),
|
|
3297
|
+
].some((under) => readings.some((reading) => kindReadingOf(reading, config.pk.composite, (field) => ownValue(row, field)?.N, ({ record }) => composeCollectionKey(config.schema, config.collection.name, KeyComposer.extractKeyComposites(under, {}, config.pk.composite, record)), pk) !== undefined));
|
|
3298
|
+
};
|
|
2012
3299
|
/**
|
|
2013
3300
|
* The root of another aggregate at `pk`, stored there under text its values no longer compose:
|
|
2014
3301
|
* it moves first, or this move's rows would land in its partition.
|
|
@@ -2018,8 +3305,10 @@ const makeAggregate = (schema, config) => {
|
|
|
2018
3305
|
? undefined
|
|
2019
3306
|
: Item);
|
|
2020
3307
|
/**
|
|
2021
|
-
* What a run has learned
|
|
2022
|
-
*
|
|
3308
|
+
* What a run has learned, within its journal's capacity ({@link Rekey.RekeyRowContext.keep}): the
|
|
3309
|
+
* partitions holding a root or about to, each as its {@link digest}, so each edge row in one costs
|
|
3310
|
+
* no read of its own; and the keys of the rows found in a partition with no root. A partition the
|
|
3311
|
+
* run has no room for costs its edge rows a read each.
|
|
2023
3312
|
*/
|
|
2024
3313
|
const rekeyRuns = new WeakMap();
|
|
2025
3314
|
const rekeyRunOf = (ctx) => {
|
|
@@ -2027,16 +3316,28 @@ const makeAggregate = (schema, config) => {
|
|
|
2027
3316
|
rekeyRuns.set(ctx, known);
|
|
2028
3317
|
return known;
|
|
2029
3318
|
};
|
|
3319
|
+
/** `pk` holds a root, or is about to. */
|
|
3320
|
+
const markRooted = (ctx, pk) => {
|
|
3321
|
+
const { rooted } = rekeyRunOf(ctx);
|
|
3322
|
+
const key = digest(pk);
|
|
3323
|
+
if (!rooted.has(key) && ctx.keep())
|
|
3324
|
+
rooted.add(key);
|
|
3325
|
+
};
|
|
2030
3326
|
const rekeyRowBelowRoot = (row, pk, ctx) => Effect.gen(function* () {
|
|
3327
|
+
// The move of an aggregate rooted in its partition, or moving there, may take it after this
|
|
3328
|
+
// visit: whichever aggregate that is, it's kept as counted.
|
|
3329
|
+
ctx.awaitsMove(row);
|
|
2031
3330
|
const { rooted, rootless } = rekeyRunOf(ctx);
|
|
2032
|
-
if (rooted.has(pk))
|
|
3331
|
+
if (rooted.has(digest(pk)))
|
|
2033
3332
|
return {};
|
|
2034
3333
|
const { Item } = yield* rootItemAt(ctx.tableName, pk);
|
|
2035
3334
|
if (Item !== undefined) {
|
|
2036
|
-
|
|
3335
|
+
markRooted(ctx, pk);
|
|
2037
3336
|
return {};
|
|
2038
3337
|
}
|
|
2039
|
-
|
|
3338
|
+
if (ctx.keep()) {
|
|
3339
|
+
rootless.push({ [config.pk.field]: row[config.pk.field], sk: row.sk });
|
|
3340
|
+
}
|
|
2040
3341
|
return {};
|
|
2041
3342
|
});
|
|
2042
3343
|
/**
|
|
@@ -2054,7 +3355,7 @@ const makeAggregate = (schema, config) => {
|
|
|
2054
3355
|
const client = yield* Capacity.client;
|
|
2055
3356
|
let left = 0;
|
|
2056
3357
|
for (const row of rootless) {
|
|
2057
|
-
if (rooted.has(row[config.pk.field].S))
|
|
3358
|
+
if (rooted.has(digest(row[config.pk.field].S)))
|
|
2058
3359
|
continue;
|
|
2059
3360
|
const { Item } = yield* client.getItem({
|
|
2060
3361
|
TableName: ctx.tableName,
|
|
@@ -2064,11 +3365,95 @@ const makeAggregate = (schema, config) => {
|
|
|
2064
3365
|
if (Item !== undefined)
|
|
2065
3366
|
left++;
|
|
2066
3367
|
}
|
|
2067
|
-
if (left === 0)
|
|
2068
|
-
return {};
|
|
2069
|
-
return { skipped: ctx.sawWholeTable() ? { unrecognizedKey: left } : { rootNotSeen: left } };
|
|
3368
|
+
if (left === 0)
|
|
3369
|
+
return {};
|
|
3370
|
+
return { skipped: ctx.sawWholeTable() ? { unrecognizedKey: left } : { rootNotSeen: left } };
|
|
3371
|
+
});
|
|
3372
|
+
/**
|
|
3373
|
+
* The unit a root row is judged as (its stored partition's: `rekeyUnit`) and its judgment, the
|
|
3374
|
+
* aggregate's move; or, for a root nothing can place, its tally.
|
|
3375
|
+
*/
|
|
3376
|
+
const rootWork = (row, ctx) => {
|
|
3377
|
+
const pk = row[config.pk.field].S;
|
|
3378
|
+
const key = rootKeyAsRead(fromAttributeMap(row));
|
|
3379
|
+
const current = partitionUnder(config.schema, key);
|
|
3380
|
+
// Under none of the keys its values have had: nothing here can place it.
|
|
3381
|
+
if (current === undefined || !holdsPartition(row, key, pk)) {
|
|
3382
|
+
return { tally: { skipped: { unrecognizedKey: 1 } } };
|
|
3383
|
+
}
|
|
3384
|
+
markRooted(ctx, pk);
|
|
3385
|
+
markRooted(ctx, current);
|
|
3386
|
+
return { unit: rekeyUnit(pk), work: rekeyRoot(key, pk, current, ctx) };
|
|
3387
|
+
};
|
|
3388
|
+
/** Judge the root `row` as the scan does: its unit's verdict, or `undefined` for a root left. */
|
|
3389
|
+
const judgeRoot = (row, ctx) => {
|
|
3390
|
+
const judged = rootWork(row, ctx);
|
|
3391
|
+
return "unit" in judged
|
|
3392
|
+
? ctx.judge(aggregateName, judged.unit, judged.work)
|
|
3393
|
+
: Effect.succeed(undefined);
|
|
3394
|
+
};
|
|
3395
|
+
const rekeyRoot = (key, pk, current, ctx) => Effect.gen(function* () {
|
|
3396
|
+
const from = pk === current ? undefined : pk;
|
|
3397
|
+
// The chain: another aggregate may still be stored where this one goes (`foo%20bar`'s old
|
|
3398
|
+
// row where `foo bar`'s current one belongs). It's judged first, as its own unit; it leaves
|
|
3399
|
+
// no row in this one's way, and nothing is overwritten or merged whichever the scan reached
|
|
3400
|
+
// first. One still there, or one waiting on this aggregate in turn, leaves this one as it is.
|
|
3401
|
+
if (from !== undefined) {
|
|
3402
|
+
const stale = yield* staleRootAt(ctx.tableName, current);
|
|
3403
|
+
if (stale !== undefined) {
|
|
3404
|
+
const judged = yield* judgeRoot(stale, ctx);
|
|
3405
|
+
if (judged === "loop" || (yield* staleRootAt(ctx.tableName, current)) !== undefined) {
|
|
3406
|
+
return {
|
|
3407
|
+
conflicts: [
|
|
3408
|
+
{
|
|
3409
|
+
member: aggregateName,
|
|
3410
|
+
kind: "aggregate",
|
|
3411
|
+
reason: judged === "loop" ? "contended" : "taken",
|
|
3412
|
+
key: { [config.pk.field]: pk, sk: rekeyRootSk },
|
|
3413
|
+
target: { [config.pk.field]: current, sk: rekeyRootSk },
|
|
3414
|
+
message: judged === "loop"
|
|
3415
|
+
? Rekey.LOOP_MESSAGE
|
|
3416
|
+
: "Another aggregate's root is stored where this one's belongs.",
|
|
3417
|
+
},
|
|
3418
|
+
],
|
|
3419
|
+
};
|
|
3420
|
+
}
|
|
3421
|
+
}
|
|
3422
|
+
}
|
|
3423
|
+
return yield* rekeyCore(key, ctx, from).pipe(Effect.catch((error) => {
|
|
3424
|
+
if (Rekey.isDynamoClientError(error))
|
|
3425
|
+
return Effect.fail(error);
|
|
3426
|
+
const assembly = error._tag === "AggregateAssemblyError" ? error.reason : undefined;
|
|
3427
|
+
// Gone since the scan read it: deleted by a write.
|
|
3428
|
+
if (assembly === "Missing root item")
|
|
3429
|
+
return Effect.succeed({});
|
|
3430
|
+
// A root under both partition keys (its sort key is fixed, so one
|
|
3431
|
+
// partition holds one): neither copy is judged.
|
|
3432
|
+
const both = assembly === "Multiple root items found";
|
|
3433
|
+
// What went wrong, as the error says it: a tagged error's own message is empty.
|
|
3434
|
+
const detail = error._tag === "AggregateAssemblyError" ||
|
|
3435
|
+
error._tag === "AggregateDecompositionError"
|
|
3436
|
+
? error.reason
|
|
3437
|
+
: error._tag === "ValidationError"
|
|
3438
|
+
? String(error.cause ?? error.message)
|
|
3439
|
+
: error.message;
|
|
3440
|
+
return Effect.succeed({
|
|
3441
|
+
conflicts: [
|
|
3442
|
+
{
|
|
3443
|
+
member: aggregateName,
|
|
3444
|
+
kind: "aggregate",
|
|
3445
|
+
reason: both ? "bothKeys" : "failed",
|
|
3446
|
+
key: { [config.pk.field]: pk, sk: rekeyRootSk },
|
|
3447
|
+
target: { [config.pk.field]: current, sk: rekeyRootSk },
|
|
3448
|
+
message: both
|
|
3449
|
+
? "The aggregate's root is also stored under its current key."
|
|
3450
|
+
: `${error._tag}: ${detail}`,
|
|
3451
|
+
},
|
|
3452
|
+
],
|
|
3453
|
+
});
|
|
3454
|
+
}));
|
|
2070
3455
|
});
|
|
2071
|
-
const rekeyRow = (row, ctx
|
|
3456
|
+
const rekeyRow = (row, ctx) => Effect.gen(function* () {
|
|
2072
3457
|
const pk = row[config.pk.field]?.S;
|
|
2073
3458
|
if (pk === undefined || (pk !== rekeyPrefix && !pk.startsWith(`${rekeyPrefix}#`))) {
|
|
2074
3459
|
return undefined;
|
|
@@ -2076,89 +3461,60 @@ const makeAggregate = (schema, config) => {
|
|
|
2076
3461
|
if (row.sk?.S !== rekeyRootSk || row.__edd_e__?.S !== config.root.entityType) {
|
|
2077
3462
|
return yield* rekeyRowBelowRoot(row, pk, ctx);
|
|
2078
3463
|
}
|
|
2079
|
-
|
|
3464
|
+
// Judged as its partition's unit, counted when it settles (`judge`).
|
|
3465
|
+
const judged = rootWork(row, ctx);
|
|
3466
|
+
if (!("unit" in judged))
|
|
3467
|
+
return judged.tally;
|
|
3468
|
+
yield* ctx.judge(aggregateName, judged.unit, judged.work);
|
|
3469
|
+
return {};
|
|
3470
|
+
});
|
|
3471
|
+
/**
|
|
3472
|
+
* A row read with `rows` (as stored, the partitions its reader read), that the reader found
|
|
3473
|
+
* where one of its own belongs: if it's a row of an aggregate of this kind rooted in its
|
|
3474
|
+
* partition — one its value, assembled from those rows, decomposes to at that key — that
|
|
3475
|
+
* aggregate is judged, as the scan would judge its root (`yieldTo`). Nothing is read: the rows
|
|
3476
|
+
* are the reader's.
|
|
3477
|
+
*/
|
|
3478
|
+
const rekeyHolder = (row, rows, ctx) => Effect.gen(function* () {
|
|
3479
|
+
const pk = row[config.pk.field]?.S;
|
|
3480
|
+
const sk = row.sk?.S;
|
|
3481
|
+
if (pk === undefined || sk === undefined)
|
|
3482
|
+
return undefined;
|
|
3483
|
+
if (!ownedTypes.has(row.__edd_e__?.S ?? ""))
|
|
3484
|
+
return undefined;
|
|
3485
|
+
const root = rows.find((item) => item[config.pk.field]?.S === pk &&
|
|
3486
|
+
item.sk?.S === rekeyRootSk &&
|
|
3487
|
+
item.__edd_e__?.S === config.root.entityType);
|
|
3488
|
+
if (root === undefined)
|
|
3489
|
+
return undefined;
|
|
3490
|
+
const key = rootKeyAsRead(fromAttributeMap(root));
|
|
2080
3491
|
const current = partitionUnder(config.schema, key);
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
const
|
|
2090
|
-
|
|
2091
|
-
|
|
2092
|
-
|
|
2093
|
-
|
|
2094
|
-
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
|
|
2099
|
-
|
|
2100
|
-
? {}
|
|
2101
|
-
: yield* Rekey.displace(ctx, (under) => rekeyRow(stale, under, depth + 1));
|
|
2102
|
-
// A dry run moved nothing: what would stop that aggregate is what would leave it.
|
|
2103
|
-
const stillThere = ctx.dryRun
|
|
2104
|
-
? tooDeep || (first.conflicts ?? []).length > 0
|
|
2105
|
-
: (yield* staleRootAt(ctx.tableName, current)) !== undefined;
|
|
2106
|
-
if (stillThere) {
|
|
2107
|
-
return Rekey.mergeTallies(first, {
|
|
2108
|
-
conflicts: [
|
|
2109
|
-
{
|
|
2110
|
-
member: aggregateName,
|
|
2111
|
-
kind: "aggregate",
|
|
2112
|
-
reason: "taken",
|
|
2113
|
-
key: { [config.pk.field]: pk, sk: rekeyRootSk },
|
|
2114
|
-
target: { [config.pk.field]: current, sk: rekeyRootSk },
|
|
2115
|
-
message: "Another aggregate's root is stored where this one's belongs.",
|
|
2116
|
-
},
|
|
2117
|
-
],
|
|
2118
|
-
});
|
|
2119
|
-
}
|
|
2120
|
-
fromOnly = ctx.dryRun;
|
|
2121
|
-
}
|
|
2122
|
-
}
|
|
2123
|
-
const moved = yield* rekeyCore(key, ctx.dryRun, from, fromOnly, Rekey.unprovableRow(ctx)).pipe(Effect.catch((error) => {
|
|
2124
|
-
if (Rekey.isDynamoClientError(error))
|
|
2125
|
-
return Effect.fail(error);
|
|
2126
|
-
const assembly = error._tag === "AggregateAssemblyError" ? error.reason : undefined;
|
|
2127
|
-
// Gone since the scan read it: deleted by a write.
|
|
2128
|
-
if (assembly === "Missing root item")
|
|
2129
|
-
return Effect.succeed({});
|
|
2130
|
-
// A root under both partition keys (its sort key is fixed, so one
|
|
2131
|
-
// partition holds one): neither copy is judged.
|
|
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;
|
|
2140
|
-
return Effect.succeed({
|
|
2141
|
-
conflicts: [
|
|
2142
|
-
{
|
|
2143
|
-
member: aggregateName,
|
|
2144
|
-
kind: "aggregate",
|
|
2145
|
-
reason: both ? "bothKeys" : "failed",
|
|
2146
|
-
key: { [config.pk.field]: pk, sk: rekeyRootSk },
|
|
2147
|
-
target: { [config.pk.field]: current, sk: rekeyRootSk },
|
|
2148
|
-
message: both
|
|
2149
|
-
? "The aggregate's root is also stored under its current key."
|
|
2150
|
-
: `${error._tag}: ${detail}`,
|
|
2151
|
-
},
|
|
2152
|
-
],
|
|
2153
|
-
});
|
|
2154
|
-
}));
|
|
2155
|
-
return Rekey.mergeTallies(first, moved);
|
|
2156
|
-
}));
|
|
3492
|
+
if (current === undefined)
|
|
3493
|
+
return undefined;
|
|
3494
|
+
const owns = yield* Effect.gen(function* () {
|
|
3495
|
+
const items = rows
|
|
3496
|
+
.filter((item) => item[config.pk.field]?.S === pk)
|
|
3497
|
+
.map((item) => fromAttributeMap(item));
|
|
3498
|
+
yield* unpackAggregateItems(items, dispatchByType, aggregateName);
|
|
3499
|
+
const assembled = yield* assembleAggregate(assembly, rootNode, items, contextFields, key, aggregateName, systemAttrs);
|
|
3500
|
+
const groups = yield* decomposeAggregate({ ...assembled }, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
3501
|
+
const composed = yield* composeOrFail("rekey", () => buildDynamoItems(groups, config, current, undefined, keyRecord));
|
|
3502
|
+
const placed = locateRows(groups, composed, items, current, pk === current ? undefined : pk);
|
|
3503
|
+
const stored = fromAttributeMap(row);
|
|
3504
|
+
return placed.some((at) => (positionOf(at.old.pk, at.old.sk) === positionOf(pk, sk) ||
|
|
3505
|
+
positionOf(at.current.pk, at.current.sk) === positionOf(pk, sk)) &&
|
|
3506
|
+
!otherElement(at.item, stored));
|
|
3507
|
+
}).pipe(Effect.orElseSucceed(() => false));
|
|
3508
|
+
if (!owns)
|
|
3509
|
+
return undefined;
|
|
3510
|
+
return yield* judgeRoot(root, ctx);
|
|
2157
3511
|
});
|
|
2158
3512
|
const rekeyHandler = {
|
|
2159
3513
|
name: aggregateName,
|
|
2160
3514
|
types: rekeyTypes,
|
|
2161
|
-
|
|
3515
|
+
key: { pk: config.pk.field, sk: "sk" },
|
|
3516
|
+
row: rekeyRow,
|
|
3517
|
+
holder: rekeyHolder,
|
|
2162
3518
|
finish: rekeyFinish,
|
|
2163
3519
|
};
|
|
2164
3520
|
return Rekey.carry(rekeyHandler, withOperations(aggregateName, {
|
|
@@ -2219,14 +3575,20 @@ const makeAggregate = (schema, config) => {
|
|
|
2219
3575
|
})));
|
|
2220
3576
|
const assembled = { ...decoded };
|
|
2221
3577
|
// 3. Compose PK
|
|
2222
|
-
const
|
|
3578
|
+
const own = ownKeys();
|
|
3579
|
+
const pkValue = yield* composeOrFail("create", () => collectionPkOf(assembled, own.schema));
|
|
2223
3580
|
// 4. Decompose into items grouped by sub-aggregate transaction boundaries
|
|
2224
|
-
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: false }
|
|
3581
|
+
const groups = yield* decomposeAggregate(assembled, rootNode, contextFields, rootEncoders, aggregateName, config.schema, { present: true, value: written, update: false }, undefined,
|
|
3582
|
+
// The caller's own input, as given, which `EDD-9159` judges (`givenOverRow`).
|
|
3583
|
+
input);
|
|
2225
3584
|
// 5. Build DynamoDB items with composed keys (create only ever PUTs).
|
|
2226
3585
|
// Every row is new, so `created` has nothing to carry forward.
|
|
3586
|
+
// Ahead of anything marshalled: a part behind a getter is judged as it's marshalled.
|
|
3587
|
+
yield* refuseLost(groups, "aggregate.create");
|
|
2227
3588
|
const packedGroups = yield* packAggregateGroups(groups, packedByType, aggregateName, "create");
|
|
2228
|
-
const dynamoGroups = yield* composeOrFail("create", () => buildDynamoItems(packedGroups, config, pkValue, assembled, keyRecord, stampFor(now, EMPTY_CREATED)));
|
|
3589
|
+
const dynamoGroups = yield* composeOrFail("create", () => buildDynamoItems(packedGroups, config, pkValue, assembled, keyRecord, stampFor(now, EMPTY_CREATED), own));
|
|
2229
3590
|
yield* refuseOtherKindKeys(groups, "aggregate.create");
|
|
3591
|
+
yield* refuseGivenOverRows(packedGroups, dynamoGroups);
|
|
2230
3592
|
yield* refuseNotReadBack(dynamoGroups, assembled, "aggregate.create", storedAsGivenIn(groups));
|
|
2231
3593
|
// 6. Write via sub-aggregate transactions. The root item goes first in
|
|
2232
3594
|
// the first transaction, guarded by `attribute_not_exists` (#134):
|
|
@@ -2264,14 +3626,18 @@ const makeAggregate = (schema, config) => {
|
|
|
2264
3626
|
reason: String(error.cause?.message ?? error.cause),
|
|
2265
3627
|
key,
|
|
2266
3628
|
}))));
|
|
2267
|
-
|
|
3629
|
+
// Only the aggregate's own rows (DESIGN.md §7 "delete"): a row of another entity type in
|
|
3630
|
+
// its partition is an entity's or another aggregate's, and stays. Nothing is keyed by
|
|
3631
|
+
// value, so every row of the aggregate's types is deleted, whoever wrote it.
|
|
3632
|
+
const ownItems = allItems.filter((item) => typeof item.__edd_e__ === "string" && ownedTypes.has(item.__edd_e__));
|
|
3633
|
+
if (ownItems.length === 0) {
|
|
2268
3634
|
return yield* new AggregateAssemblyError({
|
|
2269
3635
|
aggregate: aggregateName,
|
|
2270
3636
|
reason: "No items found for aggregate key",
|
|
2271
3637
|
key,
|
|
2272
3638
|
});
|
|
2273
3639
|
}
|
|
2274
|
-
yield* deleteAllItems(client, tableConfig.name,
|
|
3640
|
+
yield* deleteAllItems(client, tableConfig.name, ownItems, config.pk.field);
|
|
2275
3641
|
}),
|
|
2276
3642
|
list: (filter, options) => Effect.gen(function* () {
|
|
2277
3643
|
const client = yield* Capacity.client;
|
|
@@ -2290,7 +3656,7 @@ const makeAggregate = (schema, config) => {
|
|
|
2290
3656
|
// Root-item FilterExpression. Compiled once — the same two forms
|
|
2291
3657
|
// `BoundQuery.filter()` takes, through the same `Expr` compiler, so
|
|
2292
3658
|
// there is one filter vocabulary rather than a second dialect here.
|
|
2293
|
-
const rootFilter = yield* compileListFilter(options?.filter, aggregateName);
|
|
3659
|
+
const rootFilter = yield* compileListFilter(options?.filter, aggregateName, rootStoredFormAt, storedBelowFields(schemaFields), schema);
|
|
2294
3660
|
// Attribute names that make up a resume key on the list index: the index
|
|
2295
3661
|
// key plus the table key. A `LastEvaluatedKey` supplies them when there
|
|
2296
3662
|
// is one; this is the fallback for the case a filtered request over-reads
|
|
@@ -2305,7 +3671,7 @@ const makeAggregate = (schema, config) => {
|
|
|
2305
3671
|
// DOMAIN record, so it goes through the same key form the write side
|
|
2306
3672
|
// used — otherwise `list` composes a key `create` never wrote and
|
|
2307
3673
|
// silently returns nothing (#111).
|
|
2308
|
-
const listPkComposites = yield* composeOrFail("list", () => keyCompositesOrThrow(aggregateName,
|
|
3674
|
+
const listPkComposites = yield* composeOrFail("list", () => keyCompositesOrThrow(aggregateName, AGGREGATE_KEY.listPartition, config.schema, listConfig.pk.composite, keyRecord(filter ?? {})));
|
|
2309
3675
|
// Build SK prefix from contiguous filter values matching SK composites.
|
|
2310
3676
|
// `keyValueText`, NOT `String(v)` — the write side encodes
|
|
2311
3677
|
// numerics, so `String(5)` would look for `5` where `0000000000000005`
|
|
@@ -2313,8 +3679,8 @@ const makeAggregate = (schema, config) => {
|
|
|
2313
3679
|
const skValues = [];
|
|
2314
3680
|
const listSkFilter = keyRecord(filter ?? {});
|
|
2315
3681
|
for (const attr of listConfig.sk.composite) {
|
|
2316
|
-
if (listSkFilter
|
|
2317
|
-
skValues.push(KeyComposer.keyValueText(config.schema, listSkFilter
|
|
3682
|
+
if (ownValue(listSkFilter, attr) !== undefined)
|
|
3683
|
+
skValues.push(KeyComposer.keyValueText(config.schema, ownValue(listSkFilter, attr), config.schema.casing));
|
|
2318
3684
|
else
|
|
2319
3685
|
break; // Stop at first gap (prefix matching)
|
|
2320
3686
|
}
|
|
@@ -2397,7 +3763,7 @@ const makeAggregate = (schema, config) => {
|
|
|
2397
3763
|
for (const rootItem of rootItems) {
|
|
2398
3764
|
const stored = {};
|
|
2399
3765
|
for (const composite of config.pk.composite) {
|
|
2400
|
-
stored
|
|
3766
|
+
setOwn(stored, composite, ownValue(rootItem, composite));
|
|
2401
3767
|
}
|
|
2402
3768
|
// The key the root's values compose as a read takes them, as `create` composed it.
|
|
2403
3769
|
const key = rootKeyAsRead(stored);
|
|
@@ -2484,14 +3850,40 @@ const deepEqual = (a, b) => {
|
|
|
2484
3850
|
a.size === b.size &&
|
|
2485
3851
|
[...a].every((member) => b.has(member)));
|
|
2486
3852
|
}
|
|
3853
|
+
// A zone compares as it's stored: each property a write stores of it, by this same equality, with
|
|
3854
|
+
// a named zone's name as `zoneEntriesWritten` writes it. Effect 4.1.3 keeps the name a zone was made
|
|
3855
|
+
// from, so `Etc/UTC` and `UTC` are two zones stored as one map, where 4.1.2 made them one zone:
|
|
3856
|
+
// compared by their properties, an update that sets the zone already stored wrote it again.
|
|
3857
|
+
if (isZoneInstance(a) || isZoneInstance(b)) {
|
|
3858
|
+
if (!isZoneInstance(a) || !isZoneInstance(b))
|
|
3859
|
+
return false;
|
|
3860
|
+
const aStored = zoneStored(a);
|
|
3861
|
+
const bStored = zoneStored(b);
|
|
3862
|
+
return (aStored.length === bStored.length &&
|
|
3863
|
+
aStored.every(([key, value]) => {
|
|
3864
|
+
const other = bStored.find(([at]) => at === key);
|
|
3865
|
+
return other !== undefined && deepEqual(value, other[1]);
|
|
3866
|
+
}));
|
|
3867
|
+
}
|
|
2487
3868
|
const aObj = a;
|
|
2488
3869
|
const bObj = b;
|
|
2489
|
-
|
|
2490
|
-
const
|
|
3870
|
+
// A decimal's cached normalized form holds itself, and isn't stored: compared, it never ended.
|
|
3871
|
+
const aKeys = Object.keys(aObj).filter((k) => !isCachedNormal(aObj, k));
|
|
3872
|
+
const bKeys = Object.keys(bObj).filter((k) => !isCachedNormal(bObj, k));
|
|
2491
3873
|
if (aKeys.length !== bKeys.length)
|
|
2492
3874
|
return false;
|
|
2493
3875
|
return aKeys.every((k) => deepEqual(aObj[k], bObj[k]));
|
|
2494
3876
|
};
|
|
3877
|
+
/** What a write stores of a zone: its enumerable properties, its name as `zoneEntriesWritten` gives it. */
|
|
3878
|
+
const zoneStored = (zone) => {
|
|
3879
|
+
const entries = [];
|
|
3880
|
+
for (const key in zone) {
|
|
3881
|
+
const value = zone[key];
|
|
3882
|
+
if (value !== undefined && typeof value !== "function")
|
|
3883
|
+
entries.push([key, value]);
|
|
3884
|
+
}
|
|
3885
|
+
return zoneEntriesWritten(entries, true, (value) => value, (name) => name);
|
|
3886
|
+
};
|
|
2495
3887
|
const deepEqualGroups = (a, b) => sameItems(a.items, b.items);
|
|
2496
3888
|
/** Whether two decompositions are one: the same items, in order, of the same types and attributes. */
|
|
2497
3889
|
const sameItems = (a, b) => {
|
|
@@ -2516,9 +3908,9 @@ const edgePackedFields = (edgeName, entity, itemFields, discriminator, skComposi
|
|
|
2516
3908
|
const configured = DynamoModel.getPackedFields(entity.model);
|
|
2517
3909
|
const packed = {};
|
|
2518
3910
|
for (const [field, storedAs] of Object.entries(configured)) {
|
|
2519
|
-
if (itemFields !== undefined && !(field
|
|
3911
|
+
if (itemFields !== undefined && !Object.hasOwn(itemFields, field))
|
|
2520
3912
|
continue;
|
|
2521
|
-
if (discriminator !== undefined && field
|
|
3913
|
+
if (discriminator !== undefined && Object.hasOwn(discriminator, field)) {
|
|
2522
3914
|
throw new Error(`[EDD-9072] Aggregate edge "${edgeName}": discriminator "${field}" is a packed field of ` +
|
|
2523
3915
|
`entity "${entity.entityType}". A discriminator is matched as a scalar stored value.`);
|
|
2524
3916
|
}
|
|
@@ -2526,7 +3918,7 @@ const edgePackedFields = (edgeName, entity, itemFields, discriminator, skComposi
|
|
|
2526
3918
|
throw new Error(`[EDD-9072] Aggregate edge "${edgeName}": sort-key composite "${field}" is a packed field ` +
|
|
2527
3919
|
`of entity "${entity.entityType}". Key composites must be scalar model values.`);
|
|
2528
3920
|
}
|
|
2529
|
-
packed
|
|
3921
|
+
setOwn(packed, field, storedAs);
|
|
2530
3922
|
}
|
|
2531
3923
|
return Object.keys(packed).length > 0 ? packed : undefined;
|
|
2532
3924
|
};
|
|
@@ -2542,7 +3934,7 @@ const edgeDispatchFields = (entity, itemFields, packed) => {
|
|
|
2542
3934
|
const sparse = DynamoModel.getSparseFields(entity.model);
|
|
2543
3935
|
const dispatch = new Set(Object.keys(packed ?? {}));
|
|
2544
3936
|
for (const [field, schema] of Object.entries(itemFields ?? {})) {
|
|
2545
|
-
if (field
|
|
3937
|
+
if (Object.hasOwn(sparse, field))
|
|
2546
3938
|
continue;
|
|
2547
3939
|
if (isDispatchEligible(schema))
|
|
2548
3940
|
dispatch.add(field);
|
|
@@ -2567,7 +3959,7 @@ const resolveNode = (args) => {
|
|
|
2567
3959
|
// The item is the edge value flattened: encode it field by field with
|
|
2568
3960
|
// the edge entity's model (#72), or — for an edge without an entity —
|
|
2569
3961
|
// with the model field's own class.
|
|
2570
|
-
const parentField = parentFields
|
|
3962
|
+
const parentField = ownValue(parentFields, field);
|
|
2571
3963
|
const valueFields = fieldsOf(edge.entity?.model) ??
|
|
2572
3964
|
(parentField === undefined
|
|
2573
3965
|
? undefined
|
|
@@ -2580,7 +3972,14 @@ const resolveNode = (args) => {
|
|
|
2580
3972
|
discriminator: mergedDisc,
|
|
2581
3973
|
ownDiscriminator: edge.discriminator,
|
|
2582
3974
|
ownFields: valueFields,
|
|
3975
|
+
valueSchema: modelOf(edge.entity?.model) ??
|
|
3976
|
+
(parentField === undefined ? undefined : unwrapOptionalField(parentField)),
|
|
2583
3977
|
attrEncoders: buildAttrEncoders(valueFields, resolveRef),
|
|
3978
|
+
rowKeys: args.rowKeys,
|
|
3979
|
+
readRow: readRowOf("edge", args.rowKeys, declaredValueNames.one(parentFields, field)),
|
|
3980
|
+
placed: placedFields(parentField),
|
|
3981
|
+
fieldSchema: parentField,
|
|
3982
|
+
valueReadSchema: parentField === undefined ? undefined : unwrapOptionalField(parentField),
|
|
2584
3983
|
...edgeStorage(edgePackedFields(field, edge.entity, valueFields, edge.discriminator, undefined), edge.entity, valueFields),
|
|
2585
3984
|
}));
|
|
2586
3985
|
}
|
|
@@ -2594,11 +3993,20 @@ const resolveNode = (args) => {
|
|
|
2594
3993
|
// entity's model, which is what such an element IS.
|
|
2595
3994
|
const entityFields = fieldsOf(edge.entity?.model);
|
|
2596
3995
|
const elementFields = manyElementFields(parentFields, field) ?? entityFields;
|
|
2597
|
-
const parentField = parentFields
|
|
3996
|
+
const parentField = ownValue(parentFields, field);
|
|
2598
3997
|
const arrayElement = parentField === undefined ? undefined : extractArrayElement(parentField);
|
|
2599
3998
|
const keyedValue = parentField === undefined || arrayElement !== undefined
|
|
2600
3999
|
? undefined
|
|
2601
4000
|
: extractKeyedValue(parentField);
|
|
4001
|
+
// Sort-key composites kept reading the pre-#133 encoding (the entity model's top-level
|
|
4002
|
+
// transforms) through 1.40.0, so no stored key is re-spelled. Under `escapeKeys: true` a
|
|
4003
|
+
// declared sort key is composed from the element's own values, as a plain edge's is (#241):
|
|
4004
|
+
// the entity's encoders ran over the element's field of the same name, whatever that
|
|
4005
|
+
// field is. Which composites that moves is decided by `entityEdgeEncodedComposites`.
|
|
4006
|
+
// `rekey` moves the rows; `update` moves a group's when it writes it.
|
|
4007
|
+
const entityKeyEncoders = buildKeyAttrEncoders(entityFields);
|
|
4008
|
+
const recomposed = entityEdgeEncodedComposites(edge.entity?.model, edge.sk?.composite).length > 0;
|
|
4009
|
+
const escaped = args.escapeKeys === true;
|
|
2602
4010
|
children.push(resolveNode({
|
|
2603
4011
|
fieldName: field,
|
|
2604
4012
|
entityType: edge.entityType,
|
|
@@ -2609,12 +4017,24 @@ const resolveNode = (args) => {
|
|
|
2609
4017
|
decompose: edge.decompose,
|
|
2610
4018
|
decomposeInput: edge.decompose === undefined
|
|
2611
4019
|
? undefined
|
|
2612
|
-
: storedFormFirst(field, parentFields
|
|
4020
|
+
: storedFormFirst(field, ownValue(parentFields, field), resolveRef),
|
|
2613
4021
|
ownFields: elementFields,
|
|
4022
|
+
valueSchema: manyElementSchema(parentFields, field) ?? modelOf(edge.entity?.model),
|
|
2614
4023
|
attrEncoders: buildAttrEncoders(elementFields, resolveRef, keyedValue !== undefined && edge.entity === undefined),
|
|
2615
|
-
|
|
2616
|
-
|
|
2617
|
-
|
|
4024
|
+
elementEncoder: wholeElementEncoder(field, arrayElement, edge.decompose, resolveRef),
|
|
4025
|
+
rowKeys: args.rowKeys,
|
|
4026
|
+
readRow: readRowOf("edge", args.rowKeys, declaredValueNames.many(parentFields, field, edge)),
|
|
4027
|
+
placed: edge.decompose !== undefined || edge.assemble !== undefined
|
|
4028
|
+
? undefined
|
|
4029
|
+
: placedFields(manyElementSchema(parentFields, field)),
|
|
4030
|
+
fieldSchema: parentField,
|
|
4031
|
+
valueReadSchema: manyElementSchema(parentFields, field),
|
|
4032
|
+
inputField: edge.inputField,
|
|
4033
|
+
keyAttrEncoders: recomposed && escaped ? {} : entityKeyEncoders,
|
|
4034
|
+
...(recomposed && {
|
|
4035
|
+
otherCompositionEncoders: escaped ? entityKeyEncoders : {},
|
|
4036
|
+
}),
|
|
4037
|
+
...(recomposed && escaped && { movedKeyText: true }),
|
|
2618
4038
|
// Declared sort-key composites, authoritative when present (#103).
|
|
2619
4039
|
skComposite: edge.sk?.composite,
|
|
2620
4040
|
refIdentifierField: edge.entity
|
|
@@ -2647,20 +4067,40 @@ const resolveNode = (args) => {
|
|
|
2647
4067
|
// The sub-aggregate root item carries the sub-schema's own (non-edge)
|
|
2648
4068
|
// fields; its child edges get their own encoders via recursion.
|
|
2649
4069
|
attrEncoders: buildAttrEncoders(subFields, resolveRef),
|
|
4070
|
+
readRow: readRowOf(subAggregateRowKind(bound.aggregate.edges), args.rowKeys, declaredValueNames.own(subFields, bound.aggregate.edges)),
|
|
4071
|
+
placed: placedFields(bound.aggregate.schema),
|
|
4072
|
+
// What a read decodes its value with: the field holding it in its parent, else its own
|
|
4073
|
+
// schema (#241, `EDD-9159` reads a value its schema can't place exactly as a whole).
|
|
4074
|
+
fieldSchema: parentFields?.[field] ?? bound.aggregate.schema,
|
|
4075
|
+
valueReadSchema: parentFields?.[field] === undefined
|
|
4076
|
+
? bound.aggregate.schema
|
|
4077
|
+
: unwrapOptionalField(parentFields[field]),
|
|
4078
|
+
rowKeys: args.rowKeys,
|
|
4079
|
+
escapeKeys: args.escapeKeys,
|
|
2650
4080
|
});
|
|
2651
4081
|
children.push(subChildren);
|
|
2652
4082
|
}
|
|
2653
4083
|
}
|
|
2654
4084
|
}
|
|
2655
4085
|
const ownFields = args.ownFields ?? parentFields;
|
|
4086
|
+
const storedNames = ownFields === undefined && args.valueSchema !== undefined
|
|
4087
|
+
? storedFieldNames(args.valueSchema)
|
|
4088
|
+
: undefined;
|
|
2656
4089
|
return {
|
|
2657
4090
|
fieldName,
|
|
2658
4091
|
entityType,
|
|
2659
4092
|
cardinality,
|
|
2660
4093
|
ownFields,
|
|
4094
|
+
...(storedNames !== undefined && { storedNames }),
|
|
2661
4095
|
// Absent optionals stay absent under `exactOptionalPropertyTypes`.
|
|
2662
4096
|
...(discriminator !== undefined && { discriminator }),
|
|
2663
4097
|
...(ownDiscriminator !== undefined && { ownDiscriminator }),
|
|
4098
|
+
readRow: args.readRow,
|
|
4099
|
+
...(args.placed !== undefined && { placed: args.placed }),
|
|
4100
|
+
...(args.fieldSchema !== undefined && { fieldSchema: args.fieldSchema }),
|
|
4101
|
+
...(args.valueReadSchema !== undefined && { valueReadSchema: args.valueReadSchema }),
|
|
4102
|
+
...(args.inputField !== undefined &&
|
|
4103
|
+
args.inputField !== fieldName && { inputField: args.inputField }),
|
|
2664
4104
|
children,
|
|
2665
4105
|
...(assemble !== undefined && { assemble }),
|
|
2666
4106
|
...(decompose !== undefined && { decompose }),
|
|
@@ -2670,7 +4110,12 @@ const resolveNode = (args) => {
|
|
|
2670
4110
|
...(args.packed !== undefined && { packed: args.packed }),
|
|
2671
4111
|
...(args.dispatch !== undefined && { dispatch: args.dispatch }),
|
|
2672
4112
|
attrEncoders,
|
|
4113
|
+
...(args.elementEncoder !== undefined && { elementEncoder: args.elementEncoder }),
|
|
2673
4114
|
...(keyAttrEncoders !== undefined && { keyAttrEncoders }),
|
|
4115
|
+
...(args.otherCompositionEncoders !== undefined && {
|
|
4116
|
+
otherCompositionEncoders: args.otherCompositionEncoders,
|
|
4117
|
+
}),
|
|
4118
|
+
...(args.movedKeyText === true && { movedKeyText: true }),
|
|
2674
4119
|
};
|
|
2675
4120
|
};
|
|
2676
4121
|
// ---------------------------------------------------------------------------
|
|
@@ -2794,7 +4239,7 @@ stored) => Effect.gen(function* () {
|
|
|
2794
4239
|
const assembleAggregate = (assembly, rootNode, allItems, _contextFields, key, aggregateName,
|
|
2795
4240
|
/** Library-managed attribute names (system timestamps) to drop before decode. */
|
|
2796
4241
|
systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
2797
|
-
const reached = assemblyWalk(rootNode, allItems, (node, item) => takesRow(node, item.__edd_e__, (attr) => item
|
|
4242
|
+
const reached = assemblyWalk(rootNode, allItems, (node, item) => takesRow(node, item.__edd_e__, (attr) => ownValue(item, attr)));
|
|
2798
4243
|
// Find the root item
|
|
2799
4244
|
const rootItems = reached.get(rootNode) ?? [];
|
|
2800
4245
|
if (rootItems.length === 0) {
|
|
@@ -2817,37 +4262,11 @@ systemAttrs = EMPTY_ATTRS) => Effect.gen(function* () {
|
|
|
2817
4262
|
for (const child of rootNode.children) {
|
|
2818
4263
|
const assembled = yield* assembleNode(child, reached, key, aggregateName, systemAttrs);
|
|
2819
4264
|
if (child.fieldName !== null && assembled !== undefined) {
|
|
2820
|
-
edgeValues
|
|
4265
|
+
setOwn(edgeValues, child.fieldName, assembled);
|
|
2821
4266
|
}
|
|
2822
4267
|
}
|
|
2823
4268
|
// Combine root item fields (minus DynamoDB metadata + context) with assembled edges
|
|
2824
|
-
const rootFields =
|
|
2825
|
-
const edgeFieldNames = new Set(rootNode.children.map((c) => c.fieldName).filter(Boolean));
|
|
2826
|
-
const metaFields = new Set([
|
|
2827
|
-
"__edd_e__",
|
|
2828
|
-
"pk",
|
|
2829
|
-
"sk",
|
|
2830
|
-
"gsi1pk",
|
|
2831
|
-
"gsi1sk",
|
|
2832
|
-
"gsi2pk",
|
|
2833
|
-
"gsi2sk",
|
|
2834
|
-
"gsi3pk",
|
|
2835
|
-
"gsi3sk",
|
|
2836
|
-
"gsi4pk",
|
|
2837
|
-
"gsi4sk",
|
|
2838
|
-
"gsi5pk",
|
|
2839
|
-
"gsi5sk",
|
|
2840
|
-
"lsi1sk",
|
|
2841
|
-
"lsi2sk",
|
|
2842
|
-
...stampsToStrip(rootNode, systemAttrs),
|
|
2843
|
-
]);
|
|
2844
|
-
for (const [fieldKey, value] of Object.entries(rootItem)) {
|
|
2845
|
-
if (metaFields.has(fieldKey))
|
|
2846
|
-
continue;
|
|
2847
|
-
if (edgeFieldNames.has(fieldKey))
|
|
2848
|
-
continue;
|
|
2849
|
-
rootFields[fieldKey] = value;
|
|
2850
|
-
}
|
|
4269
|
+
const rootFields = rowValueAsRead(rootNode, rootItem, systemAttrs);
|
|
2851
4270
|
// Merge raw (wire-form) root fields with assembled edge items.
|
|
2852
4271
|
const assembled = { ...rootFields, ...edgeValues };
|
|
2853
4272
|
// Decode through `decodeSchema` — a tolerant clone of the aggregate schema
|
|
@@ -2918,47 +4337,75 @@ const assembleNode = (node, reached, key, aggregateName, systemAttrs = EMPTY_ATT
|
|
|
2918
4337
|
for (const child of node.children) {
|
|
2919
4338
|
const assembled = yield* assembleNode(child, reached, key, aggregateName, systemAttrs);
|
|
2920
4339
|
if (child.fieldName !== null && assembled !== undefined) {
|
|
2921
|
-
edgeValues
|
|
4340
|
+
setOwn(edgeValues, child.fieldName, assembled);
|
|
2922
4341
|
}
|
|
2923
4342
|
}
|
|
2924
4343
|
// Build sub-aggregate result: sub-root fields + assembled edges
|
|
2925
|
-
|
|
2926
|
-
const edgeFieldNames = new Set(node.children.map((c) => c.fieldName).filter(Boolean));
|
|
2927
|
-
const stripped = stampsToStrip(node, systemAttrs);
|
|
2928
|
-
for (const [fieldKey, value] of Object.entries(subRootItem)) {
|
|
2929
|
-
// Skip DynamoDB metadata, discriminator attributes, and edge fields
|
|
2930
|
-
if (fieldKey === "__edd_e__")
|
|
2931
|
-
continue;
|
|
2932
|
-
if (fieldKey.startsWith("pk") || fieldKey.startsWith("sk"))
|
|
2933
|
-
continue;
|
|
2934
|
-
if (fieldKey.startsWith("gsi") || fieldKey.startsWith("lsi"))
|
|
2935
|
-
continue;
|
|
2936
|
-
if (stripped.has(fieldKey))
|
|
2937
|
-
continue;
|
|
2938
|
-
if (edgeFieldNames.has(fieldKey))
|
|
2939
|
-
continue;
|
|
2940
|
-
// Skip discriminator attributes
|
|
2941
|
-
if (node.discriminator && fieldKey in node.discriminator)
|
|
2942
|
-
continue;
|
|
2943
|
-
subFields[fieldKey] = value;
|
|
2944
|
-
}
|
|
2945
|
-
return { ...subFields, ...edgeValues };
|
|
4344
|
+
return { ...rowValueAsRead(node, subRootItem, systemAttrs), ...edgeValues };
|
|
2946
4345
|
}
|
|
2947
4346
|
// Simple one-to-one edge — if no matching items, return undefined
|
|
2948
4347
|
// (the Schema decode will catch truly required missing fields)
|
|
2949
4348
|
if (matchingItems.length === 0)
|
|
2950
4349
|
return undefined;
|
|
2951
4350
|
// Return the item (stripped of DynamoDB metadata)
|
|
2952
|
-
|
|
2953
|
-
return stripMetadata(item, stampsToStrip(node, systemAttrs));
|
|
4351
|
+
return rowValueAsRead(node, matchingItems[0], systemAttrs);
|
|
2954
4352
|
}
|
|
2955
|
-
// Many edge: collect all matching items
|
|
2956
|
-
|
|
4353
|
+
// Many edge: collect all matching items. A custom `assemble` is handed each row with its
|
|
4354
|
+
// discriminator attributes, as the aggregates guide says.
|
|
2957
4355
|
if (node.assemble) {
|
|
2958
|
-
return node.assemble(
|
|
4356
|
+
return node.assemble(matchingItems.map((item) => rowValueAsRead(node, item, systemAttrs)));
|
|
2959
4357
|
}
|
|
2960
|
-
return
|
|
4358
|
+
return elementRows(node, matchingItems, systemAttrs).map((item) => rowValueAsRead(node, item, systemAttrs));
|
|
2961
4359
|
});
|
|
4360
|
+
/**
|
|
4361
|
+
* The rows a `many` edge's elements are read from, in order (#241): each row assembly hands the
|
|
4362
|
+
* edge, but two rows of one element, copies of each other ({@link copiesOfOneElement}), are the
|
|
4363
|
+
* element once.
|
|
4364
|
+
*/
|
|
4365
|
+
const elementRows = (node, matchingItems, systemAttrs) => node.movedKeyText === true
|
|
4366
|
+
? matchingItems.filter((item, i) => !matchingItems
|
|
4367
|
+
.slice(0, i)
|
|
4368
|
+
.some((earlier) => copiesOfOneElement(node, earlier, item, systemAttrs)))
|
|
4369
|
+
: matchingItems;
|
|
4370
|
+
/**
|
|
4371
|
+
* The row a read takes each value of an aggregate from, by the value's path in it (#241, the path
|
|
4372
|
+
* decomposition gives each item, as JSON): the root's row, a `one` edge's, a sub-aggregate's, and
|
|
4373
|
+
* each element's of a `many` edge without a custom `decompose` or `assemble`. Read off assembly's
|
|
4374
|
+
* own walk and choices ({@link assemblyWalk}, {@link elementRows}): a value's row is the one it was
|
|
4375
|
+
* read from.
|
|
4376
|
+
*/
|
|
4377
|
+
const rowsReadAt = (rootNode, allItems, systemAttrs) => {
|
|
4378
|
+
const reached = assemblyWalk(rootNode, allItems, (node, item) => takesRow(node, item.__edd_e__, (attr) => item[attr]));
|
|
4379
|
+
const at = new Map();
|
|
4380
|
+
const rootItems = reached.get(rootNode) ?? [];
|
|
4381
|
+
if (rootItems.length !== 1)
|
|
4382
|
+
return at;
|
|
4383
|
+
at.set(JSON.stringify([]), rootItems[0]);
|
|
4384
|
+
const visit = (node, path) => {
|
|
4385
|
+
const rows = reached.get(node) ?? [];
|
|
4386
|
+
if (node.cardinality === "one") {
|
|
4387
|
+
if (node.children.length > 0 && rows.length !== 1)
|
|
4388
|
+
return;
|
|
4389
|
+
if (rows.length > 0)
|
|
4390
|
+
at.set(JSON.stringify(path), rows[0]);
|
|
4391
|
+
for (const child of node.children) {
|
|
4392
|
+
if (child.fieldName !== null)
|
|
4393
|
+
visit(child, [...path, child.fieldName]);
|
|
4394
|
+
}
|
|
4395
|
+
return;
|
|
4396
|
+
}
|
|
4397
|
+
if (node.assemble !== undefined || node.decompose !== undefined)
|
|
4398
|
+
return;
|
|
4399
|
+
elementRows(node, rows, systemAttrs).forEach((row, i) => {
|
|
4400
|
+
at.set(JSON.stringify([...path, i]), row);
|
|
4401
|
+
});
|
|
4402
|
+
};
|
|
4403
|
+
for (const child of rootNode.children) {
|
|
4404
|
+
if (child.fieldName !== null)
|
|
4405
|
+
visit(child, [child.fieldName]);
|
|
4406
|
+
}
|
|
4407
|
+
return at;
|
|
4408
|
+
};
|
|
2962
4409
|
// ---------------------------------------------------------------------------
|
|
2963
4410
|
// Internal: Strip DynamoDB metadata from items
|
|
2964
4411
|
// ---------------------------------------------------------------------------
|
|
@@ -2968,23 +4415,77 @@ const stampsToStrip = (node, systemAttrs) => {
|
|
|
2968
4415
|
const own = node.ownFields;
|
|
2969
4416
|
if (own === undefined)
|
|
2970
4417
|
return systemAttrs;
|
|
2971
|
-
const kept = [...systemAttrs].filter((name) => !(name
|
|
4418
|
+
const kept = [...systemAttrs].filter((name) => !Object.hasOwn(own, name));
|
|
2972
4419
|
return kept.length === systemAttrs.size ? systemAttrs : new Set(kept);
|
|
2973
4420
|
};
|
|
2974
|
-
|
|
4421
|
+
/**
|
|
4422
|
+
* A row of `node` as a read hands its value over (#241): without what `readTakesOff` takes off it
|
|
4423
|
+
* and the stamps its value doesn't declare (`stampsToStrip`), and, on a row with edges of its own
|
|
4424
|
+
* (the root's, a sub-aggregate's), without the edges' names, whose values are their own rows', and a
|
|
4425
|
+
* sub-aggregate's discriminator. Assembly reads every row through it, and so does `create`'s
|
|
4426
|
+
* judgement of a value given (`EDD-9159`): the one place a row becomes a value.
|
|
4427
|
+
*/
|
|
4428
|
+
const rowValueAsRead = (node, row, systemAttrs = EMPTY_ATTRS) => {
|
|
4429
|
+
const stamps = stampsToStrip(node, systemAttrs);
|
|
4430
|
+
const withEdges = node.children.length > 0;
|
|
2975
4431
|
const result = {};
|
|
2976
|
-
for (const [key, value] of Object.entries(
|
|
2977
|
-
if (key
|
|
4432
|
+
for (const [key, value] of Object.entries(row)) {
|
|
4433
|
+
if (readTakesOff(node.readRow, key) || stamps.has(key))
|
|
4434
|
+
continue;
|
|
4435
|
+
if (withEdges) {
|
|
4436
|
+
if (node.children.some((child) => child.fieldName === key))
|
|
4437
|
+
continue;
|
|
4438
|
+
if (node.discriminator !== undefined && Object.hasOwn(node.discriminator, key))
|
|
4439
|
+
continue;
|
|
4440
|
+
}
|
|
4441
|
+
setOwn(result, key, value);
|
|
4442
|
+
}
|
|
4443
|
+
return result;
|
|
4444
|
+
};
|
|
4445
|
+
/**
|
|
4446
|
+
* Whether two rows of an `entity:` edge whose key text this release moved ({@link
|
|
4447
|
+
* ResolvedNode.movedKeyText}) are copies of one element (#241): a read gives the same value of both,
|
|
4448
|
+
* so they differ only in key text and in the timestamps the library stamps beside the value. A
|
|
4449
|
+
* 1.40.0 writer leaves such a copy under its text beside each row this release wrote (DESIGN.md §11
|
|
4450
|
+
* "Writers of two releases"). The one decision: a read hands the element back once (`assembleNode`),
|
|
4451
|
+
* and `rekey` deletes the copy under 1.40.0's text; two rows of one key that differ are refused by a
|
|
4452
|
+
* write and reported by `rekey`, naming both ({@link doubledKeys}).
|
|
4453
|
+
*/
|
|
4454
|
+
const copiesOfOneElement = (node, a, b, systemAttrs) => {
|
|
4455
|
+
if (node.movedKeyText !== true)
|
|
4456
|
+
return false;
|
|
4457
|
+
return deepEqual(rowValueAsRead(node, a, systemAttrs), rowValueAsRead(node, b, systemAttrs));
|
|
4458
|
+
};
|
|
4459
|
+
/**
|
|
4460
|
+
* The keys two items compose that hold two rows of one element, read under both key texts (#241):
|
|
4461
|
+
* each item's 1.40.0 text (`otherCompositionSortKey`) is one text, and the read holds a row of its
|
|
4462
|
+
* type there and at the key, as a 1.40.0 writer leaves a group this release moved. Their values
|
|
4463
|
+
* differ ({@link copiesOfOneElement} hands a copy back once), so which is the element can't be told
|
|
4464
|
+
* from what's stored. Maps each such key to the row under 1.40.0's text. A key two items compose
|
|
4465
|
+
* otherwise is a collision (`refuseSharedSortKeys`).
|
|
4466
|
+
*/
|
|
4467
|
+
const doubledKeys = (items, schema, rowAt) => {
|
|
4468
|
+
const byKey = new Map();
|
|
4469
|
+
for (const item of items) {
|
|
4470
|
+
if (item.node.movedKeyText !== true)
|
|
2978
4471
|
continue;
|
|
2979
|
-
|
|
4472
|
+
const sk = composeKey(schema, item.entityType, [...item.skComposites]);
|
|
4473
|
+
byKey.set(sk, [...(byKey.get(sk) ?? []), item]);
|
|
4474
|
+
}
|
|
4475
|
+
const doubled = new Map();
|
|
4476
|
+
for (const [sk, sharing] of byKey) {
|
|
4477
|
+
if (sharing.length < 2)
|
|
2980
4478
|
continue;
|
|
2981
|
-
|
|
4479
|
+
const froms = new Set(sharing.map((item) => otherCompositionSortKey(schema, item)));
|
|
4480
|
+
const [from] = froms;
|
|
4481
|
+
if (froms.size !== 1 || from === undefined || from === sk)
|
|
2982
4482
|
continue;
|
|
2983
|
-
|
|
4483
|
+
const type = sharing[0].entityType;
|
|
4484
|
+
if (rowAt(sk)?.__edd_e__ !== type || rowAt(from)?.__edd_e__ !== type)
|
|
2984
4485
|
continue;
|
|
2985
|
-
|
|
4486
|
+
doubled.set(sk, from);
|
|
2986
4487
|
}
|
|
2987
|
-
return
|
|
4488
|
+
return doubled;
|
|
2988
4489
|
};
|
|
2989
4490
|
/** An object as given, to name it in an error, whatever its `toString` (a JSON body's may be text). */
|
|
2990
4491
|
const describeObject = (value) => {
|
|
@@ -3025,8 +4526,10 @@ const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen
|
|
|
3025
4526
|
// Collect all ref IDs from the entire input hierarchy
|
|
3026
4527
|
const refRequests = [];
|
|
3027
4528
|
collectRefIdsFromEdges(refRequests, input, edges, fields, [], "");
|
|
4529
|
+
// A `many` edge's value given under its `inputField` is decoded under its field's name, ids
|
|
4530
|
+
// or not (#241): up to 1.40.0 it was renamed only where an id was fetched.
|
|
3028
4531
|
if (refRequests.length === 0)
|
|
3029
|
-
return input;
|
|
4532
|
+
return renameInputFields(input, edges);
|
|
3030
4533
|
// Group by entity type for efficient fetching
|
|
3031
4534
|
const byEntityType = new Map();
|
|
3032
4535
|
for (const req of refRequests) {
|
|
@@ -3183,30 +4686,45 @@ const hydrateAggregateRefs = (input, edges, fields, aggregateName) => Effect.gen
|
|
|
3183
4686
|
const lookupKey = lookupKeys.get(req);
|
|
3184
4687
|
return lookupKey === undefined ? undefined : hydratedLookup.get(lookupKey);
|
|
3185
4688
|
});
|
|
3186
|
-
renameInputFields(result, edges);
|
|
3187
|
-
return result;
|
|
4689
|
+
return renameInputFields(result, edges);
|
|
3188
4690
|
});
|
|
3189
4691
|
/**
|
|
3190
|
-
*
|
|
3191
|
-
*
|
|
4692
|
+
* The name `create`'s input `data` holds a `many` edge's value under (#241): its `inputField`, where
|
|
4693
|
+
* `data` holds that name, else the field's. The one lookup of an edge's value in what a caller gave:
|
|
4694
|
+
* the ids hydration fetches, the rename before decoding ({@link renameInputFields}) and the value
|
|
4695
|
+
* `EDD-9159` judges ({@link inputFor}).
|
|
4696
|
+
*/
|
|
4697
|
+
const inputNameIn = (data, field, inputField) => inputField !== undefined && inputField !== field && inputField in data ? inputField : field;
|
|
4698
|
+
/**
|
|
4699
|
+
* `data` with each `many` edge's value under its field's name ({@link inputNameIn}), through
|
|
4700
|
+
* sub-aggregates, so the domain schema decodes it: a copy where one is renamed, `data` itself where
|
|
4701
|
+
* none is. The caller's own objects are never changed.
|
|
3192
4702
|
*/
|
|
3193
4703
|
const renameInputFields = (data, edges) => {
|
|
4704
|
+
let renamed;
|
|
3194
4705
|
for (const [edgeName, edge] of Object.entries(edges)) {
|
|
3195
4706
|
if (!("_tag" in edge))
|
|
3196
4707
|
continue;
|
|
3197
|
-
if (edge._tag === "ManyEdge"
|
|
3198
|
-
|
|
3199
|
-
|
|
3200
|
-
|
|
3201
|
-
}
|
|
4708
|
+
if (edge._tag === "ManyEdge") {
|
|
4709
|
+
const name = inputNameIn(data, edgeName, edge.inputField);
|
|
4710
|
+
if (name === edgeName)
|
|
4711
|
+
continue;
|
|
4712
|
+
renamed ??= { ...data };
|
|
4713
|
+
setOwn(renamed, edgeName, givenValue(data, name));
|
|
4714
|
+
delete renamed[name];
|
|
3202
4715
|
}
|
|
3203
4716
|
else if (edge._tag === "BoundSubAggregate") {
|
|
3204
|
-
const sub = data
|
|
4717
|
+
const sub = givenValue(data, edgeName);
|
|
3205
4718
|
if (sub != null && typeof sub === "object") {
|
|
3206
|
-
renameInputFields(sub, edge.aggregate.edges);
|
|
4719
|
+
const subRenamed = renameInputFields(sub, edge.aggregate.edges);
|
|
4720
|
+
if (subRenamed !== sub) {
|
|
4721
|
+
renamed ??= { ...data };
|
|
4722
|
+
setOwn(renamed, edgeName, subRenamed);
|
|
4723
|
+
}
|
|
3207
4724
|
}
|
|
3208
4725
|
}
|
|
3209
4726
|
}
|
|
4727
|
+
return renamed ?? data;
|
|
3210
4728
|
};
|
|
3211
4729
|
/** An id given for an edge's entity: the id as given, and as a value of its key composite. */
|
|
3212
4730
|
const refId = (entity, given) => ({ given, id: refIdValue(entity, given) });
|
|
@@ -3277,7 +4795,7 @@ at) => {
|
|
|
3277
4795
|
else if (edge._tag === "ManyEdge" && edge.entity) {
|
|
3278
4796
|
// ManyEdge with entity → walk array elements for ref IDs
|
|
3279
4797
|
const entity = edge.entity;
|
|
3280
|
-
const inputKey = edge.inputField
|
|
4798
|
+
const inputKey = inputNameIn(input, edgeName, edge.inputField);
|
|
3281
4799
|
const arr = given(input, inputKey);
|
|
3282
4800
|
if (Array.isArray(arr)) {
|
|
3283
4801
|
const entityFieldName = deriveEntityFieldName(entity);
|
|
@@ -3375,7 +4893,7 @@ const cloneInput = (value, seen = new WeakMap()) => {
|
|
|
3375
4893
|
const copy = {};
|
|
3376
4894
|
seen.set(value, copy);
|
|
3377
4895
|
for (const [key, entry] of Object.entries(value))
|
|
3378
|
-
copy
|
|
4896
|
+
setOwn(copy, key, cloneInput(entry, seen));
|
|
3379
4897
|
return copy;
|
|
3380
4898
|
};
|
|
3381
4899
|
/**
|
|
@@ -3395,7 +4913,7 @@ const replaceRefIds = (input, refRequests, lookup) => {
|
|
|
3395
4913
|
// Navigate to the target location in the result
|
|
3396
4914
|
let target = result;
|
|
3397
4915
|
for (const segment of segments) {
|
|
3398
|
-
const next = target
|
|
4916
|
+
const next = ownValue(target, segment);
|
|
3399
4917
|
if (next == null || typeof next !== "object")
|
|
3400
4918
|
break;
|
|
3401
4919
|
target = next;
|
|
@@ -3407,7 +4925,7 @@ const replaceRefIds = (input, refRequests, lookup) => {
|
|
|
3407
4925
|
else {
|
|
3408
4926
|
// Replace: remove ${field}Id, add ${field}: data
|
|
3409
4927
|
delete target[req.idFieldName];
|
|
3410
|
-
target
|
|
4928
|
+
setOwn(target, req.fieldName, data);
|
|
3411
4929
|
}
|
|
3412
4930
|
}
|
|
3413
4931
|
return result;
|
|
@@ -3416,6 +4934,183 @@ const replaceRefIds = (input, refRequests, lookup) => {
|
|
|
3416
4934
|
const storedAsGivenIn = (groups) => [
|
|
3417
4935
|
...new Set(groups.flatMap((group) => group.items.flatMap((item) => item.storedAsGiven.map((field) => `"${field}" of "${item.member}"`)))),
|
|
3418
4936
|
];
|
|
4937
|
+
/**
|
|
4938
|
+
* `create`'s input for the edge `child` of the caller's value `input`, as given (#241): under the
|
|
4939
|
+
* name the input holds it ({@link inputNameIn}: a `many` edge's `inputField`), read with `given`. A
|
|
4940
|
+
* `one` edge given an id (`${field}Id`) gives no value at its place: what's stored there is the
|
|
4941
|
+
* entity's.
|
|
4942
|
+
*/
|
|
4943
|
+
const inputFor = (input, child) => input !== null && typeof input === "object"
|
|
4944
|
+
? given(input, inputNameIn(input, child.fieldName, child.inputField))
|
|
4945
|
+
: undefined;
|
|
4946
|
+
/**
|
|
4947
|
+
* The context values a write copies onto every row beneath the root, from the root's value: in
|
|
4948
|
+
* their stored form (`stored`, what those rows hold) and as their keys read them (`key`). A domain
|
|
4949
|
+
* date is encoded before marshalling, which would store it as `{ M: {} }`.
|
|
4950
|
+
*/
|
|
4951
|
+
const contextValuesOf = (assembled, contextFields, encoders) => {
|
|
4952
|
+
const contextValues = { stored: {}, key: {} };
|
|
4953
|
+
for (const field of contextFields) {
|
|
4954
|
+
const value = givenValue(assembled, field);
|
|
4955
|
+
const stored = ownValue(encoders.stored, field);
|
|
4956
|
+
const key = ownValue(encoders.key, field);
|
|
4957
|
+
setOwn(contextValues.stored, field, stored && value != null ? stored(value) : value);
|
|
4958
|
+
setOwn(contextValues.key, field, key && value != null ? key(value) : value);
|
|
4959
|
+
}
|
|
4960
|
+
return contextValues;
|
|
4961
|
+
};
|
|
4962
|
+
/**
|
|
4963
|
+
* `value` with `changes` over its own properties, built as a read builds it (#241): a plain object
|
|
4964
|
+
* copied, a `Schema.Class` instance made by its class's constructor (as decoding makes one), so its
|
|
4965
|
+
* initializers and private fields are its own. `undefined` for any other object, or where the
|
|
4966
|
+
* constructor refuses the fields or the instance it makes holds other properties than `value`: the
|
|
4967
|
+
* caller keeps `value` as it was. Never a copy of an instance by its prototype, which a private
|
|
4968
|
+
* field or a constructor's invariant can't survive.
|
|
4969
|
+
*/
|
|
4970
|
+
const rebuiltWith = (value, changes) => {
|
|
4971
|
+
const proto = Object.getPrototypeOf(value);
|
|
4972
|
+
if (proto === null || proto === Object.prototype) {
|
|
4973
|
+
return Object.assign(Object.create(proto), value, changes);
|
|
4974
|
+
}
|
|
4975
|
+
const made = proto.constructor;
|
|
4976
|
+
if (typeof made !== "function" ||
|
|
4977
|
+
made.prototype !== proto ||
|
|
4978
|
+
!Schema.isSchema(made) ||
|
|
4979
|
+
!("fields" in made)) {
|
|
4980
|
+
return undefined;
|
|
4981
|
+
}
|
|
4982
|
+
const fields = {};
|
|
4983
|
+
for (const name of Object.keys(made.fields)) {
|
|
4984
|
+
if (Object.hasOwn(changes, name))
|
|
4985
|
+
fields[name] = changes[name];
|
|
4986
|
+
else if (Object.hasOwn(value, name))
|
|
4987
|
+
fields[name] = value[name];
|
|
4988
|
+
}
|
|
4989
|
+
let rebuilt;
|
|
4990
|
+
try {
|
|
4991
|
+
rebuilt = new made(fields);
|
|
4992
|
+
}
|
|
4993
|
+
catch {
|
|
4994
|
+
return undefined;
|
|
4995
|
+
}
|
|
4996
|
+
const own = Reflect.ownKeys(value);
|
|
4997
|
+
return Reflect.ownKeys(rebuilt).length === own.length &&
|
|
4998
|
+
own.every((key) => Object.hasOwn(rebuilt, key))
|
|
4999
|
+
? rebuilt
|
|
5000
|
+
: undefined;
|
|
5001
|
+
};
|
|
5002
|
+
/**
|
|
5003
|
+
* `update`'s result with each copy of a context attribute a member value holds set to what its row
|
|
5004
|
+
* now holds (#241). A write copies the root's context value (`stored`, {@link contextValuesOf})
|
|
5005
|
+
* onto every row beneath the root, over what the member value held there: up to 1.40.0 `update`
|
|
5006
|
+
* returned the copy the mutated state held. A row the write didn't send keeps what it held when
|
|
5007
|
+
* read (`rowAt`). Only a name the value holds as its own, and only one the write stores as a copy
|
|
5008
|
+
* on that row (`copiesOn`), is set, to the row's value as a read decodes it: through the member's
|
|
5009
|
+
* schema where it places the name, as it is where the member keeps what it's given. Where that read
|
|
5010
|
+
* holds nothing or can't be made (a discriminator, a place the schema can't place exactly, a `many`
|
|
5011
|
+
* edge with a custom `decompose` or `assemble`, a value whose row can't be told), the value keeps
|
|
5012
|
+
* what the state held. Nothing is added or taken away, and a value no copy changes is the one the
|
|
5013
|
+
* mutation returned; a changed one is built as a read builds it ({@link rebuiltWith}), and where it
|
|
5014
|
+
* can't be, the value is the mutation's, as on 1.40.0.
|
|
5015
|
+
*/
|
|
5016
|
+
const contextCopiesAsStored = (root, decoded, stored, rowAt, copiesOn, resolveRef) => {
|
|
5017
|
+
// A declared field's decode, as assembly reads it.
|
|
5018
|
+
const reads = new Map();
|
|
5019
|
+
const readField = (name, field) => {
|
|
5020
|
+
const byName = reads.get(field) ?? new Map();
|
|
5021
|
+
reads.set(field, byName);
|
|
5022
|
+
let read = byName.get(name);
|
|
5023
|
+
if (read === undefined) {
|
|
5024
|
+
read = Schema.decodeUnknownOption(readingInstances(substituteSchemaDeep(Schema.Struct({ [name]: field }), {
|
|
5025
|
+
tolerantTransforms: true,
|
|
5026
|
+
decodeOnly: true,
|
|
5027
|
+
resolveRef,
|
|
5028
|
+
absentReads: true,
|
|
5029
|
+
})));
|
|
5030
|
+
byName.set(name, read);
|
|
5031
|
+
}
|
|
5032
|
+
return read;
|
|
5033
|
+
};
|
|
5034
|
+
// What a read hands back of the context attribute `name` on the row `now` of `node`: `None` where
|
|
5035
|
+
// it can't be told or holds nothing.
|
|
5036
|
+
const readCopy = (node, now, name) => {
|
|
5037
|
+
const placed = node.placed;
|
|
5038
|
+
let row;
|
|
5039
|
+
try {
|
|
5040
|
+
if (readTakesOff(node.readRow, name))
|
|
5041
|
+
return Option.none();
|
|
5042
|
+
if ("row" in now)
|
|
5043
|
+
row = Object.hasOwn(now.row, name) ? now.row[name] : undefined;
|
|
5044
|
+
else
|
|
5045
|
+
row = stored[name] === undefined ? undefined : asRead(stored[name]);
|
|
5046
|
+
}
|
|
5047
|
+
catch {
|
|
5048
|
+
return Option.none();
|
|
5049
|
+
}
|
|
5050
|
+
if (row === undefined)
|
|
5051
|
+
return Option.none();
|
|
5052
|
+
if (placed === "any")
|
|
5053
|
+
return Option.some(row);
|
|
5054
|
+
if (placed === undefined || !Object.hasOwn(placed, name))
|
|
5055
|
+
return Option.none();
|
|
5056
|
+
return Option.flatMap(readField(name, placed[name])({ [name]: row }), (read) => Object.hasOwn(read, name) && read[name] !== undefined
|
|
5057
|
+
? Option.some(read[name])
|
|
5058
|
+
: Option.none());
|
|
5059
|
+
};
|
|
5060
|
+
const member = (node, value, path) => {
|
|
5061
|
+
if (value === null || typeof value !== "object" || Array.isArray(value))
|
|
5062
|
+
return value;
|
|
5063
|
+
const names = copiesOn(node).filter((name) => Object.hasOwn(value, name));
|
|
5064
|
+
if (names.length === 0)
|
|
5065
|
+
return value;
|
|
5066
|
+
const now = rowAt(path);
|
|
5067
|
+
if (now === undefined)
|
|
5068
|
+
return value;
|
|
5069
|
+
const changes = {};
|
|
5070
|
+
let changed = false;
|
|
5071
|
+
for (const name of names) {
|
|
5072
|
+
const read = readCopy(node, now, name);
|
|
5073
|
+
if (Option.isNone(read))
|
|
5074
|
+
continue;
|
|
5075
|
+
if (sameValue(read.value, value[name]))
|
|
5076
|
+
continue;
|
|
5077
|
+
changes[name] = read.value;
|
|
5078
|
+
changed = true;
|
|
5079
|
+
}
|
|
5080
|
+
return changed ? (rebuiltWith(value, changes) ?? value) : value;
|
|
5081
|
+
};
|
|
5082
|
+
const walk = (node, value, path) => {
|
|
5083
|
+
if (value === null || typeof value !== "object")
|
|
5084
|
+
return value;
|
|
5085
|
+
const changes = {};
|
|
5086
|
+
let changed = false;
|
|
5087
|
+
for (const child of node.children) {
|
|
5088
|
+
const name = child.fieldName;
|
|
5089
|
+
if (!Object.hasOwn(value, name))
|
|
5090
|
+
continue;
|
|
5091
|
+
const was = value[name];
|
|
5092
|
+
const at = [...path, name];
|
|
5093
|
+
let now;
|
|
5094
|
+
if (child.cardinality === "many") {
|
|
5095
|
+
if (child.decompose !== undefined || child.assemble !== undefined || !Array.isArray(was)) {
|
|
5096
|
+
continue;
|
|
5097
|
+
}
|
|
5098
|
+
const elements = was.map((element, index) => member(child, element, [...at, index]));
|
|
5099
|
+
now = elements.every((element, i) => element === was[i]) ? was : elements;
|
|
5100
|
+
}
|
|
5101
|
+
else {
|
|
5102
|
+
const held = member(child, was, at);
|
|
5103
|
+
now = child.children.length > 0 ? walk(child, held, at) : held;
|
|
5104
|
+
}
|
|
5105
|
+
if (now === was)
|
|
5106
|
+
continue;
|
|
5107
|
+
changes[name] = now;
|
|
5108
|
+
changed = true;
|
|
5109
|
+
}
|
|
5110
|
+
return changed ? (rebuiltWith(value, changes) ?? value) : value;
|
|
5111
|
+
};
|
|
5112
|
+
return walk(root, decoded, []);
|
|
5113
|
+
};
|
|
3419
5114
|
/**
|
|
3420
5115
|
* Decompose an assembled domain object into DynamoDB items grouped by
|
|
3421
5116
|
* sub-aggregate transaction boundaries.
|
|
@@ -3425,21 +5120,21 @@ const decomposeAggregate = (assembled, rootNode, contextFields, encoders, aggreg
|
|
|
3425
5120
|
* A write's own value (`create`'s input, the state `update`'s mutation returned), before it was
|
|
3426
5121
|
* decoded: a custom `decompose` is handed it read as on 1.39.0. Undefined for what was read.
|
|
3427
5122
|
*/
|
|
3428
|
-
written
|
|
5123
|
+
written,
|
|
5124
|
+
/**
|
|
5125
|
+
* `"keep"`: two items composing one sort key aren't refused here. `update` judges that itself
|
|
5126
|
+
* ({@link refuseSharedSortKeys}) over the groups it writes, since rows stored under two keys can
|
|
5127
|
+
* compose one now (#241).
|
|
5128
|
+
*/
|
|
5129
|
+
sharedKeys,
|
|
5130
|
+
/** `create`'s input as the caller gave it, for each row's {@link DecomposedItem.input}. */
|
|
5131
|
+
input) => Effect.gen(function* () {
|
|
3429
5132
|
const items = [];
|
|
3430
5133
|
const encodeWith = (set, field, value, asGiven) => {
|
|
3431
|
-
const encode = set
|
|
5134
|
+
const encode = ownValue(set, field);
|
|
3432
5135
|
return encode && value != null ? encode(value, asGiven) : value;
|
|
3433
5136
|
};
|
|
3434
|
-
|
|
3435
|
-
// Domain Date/DateTime objects must be encoded before toAttributeMap() marshalling,
|
|
3436
|
-
// otherwise Date objects become { M: {} } (no enumerable properties).
|
|
3437
|
-
const contextValues = { stored: {}, key: {} };
|
|
3438
|
-
for (const field of contextFields) {
|
|
3439
|
-
const value = assembled[field];
|
|
3440
|
-
contextValues.stored[field] = encodeWith(encoders.stored, field, value);
|
|
3441
|
-
contextValues.key[field] = encodeWith(encoders.key, field, value);
|
|
3442
|
-
}
|
|
5137
|
+
const contextValues = contextValuesOf(assembled, contextFields, encoders);
|
|
3443
5138
|
// Root item: fields not claimed by edges
|
|
3444
5139
|
const edgeFieldNames = new Set(rootNode.children.map((c) => c.fieldName).filter(Boolean));
|
|
3445
5140
|
const rootAttrs = {};
|
|
@@ -3449,12 +5144,16 @@ written) => Effect.gen(function* () {
|
|
|
3449
5144
|
for (const [key, value] of Object.entries(assembled)) {
|
|
3450
5145
|
if (edgeFieldNames.has(key))
|
|
3451
5146
|
continue;
|
|
3452
|
-
rootAttrs
|
|
3453
|
-
rootKeyAttrs
|
|
5147
|
+
setOwn(rootAttrs, key, encodeWith(encoders.stored, key, value, () => rootAsGiven.push(key)));
|
|
5148
|
+
setOwn(rootKeyAttrs, key, encodeWith(encoders.key, key, value));
|
|
3454
5149
|
}
|
|
3455
5150
|
items.push({
|
|
3456
5151
|
entityType: rootNode.entityType,
|
|
3457
5152
|
attributes: rootAttrs,
|
|
5153
|
+
own: rootAttrs,
|
|
5154
|
+
...(input !== undefined && { input }),
|
|
5155
|
+
value: assembled,
|
|
5156
|
+
path: [],
|
|
3458
5157
|
keyAttributes: rootKeyAttrs,
|
|
3459
5158
|
transactionGroup: "root",
|
|
3460
5159
|
skComposites: [],
|
|
@@ -3466,42 +5165,66 @@ written) => Effect.gen(function* () {
|
|
|
3466
5165
|
});
|
|
3467
5166
|
// Decompose each edge
|
|
3468
5167
|
for (const child of rootNode.children) {
|
|
3469
|
-
const fieldValue = assembled
|
|
3470
|
-
yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], other: () => [] }, aggregateName, schema, writtenField(written, child.fieldName));
|
|
5168
|
+
const fieldValue = givenValue(assembled, child.fieldName);
|
|
5169
|
+
yield* decomposeNode(items, child, fieldValue, contextValues, "root", { current: [], other: () => [] }, aggregateName, schema, writtenField(written, child.fieldName), inputFor(input, child), [child.fieldName]);
|
|
5170
|
+
}
|
|
5171
|
+
if (sharedKeys !== "keep")
|
|
5172
|
+
yield* refuseSharedSortKeys(items, schema, aggregateName);
|
|
5173
|
+
// Group by transaction
|
|
5174
|
+
const groups = new Map();
|
|
5175
|
+
for (const item of items) {
|
|
5176
|
+
const list = groups.get(item.transactionGroup) ?? [];
|
|
5177
|
+
list.push(item);
|
|
5178
|
+
groups.set(item.transactionGroup, list);
|
|
3471
5179
|
}
|
|
3472
|
-
|
|
3473
|
-
|
|
3474
|
-
|
|
3475
|
-
|
|
3476
|
-
|
|
3477
|
-
|
|
5180
|
+
return [...groups.entries()].map(([name, groupItems]) => ({ name, items: groupItems }));
|
|
5181
|
+
});
|
|
5182
|
+
/**
|
|
5183
|
+
* Two items composing the same sort key are two writes to one row. DynamoDB rejects the whole
|
|
5184
|
+
* TransactWriteItems with a ValidationException ("Transaction request cannot include multiple
|
|
5185
|
+
* operations on one item") that names no edge, and carries no CancellationReasons — so
|
|
5186
|
+
* `writeTransactionGroups` cannot decode it and the collision reaches the caller as an opaque
|
|
5187
|
+
* client error. Caught where the edge that produced it is still known (#103).
|
|
5188
|
+
*
|
|
5189
|
+
* `written`: the items a write sends; a pair neither of which it sends is left (`update` over rows
|
|
5190
|
+
* stored under two keys that compose one now, #241).
|
|
5191
|
+
*/
|
|
5192
|
+
const refuseSharedSortKeys = (items, schema, aggregateName, written,
|
|
5193
|
+
/** Keys holding two rows of one element ({@link doubledKeys}), each to its row under 1.40.0's text. */
|
|
5194
|
+
doubled) => {
|
|
3478
5195
|
const seen = new Map();
|
|
3479
5196
|
for (const item of items) {
|
|
3480
5197
|
const sk = composeKey(schema, item.entityType, [...item.skComposites]);
|
|
3481
|
-
const prior = seen.get(sk);
|
|
5198
|
+
const prior = (seen.get(sk) ?? []).find((other) => written === undefined || written(other) || written(item));
|
|
5199
|
+
const other = doubled?.get(sk);
|
|
5200
|
+
if (prior !== undefined && other !== undefined) {
|
|
5201
|
+
return Effect.fail(new AggregateDecompositionError({
|
|
5202
|
+
aggregate: aggregateName,
|
|
5203
|
+
member: item.member,
|
|
5204
|
+
reason: `"${item.member}" holds two values of the element keyed "${sk}": the row stored there ` +
|
|
5205
|
+
`and the row under "${other}", the key text 1.40.0 composed, hold different values, ` +
|
|
5206
|
+
"as a 1.40.0 writer leaves a group this release keyed, so one would overwrite the " +
|
|
5207
|
+
`other. Update the aggregate stating the elements "${item.member}" should hold, one ` +
|
|
5208
|
+
"for each key: that write stores them under this release's key text and deletes the " +
|
|
5209
|
+
"rows under 1.40.0's.",
|
|
5210
|
+
}));
|
|
5211
|
+
}
|
|
3482
5212
|
if (prior !== undefined) {
|
|
3483
5213
|
const hint = prior.member === item.member
|
|
3484
5214
|
? ` Give the "${item.member}" edge a declared sort key naming attributes that differ` +
|
|
3485
5215
|
` between its elements: ${item.member}: Aggregate.many({ …, sk: { composite: [...] } }).`
|
|
3486
5216
|
: "";
|
|
3487
|
-
return
|
|
5217
|
+
return Effect.fail(new AggregateDecompositionError({
|
|
3488
5218
|
aggregate: aggregateName,
|
|
3489
5219
|
member: item.member,
|
|
3490
5220
|
reason: `"${prior.member}" and "${item.member}" both compose the sort key "${sk}", ` +
|
|
3491
5221
|
`so one would overwrite the other.${hint}`,
|
|
3492
|
-
});
|
|
5222
|
+
}));
|
|
3493
5223
|
}
|
|
3494
|
-
seen.set(sk, item);
|
|
3495
|
-
}
|
|
3496
|
-
// Group by transaction
|
|
3497
|
-
const groups = new Map();
|
|
3498
|
-
for (const item of items) {
|
|
3499
|
-
const list = groups.get(item.transactionGroup) ?? [];
|
|
3500
|
-
list.push(item);
|
|
3501
|
-
groups.set(item.transactionGroup, list);
|
|
5224
|
+
seen.set(sk, [...(seen.get(sk) ?? []), item]);
|
|
3502
5225
|
}
|
|
3503
|
-
return
|
|
3504
|
-
}
|
|
5226
|
+
return Effect.void;
|
|
5227
|
+
};
|
|
3505
5228
|
/**
|
|
3506
5229
|
* Merge context values into decomposed item attributes.
|
|
3507
5230
|
* Context values always override entity-specific fields — the aggregate root
|
|
@@ -3509,7 +5232,7 @@ written) => Effect.gen(function* () {
|
|
|
3509
5232
|
*/
|
|
3510
5233
|
const mergeContextValues = (attrs, contextValues) => {
|
|
3511
5234
|
for (const [key, value] of Object.entries(contextValues)) {
|
|
3512
|
-
attrs
|
|
5235
|
+
setOwn(attrs, key, value);
|
|
3513
5236
|
}
|
|
3514
5237
|
};
|
|
3515
5238
|
/**
|
|
@@ -3673,6 +5396,13 @@ const entityWriters = (entity) => {
|
|
|
3673
5396
|
if (tombstone !== undefined) {
|
|
3674
5397
|
anyText(["__edd_removed__", KEY_TEXT], [tombstone], table, (field) => `its projection tombstones' "${field}"`);
|
|
3675
5398
|
}
|
|
5399
|
+
// The row token (#237), on the rows and tombstones of a read model several projections write,
|
|
5400
|
+
// where its name is free (`rowTokenInUse`). The table's TTL attribute isn't known here: a
|
|
5401
|
+
// read model whose TTL attribute alone is named `__edd_rt__` is counted as writing it, which
|
|
5402
|
+
// only adds a writer of an attribute no key is made of.
|
|
5403
|
+
if (rowTokened(e) && rowTokenInUse(e, undefined)) {
|
|
5404
|
+
anyText([ROW_TOKEN], tombstone === undefined ? [own] : [own, tombstone], table, (field) => `its projection rows' "${field}"`);
|
|
5405
|
+
}
|
|
3676
5406
|
for (const constraint of Object.keys(e.unique ?? {})) {
|
|
3677
5407
|
const sentinel = composeUniqueKey(schema, type, constraint, [], {
|
|
3678
5408
|
casing: index.casing,
|
|
@@ -3721,6 +5451,8 @@ const entityWriters = (entity) => {
|
|
|
3721
5451
|
anyText([
|
|
3722
5452
|
...(outbox.sk === undefined ? [] : [outbox.sk]),
|
|
3723
5453
|
OUTBOX_ROW_SK,
|
|
5454
|
+
// The mark, where its items carry one: where its name is a key's, that is listed.
|
|
5455
|
+
...(outboxMarkInUse(e) ? [OUTBOX_READ_MODEL] : []),
|
|
3724
5456
|
"effect",
|
|
3725
5457
|
"source",
|
|
3726
5458
|
"streamId",
|
|
@@ -3822,11 +5554,45 @@ const otherSortKey = (schema, item, sk) => {
|
|
|
3822
5554
|
return sk;
|
|
3823
5555
|
}
|
|
3824
5556
|
};
|
|
5557
|
+
/** A node's own static discriminator values, those its sort key composes: a function is computed. */
|
|
5558
|
+
const ownDiscriminatorEntries = (node) => node.ownDiscriminator === undefined
|
|
5559
|
+
? []
|
|
5560
|
+
: Object.entries(node.ownDiscriminator).filter(([, v]) => typeof v !== "function");
|
|
5561
|
+
/** A decomposed row's sort key; `undefined` for one its values can't compose. */
|
|
5562
|
+
const sortKeyOf = (schema, item) => {
|
|
5563
|
+
try {
|
|
5564
|
+
return composeKey(schema, item.entityType, [...item.skComposites]);
|
|
5565
|
+
}
|
|
5566
|
+
catch {
|
|
5567
|
+
return undefined;
|
|
5568
|
+
}
|
|
5569
|
+
};
|
|
5570
|
+
/**
|
|
5571
|
+
* A decomposed row's sort key under the other composition of an `entity:` edge's sort key
|
|
5572
|
+
* ({@link DecomposedItem.skCompositesOtherComposition}); `undefined` when it has none.
|
|
5573
|
+
*/
|
|
5574
|
+
const otherCompositionSortKey = (schema, item) => {
|
|
5575
|
+
try {
|
|
5576
|
+
const composites = item.skCompositesOtherComposition?.();
|
|
5577
|
+
return composites === undefined
|
|
5578
|
+
? undefined
|
|
5579
|
+
: composeKey(schema, item.entityType, [...composites]);
|
|
5580
|
+
}
|
|
5581
|
+
catch {
|
|
5582
|
+
return undefined;
|
|
5583
|
+
}
|
|
5584
|
+
};
|
|
5585
|
+
/**
|
|
5586
|
+
* The values a node's row is decomposed from: what `value` gives for each field the node declares,
|
|
5587
|
+
* however it gives it (its own property, a getter, its prototype), and its other own properties. A
|
|
5588
|
+
* spread copies the own ones alone. Not an object: what a spread of it gives.
|
|
5589
|
+
*/
|
|
5590
|
+
const rowValues = (node, value) => value !== null && typeof value === "object"
|
|
5591
|
+
? declaredCopy(value, Object.keys(node.ownFields ?? {}))
|
|
5592
|
+
: { ...value };
|
|
3825
5593
|
/** A node's own static discriminator values as {@link DiscriminatorValues}. */
|
|
3826
5594
|
const ownDiscriminatorValues = (node, schema) => {
|
|
3827
|
-
const entries = node
|
|
3828
|
-
? []
|
|
3829
|
-
: Object.entries(node.ownDiscriminator).filter(([, v]) => typeof v !== "function");
|
|
5595
|
+
const entries = ownDiscriminatorEntries(node);
|
|
3830
5596
|
return {
|
|
3831
5597
|
current: entries.flatMap(([k, v]) => [k, KeyComposer.keyValueText(schema, v, schema.casing)]),
|
|
3832
5598
|
other: () => entries.flatMap(([k, v]) => [k, otherKeyText(schema, v)]),
|
|
@@ -3841,7 +5607,11 @@ const decomposeNode = (items, node, value, contextValues, parentGroup,
|
|
|
3841
5607
|
/** The parent's discriminator values, in today's text and in 1.36's (#171). */
|
|
3842
5608
|
parentDiscriminators, aggregateName, schema,
|
|
3843
5609
|
/** The caller's own value here, on a write (see {@link Written}). */
|
|
3844
|
-
written
|
|
5610
|
+
written,
|
|
5611
|
+
/** `create`'s input here, as the caller gave it ({@link DecomposedItem.input}). */
|
|
5612
|
+
input,
|
|
5613
|
+
/** Where `value` is in the value decomposed ({@link DecomposedItem.path}). */
|
|
5614
|
+
path) => Effect.gen(function* () {
|
|
3845
5615
|
// Optional edges may have null/undefined values — skip decomposition
|
|
3846
5616
|
if (value == null)
|
|
3847
5617
|
return;
|
|
@@ -3863,24 +5633,29 @@ written) => Effect.gen(function* () {
|
|
|
3863
5633
|
// Sub-aggregate root item: fields not claimed by child edges
|
|
3864
5634
|
const childEdgeNames = new Set(node.children.map((c) => c.fieldName).filter(Boolean));
|
|
3865
5635
|
const subRootAttrs = {};
|
|
3866
|
-
for (const [key, val] of Object.entries(subValue)) {
|
|
5636
|
+
for (const [key, val] of Object.entries(rowValues(node, subValue))) {
|
|
3867
5637
|
if (childEdgeNames.has(key))
|
|
3868
5638
|
continue;
|
|
3869
|
-
subRootAttrs
|
|
5639
|
+
setOwn(subRootAttrs, key, val);
|
|
3870
5640
|
}
|
|
3871
5641
|
// Serialize this node's own date fields to their wire primitive (#72).
|
|
3872
5642
|
const storedAsGiven = applyNodeAttrEncoders(subRootAttrs, node.attrEncoders);
|
|
5643
|
+
const subRootOwn = { ...subRootAttrs };
|
|
3873
5644
|
// Inject context and discriminator
|
|
3874
5645
|
mergeContextValues(subRootAttrs, contextValues.stored);
|
|
3875
5646
|
if (node.discriminator) {
|
|
3876
5647
|
for (const [k, v] of Object.entries(node.discriminator)) {
|
|
3877
5648
|
if (typeof v !== "function")
|
|
3878
|
-
subRootAttrs
|
|
5649
|
+
setOwn(subRootAttrs, k, v);
|
|
3879
5650
|
}
|
|
3880
5651
|
}
|
|
3881
5652
|
items.push({
|
|
3882
5653
|
entityType: node.entityType,
|
|
3883
5654
|
attributes: subRootAttrs,
|
|
5655
|
+
own: subRootOwn,
|
|
5656
|
+
...(input !== undefined && { input }),
|
|
5657
|
+
value: subValue,
|
|
5658
|
+
path,
|
|
3884
5659
|
transactionGroup: txGroup,
|
|
3885
5660
|
skComposites: discValues.current,
|
|
3886
5661
|
skCompositesOther: discValues.other,
|
|
@@ -3891,30 +5666,35 @@ written) => Effect.gen(function* () {
|
|
|
3891
5666
|
});
|
|
3892
5667
|
// Decompose children within this sub-aggregate
|
|
3893
5668
|
for (const child of node.children) {
|
|
3894
|
-
const childValue = subValue
|
|
3895
|
-
yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, schema, writtenField(written, child.fieldName));
|
|
5669
|
+
const childValue = givenValue(subValue, child.fieldName);
|
|
5670
|
+
yield* decomposeNode(items, child, childValue, contextValues, txGroup, discValues, aggregateName, schema, writtenField(written, child.fieldName), inputFor(input, child), [...path, child.fieldName]);
|
|
3896
5671
|
}
|
|
3897
5672
|
}
|
|
3898
5673
|
else if (node.cardinality === "one") {
|
|
3899
5674
|
// Simple one-to-one edge (no children)
|
|
3900
|
-
const attrs =
|
|
5675
|
+
const attrs = rowValues(node, value);
|
|
3901
5676
|
// Serialize this edge entity's own date fields to their wire primitive (#72).
|
|
3902
5677
|
const storedAsGiven = applyNodeAttrEncoders(attrs, node.attrEncoders);
|
|
5678
|
+
const own = { ...attrs };
|
|
3903
5679
|
mergeContextValues(attrs, contextValues.stored);
|
|
3904
5680
|
if (node.discriminator) {
|
|
3905
5681
|
for (const [k, v] of Object.entries(node.discriminator)) {
|
|
3906
5682
|
if (typeof v !== "function")
|
|
3907
|
-
attrs
|
|
5683
|
+
setOwn(attrs, k, v);
|
|
3908
5684
|
}
|
|
3909
5685
|
}
|
|
3910
5686
|
// Own discriminator values as name#value pairs for SK composition
|
|
3911
|
-
const
|
|
5687
|
+
const ownDiscriminators = ownDiscriminatorValues(node, schema);
|
|
3912
5688
|
items.push({
|
|
3913
5689
|
entityType: node.entityType,
|
|
3914
5690
|
attributes: attrs,
|
|
5691
|
+
own,
|
|
5692
|
+
...(input !== undefined && { input }),
|
|
5693
|
+
value,
|
|
5694
|
+
path,
|
|
3915
5695
|
transactionGroup: parentGroup,
|
|
3916
|
-
skComposites: [...parentDiscriminators.current, ...
|
|
3917
|
-
skCompositesOther: () => [...parentDiscriminators.other(), ...
|
|
5696
|
+
skComposites: [...parentDiscriminators.current, ...ownDiscriminators.current],
|
|
5697
|
+
skCompositesOther: () => [...parentDiscriminators.other(), ...ownDiscriminators.other()],
|
|
3918
5698
|
member: node.fieldName ?? node.entityType,
|
|
3919
5699
|
rowStamps: node.rowStamps,
|
|
3920
5700
|
storedAsGiven,
|
|
@@ -3936,37 +5716,76 @@ written) => Effect.gen(function* () {
|
|
|
3936
5716
|
if (node.discriminator) {
|
|
3937
5717
|
for (const [k, v] of Object.entries(node.discriminator)) {
|
|
3938
5718
|
if (typeof v !== "function")
|
|
3939
|
-
attrs
|
|
5719
|
+
setOwn(attrs, k, v);
|
|
3940
5720
|
}
|
|
3941
5721
|
}
|
|
3942
5722
|
return attrs;
|
|
3943
5723
|
};
|
|
3944
|
-
|
|
5724
|
+
// An element's own value as given: the caller's element at its place, where no custom
|
|
5725
|
+
// `decompose` maps the value to rows.
|
|
5726
|
+
const givenElements = node.decompose === undefined && Array.isArray(input) ? input : [];
|
|
5727
|
+
for (const [index, elem] of arrayItems.entries()) {
|
|
5728
|
+
const elementInput = givenElements[index];
|
|
3945
5729
|
// The element's attributes in their STORED form — every nested date,
|
|
3946
|
-
// transformed scalar and hydrated ref encoded (#72, #133)
|
|
3947
|
-
|
|
3948
|
-
const storedAsGiven =
|
|
5730
|
+
// transformed scalar and hydrated ref encoded (#72, #133), and an element
|
|
5731
|
+
// whose schema shows no fields encoded as a whole (#241).
|
|
5732
|
+
const { attrs, storedAsGiven } = storedElement(elem, node);
|
|
5733
|
+
const own = { ...attrs };
|
|
3949
5734
|
withContext(attrs, contextValues.stored);
|
|
3950
5735
|
// The sort key is read from the element as the pre-#133 encoders left
|
|
3951
5736
|
// it, NOT from `attrs`: encoding a ref's nested `NumberFromString` turns
|
|
3952
5737
|
// a padded `0000000000000005` key segment into `5`, so composing from
|
|
3953
5738
|
// the stored form would re-spell (and orphan) existing rows.
|
|
3954
|
-
const keyAttrs =
|
|
5739
|
+
const keyAttrs = rowValues(node, elem);
|
|
3955
5740
|
applyNodeAttrEncoders(keyAttrs, node.keyAttrEncoders);
|
|
3956
5741
|
withContext(keyAttrs, contextValues.key);
|
|
3957
5742
|
const values = yield* manyEdgeSkComposites(node, keyAttrs, aggregateName);
|
|
5743
|
+
// The values the other composition reads (#241): what 1.40.0 composed under either
|
|
5744
|
+
// setting, or, under `false`, what `escapeKeys: true` composes. Read only by `update` and
|
|
5745
|
+
// `rekey`, and a value it can't place gives none.
|
|
5746
|
+
const otherEncoders = node.otherCompositionEncoders;
|
|
5747
|
+
const otherValues = () => {
|
|
5748
|
+
if (otherEncoders === undefined)
|
|
5749
|
+
return undefined;
|
|
5750
|
+
const from = { ...elem };
|
|
5751
|
+
applyNodeAttrEncoders(from, otherEncoders);
|
|
5752
|
+
withContext(from, contextValues.key);
|
|
5753
|
+
return declaredSkComposites(node, from);
|
|
5754
|
+
};
|
|
5755
|
+
const escaped = schema.escapeKeys === true;
|
|
3958
5756
|
items.push({
|
|
3959
5757
|
entityType: node.entityType,
|
|
3960
5758
|
attributes: attrs,
|
|
5759
|
+
own,
|
|
5760
|
+
...(elementInput !== undefined && { input: elementInput }),
|
|
5761
|
+
...(node.decompose === undefined && { value: elem, path: [...path, index] }),
|
|
3961
5762
|
transactionGroup: parentGroup,
|
|
3962
5763
|
skComposites: [
|
|
3963
5764
|
...parentDiscriminators.current,
|
|
3964
5765
|
...values.map((value) => KeyComposer.keyValueText(schema, value, schema.casing)),
|
|
3965
5766
|
],
|
|
5767
|
+
// Under `escapeKeys: true` an `entity:` edge's rows in the other setting's text were
|
|
5768
|
+
// composed by 1.40.0's composition: every release composed it under `false`.
|
|
3966
5769
|
skCompositesOther: () => [
|
|
3967
5770
|
...parentDiscriminators.other(),
|
|
3968
|
-
...values.map((value) => otherKeyText(schema, value)),
|
|
5771
|
+
...((escaped ? otherValues() : undefined) ?? values).map((value) => otherKeyText(schema, value)),
|
|
3969
5772
|
],
|
|
5773
|
+
...(otherEncoders !== undefined && {
|
|
5774
|
+
skCompositesOtherComposition: () => {
|
|
5775
|
+
const other = otherValues();
|
|
5776
|
+
if (other === undefined)
|
|
5777
|
+
return undefined;
|
|
5778
|
+
return escaped
|
|
5779
|
+
? [
|
|
5780
|
+
...parentDiscriminators.current,
|
|
5781
|
+
...other.map((value) => KeyComposer.keyValueText(schema, value, schema.casing)),
|
|
5782
|
+
]
|
|
5783
|
+
: [
|
|
5784
|
+
...parentDiscriminators.other(),
|
|
5785
|
+
...other.map((value) => otherKeyText(schema, value)),
|
|
5786
|
+
];
|
|
5787
|
+
},
|
|
5788
|
+
}),
|
|
3970
5789
|
otherKindSortKey: (targets) => {
|
|
3971
5790
|
const slots = values.map((_, i) => String(i));
|
|
3972
5791
|
const settings = [
|
|
@@ -3979,7 +5798,7 @@ written) => Effect.gen(function* () {
|
|
|
3979
5798
|
for (const [parents, text] of settings) {
|
|
3980
5799
|
const sortKey = (record) => composeKey(schema, node.entityType, [
|
|
3981
5800
|
...parents(),
|
|
3982
|
-
...slots.map((slot) => text(record
|
|
5801
|
+
...slots.map((slot) => text(ownValue(record, slot))),
|
|
3983
5802
|
]);
|
|
3984
5803
|
const reading = kindReadingOf({ ...values }, slots, () => undefined, ({ record }) => sortKey(record), targets);
|
|
3985
5804
|
if (reading !== undefined && reading.asOther.size > 0)
|
|
@@ -3991,7 +5810,7 @@ written) => Effect.gen(function* () {
|
|
|
3991
5810
|
try {
|
|
3992
5811
|
let from = keyAttrs;
|
|
3993
5812
|
if (taker !== node) {
|
|
3994
|
-
from =
|
|
5813
|
+
from = rowValues(node, elem);
|
|
3995
5814
|
applyNodeAttrEncoders(from, taker.keyAttrEncoders);
|
|
3996
5815
|
mergeContextValues(from, contextValues.key);
|
|
3997
5816
|
}
|
|
@@ -4023,12 +5842,12 @@ written) => Effect.gen(function* () {
|
|
|
4023
5842
|
*/
|
|
4024
5843
|
const readCompositePath = (attrs, path) => {
|
|
4025
5844
|
if (!path.includes("."))
|
|
4026
|
-
return attrs
|
|
5845
|
+
return givenValue(attrs, path);
|
|
4027
5846
|
let current = attrs;
|
|
4028
5847
|
for (const segment of path.split(".")) {
|
|
4029
5848
|
if (current == null || typeof current !== "object")
|
|
4030
5849
|
return undefined;
|
|
4031
|
-
current = current
|
|
5850
|
+
current = givenValue(current, segment);
|
|
4032
5851
|
}
|
|
4033
5852
|
return current;
|
|
4034
5853
|
};
|
|
@@ -4097,6 +5916,19 @@ const manyEdgeSkComposites = (node, attrs, aggregateName) => Effect.gen(function
|
|
|
4097
5916
|
// A number its field stores as a string holds its `NaN` in key form, as the root's key does.
|
|
4098
5917
|
return values.map((value, i) => storedNaNKeyForm(fieldAtPath(node.ownFields, declared[i]), value));
|
|
4099
5918
|
});
|
|
5919
|
+
/**
|
|
5920
|
+
* A declared sort key's composite values off `attrs`, as {@link manyEdgeSkComposites} reads them;
|
|
5921
|
+
* `undefined` for one it would refuse (missing, null or not a scalar).
|
|
5922
|
+
*/
|
|
5923
|
+
const declaredSkComposites = (node, attrs) => {
|
|
5924
|
+
const declared = node.skComposite;
|
|
5925
|
+
if (declared === undefined)
|
|
5926
|
+
return undefined;
|
|
5927
|
+
const values = declared.map((path) => readCompositePath(attrs, path));
|
|
5928
|
+
if (values.some((value) => value == null || !isScalarComposite(value)))
|
|
5929
|
+
return undefined;
|
|
5930
|
+
return values.map((value, i) => storedNaNKeyForm(fieldAtPath(node.ownFields, declared[i]), value));
|
|
5931
|
+
};
|
|
4100
5932
|
/**
|
|
4101
5933
|
* Extract ref identifier values from an item's attributes for use as SK composites.
|
|
4102
5934
|
* Walks fields looking for embedded objects that have an identifier-annotated field.
|
|
@@ -4130,7 +5962,7 @@ const extractRefIdentifiers = (attrs, refIdentifierField) => {
|
|
|
4130
5962
|
// entity. Without this an `Array(Player)` edge composes NO composites and every
|
|
4131
5963
|
// element collapses onto one row (#103).
|
|
4132
5964
|
if (ids.length === 0) {
|
|
4133
|
-
const declared = refIdentifierField !== undefined ? attrs
|
|
5965
|
+
const declared = refIdentifierField !== undefined ? ownValue(attrs, refIdentifierField) : undefined;
|
|
4134
5966
|
if (typeof declared === "string")
|
|
4135
5967
|
ids.push(declared);
|
|
4136
5968
|
else if (typeof attrs.id === "string")
|
|
@@ -4187,8 +6019,10 @@ const fillStamps = (node, value, now, which) => {
|
|
|
4187
6019
|
const added = {};
|
|
4188
6020
|
const row = node.rowStamps;
|
|
4189
6021
|
const fill = (name, declared, required, replaces, encoding) => {
|
|
4190
|
-
if (name === null ||
|
|
6022
|
+
if (name === null ||
|
|
6023
|
+
(givenValue(given, name) !== undefined && (which === "required" || !replaces))) {
|
|
4191
6024
|
return;
|
|
6025
|
+
}
|
|
4192
6026
|
if (which === "declared" ? declared : required) {
|
|
4193
6027
|
added[name] = generateTimestampPrimitive(now, encoding);
|
|
4194
6028
|
}
|
|
@@ -4198,13 +6032,14 @@ const fillStamps = (node, value, now, which) => {
|
|
|
4198
6032
|
fill(row.updatedAt, row.updatedDeclared, row.updatedRequired, row.updatedReplaces, row.updatedEncoding);
|
|
4199
6033
|
}
|
|
4200
6034
|
for (const child of node.children) {
|
|
4201
|
-
const current = given
|
|
6035
|
+
const current = givenValue(given, child.fieldName);
|
|
4202
6036
|
const next = child.cardinality === "many"
|
|
4203
6037
|
? fillRows(child, current, (row) => fillStamps(child, row, now, which))
|
|
4204
6038
|
: fillStamps(child, current, now, which);
|
|
4205
6039
|
if (next !== current)
|
|
4206
|
-
added
|
|
6040
|
+
setOwn(added, child.fieldName, next);
|
|
4207
6041
|
}
|
|
6042
|
+
// Copied as 1.40.0 copied it: a spread, and what's added.
|
|
4208
6043
|
return Object.keys(added).length === 0 ? value : { ...given, ...added };
|
|
4209
6044
|
};
|
|
4210
6045
|
/**
|
|
@@ -4213,21 +6048,76 @@ const fillStamps = (node, value, now, which) => {
|
|
|
4213
6048
|
* Only for a key the aggregate can't do without: a list's keys are sparse (`buildDynamoItems`).
|
|
4214
6049
|
*/
|
|
4215
6050
|
const keyCompositesOrThrow = (aggregateName, key, schema, composite, record) => {
|
|
4216
|
-
const absent = composite.filter((attr) => record
|
|
6051
|
+
const absent = composite.filter((attr) => givenValue(record, attr) == null);
|
|
4217
6052
|
if (absent.length > 0) {
|
|
4218
6053
|
const names = absent.map((attr) => `"${attr}"`).join(", ");
|
|
4219
6054
|
throw new KeyValueError({
|
|
4220
6055
|
value: undefined,
|
|
4221
6056
|
reason: `no value for ${names}`,
|
|
4222
|
-
message: `[EDD-9123] Aggregate "${aggregateName}": ${key} is composed from ${names}, which has
|
|
4223
|
-
`value here. An aggregate can't be read without this key, so nothing was sent. Supply
|
|
4224
|
-
`or compose the key from a field that always has one.`,
|
|
6057
|
+
message: `[EDD-9123] Aggregate "${aggregateName}": ${key.into} is composed from ${names}, which has ` +
|
|
6058
|
+
`no value here. An aggregate can't be read without this key, so nothing was sent. Supply ` +
|
|
6059
|
+
`it, or compose the key from a field that always has one.`,
|
|
4225
6060
|
});
|
|
4226
6061
|
}
|
|
4227
|
-
return KeyComposer.extractKeyComposites(schema,
|
|
6062
|
+
return KeyComposer.extractKeyComposites(schema, key, composite, record);
|
|
6063
|
+
};
|
|
6064
|
+
/**
|
|
6065
|
+
* The keys an aggregate composes from its root's values, each the definition its composites are
|
|
6066
|
+
* composed for (`DynamoSchema.ObjectKeySite.key`), so a write's own schema names it (#242).
|
|
6067
|
+
*/
|
|
6068
|
+
const AGGREGATE_KEY = {
|
|
6069
|
+
partition: { into: "its partition key" },
|
|
6070
|
+
collectionSort: { into: "its collection sort key" },
|
|
6071
|
+
listPartition: { into: "its list partition key" },
|
|
6072
|
+
listSort: { into: "its list sort key" },
|
|
4228
6073
|
};
|
|
6074
|
+
/** The sort key a row's static discriminator is composed into: the row's, by its member. */
|
|
6075
|
+
class DiscriminatorKey {
|
|
6076
|
+
member;
|
|
6077
|
+
constructor(member) {
|
|
6078
|
+
this.member = member;
|
|
6079
|
+
}
|
|
6080
|
+
}
|
|
4229
6081
|
const EMPTY_CREATED = new Map();
|
|
4230
6082
|
const hasKeyValue = (value) => value !== undefined && value !== null;
|
|
6083
|
+
/**
|
|
6084
|
+
* A stamp in the date form `to`: as it is when it's in that form already, else the instant it holds
|
|
6085
|
+
* in the form `from`, written in `to`'s. A row written before #241 holds a date under
|
|
6086
|
+
* `Schema.optional` as ISO text where its field declares another encoding; that is the only pair of
|
|
6087
|
+
* forms that differ, and with `to` and `from` the same this is the value as it is. Anything neither
|
|
6088
|
+
* form takes is as it is.
|
|
6089
|
+
*/
|
|
6090
|
+
const inStampForm = (value, to, from) => {
|
|
6091
|
+
if (value === undefined ||
|
|
6092
|
+
to === null ||
|
|
6093
|
+
from === null ||
|
|
6094
|
+
(to.storage === from.storage && to.domain === from.domain)) {
|
|
6095
|
+
return value;
|
|
6096
|
+
}
|
|
6097
|
+
const forms = stampForms(to, from);
|
|
6098
|
+
if (Option.isSome(forms.inTo(value)))
|
|
6099
|
+
return value;
|
|
6100
|
+
return Option.match(forms.fromInstant(value), {
|
|
6101
|
+
onNone: () => value,
|
|
6102
|
+
onSome: (instant) => Option.getOrElse(forms.toWire(instant), () => value),
|
|
6103
|
+
});
|
|
6104
|
+
};
|
|
6105
|
+
const stampFormCache = new Map();
|
|
6106
|
+
/** The decoders and encoder `inStampForm` uses for a pair of forms, built once per pair. */
|
|
6107
|
+
const stampForms = (to, from) => {
|
|
6108
|
+
const id = `${to.storage}:${to.domain}<${from.storage}:${from.domain}`;
|
|
6109
|
+
const cached = stampFormCache.get(id);
|
|
6110
|
+
if (cached !== undefined)
|
|
6111
|
+
return cached;
|
|
6112
|
+
const strict = (encoding) => buildDateTransform(encoding, { strictWireKind: true });
|
|
6113
|
+
const forms = {
|
|
6114
|
+
inTo: Schema.decodeUnknownOption(strict(to)),
|
|
6115
|
+
fromInstant: Schema.decodeUnknownOption(strict(from)),
|
|
6116
|
+
toWire: Schema.encodeUnknownOption(buildDateTransform(to)),
|
|
6117
|
+
};
|
|
6118
|
+
stampFormCache.set(id, forms);
|
|
6119
|
+
return forms;
|
|
6120
|
+
};
|
|
4231
6121
|
/**
|
|
4232
6122
|
* Convert decomposed items into DynamoDB attribute maps with composed keys.
|
|
4233
6123
|
*
|
|
@@ -4249,10 +6139,25 @@ rootValue,
|
|
|
4249
6139
|
* spells them when it reads, and the only way to guarantee that is for both
|
|
4250
6140
|
* to go through the same function (#111).
|
|
4251
6141
|
*/
|
|
4252
|
-
keyRecord, stamp
|
|
4253
|
-
|
|
4254
|
-
|
|
6142
|
+
keyRecord, stamp,
|
|
6143
|
+
/**
|
|
6144
|
+
* A write's own keys (`create`, `update`): each key composed here from an object composing
|
|
6145
|
+
* `[object Object]` refuses the write where it's composed (`EDD-9162`), and so does a row's
|
|
6146
|
+
* static discriminator. Absent, the keys are composed as they always were.
|
|
6147
|
+
*/
|
|
6148
|
+
own) => groups.map((group) => {
|
|
6149
|
+
// The key attributes the library writes on each row (#241, `EDD-9159` judges a value given there).
|
|
6150
|
+
const written = [];
|
|
6151
|
+
const items = group.items.map((item) => {
|
|
4255
6152
|
const attrs = { ...item.attributes };
|
|
6153
|
+
const schema = own?.schema ?? config.schema;
|
|
6154
|
+
if (own !== undefined) {
|
|
6155
|
+
for (const [attr, value] of own.discriminators(item.node)) {
|
|
6156
|
+
KeyComposer.siteCompositeText(schema, value, attr, new DiscriminatorKey(item.member), "sk");
|
|
6157
|
+
}
|
|
6158
|
+
}
|
|
6159
|
+
const library = ["__edd_e__", config.pk.field, "sk"];
|
|
6160
|
+
written.push(library);
|
|
4256
6161
|
// Add entity type discriminator
|
|
4257
6162
|
attrs.__edd_e__ = item.entityType;
|
|
4258
6163
|
// PK: shared collection key
|
|
@@ -4263,24 +6168,36 @@ keyRecord, stamp) => groups.map((group) => ({
|
|
|
4263
6168
|
// propagated onto edge items via `context`; known first, so a key over one holds what the row
|
|
4264
6169
|
// holds. A date the row declares holds what the row does: on `create` the stamp `fillStamps`
|
|
4265
6170
|
// put there, on `update` a value the mutation changed, and `created` stays what's stored
|
|
4266
|
-
// whatever the mutation did to it.
|
|
6171
|
+
// whatever the mutation did to it. One kept from the stored row is written in the row's form
|
|
6172
|
+
// (a row written before #241 holds a date under `Schema.optional` as ISO text), and a key over
|
|
6173
|
+
// one reads it in the key's form, so a key never moves with a stored form (`keyed`).
|
|
4267
6174
|
const stamped = {};
|
|
6175
|
+
const keyed = {};
|
|
4268
6176
|
const row = item.rowStamps;
|
|
4269
6177
|
if (stamp && row !== undefined) {
|
|
4270
6178
|
const { existingCreated, now } = stamp;
|
|
4271
6179
|
const sk = attrs.sk;
|
|
4272
6180
|
if (row.createdAt !== null) {
|
|
4273
|
-
const held = row.createdDeclared ? item.attributes
|
|
6181
|
+
const held = row.createdDeclared ? ownValue(item.attributes, row.createdAt) : undefined;
|
|
6182
|
+
const kept = existingCreated.get(sk);
|
|
4274
6183
|
stamped[row.createdAt] =
|
|
4275
|
-
|
|
6184
|
+
kept !== undefined
|
|
6185
|
+
? inStampForm(kept, row.createdStored, row.createdKey)
|
|
6186
|
+
: (held ?? generateTimestampPrimitive(now, row.createdStored));
|
|
6187
|
+
keyed[row.createdAt] = inStampForm(stamped[row.createdAt], row.createdKey, row.createdStored);
|
|
4276
6188
|
}
|
|
4277
6189
|
if (row.updatedAt !== null) {
|
|
4278
|
-
const held = row.updatedDeclared ? item.attributes
|
|
6190
|
+
const held = row.updatedDeclared ? ownValue(item.attributes, row.updatedAt) : undefined;
|
|
4279
6191
|
const before = stamp.updatedBefore;
|
|
4280
6192
|
const supplied = held !== undefined && !(before?.has(sk) && deepEqual(before.get(sk), held));
|
|
6193
|
+
const kept = stamp.existingUpdated?.get(sk);
|
|
4281
6194
|
stamped[row.updatedAt] =
|
|
4282
|
-
|
|
4283
|
-
|
|
6195
|
+
kept !== undefined
|
|
6196
|
+
? inStampForm(kept, row.updatedStored, row.updatedKey)
|
|
6197
|
+
: supplied
|
|
6198
|
+
? held
|
|
6199
|
+
: generateTimestampPrimitive(now, row.updatedStored);
|
|
6200
|
+
keyed[row.updatedAt] = inStampForm(stamped[row.updatedAt], row.updatedKey, row.updatedStored);
|
|
4284
6201
|
}
|
|
4285
6202
|
}
|
|
4286
6203
|
// Collection SK mirror — only written when an index is actually provisioned.
|
|
@@ -4292,8 +6209,9 @@ keyRecord, stamp) => groups.map((group) => ({
|
|
|
4292
6209
|
if (rootValue !== undefined &&
|
|
4293
6210
|
config.collection.index !== undefined &&
|
|
4294
6211
|
collectionSk !== undefined) {
|
|
6212
|
+
library.push(collectionSk.field);
|
|
4295
6213
|
attrs[collectionSk.field] = isRootItem
|
|
4296
|
-
? composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(config.root.entityType,
|
|
6214
|
+
? composeCollectionKey(config.schema, config.collection.name, keyCompositesOrThrow(config.root.entityType, AGGREGATE_KEY.collectionSort, schema, collectionSk.composite, keyRecord({ ...rootValue, ...keyed })))
|
|
4297
6215
|
: composeKey(config.schema, item.entityType, [...item.skComposites]);
|
|
4298
6216
|
}
|
|
4299
6217
|
// List collection GSI keys (root items only). Sparse, as an entity index is: a row with no
|
|
@@ -4303,11 +6221,11 @@ keyRecord, stamp) => groups.map((group) => ({
|
|
|
4303
6221
|
if (rootValue !== undefined && isRootItem && config.list) {
|
|
4304
6222
|
const listKeyValues = keyRecord({
|
|
4305
6223
|
...(item.keyAttributes ?? item.attributes),
|
|
4306
|
-
...
|
|
6224
|
+
...keyed,
|
|
4307
6225
|
});
|
|
4308
6226
|
const listComposites = [...config.list.pk.composite, ...config.list.sk.composite];
|
|
4309
|
-
if (listComposites.every((attr) => hasKeyValue(listKeyValues
|
|
4310
|
-
const listPkComposites = KeyComposer.extractKeyComposites(
|
|
6227
|
+
if (listComposites.every((attr) => hasKeyValue(ownValue(listKeyValues, attr)))) {
|
|
6228
|
+
const listPkComposites = KeyComposer.extractKeyComposites(schema, AGGREGATE_KEY.listPartition, config.list.pk.composite, listKeyValues);
|
|
4311
6229
|
if (config.list.cardinality) {
|
|
4312
6230
|
const shard = hashToShard(pkValue, config.list.cardinality);
|
|
4313
6231
|
attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, [
|
|
@@ -4318,13 +6236,15 @@ keyRecord, stamp) => groups.map((group) => ({
|
|
|
4318
6236
|
else {
|
|
4319
6237
|
attrs[config.list.pk.field] = composeCollectionKey(config.schema, config.list.name, listPkComposites);
|
|
4320
6238
|
}
|
|
4321
|
-
const listSkComposites = KeyComposer.extractKeyComposites(
|
|
6239
|
+
const listSkComposites = KeyComposer.extractKeyComposites(schema, AGGREGATE_KEY.listSort, config.list.sk.composite, listKeyValues);
|
|
4322
6240
|
attrs[config.list.sk.field] = composeCollectionKey(config.schema, config.list.name, listSkComposites);
|
|
6241
|
+
library.push(config.list.pk.field, config.list.sk.field);
|
|
4323
6242
|
}
|
|
4324
6243
|
}
|
|
4325
6244
|
return toAttributeMap({ ...attrs, ...stamped });
|
|
4326
|
-
})
|
|
4327
|
-
}
|
|
6245
|
+
});
|
|
6246
|
+
return { group: group.name, items, written };
|
|
6247
|
+
});
|
|
4328
6248
|
function writeTransactionGroups(client, tableName, groups, aggregateName, keys, rootGuard) {
|
|
4329
6249
|
return Effect.gen(function* () {
|
|
4330
6250
|
// Each group is its own transaction (DynamoDB: 100 items per
|
|
@@ -4378,6 +6298,11 @@ function writeTransactionGroups(client, tableName, groups, aggregateName, keys,
|
|
|
4378
6298
|
limit: diagnosis.limit,
|
|
4379
6299
|
committed: already,
|
|
4380
6300
|
operation: rootGuard !== undefined ? "create" : "update",
|
|
6301
|
+
// Over only because of the rows it moves off 1.40.0's text: `rekey` moves them.
|
|
6302
|
+
...(group.previous !== undefined &&
|
|
6303
|
+
diagnosis.count - group.previous <= diagnosis.limit && {
|
|
6304
|
+
previousKeyText: group.previous,
|
|
6305
|
+
}),
|
|
4381
6306
|
cause: original,
|
|
4382
6307
|
})
|
|
4383
6308
|
: diagnosedValidationError(diagnosis, original, {
|
|
@@ -4524,7 +6449,7 @@ const placeRows = (slots, held) => {
|
|
|
4524
6449
|
return placements;
|
|
4525
6450
|
};
|
|
4526
6451
|
// ---------------------------------------------------------------------------
|
|
4527
|
-
// Internal: Delete
|
|
6452
|
+
// Internal: Delete an aggregate's rows from its partition
|
|
4528
6453
|
// ---------------------------------------------------------------------------
|
|
4529
6454
|
const deleteAllItems = (client, tableName, allItems, pkField) => Effect.gen(function* () {
|
|
4530
6455
|
// Extract primary keys from items
|
|
@@ -4582,13 +6507,16 @@ const DELETE_BASE_DELAY_MS = 100;
|
|
|
4582
6507
|
* empty part directly under `and` is left out, and one anywhere else — or an
|
|
4583
6508
|
* `or()` with no parts — is refused with a `ValidationError` before anything
|
|
4584
6509
|
* is sent. An `isIn` with no values is sent, and DynamoDB's rejection of its
|
|
4585
|
-
* `IN ()` diagnosed (#144).
|
|
6510
|
+
* `IN ()` diagnosed (#144). Each path is named as an entity query's filter names it (#238): below
|
|
6511
|
+
* a field, a struct that renames its keys as it's stored is named by its stored names (`below`).
|
|
4586
6512
|
*/
|
|
4587
|
-
const compileListFilter = (filter, aggregateName
|
|
6513
|
+
const compileListFilter = (filter, aggregateName, storedAt, below,
|
|
6514
|
+
/** The aggregate's model: a callback's `.entry()` resolves on its sparse maps (`pathBuilderOf`). */
|
|
6515
|
+
model) => {
|
|
4588
6516
|
if (filter === undefined)
|
|
4589
6517
|
return Effect.succeed(undefined);
|
|
4590
6518
|
const expr = typeof filter === "function"
|
|
4591
|
-
? filter(
|
|
6519
|
+
? filter(pathBuilderOf([model]), createConditionOps())
|
|
4592
6520
|
: parseSimpleShorthand(filter);
|
|
4593
6521
|
const problem = emptyPartProblem(expr);
|
|
4594
6522
|
if (problem !== undefined) {
|
|
@@ -4598,7 +6526,10 @@ const compileListFilter = (filter, aggregateName) => {
|
|
|
4598
6526
|
cause: `list filter: ${problem} Nothing was sent.`,
|
|
4599
6527
|
}));
|
|
4600
6528
|
}
|
|
4601
|
-
|
|
6529
|
+
// Its operands in the form the root row holds (#242), named as an entity query's filter names
|
|
6530
|
+
// them (#238).
|
|
6531
|
+
const named = entityNaming(undefined, storedAt, undefined, below).renameExpr?.(expr) ?? expr;
|
|
6532
|
+
return Effect.succeed(isEmptyExpr(expr) ? undefined : compileExpr(named));
|
|
4602
6533
|
};
|
|
4603
6534
|
/**
|
|
4604
6535
|
* @internal DynamoDB `Limit` for the next request — the same rule `Query.ts`
|
|
@@ -4626,10 +6557,10 @@ const listKeyFromItem = (item, names) => {
|
|
|
4626
6557
|
return undefined;
|
|
4627
6558
|
const key = {};
|
|
4628
6559
|
for (const name of names) {
|
|
4629
|
-
const value = item
|
|
6560
|
+
const value = ownValue(item, name);
|
|
4630
6561
|
if (value === undefined)
|
|
4631
6562
|
return undefined;
|
|
4632
|
-
key
|
|
6563
|
+
setOwn(key, name, value);
|
|
4633
6564
|
}
|
|
4634
6565
|
return key;
|
|
4635
6566
|
};
|