effect-dynamodb 1.43.0 → 1.44.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Aggregate.d.ts +88 -13
- package/dist/Aggregate.d.ts.map +1 -1
- package/dist/Aggregate.js +604 -278
- package/dist/Aggregate.js.map +1 -1
- package/dist/BlobGc.d.ts +2 -2
- package/dist/BlobGc.d.ts.map +1 -1
- package/dist/DynamoClient.d.ts +1 -1
- package/dist/DynamoClient.d.ts.map +1 -1
- package/dist/DynamoClient.js.map +1 -1
- package/dist/Entity.d.ts +12 -4
- package/dist/Entity.d.ts.map +1 -1
- package/dist/Entity.js +455 -214
- package/dist/Entity.js.map +1 -1
- package/dist/Transaction.js +2 -1
- package/dist/Transaction.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/internal/AggregateWrite.d.ts +130 -0
- package/dist/internal/AggregateWrite.d.ts.map +1 -0
- package/dist/internal/AggregateWrite.js +341 -0
- package/dist/internal/AggregateWrite.js.map +1 -0
- package/dist/internal/ExpressionLimits.d.ts +22 -3
- package/dist/internal/ExpressionLimits.d.ts.map +1 -1
- package/dist/internal/ExpressionLimits.js +46 -7
- package/dist/internal/ExpressionLimits.js.map +1 -1
- package/dist/internal/ItemSize.d.ts +7 -1
- package/dist/internal/ItemSize.d.ts.map +1 -1
- package/dist/internal/ItemSize.js +13 -5
- package/dist/internal/ItemSize.js.map +1 -1
- package/dist/internal/TransactPlan.d.ts +18 -1
- package/dist/internal/TransactPlan.d.ts.map +1 -1
- package/dist/internal/TransactPlan.js +45 -7
- package/dist/internal/TransactPlan.js.map +1 -1
- package/dist/internal/TransactWriteOps.d.ts +1 -1
- package/dist/internal/TransactWriteOps.d.ts.map +1 -1
- package/dist/internal/TransactWriteOps.js +8 -8
- package/dist/internal/TransactWriteOps.js.map +1 -1
- package/package.json +2 -2
package/dist/Aggregate.js
CHANGED
|
@@ -12,7 +12,7 @@ import { TypeId as SchemaAggregateTypeId } from "@effect-dynamodb/schema/Aggrega
|
|
|
12
12
|
import { Compression } from "@effect-dynamodb/schema/Compression.js";
|
|
13
13
|
import * as DynamoModel from "@effect-dynamodb/schema/DynamoModel.js";
|
|
14
14
|
import { composeCollectionKey, composeKey, composeUniqueKey, KEY_DELIMITER, } from "@effect-dynamodb/schema/DynamoSchema.js";
|
|
15
|
-
import { AggregateAssemblyError, AggregateDecompositionError,
|
|
15
|
+
import { AggregateAssemblyError, AggregateDecompositionError, ConditionalCheckFailed, DynamoError, DynamoValidationError, isAwsTransactionCancelled, OptimisticLockError, RefNotFound, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
|
|
16
16
|
import { fieldAtPath, kindReadingOf, kindTargets, makeCompositeKeyForm, readBackAs, readBackUnsure, readsBackOtherwise, refuseInexact, storedNaNKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
|
|
17
17
|
import { refOffloadRefusal } from "@effect-dynamodb/schema/internal/EntityOffload.js";
|
|
18
18
|
import { buildDateTransform, containedKindOf, containedOperand, containsWireTransform, entityRefsOf, heldRefMember, keepsAsGiven, matchDateRepresentation, optionalField, refHeldTarget, resolveSystemFields, substituteSchemaDeep, unionHoldsRef, validateNoTransformOverride, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
|
|
@@ -33,7 +33,7 @@ import { BigDecimal, Cause, Chunk, Context, DateTime, Effect, Equal, Exit, HashM
|
|
|
33
33
|
import * as Batch from "./Batch.js";
|
|
34
34
|
import { BlobStore } from "./BlobStore.js";
|
|
35
35
|
import { fromDefinition as entityFromDefinition } from "./Entity.js";
|
|
36
|
-
import
|
|
36
|
+
import * as AggregateWrite from "./internal/AggregateWrite.js";
|
|
37
37
|
import * as BlobLedger from "./internal/BlobLedger.js";
|
|
38
38
|
import { entityNaming } from "./internal/BoundQuery.js";
|
|
39
39
|
import * as Capacity from "./internal/Capacity.js";
|
|
@@ -52,15 +52,15 @@ import { codecRequirements, hasStoredForm, packItemSync, unpackItemSync, unregis
|
|
|
52
52
|
import { pathBuilderOf } from "./internal/PathBuilder.js";
|
|
53
53
|
import * as Rekey from "./internal/Rekey.js";
|
|
54
54
|
import { asRead, notReadBack, notStoredForm, readBackRefusal } from "./internal/RoundTrip.js";
|
|
55
|
-
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";
|
|
56
|
-
import {
|
|
55
|
+
import { composePrimaryKeyOrFail, freshIncarnationToken, 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";
|
|
56
|
+
import { diagnoseFailure, explainDiagnosis, mergeKeyAttributes, withCause, } from "./internal/WriteDiagnosis.js";
|
|
57
57
|
import { fromAttributeMap, isCachedNormal, toAttributeMap, toAttributeValue, unstorableIn, } from "./Marshaller.js";
|
|
58
58
|
import { addTableKeyAttributes, resolvePrimaryKey } from "./Table.js";
|
|
59
59
|
// Internal modules (decomposed from Aggregate.ts)
|
|
60
60
|
export { isManyEdge, isOneEdge, isRefEdge, many, one, ref, } from "@effect-dynamodb/schema/internal/AggregateEdges.js";
|
|
61
61
|
export { deriveAggregateSchemas, deriveElementInputSchema, deriveEntityFieldName, extractArrayElement, getSchemaFields, isFieldOptional, isSchemaMatchingEntity, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
62
62
|
import { makeCursor, } from "@effect-dynamodb/schema/internal/AggregateCursor.js";
|
|
63
|
-
import { declaredValueNames, deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, isSchemaMatchingEntity, manyEdgePaths, manyElementFields, manyElementSchema, readRowOf, readTakesOff, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseAggregateProtoName, refuseManySortKeysOverMovingValue, resolveAggregateStamps, rowKeysOn, subAggregateRowKind, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
63
|
+
import { aggregateVersionField, declaredValueNames, deriveAggregateSchemas, deriveEntityFieldName, elementHoldsRef, given, holdsRefId, isEntityElement, isFieldOptional, isSchemaMatchingEntity, manyEdgePaths, manyElementFields, manyElementSchema, readRowOf, readTakesOff, refIdField, refIdValue, refKeyComposite, refKeyComposites, refuseAggregateKeyOverMovingValue, refuseAggregateKeysOverBothKinds, refuseAggregateProtoName, refuseAggregateVersioning, refuseManySortKeysOverMovingValue, resolveAggregateStamps, rowKeysOn, subAggregateRowKind, unwrapModel, } from "@effect-dynamodb/schema/internal/AggregateSchemas.js";
|
|
64
64
|
// ---------------------------------------------------------------------------
|
|
65
65
|
// TypeId
|
|
66
66
|
// ---------------------------------------------------------------------------
|
|
@@ -1188,9 +1188,29 @@ const makeAggregate = (schema, config) => {
|
|
|
1188
1188
|
updatedKey: storedIn(schemaFields, timestampFields.updatedAt, timestampFields.updatedAtCollision, timestampFields.updatedAtEncoding, true),
|
|
1189
1189
|
}
|
|
1190
1190
|
: undefined;
|
|
1191
|
+
// `versioned` and `fence` (#168, `docs/designs/aggregate-concurrency.md` §3.4, §3.5): judged at
|
|
1192
|
+
// load (`EDD-9177`, `EDD-9179`). The version is a number on the root row, beside the entity's hidden
|
|
1193
|
+
// incarnation token; `versioned` implies the fence.
|
|
1194
|
+
refuseAggregateVersioning(aggregateName, config, schemaFields, schema);
|
|
1195
|
+
const versionField = aggregateVersionField(config.versioned);
|
|
1196
|
+
const fenced = versionField !== undefined || config.fence === true;
|
|
1197
|
+
/**
|
|
1198
|
+
* The root model declares the version field: a read hands it over (0 for a root without one). A
|
|
1199
|
+
* root of members (a union, a suspended schema) declares it when a member does.
|
|
1200
|
+
*/
|
|
1201
|
+
const versionDeclared = versionField !== undefined &&
|
|
1202
|
+
(schemaFields === undefined
|
|
1203
|
+
? storedFieldNames(schema).includes(versionField)
|
|
1204
|
+
: ownValue(schemaFields, versionField) !== undefined);
|
|
1205
|
+
/** The root's sort key: composed from its entity type alone, under every key-text setting. */
|
|
1206
|
+
const rootSortKey = composeKey(config.schema, config.root.entityType, []);
|
|
1191
1207
|
// What the read path may drop before decoding: each node drops those its rows
|
|
1192
|
-
// don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object.
|
|
1193
|
-
|
|
1208
|
+
// don't declare ({@link stampsToStrip}). Declared, it belongs to the domain object. A versioned
|
|
1209
|
+
// root's version is dropped the same way, and its incarnation token always (#168).
|
|
1210
|
+
const systemAttrs = new Set([
|
|
1211
|
+
...[timestampFields.createdAt, timestampFields.updatedAt].filter((name) => name !== null),
|
|
1212
|
+
...(versionField === undefined ? [] : [versionField, INCARNATION_TOKEN]),
|
|
1213
|
+
]);
|
|
1194
1214
|
const requiredIn = (fields, name) => name !== null && ownValue(fields, name) !== undefined && !isFieldOptional(fields[name]);
|
|
1195
1215
|
// On `create`, a stamp replaces a value the input holds, as on 1.39.0, except under a date the root
|
|
1196
1216
|
// declares `Schema.optional`: 1.39.0 left that field the caller's and stored a value passed for it.
|
|
@@ -1251,6 +1271,8 @@ const makeAggregate = (schema, config) => {
|
|
|
1251
1271
|
cardinality: "root",
|
|
1252
1272
|
edges: config.edges,
|
|
1253
1273
|
parentFields: schemaFields,
|
|
1274
|
+
// A root that exposes no `.fields` (a union, a suspended schema): its stored names.
|
|
1275
|
+
valueSchema: schema,
|
|
1254
1276
|
resolveRef,
|
|
1255
1277
|
escapeKeys: config.schema.escapeKeys === true,
|
|
1256
1278
|
rowKeys: config,
|
|
@@ -1404,6 +1426,14 @@ const makeAggregate = (schema, config) => {
|
|
|
1404
1426
|
// assembly read diagnoses it, naming the aggregate and the index (#144).
|
|
1405
1427
|
const consistentRead = config.consistentRead ?? false;
|
|
1406
1428
|
const tablePrimary = resolvePrimaryKey(config.table.entities);
|
|
1429
|
+
/**
|
|
1430
|
+
* Whether `update`, an If-Match and `delete`'s second read read strongly consistent whatever
|
|
1431
|
+
* `consistentRead` says (#168, D11 reversed): on the base table only. A collection index is read
|
|
1432
|
+
* as `consistentRead` says, as on 1.43.0: an index keyed on the table's own partition key may be a
|
|
1433
|
+
* GSI (one added to a table after it was created, where an LSI can't be), which DynamoDB refuses a
|
|
1434
|
+
* consistent read of, so only the caller's `consistentRead: true` says it is an LSI.
|
|
1435
|
+
*/
|
|
1436
|
+
const readConsistent = config.collection.index === undefined;
|
|
1407
1437
|
if (tablePrimary !== undefined && config.collection.index === undefined) {
|
|
1408
1438
|
if (config.pk.field !== tablePrimary.pk) {
|
|
1409
1439
|
throw new Error(`[EDD-9041] Aggregate "${aggregateName}": collection PK field "${config.pk.field}" is ` +
|
|
@@ -1523,10 +1553,27 @@ const makeAggregate = (schema, config) => {
|
|
|
1523
1553
|
"Drop `consistentRead` from the aggregate, or key it on the table's primary " +
|
|
1524
1554
|
"partition key so assembly reads the base table.", original);
|
|
1525
1555
|
/** Compose the PK and query all items; a rejected read fails as `rejected` names it. */
|
|
1526
|
-
|
|
1527
|
-
|
|
1528
|
-
|
|
1529
|
-
|
|
1556
|
+
/**
|
|
1557
|
+
* A versioned root the model declares the version of reads 0 without one (#168, §3.5): a root
|
|
1558
|
+
* written before `versioned` was turned on. In place, on rows read.
|
|
1559
|
+
*/
|
|
1560
|
+
const withReadVersion = (rows) => {
|
|
1561
|
+
if (!versionDeclared)
|
|
1562
|
+
return;
|
|
1563
|
+
for (const row of rows) {
|
|
1564
|
+
if (row.__edd_e__ === config.root.entityType &&
|
|
1565
|
+
row.sk === rootSortKey &&
|
|
1566
|
+
!hasOwnName(row, versionField)) {
|
|
1567
|
+
setOwn(row, versionField, 0);
|
|
1568
|
+
}
|
|
1569
|
+
}
|
|
1570
|
+
};
|
|
1571
|
+
const readPartition = (key, rejected, rekeyRead) => Effect.flatMap(readPartitionRaw(key, rejected, rekeyRead), (read) => {
|
|
1572
|
+
withReadVersion(read.allItems);
|
|
1573
|
+
// Packed edge attributes, read by their stored form (#147); offloaded ones resolved
|
|
1574
|
+
// eagerly, both kinds (#179, design §8.4).
|
|
1575
|
+
return Effect.as(loadAggregateItems(read.allItems, readPlans), read);
|
|
1576
|
+
});
|
|
1530
1577
|
// A root row's partition key composites as a read takes them: decoded through their fields, as
|
|
1531
1578
|
// assembly decodes the root row. `create` composes the key from the value it holds, so a key
|
|
1532
1579
|
// composed again from a stored row (`list`, `rekey`) is composed from these, never from the
|
|
@@ -1613,8 +1660,8 @@ const makeAggregate = (schema, config) => {
|
|
|
1613
1660
|
const readPartitionRaw = (key, rejected, rekeyRead) => Effect.gen(function* () {
|
|
1614
1661
|
const client = yield* Capacity.client;
|
|
1615
1662
|
const tableConfig = yield* config.table.Tag;
|
|
1616
|
-
const pkValue = yield* composeOrFail("key", () => collectionPkOf(key));
|
|
1617
|
-
const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead, rejected, rekeyRead?.stored);
|
|
1663
|
+
const pkValue = rekeyRead?.partition ?? (yield* composeOrFail("key", () => collectionPkOf(key)));
|
|
1664
|
+
const read = (partition) => queryAllItems(client, tableConfig.name, config.collection.index, config.pk.field, partition, consistentRead || rekeyRead?.consistent === true, rejected, rekeyRead?.stored);
|
|
1618
1665
|
const from = rekeyRead?.from;
|
|
1619
1666
|
const allItems = from === undefined
|
|
1620
1667
|
? yield* read(pkValue)
|
|
@@ -2103,7 +2150,7 @@ const makeAggregate = (schema, config) => {
|
|
|
2103
2150
|
operation: `${operation}.consistentRead`,
|
|
2104
2151
|
cause: assemblyReadCause(operation, diagnosis, original),
|
|
2105
2152
|
}), rekeyRead);
|
|
2106
|
-
const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps);
|
|
2153
|
+
const derivedSchemas = deriveAggregateSchemas(schema, config.edges, config.pk.composite, config.timestamps, versionField === undefined ? [] : [versionField]);
|
|
2107
2154
|
/** A stored row's position: its partition and sort key. */
|
|
2108
2155
|
const positionOf = (pk, sk) => Rekey.identity(pk, sk);
|
|
2109
2156
|
/**
|
|
@@ -2594,8 +2641,9 @@ const makeAggregate = (schema, config) => {
|
|
|
2594
2641
|
return stale;
|
|
2595
2642
|
};
|
|
2596
2643
|
/**
|
|
2597
|
-
* `[EDD-9160]` (#241): an update about to
|
|
2598
|
-
* stored under a sort key other than the one this
|
|
2644
|
+
* `[EDD-9160]` (#241): an update about to send or delete a row (#168: judged per row, not per
|
|
2645
|
+
* group) whose value was read from a row stored under a sort key other than the one this
|
|
2646
|
+
* configuration composes for that value, through
|
|
2599
2647
|
* the function the write itself keys rows with ({@link sortKeyOf}). Each value's row is the one a
|
|
2600
2648
|
* read took it from ({@link rowsReadAt}). Such a row was written under the other `escapeKeys`
|
|
2601
2649
|
* setting (`$`, `#` or another escaped character, a number other than a non-negative integer
|
|
@@ -2607,8 +2655,6 @@ const makeAggregate = (schema, config) => {
|
|
|
2607
2655
|
*/
|
|
2608
2656
|
const refuseOtherSettingRows = (oldGroups, written, readAt, moved) => {
|
|
2609
2657
|
for (const group of oldGroups) {
|
|
2610
|
-
if (!written(group.name))
|
|
2611
|
-
continue;
|
|
2612
2658
|
for (const item of group.items) {
|
|
2613
2659
|
if (item.path === undefined)
|
|
2614
2660
|
continue;
|
|
@@ -2617,6 +2663,8 @@ const makeAggregate = (schema, config) => {
|
|
|
2617
2663
|
const sk = sortKeyOf(config.schema, item);
|
|
2618
2664
|
if (typeof stored !== "string" || sk === undefined || stored === sk)
|
|
2619
2665
|
continue;
|
|
2666
|
+
if (!written(group.name, sk))
|
|
2667
|
+
continue;
|
|
2620
2668
|
if (moved.get(group.name)?.includes(stored) === true)
|
|
2621
2669
|
continue;
|
|
2622
2670
|
return Effect.fail(new ValidationError({
|
|
@@ -2634,8 +2682,28 @@ const makeAggregate = (schema, config) => {
|
|
|
2634
2682
|
}
|
|
2635
2683
|
return Effect.void;
|
|
2636
2684
|
};
|
|
2637
|
-
const updateCore = (key, mutationFn) => Effect.gen(function* () {
|
|
2638
|
-
const
|
|
2685
|
+
const updateCore = (key, mutationFn, options) => Effect.gen(function* () {
|
|
2686
|
+
const expectedVersion = options?.expectedVersion;
|
|
2687
|
+
// `[EDD-9178]` (#168): an unversioned aggregate keeps no version to compare. Refused before
|
|
2688
|
+
// anything is read.
|
|
2689
|
+
if (expectedVersion !== undefined && versionField === undefined) {
|
|
2690
|
+
return yield* new ValidationError({
|
|
2691
|
+
entityType: aggregateName,
|
|
2692
|
+
operation: "aggregate.update",
|
|
2693
|
+
cause: new Error(`[EDD-9178] Aggregate "${aggregateName}": \`expectedVersion\` on an aggregate that ` +
|
|
2694
|
+
"isn't `versioned`, which keeps no version to compare it with. Turn on `versioned` " +
|
|
2695
|
+
"in `Aggregate.make`, or drop `expectedVersion`. Nothing was read or written."),
|
|
2696
|
+
});
|
|
2697
|
+
}
|
|
2698
|
+
// The rows as stored, kept beside the ones read: each row the write sends is guarded on its
|
|
2699
|
+
// stored form, never on a row unmarshalled and marshalled again (#168, §3.2). Read strongly
|
|
2700
|
+
// consistent where the collection allows (D11 reversed): a guard on an out-of-date read fails
|
|
2701
|
+
// on every attempt until the read catches up.
|
|
2702
|
+
const stored = [];
|
|
2703
|
+
const { client, tableConfig, pkValue, allItems } = yield* fetchPartition(key, "update", {
|
|
2704
|
+
stored,
|
|
2705
|
+
consistent: readConsistent,
|
|
2706
|
+
});
|
|
2639
2707
|
if (allItems.length === 0) {
|
|
2640
2708
|
return yield* new AggregateAssemblyError({
|
|
2641
2709
|
aggregate: aggregateName,
|
|
@@ -2643,8 +2711,26 @@ const makeAggregate = (schema, config) => {
|
|
|
2643
2711
|
key,
|
|
2644
2712
|
});
|
|
2645
2713
|
}
|
|
2714
|
+
const rawBySk = new Map();
|
|
2715
|
+
for (const row of stored) {
|
|
2716
|
+
const sk = row.sk?.S;
|
|
2717
|
+
if (sk !== undefined)
|
|
2718
|
+
rawBySk.set(sk, row);
|
|
2719
|
+
}
|
|
2720
|
+
const rawRoot = rawBySk.get(rootSortKey);
|
|
2646
2721
|
// 1. Assemble current state
|
|
2647
2722
|
const current = yield* assembleAggregate(assembly, rootNode, allItems, contextFields, key, aggregateName, systemAttrs);
|
|
2723
|
+
// A versioned root's version and incarnation token as read (#168, §3.5): 0 and none on a root
|
|
2724
|
+
// written before `versioned` was turned on.
|
|
2725
|
+
const versionRead = versionField === undefined ? undefined : storedRootVersion(rawRoot, versionField);
|
|
2726
|
+
if (expectedVersion !== undefined && versionRead.version !== expectedVersion) {
|
|
2727
|
+
return yield* new OptimisticLockError({
|
|
2728
|
+
entityType: aggregateName,
|
|
2729
|
+
key,
|
|
2730
|
+
expectedVersion,
|
|
2731
|
+
actualVersion: versionRead.version,
|
|
2732
|
+
});
|
|
2733
|
+
}
|
|
2648
2734
|
const now = yield* DateTime.now;
|
|
2649
2735
|
// 2. Apply mutation — provide optics context for composable updates
|
|
2650
2736
|
const state = toPlainState(current);
|
|
@@ -2653,6 +2739,7 @@ const makeAggregate = (schema, config) => {
|
|
|
2653
2739
|
cursor: makeCursor(state, opticRoot),
|
|
2654
2740
|
optic: opticRoot,
|
|
2655
2741
|
current: current,
|
|
2742
|
+
...(versionRead !== undefined && { version: versionRead.version }),
|
|
2656
2743
|
});
|
|
2657
2744
|
// An offloaded edge field takes its value, never a stream, handle, source or lazy value
|
|
2658
2745
|
// (`[EDD-9120]`, #179).
|
|
@@ -2664,7 +2751,12 @@ const makeAggregate = (schema, config) => {
|
|
|
2664
2751
|
// update path), and a transformation with one type on both sides isn't
|
|
2665
2752
|
// applied again to a value it already made.
|
|
2666
2753
|
// A row the mutation added doesn't need the dates the library stamps.
|
|
2667
|
-
|
|
2754
|
+
// A version the root declares is the library's: the one read, whatever the mutation set.
|
|
2755
|
+
const filled = fillStamps(rootNode, updated, now, "required");
|
|
2756
|
+
const written = versionDeclared &&
|
|
2757
|
+
ownValue(filled, versionField) !== versionRead.version
|
|
2758
|
+
? { ...filled, [versionField]: versionRead.version }
|
|
2759
|
+
: filled;
|
|
2668
2760
|
const decoded = yield* Schema.decodeUnknownEffect(mutatedStateSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
|
|
2669
2761
|
entityType: aggregateName,
|
|
2670
2762
|
operation: "aggregate.update",
|
|
@@ -2801,20 +2893,6 @@ const makeAggregate = (schema, config) => {
|
|
|
2801
2893
|
yield* refuseNotReadBack(newDynamo, key, "aggregate.update", storedAsGivenIn(newGroups));
|
|
2802
2894
|
// The row each value of the state was read from (#241).
|
|
2803
2895
|
const readAt = rowsReadAt(rootNode, allItems, systemAttrs);
|
|
2804
|
-
yield* refuseOtherSettingRows(oldGroups, groupChanged, readAt, previousRows);
|
|
2805
|
-
// Route and upload the offloaded attributes of the groups the write sends, every one afresh
|
|
2806
|
-
// (#179, design §6.9), before the first transaction: decided on the decomposed values above,
|
|
2807
|
-
// so an unchanged group uploads nothing, and no pointer read from the partition is written
|
|
2808
|
-
// back (each changed group's values were read eagerly, and are uploaded again).
|
|
2809
|
-
const sentDynamo = yield* routeBuiltGroups(newDynamo.filter((g) => groupChanged(g.group)), offloadInfoByType, {
|
|
2810
|
-
table: tableConfig.name,
|
|
2811
|
-
pkAttribute: config.pk.field,
|
|
2812
|
-
operation: "Aggregate.update",
|
|
2813
|
-
escapeKeys: config.schema.escapeKeys === true,
|
|
2814
|
-
});
|
|
2815
|
-
const newItemsByGroup = new Map(sentDynamo.map((g) => [g.group, g.items]));
|
|
2816
|
-
// The rows as built, values inline: what the result is assembled from (no store I/O).
|
|
2817
|
-
const builtByGroup = new Map(newDynamo.map((g) => [g.group, g.items]));
|
|
2818
2896
|
const oldItemsByGroup = new Map(oldDynamo.map((g) => [g.group, g.items]));
|
|
2819
2897
|
// Every sk that survives anywhere in the new decomposition — an old item is
|
|
2820
2898
|
// an orphan to DELETE only if its key appears in no new group at all.
|
|
@@ -2823,88 +2901,365 @@ const makeAggregate = (schema, config) => {
|
|
|
2823
2901
|
for (const item of g.items)
|
|
2824
2902
|
survivingSks.add(skOf(item));
|
|
2825
2903
|
}
|
|
2826
|
-
// 7.
|
|
2827
|
-
|
|
2828
|
-
|
|
2904
|
+
// 7. The rows the write sends (#168, D2, design §3.3). A changed group sends the rows whose
|
|
2905
|
+
// decomposed value changed, the rows the new value adds and its `Delete`s; an unchanged row
|
|
2906
|
+
// isn't sent and keeps its `updated`. Every row of a group is sent when a context field
|
|
2907
|
+
// changed or the group's copies of one are stale (#241). Rows are matched old to new by the
|
|
2908
|
+
// sort key they compose, not by group: an item can change group without changing key.
|
|
2909
|
+
const oldBySk = new Map();
|
|
2910
|
+
oldGroups.forEach((group, g) => {
|
|
2911
|
+
group.items.forEach((item, i) => {
|
|
2912
|
+
const sk = skOf(oldDynamo[g].items[i]);
|
|
2913
|
+
oldBySk.set(sk, [...(oldBySk.get(sk) ?? []), item]);
|
|
2914
|
+
});
|
|
2915
|
+
});
|
|
2916
|
+
// Rows read under the sort key text 1.40.0 composed, which a changed group moves (#241).
|
|
2917
|
+
const movedFrom = new Set([...previousRows.values()].flat());
|
|
2918
|
+
/** The row a value was read from: by its place in the value, else at its key. */
|
|
2919
|
+
const readFrom = (item, sk) => (item.path === undefined ? undefined : readAt.get(JSON.stringify(item.path))) ??
|
|
2920
|
+
readRows.get(sk);
|
|
2921
|
+
/** Whether a new item is its row as read: one old item composes its key, alike, and was read. */
|
|
2922
|
+
const unchanged = (item, sk) => {
|
|
2923
|
+
const olds = oldBySk.get(sk);
|
|
2924
|
+
if (olds === undefined || olds.length !== 1)
|
|
2925
|
+
return false;
|
|
2926
|
+
const old = olds[0];
|
|
2927
|
+
if (old.entityType !== item.entityType || !deepEqual(old.attributes, item.attributes)) {
|
|
2928
|
+
return false;
|
|
2929
|
+
}
|
|
2930
|
+
const row = readFrom(old, sk);
|
|
2931
|
+
return row !== undefined && !(typeof row.sk === "string" && movedFrom.has(row.sk));
|
|
2932
|
+
};
|
|
2933
|
+
// Every group's name, in order: the root's first, then the new value's, then the old one's.
|
|
2934
|
+
const rootGroup = rootRead?.transactionGroup;
|
|
2935
|
+
const groupNames = [
|
|
2936
|
+
...new Set([
|
|
2937
|
+
...(rootGroup === undefined ? [] : [rootGroup]),
|
|
2938
|
+
...newGroupMap.keys(),
|
|
2939
|
+
...oldGroupMap.keys(),
|
|
2940
|
+
]),
|
|
2941
|
+
];
|
|
2942
|
+
const sentRows = [];
|
|
2943
|
+
const deletedRows = [];
|
|
2944
|
+
const changedGroups = new Set();
|
|
2945
|
+
// Each item's member path (D15): a `many` element by its sort key values.
|
|
2946
|
+
const elementKeys = new Map();
|
|
2947
|
+
for (const item of [...oldGroups, ...newGroups].flatMap((group) => group.items)) {
|
|
2948
|
+
const last = item.path?.at(-1);
|
|
2949
|
+
if (typeof last === "number" && item.elementKey !== undefined) {
|
|
2950
|
+
elementKeys.set(JSON.stringify(item.path), item.elementKey);
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
const nameOf = (item, sk) => item === undefined ? sk : memberPath(item, elementKeys);
|
|
2829
2954
|
for (const name of groupNames) {
|
|
2830
2955
|
if (!groupChanged(name))
|
|
2831
2956
|
continue;
|
|
2832
|
-
|
|
2957
|
+
changedGroups.add(name);
|
|
2958
|
+
const whole = contextChanged || stale.has(name);
|
|
2959
|
+
const g = newGroups.findIndex((group) => group.name === name);
|
|
2960
|
+
if (g >= 0) {
|
|
2961
|
+
newGroups[g].items.forEach((item, i) => {
|
|
2962
|
+
const sk = skOf(newDynamo[g].items[i]);
|
|
2963
|
+
if (!whole && unchanged(item, sk))
|
|
2964
|
+
return;
|
|
2965
|
+
sentRows.push({ group: name, g, i, item, sk });
|
|
2966
|
+
});
|
|
2967
|
+
}
|
|
2833
2968
|
// Each row once: two old items can compose one key (rows stored under two keys, #241).
|
|
2834
2969
|
const deleteSks = new Set((oldItemsByGroup.get(name) ?? [])
|
|
2835
2970
|
.map((item) => skOf(item))
|
|
2836
2971
|
.filter((sk) => !survivingSks.has(sk)));
|
|
2837
2972
|
// A row read under the text 1.40.0 composed goes in the same transaction (#241).
|
|
2838
|
-
const
|
|
2839
|
-
|
|
2840
|
-
|
|
2841
|
-
|
|
2842
|
-
|
|
2843
|
-
|
|
2844
|
-
|
|
2845
|
-
|
|
2973
|
+
for (const sk of previousRows.get(name) ?? []) {
|
|
2974
|
+
if (!survivingSks.has(sk))
|
|
2975
|
+
deleteSks.add(sk);
|
|
2976
|
+
}
|
|
2977
|
+
// Only a row read: a key nothing was read at holds nothing to delete.
|
|
2978
|
+
for (const sk of deleteSks) {
|
|
2979
|
+
if (rawBySk.has(sk)) {
|
|
2980
|
+
deletedRows.push({ group: name, sk, name: nameOf(oldBySk.get(sk)?.[0], sk) });
|
|
2981
|
+
}
|
|
2982
|
+
}
|
|
2983
|
+
}
|
|
2984
|
+
const sentSks = new Set(sentRows.map((row) => row.sk));
|
|
2985
|
+
// `EDD-9160`, judged on the rows the write sends (§3.3): an unchanged row under the other
|
|
2986
|
+
// setting's text in a changed group isn't sent, and stays for `rekey`.
|
|
2987
|
+
yield* refuseOtherSettingRows(oldGroups, (group, sk) => changedGroups.has(group) && (sentSks.has(sk) || !survivingSks.has(sk)), readAt, previousRows);
|
|
2988
|
+
// With `ownsRows`, every row of its types in the partition is the aggregate's (DESIGN.md §7
|
|
2989
|
+
// "Which rows in its partition are an aggregate's"): the rows read of each node whose
|
|
2990
|
+
// decomposition changed that the new value doesn't write are deleted too (`ownedRowsLeft`),
|
|
2991
|
+
// in the update's own transactions, each while it's gone or still as read (D10).
|
|
2992
|
+
const touched = new Set([
|
|
2993
|
+
...sentRows.map(({ group }) => group),
|
|
2994
|
+
...deletedRows.map(({ group }) => group),
|
|
2995
|
+
]);
|
|
2996
|
+
const cleanup = ownsRows
|
|
2997
|
+
? ownedRowsLeft(allItems, pkValue, oldGroups, newGroups, touched, survivingSks, deletedRows.map(({ sk }) => sk))
|
|
2998
|
+
: [];
|
|
2999
|
+
const anything = sentRows.length > 0 || deletedRows.length > 0 || cleanup.length > 0;
|
|
3000
|
+
// A versioned root moves by one on every write that sends anything (§3.5), under its token,
|
|
3001
|
+
// or a fresh one on a root written before `versioned` was turned on.
|
|
3002
|
+
const token = versionRead === undefined || !anything
|
|
3003
|
+
? undefined
|
|
3004
|
+
: (versionRead.token ?? (yield* freshIncarnationToken));
|
|
3005
|
+
const nextVersion = versionRead === undefined ? undefined : versionRead.version + 1;
|
|
3006
|
+
const rootSent = sentRows.some((row) => row.sk === rootSortKey && row.item.node === rootNode);
|
|
3007
|
+
/** A row as built, a versioned root's carrying its next version and token. */
|
|
3008
|
+
const builtOf = (row) => {
|
|
3009
|
+
const built = newDynamo[row.g].items[row.i];
|
|
3010
|
+
if (versionField === undefined || row.sk !== rootSortKey || row.item.node !== rootNode) {
|
|
3011
|
+
return built;
|
|
3012
|
+
}
|
|
3013
|
+
return {
|
|
3014
|
+
...built,
|
|
3015
|
+
[versionField]: { N: String(nextVersion) },
|
|
3016
|
+
[INCARNATION_TOKEN]: { S: token },
|
|
3017
|
+
};
|
|
3018
|
+
};
|
|
3019
|
+
// Route and upload the offloaded attributes of the rows the write sends, every one afresh
|
|
3020
|
+
// (#179, design §6.9), before the first transaction: decided on the decomposed values above,
|
|
3021
|
+
// so an unchanged row uploads nothing, and no pointer read from the partition is written
|
|
3022
|
+
// back (each sent row's values were read eagerly, and are uploaded again).
|
|
3023
|
+
const sentByGroup = new Map();
|
|
3024
|
+
for (const row of sentRows) {
|
|
3025
|
+
sentByGroup.set(row.group, [...(sentByGroup.get(row.group) ?? []), row]);
|
|
3026
|
+
}
|
|
3027
|
+
const routed = yield* routeBuiltGroups([...sentByGroup].map(([group, rows]) => ({
|
|
3028
|
+
group,
|
|
3029
|
+
items: rows.map(builtOf),
|
|
3030
|
+
written: rows.map((row) => newDynamo[row.g].written[row.i]),
|
|
3031
|
+
rows,
|
|
3032
|
+
})), offloadInfoByType, {
|
|
3033
|
+
table: tableConfig.name,
|
|
3034
|
+
pkAttribute: config.pk.field,
|
|
3035
|
+
operation: "Aggregate.update",
|
|
3036
|
+
escapeKeys: config.schema.escapeKeys === true,
|
|
3037
|
+
});
|
|
3038
|
+
// 8. The write's units (§3.1): the root's group first, then each changed group, then each
|
|
3039
|
+
// cleanup `Delete`, every item guarded (§3.2) and asking for the row as stored when its
|
|
3040
|
+
// condition fails.
|
|
3041
|
+
const tableName = tableConfig.name;
|
|
3042
|
+
const pkField = config.pk.field;
|
|
3043
|
+
const updatedPrefer = stampFields?.updatedAt ? [stampFields.updatedAt] : [];
|
|
3044
|
+
const preferFor = (entityType) => versionField !== undefined && entityType === config.root.entityType
|
|
3045
|
+
? [versionField, INCARNATION_TOKEN, ...updatedPrefer]
|
|
3046
|
+
: updatedPrefer;
|
|
3047
|
+
const absentFor = (entityType) => writableAttributes.get(entityType) ?? [];
|
|
3048
|
+
const keyAt = (sk) => toAttributeMap({ [pkField]: pkValue, sk });
|
|
3049
|
+
const typeOf = (read) => read.__edd_e__?.S ?? aggregateName;
|
|
3050
|
+
const putOf = (row, item) => {
|
|
3051
|
+
const read = rawBySk.get(row.sk);
|
|
3052
|
+
const isRoot = row.sk === rootSortKey && row.item.node === rootNode;
|
|
3053
|
+
const name = nameOf(row.item, row.sk);
|
|
3054
|
+
const expects = isRoot ? versionRead : undefined;
|
|
3055
|
+
if (read === undefined) {
|
|
3056
|
+
return {
|
|
3057
|
+
action: {
|
|
3058
|
+
Put: AggregateWrite.withAllOld({
|
|
3059
|
+
TableName: tableName,
|
|
3060
|
+
Item: item,
|
|
3061
|
+
...AggregateWrite.absentGuard(pkField),
|
|
3062
|
+
}),
|
|
3063
|
+
},
|
|
3064
|
+
role: isRoot ? "root" : "new",
|
|
3065
|
+
name,
|
|
3066
|
+
expects,
|
|
3067
|
+
};
|
|
3068
|
+
}
|
|
3069
|
+
const entityType = typeOf(read);
|
|
3070
|
+
const put = (bySize) => ({
|
|
3071
|
+
Put: AggregateWrite.withAllOld({
|
|
3072
|
+
TableName: tableName,
|
|
3073
|
+
Item: item,
|
|
3074
|
+
...AggregateWrite.rowGuard(read, pkField, preferFor(entityType), absentFor(entityType), bySize),
|
|
3075
|
+
}),
|
|
3076
|
+
});
|
|
3077
|
+
return { action: put(), role: isRoot ? "root" : "row", name, read, sized: put, expects };
|
|
3078
|
+
};
|
|
3079
|
+
const deleteOf = (row) => {
|
|
3080
|
+
const read = rawBySk.get(row.sk);
|
|
3081
|
+
const entityType = typeOf(read);
|
|
3082
|
+
const remove = (bySize) => ({
|
|
3083
|
+
Delete: AggregateWrite.withAllOld({
|
|
3084
|
+
TableName: tableName,
|
|
3085
|
+
Key: keyAt(row.sk),
|
|
3086
|
+
...AggregateWrite.rowGuard(read, pkField, preferFor(entityType), absentFor(entityType), bySize),
|
|
3087
|
+
}),
|
|
3088
|
+
});
|
|
3089
|
+
return { action: remove(), role: "row", name: row.name, read, sized: remove };
|
|
3090
|
+
};
|
|
3091
|
+
const units = [];
|
|
3092
|
+
const routedByGroup = new Map(routed.map((group) => [group.group, group]));
|
|
3093
|
+
for (const name of groupNames) {
|
|
3094
|
+
const sent = routedByGroup.get(name);
|
|
3095
|
+
const items = [
|
|
3096
|
+
...(sent === undefined ? [] : sent.rows.map((row, k) => putOf(row, sent.items[k]))),
|
|
3097
|
+
...deletedRows.filter((row) => row.group === name).map(deleteOf),
|
|
3098
|
+
];
|
|
3099
|
+
if (items.length === 0)
|
|
2846
3100
|
continue;
|
|
2847
|
-
|
|
3101
|
+
// The root first in its unit: what a request holding it is fenced by.
|
|
3102
|
+
items.sort((a, b) => Number(b.role === "root") - Number(a.role === "root"));
|
|
3103
|
+
const previous = (previousRows.get(name) ?? []).filter((sk) => !survivingSks.has(sk));
|
|
3104
|
+
units.push({
|
|
2848
3105
|
group: name,
|
|
2849
|
-
|
|
2850
|
-
deletes,
|
|
3106
|
+
items,
|
|
2851
3107
|
...(previous.length > 0 && { previous: previous.length }),
|
|
2852
3108
|
});
|
|
2853
3109
|
}
|
|
2854
|
-
//
|
|
2855
|
-
|
|
2856
|
-
|
|
2857
|
-
|
|
2858
|
-
|
|
2859
|
-
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
3110
|
+
// A versioned root not rewritten moves its version with an `Update` of the root, first (§3.4).
|
|
3111
|
+
if (versionField !== undefined && anything && !rootSent) {
|
|
3112
|
+
const condition = [
|
|
3113
|
+
"attribute_exists(#pk)",
|
|
3114
|
+
versionRead.version === 0 ? "(attribute_not_exists(#ver) OR #ver = :v)" : "#ver = :v",
|
|
3115
|
+
versionRead.token === undefined ? "attribute_not_exists(#inc)" : "#inc = :inc",
|
|
3116
|
+
].join(" AND ");
|
|
3117
|
+
const versionUpdate = {
|
|
3118
|
+
action: {
|
|
3119
|
+
Update: AggregateWrite.withAllOld({
|
|
3120
|
+
TableName: tableName,
|
|
3121
|
+
Key: keyAt(rootSortKey),
|
|
3122
|
+
UpdateExpression: "SET #ver = :v1, #inc = :inc",
|
|
3123
|
+
ConditionExpression: condition,
|
|
3124
|
+
ExpressionAttributeNames: {
|
|
3125
|
+
"#pk": pkField,
|
|
3126
|
+
"#ver": versionField,
|
|
3127
|
+
"#inc": INCARNATION_TOKEN,
|
|
3128
|
+
},
|
|
3129
|
+
ExpressionAttributeValues: {
|
|
3130
|
+
":v": { N: String(versionRead.version) },
|
|
3131
|
+
":v1": { N: String(nextVersion) },
|
|
3132
|
+
":inc": { S: token },
|
|
3133
|
+
},
|
|
3134
|
+
}),
|
|
3135
|
+
},
|
|
3136
|
+
role: "root",
|
|
3137
|
+
name: "",
|
|
3138
|
+
read: rawRoot,
|
|
3139
|
+
expects: versionRead,
|
|
3140
|
+
};
|
|
3141
|
+
const first = units.findIndex((unit) => unit.group === rootGroup);
|
|
3142
|
+
if (first >= 0) {
|
|
3143
|
+
const unit = units[first];
|
|
3144
|
+
units.splice(first, 1);
|
|
3145
|
+
units.unshift({ ...unit, items: [versionUpdate, ...unit.items] });
|
|
3146
|
+
}
|
|
3147
|
+
else {
|
|
3148
|
+
units.unshift({ group: rootGroup ?? aggregateName, items: [versionUpdate] });
|
|
3149
|
+
}
|
|
2863
3150
|
}
|
|
2864
|
-
|
|
2865
|
-
|
|
3151
|
+
for (const row of cleanup) {
|
|
3152
|
+
const read = rawBySk.get(row.sk);
|
|
3153
|
+
if (read === undefined)
|
|
3154
|
+
continue;
|
|
3155
|
+
const remove = (bySize) => ({
|
|
3156
|
+
Delete: AggregateWrite.withAllOld({
|
|
3157
|
+
TableName: tableName,
|
|
3158
|
+
Key: keyAt(row.sk),
|
|
3159
|
+
...AggregateWrite.goneOrAsReadGuard(read, pkField, preferFor(row.entityType), absentFor(row.entityType), row.entityType, bySize),
|
|
3160
|
+
}),
|
|
3161
|
+
});
|
|
3162
|
+
units.push({
|
|
3163
|
+
group: row.sk,
|
|
3164
|
+
items: [{ action: remove(), role: "cleanup", name: row.sk, read, sized: remove }],
|
|
3165
|
+
});
|
|
3166
|
+
}
|
|
3167
|
+
// The fence (§3.4) on each request without the root: the root's next version and token on a
|
|
3168
|
+
// versioned aggregate, its existence with `fence: true`, nothing otherwise.
|
|
3169
|
+
const fence = versionField !== undefined && anything
|
|
3170
|
+
? {
|
|
3171
|
+
action: {
|
|
3172
|
+
ConditionCheck: AggregateWrite.withAllOld({
|
|
3173
|
+
TableName: tableName,
|
|
3174
|
+
Key: keyAt(rootSortKey),
|
|
3175
|
+
ConditionExpression: "#ver = :v1 AND #inc = :inc",
|
|
3176
|
+
ExpressionAttributeNames: { "#ver": versionField, "#inc": INCARNATION_TOKEN },
|
|
3177
|
+
ExpressionAttributeValues: {
|
|
3178
|
+
":v1": { N: String(nextVersion) },
|
|
3179
|
+
":inc": { S: token },
|
|
3180
|
+
},
|
|
3181
|
+
}),
|
|
3182
|
+
},
|
|
3183
|
+
role: "fence",
|
|
3184
|
+
name: "",
|
|
3185
|
+
expects: { version: nextVersion, token, reported: versionRead.version },
|
|
3186
|
+
}
|
|
3187
|
+
: fenced
|
|
3188
|
+
? {
|
|
3189
|
+
action: {
|
|
3190
|
+
ConditionCheck: AggregateWrite.withAllOld({
|
|
3191
|
+
TableName: tableName,
|
|
3192
|
+
Key: keyAt(rootSortKey),
|
|
3193
|
+
ConditionExpression: "attribute_exists(#pk)",
|
|
3194
|
+
ExpressionAttributeNames: { "#pk": pkField },
|
|
3195
|
+
}),
|
|
3196
|
+
},
|
|
3197
|
+
role: "fence",
|
|
3198
|
+
name: "",
|
|
3199
|
+
}
|
|
3200
|
+
: undefined;
|
|
3201
|
+
if (anything) {
|
|
3202
|
+
yield* AggregateWrite.sendUnits(client, units, {
|
|
3203
|
+
tableName,
|
|
3204
|
+
aggregateName,
|
|
3205
|
+
keys: groupKeys,
|
|
3206
|
+
operation: "update",
|
|
3207
|
+
fence,
|
|
3208
|
+
verdict: AggregateWrite.updateVerdict({
|
|
3209
|
+
aggregateName,
|
|
3210
|
+
key,
|
|
3211
|
+
pkField,
|
|
3212
|
+
versioned: versionField === undefined
|
|
3213
|
+
? undefined
|
|
3214
|
+
: { field: versionField, read: versionRead.version },
|
|
3215
|
+
}),
|
|
3216
|
+
});
|
|
2866
3217
|
}
|
|
2867
|
-
if (!returnsStamps) {
|
|
3218
|
+
if (!returnsStamps && !(versionDeclared && anything)) {
|
|
2868
3219
|
// 1.40.0's result, the mutated state as decoded, with one change (#241): a member value's
|
|
2869
3220
|
// copy of a context attribute is what its row now holds: the root's, on a row the write
|
|
2870
|
-
// sent; what it held when read, on one it didn't.
|
|
3221
|
+
// sent; what it held when read, on one it didn't (judged per row, #168).
|
|
3222
|
+
const sentPaths = new Set(sentRows.flatMap(({ item }) => item.path === undefined ? [] : [JSON.stringify(item.path)]));
|
|
2871
3223
|
const rowsNow = new Map();
|
|
2872
3224
|
for (const group of newGroups) {
|
|
2873
|
-
const sent = groupChanged(group.name);
|
|
2874
3225
|
for (const item of group.items) {
|
|
2875
3226
|
if (item.path === undefined)
|
|
2876
3227
|
continue;
|
|
3228
|
+
const path = JSON.stringify(item.path);
|
|
2877
3229
|
let now;
|
|
2878
|
-
if (
|
|
3230
|
+
if (sentPaths.has(path))
|
|
2879
3231
|
now = { written: true };
|
|
2880
3232
|
else {
|
|
2881
|
-
// A
|
|
2882
|
-
const row = readAt.get(
|
|
3233
|
+
// A row the write didn't send holds the value it was read as.
|
|
3234
|
+
const row = readAt.get(path);
|
|
2883
3235
|
if (row !== undefined)
|
|
2884
3236
|
now = { row };
|
|
2885
3237
|
}
|
|
2886
3238
|
if (now !== undefined)
|
|
2887
|
-
rowsNow.set(
|
|
3239
|
+
rowsNow.set(path, now);
|
|
2888
3240
|
}
|
|
2889
3241
|
}
|
|
2890
3242
|
return withStoredContextCopies(decoded, (path) => rowsNow.get(JSON.stringify(path)));
|
|
2891
3243
|
}
|
|
2892
|
-
// A stamp the domain object holds: what's returned is what's stored, as `get`
|
|
2893
|
-
// and no read is needed to know that. The partition as read, with these writes
|
|
2894
|
-
// 1.40.0 assembled it.
|
|
2895
|
-
const
|
|
3244
|
+
// A stamp or a version the domain object holds: what's returned is what's stored, as `get`
|
|
3245
|
+
// would read it, and no read is needed to know that. The partition as read, with these writes
|
|
3246
|
+
// applied, as 1.40.0 assembled it.
|
|
3247
|
+
const storedNow = new Map(allItems.map((item) => [String(item.sk), item]));
|
|
2896
3248
|
for (const { sk } of cleanup)
|
|
2897
|
-
|
|
2898
|
-
for (const {
|
|
2899
|
-
|
|
2900
|
-
|
|
2901
|
-
|
|
2902
|
-
|
|
2903
|
-
|
|
2904
|
-
|
|
2905
|
-
|
|
2906
|
-
|
|
2907
|
-
|
|
3249
|
+
storedNow.delete(sk);
|
|
3250
|
+
for (const { sk } of deletedRows)
|
|
3251
|
+
storedNow.delete(sk);
|
|
3252
|
+
// The rows as built, not as sent: an offloaded value is inline there (#179).
|
|
3253
|
+
const writtenRows = sentRows.map((row) => fromAttributeMap(builtOf(row)));
|
|
3254
|
+
yield* unpackAggregateItems(writtenRows, dispatchByType, aggregateName);
|
|
3255
|
+
for (const row of writtenRows)
|
|
3256
|
+
storedNow.set(String(row.sk), row);
|
|
3257
|
+
if (versionDeclared && anything && !rootSent) {
|
|
3258
|
+
const root = storedNow.get(rootSortKey);
|
|
3259
|
+
if (root !== undefined)
|
|
3260
|
+
storedNow.set(rootSortKey, { ...root, [versionField]: nextVersion });
|
|
3261
|
+
}
|
|
3262
|
+
return (yield* assembleAggregate(assembly, rootNode, [...storedNow.values()], contextFields, key, aggregateName, systemAttrs));
|
|
2908
3263
|
});
|
|
2909
3264
|
/** How many times `rekey` reads an aggregate again after a write changed it in between. */
|
|
2910
3265
|
const REKEY_ATTEMPTS = 3;
|
|
@@ -2941,6 +3296,12 @@ const makeAggregate = (schema, config) => {
|
|
|
2941
3296
|
walk(child);
|
|
2942
3297
|
};
|
|
2943
3298
|
walk(rootNode);
|
|
3299
|
+
// A versioned root's version and incarnation token (#168): a guard checks each is as read.
|
|
3300
|
+
if (versionField !== undefined) {
|
|
3301
|
+
const root = byType.get(rootNode.entityType);
|
|
3302
|
+
root.add(versionField);
|
|
3303
|
+
root.add(INCARNATION_TOKEN);
|
|
3304
|
+
}
|
|
2944
3305
|
return new Map([...byType].map(([entityType, names]) => [entityType, [...names].sort()]));
|
|
2945
3306
|
})();
|
|
2946
3307
|
/**
|
|
@@ -3275,9 +3636,27 @@ const makeAggregate = (schema, config) => {
|
|
|
3275
3636
|
: undefined;
|
|
3276
3637
|
const itemOf = (r) => {
|
|
3277
3638
|
const row = rows[r];
|
|
3278
|
-
if (!row.custom)
|
|
3279
|
-
return built[r];
|
|
3280
3639
|
const at = row.placement === "old" ? row.old : row.current;
|
|
3640
|
+
if (!row.custom) {
|
|
3641
|
+
const item = built[r];
|
|
3642
|
+
if (versionField === undefined ||
|
|
3643
|
+
item.sk?.S !== rootSortKey ||
|
|
3644
|
+
item.__edd_e__?.S !== config.root.entityType) {
|
|
3645
|
+
return item;
|
|
3646
|
+
}
|
|
3647
|
+
// A versioned root moves with its version and incarnation token as read (#168): built
|
|
3648
|
+
// from the model, it holds the version only where the model declares it, and the
|
|
3649
|
+
// token never, so a moved root would read as version 0 and a new incarnation.
|
|
3650
|
+
const read = storedAt.get(positionOf(at.pk, at.sk)) ?? {};
|
|
3651
|
+
const held = [versionField, INCARNATION_TOKEN];
|
|
3652
|
+
const moved = Object.fromEntries(Object.entries(item).filter(([name]) => !held.includes(name)));
|
|
3653
|
+
for (const name of held) {
|
|
3654
|
+
const value = read[name];
|
|
3655
|
+
if (value !== undefined)
|
|
3656
|
+
moved[name] = value;
|
|
3657
|
+
}
|
|
3658
|
+
return moved;
|
|
3659
|
+
}
|
|
3281
3660
|
return {
|
|
3282
3661
|
...storedAt.get(positionOf(at.pk, at.sk)),
|
|
3283
3662
|
[config.pk.field]: { S: row.current.pk },
|
|
@@ -3715,6 +4094,7 @@ const makeAggregate = (schema, config) => {
|
|
|
3715
4094
|
const items = rows
|
|
3716
4095
|
.filter((item) => item[config.pk.field]?.S === pk)
|
|
3717
4096
|
.map((item) => fromAttributeMap(item));
|
|
4097
|
+
withReadVersion(items);
|
|
3718
4098
|
yield* loadAggregateItems(items, readPlans);
|
|
3719
4099
|
const assembled = yield* assembleAggregate(assembly, rootNode, items, contextFields, key, aggregateName, systemAttrs);
|
|
3720
4100
|
const groups = yield* decomposeAggregate({ ...assembled }, rootNode, contextFields, rootEncoders, aggregateName, config.schema);
|
|
@@ -3818,7 +4198,10 @@ const makeAggregate = (schema, config) => {
|
|
|
3818
4198
|
// over what the input holds for it unless the root declares it
|
|
3819
4199
|
// optional, so what's composed and returned is what's stored.
|
|
3820
4200
|
const now = yield* DateTime.now;
|
|
3821
|
-
const
|
|
4201
|
+
const stamped = fillStamps(rootNode, hydrated, now, "declared");
|
|
4202
|
+
// A versioned root starts at 1 (#168, §3.5): a version the root declares is the
|
|
4203
|
+
// library's, whatever the input holds.
|
|
4204
|
+
const written = versionDeclared ? { ...stamped, [versionField]: 1 } : stamped;
|
|
3822
4205
|
const decoded = yield* Schema.decodeUnknownEffect(writeSchema)(written).pipe(Effect.mapError((cause) => new ValidationError({
|
|
3823
4206
|
entityType: aggregateName,
|
|
3824
4207
|
operation: "aggregate.create",
|
|
@@ -3849,38 +4232,65 @@ const makeAggregate = (schema, config) => {
|
|
|
3849
4232
|
operation: "Aggregate.create",
|
|
3850
4233
|
escapeKeys: config.schema.escapeKeys === true,
|
|
3851
4234
|
});
|
|
3852
|
-
// 6. Write
|
|
3853
|
-
// the first
|
|
3854
|
-
// an existing aggregate cancels it before any edge or
|
|
3855
|
-
// row is written. Rows below the root need no guard of their own
|
|
3856
|
-
// they are only ever written after the root's
|
|
3857
|
-
|
|
3858
|
-
const
|
|
3859
|
-
const
|
|
4235
|
+
// 6. Write: every group in one transaction when they fit (#168, §3.7), else whole groups
|
|
4236
|
+
// in as few as fit, the root's first. The root item is guarded by
|
|
4237
|
+
// `attribute_not_exists` (#134): an existing aggregate cancels it before any edge or
|
|
4238
|
+
// sub-aggregate row is written. Rows below the root need no guard of their own: past one
|
|
4239
|
+
// transaction they are only ever written after the root's has committed. A versioned
|
|
4240
|
+
// root holds version 1 and a fresh incarnation token.
|
|
4241
|
+
const token = versionField === undefined ? undefined : yield* freshIncarnationToken;
|
|
4242
|
+
const isRoot = (item) => item.sk?.S === rootSortKey;
|
|
4243
|
+
const rootKey = { [config.pk.field]: pkValue, sk: rootSortKey };
|
|
4244
|
+
const units = [...sentGroups]
|
|
3860
4245
|
.sort((a, b) => Number(b.items.some(isRoot)) - Number(a.items.some(isRoot)))
|
|
3861
|
-
.map((
|
|
3862
|
-
group:
|
|
3863
|
-
|
|
3864
|
-
|
|
4246
|
+
.map((group) => ({
|
|
4247
|
+
group: group.group,
|
|
4248
|
+
items: [...group.items]
|
|
4249
|
+
.sort((a, b) => Number(isRoot(b)) - Number(isRoot(a)))
|
|
4250
|
+
.map((item) => isRoot(item)
|
|
4251
|
+
? {
|
|
4252
|
+
action: {
|
|
4253
|
+
Put: {
|
|
4254
|
+
TableName: tableConfig.name,
|
|
4255
|
+
Item: versionField === undefined
|
|
4256
|
+
? item
|
|
4257
|
+
: {
|
|
4258
|
+
...item,
|
|
4259
|
+
[versionField]: { N: "1" },
|
|
4260
|
+
[INCARNATION_TOKEN]: { S: token },
|
|
4261
|
+
},
|
|
4262
|
+
...AggregateWrite.absentGuard(config.pk.field),
|
|
4263
|
+
},
|
|
4264
|
+
},
|
|
4265
|
+
role: "root",
|
|
4266
|
+
name: "",
|
|
4267
|
+
}
|
|
4268
|
+
: {
|
|
4269
|
+
action: { Put: { TableName: tableConfig.name, Item: item } },
|
|
4270
|
+
role: "new",
|
|
4271
|
+
name: item.sk?.S ?? "",
|
|
4272
|
+
}),
|
|
3865
4273
|
}));
|
|
3866
|
-
yield*
|
|
3867
|
-
|
|
3868
|
-
|
|
3869
|
-
|
|
4274
|
+
yield* AggregateWrite.sendUnits(client, units, {
|
|
4275
|
+
tableName: tableConfig.name,
|
|
4276
|
+
aggregateName,
|
|
4277
|
+
keys: groupKeys,
|
|
4278
|
+
operation: "create",
|
|
4279
|
+
verdict: (reasons, items) => reasons.some((reason, i) => reason?.Code === "ConditionalCheckFailed" && items[i]?.role === "root")
|
|
4280
|
+
? new ConditionalCheckFailed({ entityType: config.root.entityType, key: rootKey })
|
|
4281
|
+
: undefined,
|
|
3870
4282
|
});
|
|
3871
4283
|
return decoded;
|
|
3872
4284
|
}),
|
|
3873
|
-
update: (key, mutationFn) => updateCore(key, mutationFn),
|
|
4285
|
+
update: (key, mutationFn, options) => updateCore(key, mutationFn, options),
|
|
3874
4286
|
delete: (key) => Effect.gen(function* () {
|
|
3875
|
-
|
|
3876
|
-
//
|
|
3877
|
-
//
|
|
3878
|
-
(diagnosis, original) => new DynamoValidationError({
|
|
4287
|
+
// `delete` declares no `ValidationError`: a rejected read keeps DynamoDB's own tag, its
|
|
4288
|
+
// message explained; nor a key with no value, reported as a key that finds nothing.
|
|
4289
|
+
// The caller's key is read once (#239): a second read of the partition is given its key.
|
|
4290
|
+
const read = (consistent, partition) => readPartitionRaw(key, (diagnosis, original) => new DynamoValidationError({
|
|
3879
4291
|
operation: "Query",
|
|
3880
4292
|
cause: assemblyReadCause("delete", diagnosis, original),
|
|
3881
|
-
})).pipe(
|
|
3882
|
-
// Nor a key with no value: nothing to read, reported as a key that finds nothing.
|
|
3883
|
-
Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
|
|
4293
|
+
}), consistent || partition !== undefined ? { consistent, partition } : undefined).pipe(Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
|
|
3884
4294
|
aggregate: aggregateName,
|
|
3885
4295
|
reason: String(error.cause?.message ?? error.cause),
|
|
3886
4296
|
key,
|
|
@@ -3888,15 +4298,52 @@ const makeAggregate = (schema, config) => {
|
|
|
3888
4298
|
// Only the aggregate's own rows (DESIGN.md §7 "delete"): a row of another entity type in
|
|
3889
4299
|
// its partition is an entity's or another aggregate's, and stays. Nothing is keyed by
|
|
3890
4300
|
// value, so every row of the aggregate's types is deleted, whoever wrote it.
|
|
3891
|
-
const
|
|
3892
|
-
|
|
3893
|
-
|
|
4301
|
+
const ownOf = (items) => items.filter((item) => typeof item.__edd_e__ === "string" && ownedTypes.has(item.__edd_e__));
|
|
4302
|
+
const isRootRow = (item) => item.__edd_e__ === config.root.entityType && item.sk === rootSortKey;
|
|
4303
|
+
const notFound = new AggregateAssemblyError({
|
|
4304
|
+
aggregate: aggregateName,
|
|
4305
|
+
reason: "No items found for aggregate key",
|
|
4306
|
+
key,
|
|
4307
|
+
});
|
|
4308
|
+
if (fenced) {
|
|
4309
|
+
// With the fence (#168, §3.8): the root first, so no update commits after it (each
|
|
4310
|
+
// checks the root), then one read, consistent where the collection allows, and the rest.
|
|
4311
|
+
const client = yield* Capacity.client;
|
|
4312
|
+
const tableConfig = yield* config.table.Tag;
|
|
4313
|
+
const pkValue = yield* composeOrFail("key", () => collectionPkOf(key)).pipe(Effect.catchTag("ValidationError", (error) => Effect.fail(new AggregateAssemblyError({
|
|
3894
4314
|
aggregate: aggregateName,
|
|
3895
|
-
reason:
|
|
4315
|
+
reason: String(error.cause?.message ?? error.cause),
|
|
3896
4316
|
key,
|
|
4317
|
+
}))));
|
|
4318
|
+
const removed = yield* client.deleteItem({
|
|
4319
|
+
TableName: tableConfig.name,
|
|
4320
|
+
Key: toAttributeMap({ [config.pk.field]: pkValue, sk: rootSortKey }),
|
|
4321
|
+
ReturnValues: "ALL_OLD",
|
|
3897
4322
|
});
|
|
4323
|
+
const { allItems } = yield* read(readConsistent, pkValue);
|
|
4324
|
+
const ownItems = ownOf(allItems);
|
|
4325
|
+
if (removed.Attributes === undefined && ownItems.length === 0) {
|
|
4326
|
+
return yield* notFound;
|
|
4327
|
+
}
|
|
4328
|
+
// A root found after the root was deleted is a `create` that reused the key in between:
|
|
4329
|
+
// its aggregate is left as it is, as the sweep without the fence leaves it (§3.8).
|
|
4330
|
+
if (ownItems.length > 0 && !ownItems.some(isRootRow)) {
|
|
4331
|
+
yield* deleteAllItems(client, tableConfig.name, ownItems, config.pk.field);
|
|
4332
|
+
}
|
|
4333
|
+
return;
|
|
3898
4334
|
}
|
|
4335
|
+
const { client, tableConfig, allItems, pkValue } = yield* read(false);
|
|
4336
|
+
const ownItems = ownOf(allItems);
|
|
4337
|
+
if (ownItems.length === 0)
|
|
4338
|
+
return yield* notFound;
|
|
3899
4339
|
yield* deleteAllItems(client, tableConfig.name, ownItems, config.pk.field);
|
|
4340
|
+
// Without the fence (§2.6, §3.8): one more read, consistent where the collection allows,
|
|
4341
|
+
// finds the rows a write added after the first, and deletes them, unless it finds a root:
|
|
4342
|
+
// a `create` reused the key, and its aggregate is left as it is.
|
|
4343
|
+
const swept = ownOf((yield* read(readConsistent, pkValue)).allItems);
|
|
4344
|
+
if (swept.length > 0 && !swept.some(isRootRow)) {
|
|
4345
|
+
yield* deleteAllItems(client, tableConfig.name, swept, config.pk.field);
|
|
4346
|
+
}
|
|
3900
4347
|
}),
|
|
3901
4348
|
list: (filter, options) => Effect.gen(function* () {
|
|
3902
4349
|
const client = yield* Capacity.client;
|
|
@@ -4110,7 +4557,7 @@ const withOperations = (aggregateName, ops) => {
|
|
|
4110
4557
|
// The writes are ledger roots (#179): the edge entities' uploads settle
|
|
4111
4558
|
// by the one transaction that carries them.
|
|
4112
4559
|
create: (input) => Capacity.operation("Aggregate.create", target, BlobLedger.root(ops.create(input))),
|
|
4113
|
-
update: (key, mutationFn) => Capacity.operation("Aggregate.update", target, BlobLedger.root(ops.update(key, mutationFn))),
|
|
4560
|
+
update: (key, mutationFn, options) => Capacity.operation("Aggregate.update", target, BlobLedger.root(ops.update(key, mutationFn, options))),
|
|
4114
4561
|
delete: (key) => Capacity.operation("Aggregate.delete", target, BlobLedger.root(ops.delete(key))),
|
|
4115
4562
|
list: (filter, options) => Capacity.operation("Aggregate.list", target, ops.list(filter, options)),
|
|
4116
4563
|
};
|
|
@@ -4148,7 +4595,7 @@ export const bind = (aggregate) => Effect.gen(function* () {
|
|
|
4148
4595
|
schema: aggregate.schema,
|
|
4149
4596
|
get: (key) => provide(aggregate.get(key)),
|
|
4150
4597
|
create: (input) => provide(aggregate.create(input)),
|
|
4151
|
-
update: (key, mutationFn) => provide(aggregate.update(key, mutationFn)),
|
|
4598
|
+
update: (key, mutationFn, options) => provide(aggregate.update(key, mutationFn, options)),
|
|
4152
4599
|
delete: (key) => provide(aggregate.delete(key)),
|
|
4153
4600
|
list: (filter, options) => provide(aggregate.list(filter, options)),
|
|
4154
4601
|
inputSchema: aggregate.inputSchema,
|
|
@@ -4548,6 +4995,7 @@ const resolveNode = (args) => {
|
|
|
4548
4995
|
cardinality: "one",
|
|
4549
4996
|
edges: bound.aggregate.edges,
|
|
4550
4997
|
parentFields: subFields,
|
|
4998
|
+
valueSchema: bound.aggregate.schema,
|
|
4551
4999
|
resolveRef,
|
|
4552
5000
|
discriminator: inherited,
|
|
4553
5001
|
ownDiscriminator: bound.discriminator,
|
|
@@ -5166,9 +5614,11 @@ const EMPTY_ATTRS = new Set();
|
|
|
5166
5614
|
/** The timestamps a node's rows hold beside its value: those its value doesn't declare. */
|
|
5167
5615
|
const stampsToStrip = (node, systemAttrs) => {
|
|
5168
5616
|
const own = node.ownFields;
|
|
5169
|
-
|
|
5617
|
+
const stored = node.storedNames;
|
|
5618
|
+
if (own === undefined && stored === undefined)
|
|
5170
5619
|
return systemAttrs;
|
|
5171
|
-
|
|
5620
|
+
// A value of members (a union, a suspended schema) declares a name when a member does.
|
|
5621
|
+
const kept = [...systemAttrs].filter((name) => own === undefined ? !stored.includes(name) : !Object.hasOwn(own, name));
|
|
5172
5622
|
return kept.length === systemAttrs.size ? systemAttrs : new Set(kept);
|
|
5173
5623
|
};
|
|
5174
5624
|
/**
|
|
@@ -6585,6 +7035,7 @@ path) => Effect.gen(function* () {
|
|
|
6585
7035
|
own,
|
|
6586
7036
|
...(elementInput !== undefined && { input: elementInput }),
|
|
6587
7037
|
...(node.decompose === undefined && { value: elem, path: [...path, index] }),
|
|
7038
|
+
elementKey: values.map((value) => String(value)).join("#"),
|
|
6588
7039
|
transactionGroup: parentGroup,
|
|
6589
7040
|
skComposites: [
|
|
6590
7041
|
...parentDiscriminators.current,
|
|
@@ -7071,166 +7522,6 @@ own) => groups.map((group) => {
|
|
|
7071
7522
|
});
|
|
7072
7523
|
return { group: group.name, items, written };
|
|
7073
7524
|
});
|
|
7074
|
-
function writeTransactionGroups(client, tableName, groups, aggregateName, keys, rootGuard) {
|
|
7075
|
-
return Effect.gen(function* () {
|
|
7076
|
-
// Each group is its own transaction (DynamoDB: 100 items per
|
|
7077
|
-
// TransactWriteItems, Puts AND Deletes together). DynamoDB's limits are
|
|
7078
|
-
// not pre-checked (#144): a group over one is sent, rejected whole, and
|
|
7079
|
-
// diagnosed — naming the sub-aggregates earlier groups already committed,
|
|
7080
|
-
// since a multi-group write was never atomic.
|
|
7081
|
-
const committed = [];
|
|
7082
|
-
for (const [groupIndex, group] of groups.entries()) {
|
|
7083
|
-
// Each group is one transaction — Puts AND Deletes applied atomically, so an
|
|
7084
|
-
// edge add and a sibling edge removal in the same sub-aggregate commit together.
|
|
7085
|
-
const itemCount = group.puts.length + group.deletes.length;
|
|
7086
|
-
if (itemCount === 0)
|
|
7087
|
-
continue;
|
|
7088
|
-
// The root item, in the first transaction only.
|
|
7089
|
-
const rootIndex = rootGuard !== undefined && groupIndex === 0
|
|
7090
|
-
? group.puts.findIndex((item) => item.sk?.S === rootGuard.key.sk)
|
|
7091
|
-
: -1;
|
|
7092
|
-
// Build TransactWriteItems request — Puts first, then Deletes for orphans.
|
|
7093
|
-
const transactItems = [
|
|
7094
|
-
...group.puts.map((item, i) => ({
|
|
7095
|
-
Put: {
|
|
7096
|
-
TableName: tableName,
|
|
7097
|
-
Item: item,
|
|
7098
|
-
...(rootGuard !== undefined && i === rootIndex
|
|
7099
|
-
? {
|
|
7100
|
-
ConditionExpression: "attribute_not_exists(#pk)",
|
|
7101
|
-
ExpressionAttributeNames: { "#pk": rootGuard.pkField },
|
|
7102
|
-
}
|
|
7103
|
-
: {}),
|
|
7104
|
-
},
|
|
7105
|
-
})),
|
|
7106
|
-
...group.deletes.map((key) => ({ Delete: { TableName: tableName, Key: key } })),
|
|
7107
|
-
];
|
|
7108
|
-
// Named once, for both diagnoses below.
|
|
7109
|
-
const sent = () => ({
|
|
7110
|
-
_tag: "Transaction",
|
|
7111
|
-
items: transactItems,
|
|
7112
|
-
targets: () => transactItems.map((item) => {
|
|
7113
|
-
const entityType = item.Put?.Item?.__edd_e__?.S ?? aggregateName;
|
|
7114
|
-
return transactItemTarget(item, tableName, [keys.pkField, "sk"], entityType, `the ${item.Put !== undefined ? entityType : "removed"} item of ` +
|
|
7115
|
-
`sub-aggregate "${group.group}"`);
|
|
7116
|
-
}),
|
|
7117
|
-
});
|
|
7118
|
-
const already = [...committed];
|
|
7119
|
-
const diagnosed = (diagnosis, original) => diagnosis._tag === "TooManyItems"
|
|
7120
|
-
? new AggregateTransactionOverflow({
|
|
7121
|
-
aggregate: aggregateName,
|
|
7122
|
-
subgraph: group.group,
|
|
7123
|
-
itemCount: diagnosis.count,
|
|
7124
|
-
limit: diagnosis.limit,
|
|
7125
|
-
committed: already,
|
|
7126
|
-
operation: rootGuard !== undefined ? "create" : "update",
|
|
7127
|
-
// Over only because of the rows it moves off 1.40.0's text: `rekey` moves them.
|
|
7128
|
-
...(group.previous !== undefined &&
|
|
7129
|
-
diagnosis.count - group.previous <= diagnosis.limit && {
|
|
7130
|
-
previousKeyText: group.previous,
|
|
7131
|
-
}),
|
|
7132
|
-
cause: original,
|
|
7133
|
-
})
|
|
7134
|
-
: diagnosedValidationError(diagnosis, original, {
|
|
7135
|
-
operation: `Aggregate.write(${aggregateName})`,
|
|
7136
|
-
entityType: aggregateName,
|
|
7137
|
-
// Each group commits on its own: say exactly what already did.
|
|
7138
|
-
...(already.length > 0 && {
|
|
7139
|
-
committed: `earlier transactions of this write already committed sub-aggregates ` +
|
|
7140
|
-
already.map((name) => `"${name}"`).join(", ") +
|
|
7141
|
-
(rootGuard !== undefined
|
|
7142
|
-
? ", so a retried create fails on the existing root: update or delete " +
|
|
7143
|
-
"the partial aggregate instead"
|
|
7144
|
-
: ""),
|
|
7145
|
-
}),
|
|
7146
|
-
});
|
|
7147
|
-
yield* client.transactWriteItems({ TransactItems: transactItems }).pipe(
|
|
7148
|
-
// An upload over its store's `maxUploadAge` (#179, design §6.1) refuses the group before
|
|
7149
|
-
// it is sent: say what earlier groups committed.
|
|
7150
|
-
Effect.mapError((error) => already.length === 0
|
|
7151
|
-
? error
|
|
7152
|
-
: expiredWithCommitted(error, "earlier transactions of this write already committed sub-aggregates " +
|
|
7153
|
-
already.map((name) => `"${name}"`).join(", "))),
|
|
7154
|
-
// One operation per item (#144): diagnosed BEFORE the root guard's
|
|
7155
|
-
// mapping, which would read a repeat's conditional failure as an
|
|
7156
|
-
// existing root.
|
|
7157
|
-
diagnoseFailure({ sent, only: ["RepeatedItem"], rewrite: diagnosed }), Effect.mapError((error) => {
|
|
7158
|
-
if (error.cause != null &&
|
|
7159
|
-
typeof error.cause === "object" &&
|
|
7160
|
-
"name" in error.cause &&
|
|
7161
|
-
error.cause.name === "TransactionCanceledException") {
|
|
7162
|
-
const cancelled = error.cause;
|
|
7163
|
-
const reasons = cancelled.CancellationReasons;
|
|
7164
|
-
if (rootGuard !== undefined &&
|
|
7165
|
-
rootIndex >= 0 &&
|
|
7166
|
-
reasons?.[rootIndex]?.Code === "ConditionalCheckFailed") {
|
|
7167
|
-
return new ConditionalCheckFailed({
|
|
7168
|
-
entityType: rootGuard.entityType,
|
|
7169
|
-
key: rootGuard.key,
|
|
7170
|
-
});
|
|
7171
|
-
}
|
|
7172
|
-
return new TransactionCancelled({
|
|
7173
|
-
operation: "TransactWriteItems",
|
|
7174
|
-
reasons: (cancelled.CancellationReasons ?? []).map((r) => ({
|
|
7175
|
-
code: r?.Code,
|
|
7176
|
-
message: r?.Message,
|
|
7177
|
-
})),
|
|
7178
|
-
cause: error.cause,
|
|
7179
|
-
});
|
|
7180
|
-
}
|
|
7181
|
-
return error;
|
|
7182
|
-
}),
|
|
7183
|
-
// A limit DynamoDB enforced (#144), named — after the root guard's
|
|
7184
|
-
// mapping, which a conditional failure always takes.
|
|
7185
|
-
diagnoseFailure({ sent, keys: () => keys.keys, rewrite: diagnosed }));
|
|
7186
|
-
committed.push(group.group);
|
|
7187
|
-
}
|
|
7188
|
-
});
|
|
7189
|
-
}
|
|
7190
|
-
/**
|
|
7191
|
-
* `update`'s cleanup Deletes with `ownsRows` (DESIGN.md §7 "Which rows in its partition are an
|
|
7192
|
-
* aggregate's"), sent after the update's groups have committed, up to {@link TRANSACT_WRITE_ITEMS_LIMIT} to a
|
|
7193
|
-
* request: Deletes of keys already stored reach no other limit of a transaction. Each holds while
|
|
7194
|
-
* its row is gone or still of the type read, so a row another write removed in between is fine,
|
|
7195
|
-
* and one replaced with a row of another type is left. A cancelled request is sent once more
|
|
7196
|
-
* without the Deletes whose condition failed; the mutation isn't run again and nothing is read
|
|
7197
|
-
* again. A failure is reported as a later group's is: the update's groups have committed, and the
|
|
7198
|
-
* rows it didn't delete stay until the next update of their node.
|
|
7199
|
-
*/
|
|
7200
|
-
const deleteOwnedRows = (client, tableName, pkField, rows) => Effect.gen(function* () {
|
|
7201
|
-
const deleteOf = (row) => ({
|
|
7202
|
-
Delete: {
|
|
7203
|
-
TableName: tableName,
|
|
7204
|
-
Key: toAttributeMap({ [pkField]: row.pk, sk: row.sk }),
|
|
7205
|
-
ConditionExpression: "attribute_not_exists(#pk) OR #e = :e",
|
|
7206
|
-
ExpressionAttributeNames: { "#pk": pkField, "#e": "__edd_e__" },
|
|
7207
|
-
ExpressionAttributeValues: { ":e": { S: row.entityType } },
|
|
7208
|
-
},
|
|
7209
|
-
});
|
|
7210
|
-
for (let start = 0; start < rows.length; start += TRANSACT_WRITE_ITEMS_LIMIT) {
|
|
7211
|
-
const chunk = rows.slice(start, start + TRANSACT_WRITE_ITEMS_LIMIT);
|
|
7212
|
-
const reasons = yield* client
|
|
7213
|
-
.transactWriteItems({ TransactItems: chunk.map((row) => deleteOf(row)) })
|
|
7214
|
-
.pipe(Effect.as(undefined), Effect.catch((error) => isAwsTransactionCancelled(error.cause)
|
|
7215
|
-
? Effect.succeed(error.cause.CancellationReasons ?? [])
|
|
7216
|
-
: Effect.fail(error)));
|
|
7217
|
-
if (reasons === undefined)
|
|
7218
|
-
continue;
|
|
7219
|
-
const rest = chunk.filter((_, i) => reasons[i]?.Code !== "ConditionalCheckFailed");
|
|
7220
|
-
if (rest.length === 0)
|
|
7221
|
-
continue;
|
|
7222
|
-
yield* client.transactWriteItems({ TransactItems: rest.map((row) => deleteOf(row)) }).pipe(Effect.mapError((error) => isAwsTransactionCancelled(error.cause)
|
|
7223
|
-
? new TransactionCancelled({
|
|
7224
|
-
operation: "TransactWriteItems",
|
|
7225
|
-
reasons: (error.cause.CancellationReasons ?? []).map((r) => ({
|
|
7226
|
-
code: r?.Code,
|
|
7227
|
-
message: r?.Message,
|
|
7228
|
-
})),
|
|
7229
|
-
cause: error.cause,
|
|
7230
|
-
})
|
|
7231
|
-
: error));
|
|
7232
|
-
}
|
|
7233
|
-
});
|
|
7234
7525
|
/**
|
|
7235
7526
|
* Place an aggregate's rows from the keys that hold a row (#171). Each row has
|
|
7236
7527
|
* a `current` and an `old` position. Off doesn't escape sort key text,
|
|
@@ -7512,4 +7803,39 @@ const queryListPartition = (client, tableConfig, listConfig, schema, options, ag
|
|
|
7512
7803
|
}
|
|
7513
7804
|
return { items, lastKey };
|
|
7514
7805
|
});
|
|
7806
|
+
// ---------------------------------------------------------------------------
|
|
7807
|
+
// Internal: versioned roots and member paths (#168)
|
|
7808
|
+
// ---------------------------------------------------------------------------
|
|
7809
|
+
/**
|
|
7810
|
+
* A versioned root's version and incarnation token as stored (`docs/designs/aggregate-concurrency.md`
|
|
7811
|
+
* §3.5): 0 and none on a root written before `versioned` was turned on.
|
|
7812
|
+
*/
|
|
7813
|
+
const storedRootVersion = (root, field) => {
|
|
7814
|
+
const version = root?.[field]?.N;
|
|
7815
|
+
return {
|
|
7816
|
+
version: version === undefined ? 0 : Number(version),
|
|
7817
|
+
token: root?.[INCARNATION_TOKEN]?.S,
|
|
7818
|
+
};
|
|
7819
|
+
};
|
|
7820
|
+
/**
|
|
7821
|
+
* A row's member path in the aggregate (D15): its fields from the root, a `many` element by its
|
|
7822
|
+
* sort key values (`team1.lines[b]`); `""` for the root. An element of a custom `decompose` has no
|
|
7823
|
+
* place in the value: its edge and key.
|
|
7824
|
+
*/
|
|
7825
|
+
const memberPath = (item, elementKeys) => {
|
|
7826
|
+
const path = item.path;
|
|
7827
|
+
if (path === undefined)
|
|
7828
|
+
return `${item.member}[${item.elementKey ?? ""}]`;
|
|
7829
|
+
let name = "";
|
|
7830
|
+
path.forEach((segment, j) => {
|
|
7831
|
+
if (typeof segment === "number") {
|
|
7832
|
+
const key = elementKeys.get(JSON.stringify(path.slice(0, j + 1)));
|
|
7833
|
+
name += `[${key ?? segment}]`;
|
|
7834
|
+
}
|
|
7835
|
+
else {
|
|
7836
|
+
name += name === "" ? segment : `.${segment}`;
|
|
7837
|
+
}
|
|
7838
|
+
});
|
|
7839
|
+
return name;
|
|
7840
|
+
};
|
|
7515
7841
|
//# sourceMappingURL=Aggregate.js.map
|