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
|
@@ -14,22 +14,26 @@
|
|
|
14
14
|
*
|
|
15
15
|
* @internal
|
|
16
16
|
*/
|
|
17
|
-
import { isConfiguredModel } from "@effect-dynamodb/schema/DynamoModel.js";
|
|
17
|
+
import { getEncoding, isConfiguredModel, } from "@effect-dynamodb/schema/DynamoModel.js";
|
|
18
18
|
import { ConcurrentModification, isAwsConditionalCheckFailed, isAwsTransactionCancelled, ProjectionSourceConflict, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
|
|
19
19
|
import { keyFormLiterals, keyFormValueKind, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
|
|
20
|
-
import { readingStreamValues, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
|
|
20
|
+
import { isSelfDateSchema, optionalField, readingStreamValues, resolveFieldEncoding, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
|
|
21
21
|
import { decodingAsBefore } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
|
|
22
|
+
import { ownValue, setOwn } from "@effect-dynamodb/schema/internal/OwnNames.js";
|
|
22
23
|
import { getSchemaFields } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
|
|
24
|
+
import { fnv1a64 } from "@effect-dynamodb/schema/internal/ZOrderCurve.js";
|
|
23
25
|
import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
|
|
24
|
-
import { DateTime, Duration as Dur, Effect, Option, Random, Result, Schema as S, Schedule, } from "effect";
|
|
26
|
+
import { DateTime, Duration as Dur, Effect, Equal, Option, Random, Result, Schema as S, Schedule, } from "effect";
|
|
25
27
|
import { decodeMarshalledItem } from "../Entity.js";
|
|
26
28
|
import { fromAttributeMap, toAttributeMap } from "../Marshaller.js";
|
|
27
29
|
import { resolveTtlAttributeName } from "../Table.js";
|
|
30
|
+
import { attributeValueEquals } from "./AttributeValueEquals.js";
|
|
28
31
|
import * as Capacity from "./Capacity.js";
|
|
29
32
|
import { condition as entityCondition } from "./EntityCombinators.js";
|
|
30
33
|
import { handlerOf } from "./Rekey.js";
|
|
31
34
|
import { notReadBack, readBackOf } from "./RoundTrip.js";
|
|
32
|
-
import { addProjectionLayout, OUTBOX_CLAIM as CLAIM_TOKEN, OUTBOX_CLAIMED_UNTIL as CLAIMED_UNTIL, composePrimaryKey, KEY_TEXT, marshalOrFail, projectionTtlChecked, projectionTtlConflict, OUTBOX_ROW_PK as ROW_PK, OUTBOX_ROW_SK as ROW_SK, serializeSparseOrFail, validateAndBuildPutItem, } from "./TransactableOps.js";
|
|
35
|
+
import { addProjectionLayout, andRaw, asReadTerm, OUTBOX_CLAIM as CLAIM_TOKEN, OUTBOX_CLAIMED_UNTIL as CLAIMED_UNTIL, composePrimaryKey, freshRowToken, hasProjectionTombstones, KEY_TEXT, layoutTag, marshalOrFail, OUTBOX_READ_MODEL, outboxMarkInUse, projectionLayoutsOf, projectionTtlChecked, projectionTtlConflict, OUTBOX_ROW_PK as ROW_PK, OUTBOX_ROW_SK as ROW_SK, ROW_TOKEN, rowTokened, rowTokenInUse, rowTokenTerm, rowWriters, serializeSparseOrFail, validateAndBuildPutItem, } from "./TransactableOps.js";
|
|
36
|
+
import { withCause } from "./WriteDiagnosis.js";
|
|
33
37
|
// ---------------------------------------------------------------------------
|
|
34
38
|
// Removal (#154)
|
|
35
39
|
// ---------------------------------------------------------------------------
|
|
@@ -65,18 +69,33 @@ export const tombstoneMarker = (entityType) => `${entityType}#tombstone`;
|
|
|
65
69
|
export const outboxMarker = (entityType) => `${entityType}#outbox`;
|
|
66
70
|
/** Attribute names the engine owns on tombstones and outbox items. */
|
|
67
71
|
export const REMOVED_AT = "__edd_removed__";
|
|
72
|
+
/**
|
|
73
|
+
* The term a projection keeping no revision adds to a write over a tombstone it read: the row is
|
|
74
|
+
* still a tombstone (#237).
|
|
75
|
+
*/
|
|
76
|
+
const tombstoneTerm = {
|
|
77
|
+
expression: "attribute_exists(#eddRm)",
|
|
78
|
+
names: { "#eddRm": REMOVED_AT },
|
|
79
|
+
values: {},
|
|
80
|
+
};
|
|
68
81
|
/** The engine's own lost-race signal. */
|
|
69
82
|
class LostRace {
|
|
70
83
|
key;
|
|
71
|
-
|
|
84
|
+
attributes;
|
|
85
|
+
/** `attributes`: the attributes whose change failed the write's condition (#237). */
|
|
86
|
+
constructor(key, attributes) {
|
|
72
87
|
this.key = key;
|
|
88
|
+
this.attributes = attributes;
|
|
73
89
|
}
|
|
74
90
|
}
|
|
75
91
|
// ---------------------------------------------------------------------------
|
|
76
92
|
// The engine
|
|
77
93
|
// ---------------------------------------------------------------------------
|
|
78
|
-
/**
|
|
79
|
-
|
|
94
|
+
/**
|
|
95
|
+
* A key's identity: its fields, sorted, as JSON. JSON has no bigint, so one is written as an
|
|
96
|
+
* object holding its digits, which no number or string is; any other key's text is unchanged.
|
|
97
|
+
*/
|
|
98
|
+
export const keyId = (key) => JSON.stringify(Object.entries(key).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)), (_name, value) => (typeof value === "bigint" ? { bigint: value.toString() } : value));
|
|
80
99
|
/** `K | Option<K>` → `Option<K>`. */
|
|
81
100
|
export const addressed = (key) => Option.isOption(key) ? key : Option.some(key);
|
|
82
101
|
/** A map checkpoint's key. */
|
|
@@ -90,6 +109,34 @@ export const modelFields = (model) => {
|
|
|
90
109
|
const fields = getSchemaFields(schema);
|
|
91
110
|
return fields === undefined ? undefined : Object.keys(fields);
|
|
92
111
|
};
|
|
112
|
+
/**
|
|
113
|
+
* Two decoded values alike: primitives by `Object.is`, arrays and plain records entry by entry,
|
|
114
|
+
* anything else by `Equal.equals`.
|
|
115
|
+
*/
|
|
116
|
+
const sameValue = (a, b) => {
|
|
117
|
+
if (Object.is(a, b))
|
|
118
|
+
return true;
|
|
119
|
+
if (typeof a !== "object" || typeof b !== "object" || a === null || b === null)
|
|
120
|
+
return false;
|
|
121
|
+
if (Array.isArray(a) || Array.isArray(b)) {
|
|
122
|
+
return (Array.isArray(a) &&
|
|
123
|
+
Array.isArray(b) &&
|
|
124
|
+
a.length === b.length &&
|
|
125
|
+
a.every((v, i) => sameValue(v, b[i])));
|
|
126
|
+
}
|
|
127
|
+
const plain = (v) => {
|
|
128
|
+
const proto = Object.getPrototypeOf(v);
|
|
129
|
+
return proto === Object.prototype || proto === null;
|
|
130
|
+
};
|
|
131
|
+
if (plain(a) && plain(b)) {
|
|
132
|
+
const x = a;
|
|
133
|
+
const y = b;
|
|
134
|
+
const keys = Object.keys(x);
|
|
135
|
+
return (keys.length === Object.keys(y).length &&
|
|
136
|
+
keys.every((k) => Object.hasOwn(y, k) && sameValue(x[k], y[k])));
|
|
137
|
+
}
|
|
138
|
+
return Equal.equals(a, b);
|
|
139
|
+
};
|
|
93
140
|
/**
|
|
94
141
|
* @internal The outboxes on other tables of the read model's projections (`_projectionOutboxes`,
|
|
95
142
|
* the entries with a `table`): several projections of one read model may each have one. A local
|
|
@@ -103,17 +150,30 @@ export const remoteOutboxesOf = (entity) => (entity
|
|
|
103
150
|
*/
|
|
104
151
|
export const physicalTableName = (tag) => Effect.map(Effect.serviceOption(tag), (config) => Option.isSome(config) ? config.value.name : undefined);
|
|
105
152
|
/**
|
|
106
|
-
*
|
|
107
|
-
*
|
|
108
|
-
*
|
|
109
|
-
*
|
|
110
|
-
*
|
|
111
|
-
*
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
153
|
+
* The date encoding a composite field is stored under, when the library writes its text: a
|
|
154
|
+
* `DynamoModel` date schema's own, or, for an Effect date schema the entity stores by its own
|
|
155
|
+
* encoding (`Schema.DateTimeUtc`, `Schema.Date`, `Schema.DateTimeZoned`), the default or its
|
|
156
|
+
* `storedAs` override; for an optional field, its value's. `undefined` for a field that is no date,
|
|
157
|
+
* and for a date with a codec of its own (a transform to a date, `Schema.DateTimeUtcFromString`
|
|
158
|
+
* included), whose text the library doesn't know: it may hold any text, as 1.40.0 took it.
|
|
159
|
+
*/
|
|
160
|
+
const dateEncodingOf = (field, override) => {
|
|
161
|
+
const known = (schema) => getEncoding(schema) !== undefined || isSelfDateSchema(schema);
|
|
162
|
+
if (known(field))
|
|
163
|
+
return resolveFieldEncoding(field, override) ?? undefined;
|
|
164
|
+
const inner = optionalField(field)?.inner;
|
|
165
|
+
if (inner === undefined || !known(inner))
|
|
166
|
+
return undefined;
|
|
167
|
+
return resolveFieldEncoding(inner, override) ?? undefined;
|
|
168
|
+
};
|
|
169
|
+
/**
|
|
170
|
+
* What a composite of `model` can be in the keys its rows are written under
|
|
171
|
+
* (`KeyComposer.CompositeValues`), by its schema: the key text of its literals (a literal union), of
|
|
172
|
+
* `true` and `false` (a boolean), a number's or bigint's key text, or, with `dates`, a date's the
|
|
173
|
+
* library encodes (`dateEncodingOf`: an epoch's number, or ISO text); any other field (a string, a
|
|
174
|
+
* date with a codec of its own, a field the model doesn't declare) may hold any text, `#` included.
|
|
115
175
|
*/
|
|
116
|
-
const compositeValues = (model,
|
|
176
|
+
const compositeValues = (model, dates = true) => (composite) => {
|
|
117
177
|
if (model === undefined || model === null)
|
|
118
178
|
return "open";
|
|
119
179
|
const schema = isConfiguredModel(model) ? model.model : model;
|
|
@@ -121,8 +181,21 @@ const compositeValues = (model, side) => (composite) => {
|
|
|
121
181
|
if (fields === undefined || !Object.hasOwn(fields, composite))
|
|
122
182
|
return "open";
|
|
123
183
|
const field = fields[composite];
|
|
184
|
+
if (dates) {
|
|
185
|
+
const configured = isConfiguredModel(model) ? model.attributes : undefined;
|
|
186
|
+
const date = dateEncodingOf(field, configured !== undefined && Object.hasOwn(configured, composite)
|
|
187
|
+
? configured[composite].encoding
|
|
188
|
+
: undefined);
|
|
189
|
+
if (date !== undefined) {
|
|
190
|
+
return date.storage !== "string"
|
|
191
|
+
? "number"
|
|
192
|
+
: date.domain === "DateTime.Zoned"
|
|
193
|
+
? "zonedDate"
|
|
194
|
+
: "date";
|
|
195
|
+
}
|
|
196
|
+
}
|
|
124
197
|
const literals = keyFormLiterals(field);
|
|
125
|
-
if (
|
|
198
|
+
if (literals !== undefined)
|
|
126
199
|
return { values: literals };
|
|
127
200
|
const kind = keyFormValueKind(field);
|
|
128
201
|
if (kind === "number" || kind === "bigint")
|
|
@@ -139,9 +212,10 @@ const compositeValues = (model, side) => (composite) => {
|
|
|
139
212
|
* composite's name. Each value is what its type can compose (`compositeValues`), by `view`:
|
|
140
213
|
*
|
|
141
214
|
* - `"plain"`, the keys its rows are written under with values that hold no `#`: every composite is
|
|
142
|
-
* walked, to the end of the key, under the schema's setting.
|
|
143
|
-
*
|
|
144
|
-
*
|
|
215
|
+
* walked, to the end of the key, under the schema's setting. `"plain140"` is the same, a date
|
|
216
|
+
* taken as any text without `#`, as 1.40.0 took it.
|
|
217
|
+
* - `"owned"`, exactly the keys its rows can be written under, under any setting: every composite
|
|
218
|
+
* is walked, to the end of the key, a value that may hold `#` as any text.
|
|
145
219
|
*
|
|
146
220
|
* `undefined` for an entity on no table.
|
|
147
221
|
*/
|
|
@@ -151,14 +225,15 @@ const keySpaceOf = (entity, view) => {
|
|
|
151
225
|
if (member._schema === undefined || member.entityType === undefined || primary === undefined) {
|
|
152
226
|
return undefined;
|
|
153
227
|
}
|
|
154
|
-
const values = compositeValues(member.model, view
|
|
228
|
+
const values = compositeValues(member.model, view !== "plain140");
|
|
229
|
+
const plain = view === "plain" || view === "plain140";
|
|
155
230
|
try {
|
|
156
|
-
return KeyComposer.composeKeySpace(member._schema, member.entityType, member._entityVersion ?? 1, primary,
|
|
231
|
+
return KeyComposer.composeKeySpace(member._schema, member.entityType, member._entityVersion ?? 1, primary, plain
|
|
157
232
|
? (composite) => {
|
|
158
233
|
const of = values(composite);
|
|
159
234
|
return of === "open" ? "text" : of;
|
|
160
235
|
}
|
|
161
|
-
: values, { everyForm:
|
|
236
|
+
: values, { everyForm: !plain, walkOpen: !plain });
|
|
162
237
|
}
|
|
163
238
|
catch {
|
|
164
239
|
return undefined;
|
|
@@ -183,24 +258,32 @@ const outboxSpaceOf = (space) => {
|
|
|
183
258
|
/** Whether a key of one key space can be a key of the other, in both halves. */
|
|
184
259
|
const spacesMeet = (a, b) => KeyComposer.keySpacesMeet(a.pk, b.pk) && KeyComposer.keySpacesMeet(a.sk, b.sk);
|
|
185
260
|
/**
|
|
186
|
-
* Whether
|
|
187
|
-
*
|
|
188
|
-
* (`"
|
|
261
|
+
* Whether two read models' outbox items can overwrite each other, as `DynamoClient.make` and
|
|
262
|
+
* `processBatch` ask (`"plain"`): a key of one can be a key of the other with values that hold no
|
|
263
|
+
* `#`. A date's key text is its own (`"plain"`), so a date beside a label it can't spell is apart,
|
|
264
|
+
* where 1.40.0 took a date as any text (`"plain140"`) and refused them. Such a pair is apart only
|
|
265
|
+
* when no key one writes can be a key the other writes at all (`"owned"`), `#` included: a drainer
|
|
266
|
+
* tells its own items from the other's by that (`drainPending`), so each delivers exactly its own.
|
|
267
|
+
* Otherwise they're refused, as on 1.40.0.
|
|
189
268
|
*/
|
|
190
|
-
const
|
|
191
|
-
const meet = (
|
|
192
|
-
const
|
|
193
|
-
const
|
|
194
|
-
return
|
|
195
|
-
read !== undefined &&
|
|
196
|
-
spacesMeet(outboxSpaceOf(written), outboxSpaceOf(read)));
|
|
269
|
+
const overwriteEachOther = (a, b) => {
|
|
270
|
+
const meet = (view) => {
|
|
271
|
+
const x = keySpaceOf(a, view);
|
|
272
|
+
const y = keySpaceOf(b, view);
|
|
273
|
+
return x !== undefined && y !== undefined && spacesMeet(outboxSpaceOf(x), outboxSpaceOf(y));
|
|
197
274
|
};
|
|
198
|
-
|
|
275
|
+
if (meet("plain"))
|
|
276
|
+
return true;
|
|
277
|
+
return meet("plain140") && meet("owned");
|
|
199
278
|
};
|
|
200
279
|
/**
|
|
201
280
|
* Whether two entities compose every key the same way: one schema (name, version, casing,
|
|
202
281
|
* `escapeKeys`), entity type and version, primary key composites, casing and collection, and each
|
|
203
|
-
* composite of one
|
|
282
|
+
* composite of one kind of key text (a string, a number, a bigint or a boolean), whether or not one
|
|
283
|
+
* of them is limited to literals: a reader reads a literal composite as any value of its kind, and
|
|
284
|
+
* its key form composes that value as one of its kind (a literal union beside a string moves an
|
|
285
|
+
* item where the string's would, as on 1.39.0). A composite of no one kind takes the same type on
|
|
286
|
+
* both. Then either one's reader moves a row as the other's would.
|
|
204
287
|
*/
|
|
205
288
|
const sameKeys = (a, b) => {
|
|
206
289
|
const x = a;
|
|
@@ -220,7 +303,8 @@ const sameKeys = (a, b) => {
|
|
|
220
303
|
if (fields === undefined || !Object.hasOwn(fields, composite))
|
|
221
304
|
return undefined;
|
|
222
305
|
const field = fields[composite];
|
|
223
|
-
|
|
306
|
+
const kind = keyFormValueKind(field);
|
|
307
|
+
return kind !== undefined ? kind : JSON.stringify([kind, keyFormLiterals(field)]);
|
|
224
308
|
};
|
|
225
309
|
const same = (u, v) => u.length === v.length && u.every((name, i) => name === v[i]);
|
|
226
310
|
return (x.entityType === y.entityType &&
|
|
@@ -245,27 +329,31 @@ const sameKeys = (a, b) => {
|
|
|
245
329
|
* has its outbox too. Tables are compared by the physical name the context resolves (two handles
|
|
246
330
|
* on one table are one table), and by service when one isn't provided. The problem, or `undefined`.
|
|
247
331
|
*
|
|
248
|
-
*
|
|
332
|
+
* One question ({@link overwriteEachOther}): can a key of one be a key of the other with values
|
|
333
|
+
* that hold no `#`, each value what its type can compose? Then their items overwrite each other
|
|
334
|
+
* whenever their values match, in normal operation, and no one can tell whose an item is. Read
|
|
335
|
+
* models whose keys meet only through a value holding `#` bind and run, as on 1.39.0, as do two
|
|
336
|
+
* whose keys part where a value of one can't hold the other's text (a number beside a label):
|
|
337
|
+
* `drainPending` and `rekey` tell their items apart item by item ({@link outboxOwnership},
|
|
338
|
+
* {@link rekeyOutboxMember}). It is asked where, by `scope`:
|
|
249
339
|
*
|
|
250
|
-
* - `"plain"
|
|
251
|
-
*
|
|
252
|
-
*
|
|
253
|
-
*
|
|
254
|
-
*
|
|
255
|
-
* beside a label).
|
|
256
|
-
* - a table (`rekey` of it): can `rekey` read an item of one as the other's at all, a string value
|
|
257
|
-
* holding `#` included, and a literal composite read as any text, as its reader reads it? Then it
|
|
258
|
-
* couldn't tell whose an item on that table is. Only outboxes on that table are looked at. The
|
|
259
|
-
* table's own members (`scope.members`) are looked at too: an entity claims the outbox items of
|
|
260
|
-
* its entity type on its table (its own projections' outbox there), so one that can read a read
|
|
261
|
-
* model's items as its own would move them by its key. One whose keys are composed exactly as
|
|
340
|
+
* - `"plain"`: where read models are bound (`DynamoClient.make`, `EventStore.processBatch`).
|
|
341
|
+
* - a table (`rekey` of it), for projections defined since the client was made, whose outboxes
|
|
342
|
+
* are recorded only when they are: only outboxes on that table are looked at. The table's own
|
|
343
|
+
* members (`scope.members`) are looked at too: an entity claims the outbox items of its entity
|
|
344
|
+
* type on its table (its own projections' outbox there). One whose keys are composed exactly as
|
|
262
345
|
* the read model's (`sameKeys`) moves them where the read model would, and isn't refused.
|
|
263
346
|
*
|
|
347
|
+
* 1.40.0 asked `rekey` more: whether its reader could read an item of one as the other's at all, a
|
|
348
|
+
* value holding `#` included. Those pairs aren't refused from 1.41.0: `rekey` decides each item.
|
|
349
|
+
*
|
|
264
350
|
* Read models that never meet at a site that sees several at once can't be checked: their key
|
|
265
|
-
* spaces must be kept apart by whoever defines them.
|
|
351
|
+
* spaces must be kept apart by whoever defines them. Neither can a member that is no read model (a
|
|
352
|
+
* projection object built by hand, carrying its routes but no read model): it runs as on 1.39.0.
|
|
266
353
|
*/
|
|
267
|
-
export const sharedOutboxKeySpace = (site,
|
|
354
|
+
export const sharedOutboxKeySpace = (site, given, scope) => Effect.gen(function* () {
|
|
268
355
|
const plain = scope === "plain";
|
|
356
|
+
const members = given.filter(([, entity]) => typeof entity === "object" && entity !== null);
|
|
269
357
|
// Every table a member's outbox is on, by its physical name.
|
|
270
358
|
const names = new Map();
|
|
271
359
|
for (const [, entity] of members) {
|
|
@@ -284,7 +372,7 @@ export const sharedOutboxKeySpace = (site, members, scope) => Effect.gen(functio
|
|
|
284
372
|
const startOf = (space) => `(partition keys starting "${space.pk.text}", sort keys starting "${space.sk.text}": the ` +
|
|
285
373
|
"same schema name and version, primary collection, entity type and first composite)";
|
|
286
374
|
for (const [name, entity] of members) {
|
|
287
|
-
const space = keySpaceOf(entity,
|
|
375
|
+
const space = keySpaceOf(entity, "plain");
|
|
288
376
|
if (space === undefined)
|
|
289
377
|
continue;
|
|
290
378
|
for (const outbox of remoteOutboxesOf(entity)) {
|
|
@@ -297,23 +385,13 @@ export const sharedOutboxKeySpace = (site, members, scope) => Effect.gen(functio
|
|
|
297
385
|
continue;
|
|
298
386
|
if (!remoteOutboxesOf(other).some((o) => oneTable(o.table.Tag, into)))
|
|
299
387
|
continue;
|
|
300
|
-
if (
|
|
301
|
-
const otherSpace = keySpaceOf(other, "plain");
|
|
302
|
-
if (otherSpace === undefined ||
|
|
303
|
-
!spacesMeet(outboxSpaceOf(space), outboxSpaceOf(otherSpace))) {
|
|
304
|
-
continue;
|
|
305
|
-
}
|
|
306
|
-
}
|
|
307
|
-
else if (!readAsEachOther(entity, other))
|
|
388
|
+
if (!overwriteEachOther(entity, other))
|
|
308
389
|
continue;
|
|
309
390
|
return (`[EDD-9134] ${site}: ${name} writes its projection's outbox items into another ` +
|
|
310
391
|
`table${physical === undefined ? "" : ` ("${physical}")`}, where ${otherName} ` +
|
|
311
392
|
`writes its own under the same key space ${startOf(space)}. ` +
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
"couldn't tell whose an item is. "
|
|
315
|
-
: "rekey reads an item's key back by its key space, and couldn't tell whose an " +
|
|
316
|
-
"item on this table is. ") +
|
|
393
|
+
"Their items would overwrite each other whenever their keys match, and rekey " +
|
|
394
|
+
"couldn't tell whose an item is. " +
|
|
317
395
|
"Give one of them its own entity type, collection, schema or key composites.");
|
|
318
396
|
}
|
|
319
397
|
if (plain)
|
|
@@ -323,15 +401,15 @@ export const sharedOutboxKeySpace = (site, members, scope) => Effect.gen(functio
|
|
|
323
401
|
if (member === entity)
|
|
324
402
|
continue;
|
|
325
403
|
const claims = handlerOf(member)?.types.includes(`${readModelType(entity)}#outbox`);
|
|
326
|
-
if (claims !== true || sameKeys(member, entity) || !
|
|
404
|
+
if (claims !== true || sameKeys(member, entity) || !overwriteEachOther(entity, member)) {
|
|
327
405
|
continue;
|
|
328
406
|
}
|
|
329
407
|
return (`[EDD-9134] ${site}: ${name} writes its projection's outbox items into another ` +
|
|
330
408
|
`table${physical === undefined ? "" : ` ("${physical}")`}, whose member ` +
|
|
331
|
-
`${memberName}
|
|
332
|
-
`space ${startOf(space)}, and composes its keys differently.
|
|
333
|
-
"
|
|
334
|
-
"one of them its own entity type, collection, schema or key composites.");
|
|
409
|
+
`${memberName} writes the outbox items of its entity type there under the same key ` +
|
|
410
|
+
`space ${startOf(space)}, and composes its keys differently. Their items would ` +
|
|
411
|
+
"overwrite each other whenever their keys match, and rekey couldn't tell whose an " +
|
|
412
|
+
"item is. Give one of them its own entity type, collection, schema or key composites.");
|
|
335
413
|
}
|
|
336
414
|
}
|
|
337
415
|
}
|
|
@@ -339,6 +417,250 @@ export const sharedOutboxKeySpace = (site, members, scope) => Effect.gen(functio
|
|
|
339
417
|
});
|
|
340
418
|
/** An entity's type, as its rows' `__edd_e__` names it. */
|
|
341
419
|
const readModelType = (entity) => entity.entityType;
|
|
420
|
+
/**
|
|
421
|
+
* @internal The tag a read model's outbox items carry (`OUTBOX_READ_MODEL`, #237): a hash of what
|
|
422
|
+
* its rows' keys are composed from: the schema's name and version, the entity type and its
|
|
423
|
+
* version, the primary collection and the primary key's composites. Not the key text's setting
|
|
424
|
+
* (`escapeKeys`, casing), which `rekey` moves items across, nor a composite's type, which can
|
|
425
|
+
* change with the key text staying. `undefined` for an entity on no table.
|
|
426
|
+
*/
|
|
427
|
+
export const readModelTag = (entity) => {
|
|
428
|
+
const member = entity;
|
|
429
|
+
const primary = member.indexes?.primary;
|
|
430
|
+
if (member._schema === undefined || member.entityType === undefined || primary === undefined) {
|
|
431
|
+
return undefined;
|
|
432
|
+
}
|
|
433
|
+
let hash = 0x811c9dc5;
|
|
434
|
+
const text = JSON.stringify([
|
|
435
|
+
member._schema.name,
|
|
436
|
+
member._schema.version,
|
|
437
|
+
member.entityType,
|
|
438
|
+
member._entityVersion ?? 1,
|
|
439
|
+
primary.collection ?? null,
|
|
440
|
+
primary.pk.composite,
|
|
441
|
+
primary.sk.composite,
|
|
442
|
+
]);
|
|
443
|
+
for (let i = 0; i < text.length; i++) {
|
|
444
|
+
hash ^= text.charCodeAt(i);
|
|
445
|
+
hash = Math.imul(hash, 0x01000193) >>> 0;
|
|
446
|
+
}
|
|
447
|
+
return hash.toString(36);
|
|
448
|
+
};
|
|
449
|
+
/**
|
|
450
|
+
* @internal The mark an outbox item carries (`OUTBOX_READ_MODEL`, #237): the read model's tag
|
|
451
|
+
* (`readModelTag`), then the effect's, a 64-bit FNV-1a hash of the projection (`layoutTag`) and
|
|
452
|
+
* the event (its source, stream id and version). An item's `Put` replaces only an item carrying
|
|
453
|
+
* the same mark (`writeRow`): a redelivery or retry of the same effect. Any other item at its key,
|
|
454
|
+
* another projection's of the read model, another event's of the projection (its revision started
|
|
455
|
+
* again after its row was lost), or another read model's, is kept, and the item written beside it.
|
|
456
|
+
*/
|
|
457
|
+
export const outboxMark = (readModel, projection, event) => `${readModel}.${fnv1a64(new TextEncoder().encode(JSON.stringify([projection, event.source, String(event.streamId), event.version]))).toString(36)}`;
|
|
458
|
+
/** The read model an outbox item's mark names: its text before the first `.` (`outboxMark`). */
|
|
459
|
+
const markedReadModel = (mark) => {
|
|
460
|
+
const dot = mark.indexOf(".");
|
|
461
|
+
return dot < 0 ? mark : mark.slice(0, dot);
|
|
462
|
+
};
|
|
463
|
+
/**
|
|
464
|
+
* Read models whose projections write outbox items, by the service key of the table they write
|
|
465
|
+
* them to, and each read model's projections with an outbox (`layoutTag`), as they are defined.
|
|
466
|
+
*/
|
|
467
|
+
const outboxWriters = new Map();
|
|
468
|
+
const outboxProjections = new WeakMap();
|
|
469
|
+
/** The service keys of the tables a read model's projections write outbox items to. */
|
|
470
|
+
const outboxTablesOf = (readModel) => {
|
|
471
|
+
const member = readModel;
|
|
472
|
+
return (member._projectionOutboxes ?? []).map((outbox) => (outbox.table?.Tag ?? member._tableTag)?.key);
|
|
473
|
+
};
|
|
474
|
+
/**
|
|
475
|
+
* @internal Whether no other read model defined writes outbox items whose keys can be this read
|
|
476
|
+
* model's (#237), decided from the definitions: on each table its outboxes are on, every other
|
|
477
|
+
* read model with an outbox there (another key template, `readModelTag`) composes keys that can
|
|
478
|
+
* never be this one's (`keySpaceOf`, `"owned"`: any value, `#` included). Then an item without a
|
|
479
|
+
* mark at a key this read model writes was written by this read model before 1.41.0, and a `Put`
|
|
480
|
+
* of the same event replaces it, as 1.40.0's did (`writeRow`). `false` where a key space can't be
|
|
481
|
+
* composed or a table isn't known.
|
|
482
|
+
*/
|
|
483
|
+
export const outboxKeysApart = (readModel) => {
|
|
484
|
+
const own = keySpaceOf(readModel, "owned");
|
|
485
|
+
const tag = readModelTag(readModel);
|
|
486
|
+
if (own === undefined || tag === undefined)
|
|
487
|
+
return false;
|
|
488
|
+
const mine = outboxSpaceOf(own);
|
|
489
|
+
for (const table of outboxTablesOf(readModel)) {
|
|
490
|
+
if (table === undefined)
|
|
491
|
+
return false;
|
|
492
|
+
for (const other of outboxWriters.get(table) ?? []) {
|
|
493
|
+
if (other === readModel || readModelTag(other) === tag)
|
|
494
|
+
continue;
|
|
495
|
+
const space = keySpaceOf(other, "owned");
|
|
496
|
+
if (space === undefined || spacesMeet(mine, outboxSpaceOf(space)))
|
|
497
|
+
return false;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
return true;
|
|
501
|
+
};
|
|
502
|
+
const ownershipOf = new WeakMap();
|
|
503
|
+
/**
|
|
504
|
+
* @internal Whose an outbox item is, as `readModel` sees it (#237): the one decision `drainPending`
|
|
505
|
+
* and the outbox table's `rekey` make. The row it names (`__edd_row_pk__`, `__edd_row_sk__`) must
|
|
506
|
+
* have a key the read model's composer writes, under any setting, for values of its composites'
|
|
507
|
+
* kinds (`keySpaceOf`, `"owned"`: a date the library encodes as its text, a number's key text, a
|
|
508
|
+
* literal's, a string as any text, `#` included): what its reader would take (a date or a literal
|
|
509
|
+
* as any text) isn't enough. Then:
|
|
510
|
+
*
|
|
511
|
+
* - `"mine"`: the item names this read model (`OUTBOX_READ_MODEL`, from 1.41.0).
|
|
512
|
+
* - `"foreign"`: it names another, or its row's key is no key this read model writes.
|
|
513
|
+
* - `"unmarked"`: written before 1.41.0, at a key this read model writes, which another read model
|
|
514
|
+
* may write too (`[shop]` with `north#branch_b1` beside `[shop, branch]`). `drainPending` drains
|
|
515
|
+
* it, as 1.40.0 did; `rekey` asks the other read models on the table.
|
|
516
|
+
*
|
|
517
|
+
* Every key is taken as the read model's when its key space can't be composed.
|
|
518
|
+
*/
|
|
519
|
+
export const outboxOwnership = (readModel) => {
|
|
520
|
+
const known = ownershipOf.get(readModel);
|
|
521
|
+
if (known !== undefined)
|
|
522
|
+
return known;
|
|
523
|
+
const tag = readModelTag(readModel);
|
|
524
|
+
const space = keySpaceOf(readModel, "owned");
|
|
525
|
+
const whole = (text) => ({ text, after: [], open: false });
|
|
526
|
+
const decide = (item) => {
|
|
527
|
+
const pk = item[ROW_PK]?.S;
|
|
528
|
+
const sk = item[ROW_SK]?.S;
|
|
529
|
+
if (space !== undefined) {
|
|
530
|
+
if (pk === undefined || sk === undefined)
|
|
531
|
+
return "foreign";
|
|
532
|
+
if (!spacesMeet(space, { pk: whole(pk), sk: whole(sk) }))
|
|
533
|
+
return "foreign";
|
|
534
|
+
}
|
|
535
|
+
// A read model whose items carry no mark reads none (`outboxMarkInUse`): `__edd_rm__` is
|
|
536
|
+
// something else's there.
|
|
537
|
+
const marked = outboxMarkInUse(readModel) ? item[OUTBOX_READ_MODEL]?.S : undefined;
|
|
538
|
+
if (marked === undefined)
|
|
539
|
+
return "unmarked";
|
|
540
|
+
return markedReadModel(marked) === tag ? "mine" : "foreign";
|
|
541
|
+
};
|
|
542
|
+
ownershipOf.set(readModel, decide);
|
|
543
|
+
return decide;
|
|
544
|
+
};
|
|
545
|
+
/**
|
|
546
|
+
* @internal `rekey`'s one member for the outbox items of `entityType` on a table (#237): it decides
|
|
547
|
+
* whose an item is among `candidates` (registration order), and that read model moves it.
|
|
548
|
+
*
|
|
549
|
+
* - The item names its read model (`OUTBOX_READ_MODEL`), or its row's key is a key only some of
|
|
550
|
+
* them write: {@link outboxOwnership}, the one decision `drainPending` makes too. Those that can
|
|
551
|
+
* have written it and read its key back are its possible owners. None: `unregistered` when it
|
|
552
|
+
* names a read model none of them is, else `unrecognizedKey`.
|
|
553
|
+
* - One, or several moving it to one key (or each finding it current): the first moves it, with
|
|
554
|
+
* no extra read.
|
|
555
|
+
* - Otherwise, an item written before 1.41.0 at a key more than one writes, which they'd move
|
|
556
|
+
* apart: the row it names is read from each one's table (strongly consistent), at that key and
|
|
557
|
+
* at the key that read model would move it to. It is the read model's whose own row is there
|
|
558
|
+
* (`_ownsRow`: its values compose that key) when exactly one finds one and none finds a row
|
|
559
|
+
* tombstone. Otherwise it's left where it is, `ambiguousOwner` with the reason
|
|
560
|
+
* ({@link RekeyAmbiguity}), and a rerun reads and leaves it again.
|
|
561
|
+
*/
|
|
562
|
+
export const rekeyOutboxMember = (entityType, candidates) => ({
|
|
563
|
+
name: entityType,
|
|
564
|
+
types: [`${entityType}#outbox`],
|
|
565
|
+
exclusive: true,
|
|
566
|
+
row: (row, ctx) => Effect.gen(function* () {
|
|
567
|
+
const marked = row[OUTBOX_READ_MODEL]?.S;
|
|
568
|
+
const owners = candidates.flatMap((candidate) => {
|
|
569
|
+
if (outboxOwnership(candidate.readModel)(row) === "foreign")
|
|
570
|
+
return [];
|
|
571
|
+
const keys = candidate.keys(row);
|
|
572
|
+
const plan = candidate.readModel._valuelessMove(row, keys);
|
|
573
|
+
return plan === undefined ? [] : [{ candidate, keys, plan }];
|
|
574
|
+
});
|
|
575
|
+
if (owners.length === 0) {
|
|
576
|
+
const named = marked !== undefined &&
|
|
577
|
+
!candidates.some((c) => readModelTag(c.readModel) === markedReadModel(marked));
|
|
578
|
+
return { skipped: { [named ? "unregistered" : "unrecognizedKey"]: 1 } };
|
|
579
|
+
}
|
|
580
|
+
const first = owners[0];
|
|
581
|
+
const where = (plan) => plan === "current" ? "current" : JSON.stringify(plan.to);
|
|
582
|
+
if (owners.every((owner) => where(owner.plan) === where(first.plan))) {
|
|
583
|
+
return yield* first.candidate.readModel._rekeyProjectionRow(row, ctx, first.keys);
|
|
584
|
+
}
|
|
585
|
+
// Written before 1.41.0 at a key more than one of them writes, and they'd move it apart.
|
|
586
|
+
const stored = {
|
|
587
|
+
[first.keys.pk]: row[first.keys.pk]?.S,
|
|
588
|
+
[first.keys.sk]: row[first.keys.sk]?.S,
|
|
589
|
+
};
|
|
590
|
+
const rowAt = { pk: row[ROW_PK]?.S ?? "", sk: row[ROW_SK]?.S ?? "" };
|
|
591
|
+
const client = yield* Capacity.client;
|
|
592
|
+
const reads = new Map();
|
|
593
|
+
const found = [];
|
|
594
|
+
for (const { candidate, plan } of owners) {
|
|
595
|
+
const { readModel } = candidate;
|
|
596
|
+
const primary = readModel.indexes.primary;
|
|
597
|
+
const tableName = yield* physicalTableName(readModel._tableTag);
|
|
598
|
+
if (tableName === undefined || primary === undefined) {
|
|
599
|
+
found.push("unprovided");
|
|
600
|
+
continue;
|
|
601
|
+
}
|
|
602
|
+
// Where the row is, then where it would be: a move of it in between is seen at the second.
|
|
603
|
+
const at = plan !== "current" && (plan.rowTo.pk !== rowAt.pk || plan.rowTo.sk !== rowAt.sk)
|
|
604
|
+
? [rowAt, plan.rowTo]
|
|
605
|
+
: [rowAt];
|
|
606
|
+
let result = "none";
|
|
607
|
+
for (const key of at) {
|
|
608
|
+
const id = JSON.stringify([tableName, primary.pk.field, key.pk, primary.sk.field, key.sk]);
|
|
609
|
+
if (!reads.has(id)) {
|
|
610
|
+
const { Item } = yield* client.getItem({
|
|
611
|
+
TableName: tableName,
|
|
612
|
+
Key: toAttributeMap({ [primary.pk.field]: key.pk, [primary.sk.field]: key.sk }),
|
|
613
|
+
ConsistentRead: true,
|
|
614
|
+
});
|
|
615
|
+
reads.set(id, Item);
|
|
616
|
+
}
|
|
617
|
+
const there = reads.get(id);
|
|
618
|
+
const type = there?.__edd_e__?.S;
|
|
619
|
+
if (there === undefined)
|
|
620
|
+
continue;
|
|
621
|
+
if (type === `${entityType}#tombstone`)
|
|
622
|
+
result = "tombstone";
|
|
623
|
+
else if (type === entityType && readModel._ownsRow(there) && result === "none") {
|
|
624
|
+
result = "own";
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
found.push(result);
|
|
628
|
+
}
|
|
629
|
+
const own = found.flatMap((result, i) => (result === "own" ? [owners[i]] : []));
|
|
630
|
+
if (found.every((result) => result !== "tombstone" && result !== "unprovided")) {
|
|
631
|
+
if (own.length === 1) {
|
|
632
|
+
const { candidate, keys } = own[0];
|
|
633
|
+
return yield* candidate.readModel._rekeyProjectionRow(row, ctx, keys);
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
const targets = [
|
|
637
|
+
...new Map(owners.map(({ plan }) => {
|
|
638
|
+
const target = plan === "current" ? stored : plan.to;
|
|
639
|
+
return [JSON.stringify(target), target];
|
|
640
|
+
})).values(),
|
|
641
|
+
];
|
|
642
|
+
const rowText = `the row it names (${JSON.stringify(rowAt.pk)}, ${JSON.stringify(rowAt.sk)})`;
|
|
643
|
+
const gone = own.length === 0 && found.every((result) => result === "none");
|
|
644
|
+
const ambiguity = {
|
|
645
|
+
member: entityType,
|
|
646
|
+
key: stored,
|
|
647
|
+
targets,
|
|
648
|
+
reason: gone ? "rowGone" : "unsettled",
|
|
649
|
+
message: `${owners.length} read models of entity type "${entityType}" whose outboxes share this ` +
|
|
650
|
+
"table can each have written it, and would move it to different keys; it was written " +
|
|
651
|
+
"before 1.41.0, so it doesn't name its read model. " +
|
|
652
|
+
(gone
|
|
653
|
+
? `None of them has ${rowText}, at that key or where it would move it.`
|
|
654
|
+
: found.includes("unprovided")
|
|
655
|
+
? `The table of one of them isn't provided where rekey runs, so ${rowText} can't be read there.`
|
|
656
|
+
: found.includes("tombstone")
|
|
657
|
+
? `A row tombstone is at ${rowText}: it holds no values to say whose it is.`
|
|
658
|
+
: `More than one of them has a row of its own at ${rowText}.`) +
|
|
659
|
+
" It's left where it is.",
|
|
660
|
+
};
|
|
661
|
+
return { skipped: { ambiguousOwner: 1 }, ambiguous: [ambiguity] };
|
|
662
|
+
}),
|
|
663
|
+
});
|
|
342
664
|
/**
|
|
343
665
|
* @internal `[EDD-9134]` ({@link sharedOutboxKeySpace}) as a defect, from the sites that define
|
|
344
666
|
* what runs (`DynamoClient.make`, `EventStore.processBatch`), before anything runs.
|
|
@@ -402,12 +724,24 @@ export const makeEngine = (config) => {
|
|
|
402
724
|
// `removal`, for the checks of `[EDD-9133]`. Rows may be tombstones (#154) when one has
|
|
403
725
|
// `removal`: the entity's `create` takes one's place, keeping the checkpoints of the projection
|
|
404
726
|
// with `removal` that wrote it, with its revision one higher (`overTombstone`).
|
|
405
|
-
|
|
727
|
+
const ownLayout = {
|
|
406
728
|
label: config.label,
|
|
407
729
|
roles,
|
|
408
730
|
removal: config.removal !== undefined,
|
|
409
731
|
ttl: config.removal?.ttl !== undefined,
|
|
410
|
-
}
|
|
732
|
+
};
|
|
733
|
+
addProjectionLayout(readModel, ownLayout);
|
|
734
|
+
/**
|
|
735
|
+
* This projection's tag (`layoutTag`), in its outbox items' marks (`outboxMark`) and in a row
|
|
736
|
+
* token.
|
|
737
|
+
*/
|
|
738
|
+
const ownTag = layoutTag(ownLayout);
|
|
739
|
+
/** This projection's roles, by stored name. */
|
|
740
|
+
const ownRoles = new Map();
|
|
741
|
+
for (const [field, role] of roles) {
|
|
742
|
+
const name = dbName(field);
|
|
743
|
+
ownRoles.set(name, (ownRoles.get(name) ?? new Set()).add(role));
|
|
744
|
+
}
|
|
411
745
|
// Every projection's outbox, kept on the read model, one entry per distinct layout, the one defined
|
|
412
746
|
// last at the end: a second projection doesn't hide the first's, which stays callable, and one
|
|
413
747
|
// defined again adds nothing. One on another table (`table`) is moved by that table's `rekey`
|
|
@@ -432,12 +766,30 @@ export const makeEngine = (config) => {
|
|
|
432
766
|
...(holder._projectionOutboxes ?? []).filter((other) => !same(other)),
|
|
433
767
|
layout,
|
|
434
768
|
];
|
|
769
|
+
// Where its items are, beside the other read models', for `outboxKeysApart`; and that the
|
|
770
|
+
// read model has this projection with an outbox.
|
|
771
|
+
const into = (config.outbox.table?.Tag ?? readModel._tableTag)
|
|
772
|
+
?.key;
|
|
773
|
+
if (into !== undefined) {
|
|
774
|
+
const writers = outboxWriters.get(into) ?? new Set();
|
|
775
|
+
writers.add(readModel);
|
|
776
|
+
outboxWriters.set(into, writers);
|
|
777
|
+
}
|
|
778
|
+
const projections = outboxProjections.get(readModel) ?? new Set();
|
|
779
|
+
projections.add(ownTag);
|
|
780
|
+
outboxProjections.set(readModel, projections);
|
|
435
781
|
}
|
|
436
782
|
const tableName = Effect.suspend(() => Effect.map(readModel._tableTag, (tc) => tc.name));
|
|
783
|
+
/**
|
|
784
|
+
* Whether the read model's rows may carry the row token (`rowTokenInUse`, #237): decided from
|
|
785
|
+
* the definitions and the table's TTL attribute, never from a stored row.
|
|
786
|
+
*/
|
|
787
|
+
const tokenInUse = Effect.suspend(() => Effect.map(readModel._tableTag, (tc) => rowTokenInUse(readModel, resolveTtlAttributeName(tc))));
|
|
437
788
|
/** The row, read strongly consistent — raw, so a tombstone reads as one. */
|
|
438
789
|
const readRow = (key) => Effect.gen(function* () {
|
|
439
790
|
const client = yield* Capacity.client;
|
|
440
791
|
const TableName = yield* tableName;
|
|
792
|
+
const inUse = yield* tokenInUse;
|
|
441
793
|
const { Item: item } = yield* client.getItem({
|
|
442
794
|
TableName,
|
|
443
795
|
Key: toAttributeMap(composePrimaryKey(readModel, key)),
|
|
@@ -445,28 +797,31 @@ export const makeEngine = (config) => {
|
|
|
445
797
|
});
|
|
446
798
|
if (item === undefined)
|
|
447
799
|
return Option.none();
|
|
800
|
+
const token = inUse && Object.hasOwn(item, ROW_TOKEN) ? item[ROW_TOKEN] : undefined;
|
|
448
801
|
if (item.__edd_e__?.S === tombstoneMarker(entityType)) {
|
|
449
802
|
const raw = fromAttributeMap(item);
|
|
450
803
|
const values = {};
|
|
451
804
|
for (const f of keptFields) {
|
|
452
|
-
const v = raw
|
|
805
|
+
const v = ownValue(raw, dbName(f));
|
|
453
806
|
if (v !== undefined)
|
|
454
807
|
values[f] = v;
|
|
455
808
|
}
|
|
456
|
-
return Option.some({ values, tombstone: true, createdAt: undefined });
|
|
809
|
+
return Option.some({ values, tombstone: true, createdAt: undefined, item, token });
|
|
457
810
|
}
|
|
458
811
|
const decoded = (yield* decodeMarshalledItem(readModel, item));
|
|
459
812
|
let values = decoded;
|
|
460
813
|
if (fields !== undefined) {
|
|
461
814
|
values = {};
|
|
462
815
|
for (const f of fields)
|
|
463
|
-
if (decoded
|
|
464
|
-
values[f] = decoded
|
|
816
|
+
if (ownValue(decoded, f) !== undefined)
|
|
817
|
+
values[f] = ownValue(decoded, f);
|
|
465
818
|
}
|
|
466
819
|
return Option.some({
|
|
467
820
|
values: readModel._attachPrototype?.(values) ?? values,
|
|
468
821
|
tombstone: false,
|
|
469
|
-
createdAt: createdAtField === null ? undefined : decoded
|
|
822
|
+
createdAt: createdAtField === null ? undefined : ownValue(decoded, createdAtField),
|
|
823
|
+
item,
|
|
824
|
+
token,
|
|
470
825
|
});
|
|
471
826
|
});
|
|
472
827
|
/**
|
|
@@ -479,20 +834,20 @@ export const makeEngine = (config) => {
|
|
|
479
834
|
const values = Option.isSome(row) ? row.value.values : undefined;
|
|
480
835
|
const layout = config.checkpoints;
|
|
481
836
|
if (layout.kind === "scalar") {
|
|
482
|
-
const v = values
|
|
837
|
+
const v = ownValue(values, layout.field);
|
|
483
838
|
return { kind: "scalar", at: v === undefined ? 0 : Number(v) - layout.offset };
|
|
484
839
|
}
|
|
485
840
|
const mapped = layout.fields[source];
|
|
486
841
|
const fromMap = () => {
|
|
487
|
-
const map = (values
|
|
842
|
+
const map = (ownValue(values, layout.map) ?? {});
|
|
488
843
|
const v = map[instanceKey(source, streamIdStr)];
|
|
489
844
|
return { kind: "map", at: v === undefined ? 0 : Number(v) };
|
|
490
845
|
};
|
|
491
846
|
if (mapped === undefined)
|
|
492
847
|
return fromMap();
|
|
493
|
-
const stored = values
|
|
848
|
+
const stored = ownValue(values, mapped.instanceField);
|
|
494
849
|
const owner = claimed.get(source) ?? (stored === null || stored === "" ? undefined : stored);
|
|
495
|
-
const scalar = values
|
|
850
|
+
const scalar = ownValue(values, mapped.field);
|
|
496
851
|
const at = scalar === undefined ? 0 : Number(scalar) - mapped.offset;
|
|
497
852
|
// No owner recorded: a new row, or a legacy one — adopted by this instance.
|
|
498
853
|
if (owner === undefined && !adopt)
|
|
@@ -514,7 +869,7 @@ export const makeEngine = (config) => {
|
|
|
514
869
|
const revisionOf = (row) => {
|
|
515
870
|
if (config.revision === undefined || Option.isNone(row))
|
|
516
871
|
return undefined;
|
|
517
|
-
const v = row.value.values
|
|
872
|
+
const v = ownValue(row.value.values, config.revision.field);
|
|
518
873
|
return v === undefined ? undefined : Number(v);
|
|
519
874
|
};
|
|
520
875
|
/** The revision the next write stores: one higher, or `initial` for a row without one. */
|
|
@@ -533,15 +888,16 @@ export const makeEngine = (config) => {
|
|
|
533
888
|
else {
|
|
534
889
|
// Carry every field the layout owns over from the row, then advance.
|
|
535
890
|
for (const f of Object.values(layout.fields)) {
|
|
536
|
-
if (target
|
|
537
|
-
target[f.field] = previous
|
|
538
|
-
if (target
|
|
539
|
-
|
|
891
|
+
if (ownValue(target, f.field) === undefined && ownValue(previous, f.field) !== undefined)
|
|
892
|
+
target[f.field] = ownValue(previous, f.field);
|
|
893
|
+
if (ownValue(target, f.instanceField) === undefined &&
|
|
894
|
+
ownValue(previous, f.instanceField) !== undefined) {
|
|
895
|
+
target[f.instanceField] = ownValue(previous, f.instanceField);
|
|
540
896
|
}
|
|
541
897
|
}
|
|
542
898
|
const map = layout.map === undefined
|
|
543
899
|
? {}
|
|
544
|
-
: { ...(previous
|
|
900
|
+
: { ...(ownValue(previous, layout.map) ?? {}) };
|
|
545
901
|
for (const a of advanced) {
|
|
546
902
|
if (a.slot.kind === "field") {
|
|
547
903
|
const mapped = layout.fields[a.source];
|
|
@@ -553,7 +909,7 @@ export const makeEngine = (config) => {
|
|
|
553
909
|
}
|
|
554
910
|
// An empty map stays absent on a row that had none.
|
|
555
911
|
if (layout.map !== undefined &&
|
|
556
|
-
(Object.keys(map).length > 0 || previous
|
|
912
|
+
(Object.keys(map).length > 0 || ownValue(previous, layout.map) !== undefined))
|
|
557
913
|
target[layout.map] = map;
|
|
558
914
|
}
|
|
559
915
|
if (config.revision !== undefined)
|
|
@@ -589,7 +945,7 @@ export const makeEngine = (config) => {
|
|
|
589
945
|
},
|
|
590
946
|
};
|
|
591
947
|
}
|
|
592
|
-
const stored = row.value.values
|
|
948
|
+
const stored = ownValue(row.value.values, layout.field);
|
|
593
949
|
// A row written before the projection: no checkpoint yet.
|
|
594
950
|
if (stored === undefined) {
|
|
595
951
|
return {
|
|
@@ -624,7 +980,28 @@ export const makeEngine = (config) => {
|
|
|
624
980
|
const outboxReadBack = config.outbox === undefined
|
|
625
981
|
? undefined
|
|
626
982
|
: readBackOf(config.outbox.schema, () => readingStreamValues(config.outbox.schema));
|
|
627
|
-
|
|
983
|
+
/** The tag of this read model's key template (`readModelTag`), its items' marks begin with. */
|
|
984
|
+
const outboxTag = readModelTag(readModel);
|
|
985
|
+
/**
|
|
986
|
+
* The stages of this read model's outbox items, decided from the definitions (#237). Its items
|
|
987
|
+
* carry no mark where the name is something else's (`outboxMarkInUse`). An item without a mark
|
|
988
|
+
* at its key (written before 1.41.0) is its own only where no other read model's keys can be its
|
|
989
|
+
* own (`outboxKeysApart`) and no other projection of it writes outbox items (an item records
|
|
990
|
+
* its event, not its projection): then the same event's is replaced, as on 1.40.0, after the
|
|
991
|
+
* plain `Put` is cancelled. Anywhere else it is kept, and the item written beside it.
|
|
992
|
+
*/
|
|
993
|
+
const outboxStages = () => {
|
|
994
|
+
if (outboxTag === undefined || !outboxMarkInUse(readModel))
|
|
995
|
+
return ["none"];
|
|
996
|
+
return outboxKeysApart(readModel) && (outboxProjections.get(readModel)?.size ?? 0) <= 1
|
|
997
|
+
? ["plain", "sameEvent", "beside"]
|
|
998
|
+
: ["plain", "beside"];
|
|
999
|
+
};
|
|
1000
|
+
/**
|
|
1001
|
+
* The outbox items to write with the row, each at `<row sk>#outbox#<revision>#<n>`, or, at the
|
|
1002
|
+
* stage `"beside"`, at that key followed by `#<mark>` ({@link writeRow}).
|
|
1003
|
+
*/
|
|
1004
|
+
const outboxItems = (rowKey, revision, enqueued, mark, stageOf) => Effect.forEach(enqueued, (e, i) => Effect.gen(function* () {
|
|
628
1005
|
const outbox = config.outbox;
|
|
629
1006
|
const encoded = yield* S.encodeUnknownEffect(writingTuplePositions(outbox.schema))(e.effect).pipe(Effect.tap((wire) => outboxReadBack === undefined
|
|
630
1007
|
? Effect.void
|
|
@@ -632,13 +1009,23 @@ export const makeEngine = (config) => {
|
|
|
632
1009
|
const keys = outboxKeys();
|
|
633
1010
|
const rowPk = String(rowKey[primary.pk.field]);
|
|
634
1011
|
const rowSk = String(rowKey[primary.sk.field]);
|
|
635
|
-
const
|
|
1012
|
+
const stage = stageOf(i);
|
|
1013
|
+
const marked = stage === "none"
|
|
1014
|
+
? undefined
|
|
1015
|
+
: outboxMark(outboxTag, ownTag, {
|
|
1016
|
+
source: e.source,
|
|
1017
|
+
streamId: e.event.streamId,
|
|
1018
|
+
version: e.event.version,
|
|
1019
|
+
});
|
|
1020
|
+
const at = `${rowSk}#outbox#${pad(revision, 12)}#${pad(i, 4)}`;
|
|
1021
|
+
const sk = stage === "beside" ? `${at}#${marked}` : at;
|
|
636
1022
|
const item = {
|
|
637
1023
|
[keys.pk]: rowPk,
|
|
638
1024
|
[keys.sk]: sk,
|
|
639
1025
|
__edd_e__: outboxMarker(entityType),
|
|
640
1026
|
[ROW_PK]: rowPk,
|
|
641
1027
|
[ROW_SK]: rowSk,
|
|
1028
|
+
...(marked !== undefined && { [OUTBOX_READ_MODEL]: marked }),
|
|
642
1029
|
effect: encoded,
|
|
643
1030
|
source: e.source,
|
|
644
1031
|
streamId: e.event.streamId,
|
|
@@ -652,20 +1039,182 @@ export const makeEngine = (config) => {
|
|
|
652
1039
|
}
|
|
653
1040
|
return yield* marshalOrFail(entityType, `${config.label}.outbox`, () => toAttributeMap(item));
|
|
654
1041
|
}));
|
|
655
|
-
/**
|
|
656
|
-
const
|
|
1042
|
+
/** The guard's attribute, as a lost race has named it since 1.39.0: the field, by its name. */
|
|
1043
|
+
const guardLabel = config.revision?.field ?? config.checkpoints.field;
|
|
1044
|
+
/**
|
|
1045
|
+
* The item as stored when the row's write failed its condition, from a write that asked for it
|
|
1046
|
+
* (`ReturnValuesOnConditionCheckFailure: "ALL_OLD"`): none when the row is gone.
|
|
1047
|
+
*/
|
|
1048
|
+
const storedOf = (error, transaction) => {
|
|
657
1049
|
const cause = error?.cause;
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
1050
|
+
return Option.fromNullishOr(transaction ? cause?.CancellationReasons?.[0]?.Item : cause?.Item);
|
|
1051
|
+
};
|
|
1052
|
+
/**
|
|
1053
|
+
* The attributes whose change failed a write's condition (#237): the guard (the revision or
|
|
1054
|
+
* checkpoint read, named by its field), the row token read, that the row is still the tombstone
|
|
1055
|
+
* read. Told apart
|
|
1056
|
+
* from `current`, the item as stored when it failed (none: the row is gone); without it (a
|
|
1057
|
+
* write that didn't ask, sending what 1.40.0 did), every part that could have failed.
|
|
1058
|
+
*/
|
|
1059
|
+
const changedOf = (guardRaw, token, tokenTerm, held, readItem, overRead, current) => {
|
|
1060
|
+
const name = guardRaw.names["#g"];
|
|
1061
|
+
const parts = [
|
|
1062
|
+
[
|
|
1063
|
+
guardLabel,
|
|
1064
|
+
(item) => guardRaw.values[":g"] === undefined
|
|
1065
|
+
? item?.[name] === undefined
|
|
1066
|
+
: item?.[name] !== undefined &&
|
|
1067
|
+
attributeValueEquals(item[name], guardRaw.values[":g"]),
|
|
1068
|
+
],
|
|
1069
|
+
];
|
|
1070
|
+
if (tokenTerm !== undefined) {
|
|
1071
|
+
parts.push([
|
|
1072
|
+
ROW_TOKEN,
|
|
1073
|
+
(item) => token === undefined
|
|
1074
|
+
? item?.[ROW_TOKEN] === undefined
|
|
1075
|
+
: item?.[ROW_TOKEN] !== undefined && attributeValueEquals(item[ROW_TOKEN], token),
|
|
1076
|
+
]);
|
|
1077
|
+
}
|
|
1078
|
+
for (const [field, stored] of held) {
|
|
1079
|
+
const was = readItem !== undefined && Object.hasOwn(readItem, stored) ? readItem[stored] : undefined;
|
|
1080
|
+
parts.push([
|
|
1081
|
+
field,
|
|
1082
|
+
(item) => was === undefined
|
|
1083
|
+
? item?.[stored] === undefined
|
|
1084
|
+
: item?.[stored] !== undefined && attributeValueEquals(item[stored], was),
|
|
1085
|
+
]);
|
|
1086
|
+
}
|
|
1087
|
+
if (overRead !== undefined)
|
|
1088
|
+
parts.push([REMOVED_AT, (item) => item?.[REMOVED_AT] !== undefined]);
|
|
1089
|
+
if (current === undefined)
|
|
1090
|
+
return parts.map(([part]) => part);
|
|
1091
|
+
const item = Option.getOrUndefined(current);
|
|
1092
|
+
const changed = parts.filter(([, holds]) => !holds(item)).map(([part]) => part);
|
|
1093
|
+
return changed.length > 0 ? changed : parts.map(([part]) => part);
|
|
1094
|
+
};
|
|
1095
|
+
/** A lost race, from a single write's failure: the row's Put cancelled. */
|
|
1096
|
+
const lostRaceOf = (error) => isAwsConditionalCheckFailed(error?.cause);
|
|
1097
|
+
/**
|
|
1098
|
+
* The condition an outbox item's `Put` carries at `stage` (#237, `outboxStages`): nothing at its
|
|
1099
|
+
* key, or the item of the same effect (`outboxMark`); at `"sameEvent"`, also an item without a
|
|
1100
|
+
* mark of the same event (its `source`, `streamId` and `version`, as 1.40.0 stored them). None
|
|
1101
|
+
* at `"none"`. Another item cancels the write instead of being replaced ({@link writeRow}).
|
|
1102
|
+
*/
|
|
1103
|
+
const outboxGuard = (pk, Item, stage) => {
|
|
1104
|
+
if (stage === "none")
|
|
1105
|
+
return {};
|
|
1106
|
+
const rm = Item[OUTBOX_READ_MODEL];
|
|
1107
|
+
if (stage !== "sameEvent") {
|
|
1108
|
+
return {
|
|
1109
|
+
ConditionExpression: "attribute_not_exists(#pk) OR #rm = :rm",
|
|
1110
|
+
ExpressionAttributeNames: { "#pk": pk, "#rm": OUTBOX_READ_MODEL },
|
|
1111
|
+
ExpressionAttributeValues: { ":rm": rm },
|
|
1112
|
+
};
|
|
1113
|
+
}
|
|
1114
|
+
return {
|
|
1115
|
+
ConditionExpression: "attribute_not_exists(#pk) OR #rm = :rm OR " +
|
|
1116
|
+
"(attribute_not_exists(#rm) AND #es = :es AND #ei = :ei AND #ev = :ev)",
|
|
1117
|
+
ExpressionAttributeNames: {
|
|
1118
|
+
"#pk": pk,
|
|
1119
|
+
"#rm": OUTBOX_READ_MODEL,
|
|
1120
|
+
"#es": "source",
|
|
1121
|
+
"#ei": "streamId",
|
|
1122
|
+
"#ev": "version",
|
|
1123
|
+
},
|
|
1124
|
+
ExpressionAttributeValues: {
|
|
1125
|
+
":rm": rm,
|
|
1126
|
+
":es": Item.source,
|
|
1127
|
+
":ei": Item.streamId,
|
|
1128
|
+
":ev": Item.version,
|
|
1129
|
+
},
|
|
1130
|
+
};
|
|
1131
|
+
};
|
|
1132
|
+
/**
|
|
1133
|
+
* The projections a row token records after a write storing `written` (domain fields) over a
|
|
1134
|
+
* row whose token was `read` (#237): this one, each other that had written it and whose
|
|
1135
|
+
* bookkeeping the write still holds, and those this program doesn't define, kept as they are. A
|
|
1136
|
+
* write that drops a projection's bookkeeping (a rebuild, a write that drops another's data)
|
|
1137
|
+
* drops its tag, so the token describes the row as it is.
|
|
1138
|
+
*/
|
|
1139
|
+
const writersAfter = (read, written) => {
|
|
1140
|
+
const known = new Map();
|
|
1141
|
+
for (const layout of projectionLayoutsOf(readModel) ?? [])
|
|
1142
|
+
known.set(layoutTag(layout), layout);
|
|
1143
|
+
const out = [ownTag];
|
|
1144
|
+
for (const tag of rowWriters(read)) {
|
|
1145
|
+
if (tag === ownTag)
|
|
1146
|
+
continue;
|
|
1147
|
+
const layout = known.get(tag);
|
|
1148
|
+
if (layout === undefined || layout.roles.some(([field]) => written[field] !== undefined)) {
|
|
1149
|
+
out.push(tag);
|
|
1150
|
+
}
|
|
1151
|
+
}
|
|
1152
|
+
return out;
|
|
1153
|
+
};
|
|
1154
|
+
/**
|
|
1155
|
+
* Every projection's bookkeeping attribute on the read model (each field and its stored name,
|
|
1156
|
+
* once), but the one `guardRaw` already names: what proves a row read without a row token is
|
|
1157
|
+
* as read (`asReadTerm`, #237).
|
|
1158
|
+
*/
|
|
1159
|
+
const heldBookkeeping = (guardRaw) => {
|
|
1160
|
+
const seen = new Set([guardRaw.names["#g"]]);
|
|
1161
|
+
const out = [];
|
|
1162
|
+
for (const layout of projectionLayoutsOf(readModel) ?? []) {
|
|
1163
|
+
for (const [field] of layout.roles) {
|
|
1164
|
+
const stored = dbName(field);
|
|
1165
|
+
if (seen.has(stored))
|
|
1166
|
+
continue;
|
|
1167
|
+
seen.add(stored);
|
|
1168
|
+
out.push([field, stored]);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return out;
|
|
662
1172
|
};
|
|
663
1173
|
/** The row (or tombstone) and any outbox items, written as one conditional unit. */
|
|
664
|
-
const writeRow = (key, target, kept, row, enqueued, revision) => Effect.gen(function* () {
|
|
1174
|
+
const writeRow = (key, target, kept, row, enqueued, revision, carried = {}) => Effect.gen(function* () {
|
|
665
1175
|
const client = yield* Capacity.client;
|
|
666
1176
|
const TableName = yield* tableName;
|
|
667
1177
|
const rowKey = composePrimaryKey(readModel, key);
|
|
668
1178
|
const condition = guard(row);
|
|
1179
|
+
// On a read model whose rows carry the row token (#237), or on a row that holds one (a
|
|
1180
|
+
// program defining only this projection writes it too, so it never replaces another's write
|
|
1181
|
+
// landed since its read), a fresh one recording the projections whose bookkeeping the row
|
|
1182
|
+
// holds after this write (`writersAfter`), and the term naming the one read. Where the
|
|
1183
|
+
// token's name is taken (`rowTokenInUse`), none: the write sends what 1.40.0 did.
|
|
1184
|
+
const read = Option.isSome(row) ? row.value.token : undefined;
|
|
1185
|
+
const tokened = (yield* tokenInUse) && (rowTokened(readModel) || read !== undefined);
|
|
1186
|
+
const token = tokened
|
|
1187
|
+
? yield* freshRowToken(writersAfter(read, Option.isSome(target) ? target.value : { ...kept, ...carried }))
|
|
1188
|
+
: undefined;
|
|
1189
|
+
// A row read without a token, where rows carry one, was last written by a process still on
|
|
1190
|
+
// 1.40.0 (which writes none) or before the token: the term names every projection's
|
|
1191
|
+
// bookkeeping as read too (`asReadTerm`), which each of their writes changes, so this write
|
|
1192
|
+
// never replaces one landed since its read, whichever library made it (#237).
|
|
1193
|
+
const held = tokened && read === undefined && Option.isSome(row) ? heldBookkeeping(condition.raw) : [];
|
|
1194
|
+
const tokenTerm = !tokened
|
|
1195
|
+
? undefined
|
|
1196
|
+
: Option.isSome(row)
|
|
1197
|
+
? asReadTerm(readModel, row.value.item, held.map(([, stored]) => stored), true)
|
|
1198
|
+
: rowTokenTerm(undefined);
|
|
1199
|
+
// A row read without a token, a tombstone, names it: `create` over it keeps the checkpoints,
|
|
1200
|
+
// which alone would let this write replace the row the `create` wrote (#237). With one
|
|
1201
|
+
// projection keeping a revision, `create` changes it, and the write sends what 1.40.0 did.
|
|
1202
|
+
const overRead = Option.isSome(row) &&
|
|
1203
|
+
row.value.tombstone &&
|
|
1204
|
+
read === undefined &&
|
|
1205
|
+
(tokened || config.revision === undefined)
|
|
1206
|
+
? tombstoneTerm
|
|
1207
|
+
: undefined;
|
|
1208
|
+
const term = andRaw(tokenTerm, overRead);
|
|
1209
|
+
// A write naming the row token asks for the item as stored when its condition fails
|
|
1210
|
+
// (`returnOld`), so the failure names what changed; a write without one sends what 1.40.0
|
|
1211
|
+
// did (#237).
|
|
1212
|
+
const returnOld = tokenTerm !== undefined;
|
|
1213
|
+
const failed = (current) => changedOf(condition.raw, read, tokenTerm, held, Option.isSome(row) ? row.value.item : undefined, overRead, current);
|
|
1214
|
+
// A write for a row read absent, on a read model whose rows may be tombstones, proves the
|
|
1215
|
+
// key still holds nothing, as the transaction's put does: `create` never takes the place
|
|
1216
|
+
// of a tombstone written since, which 1.39.0 and 1.40.0 replaced, the removal lost (#237).
|
|
1217
|
+
const absent = Option.isNone(row) && hasProjectionTombstones(readModel);
|
|
669
1218
|
const createdAt = Option.isSome(row) ? row.value.createdAt : undefined;
|
|
670
1219
|
// A tombstone or outbox item holds no values, so its key alone says which text it is for
|
|
671
1220
|
// `rekey` (`KEY_TEXT`): one under the text of `escapeKeys: true`, where that isn't off's, is
|
|
@@ -691,10 +1240,18 @@ export const makeEngine = (config) => {
|
|
|
691
1240
|
// A sparse-map key is refused as the row's own write refuses it. The check flattens a
|
|
692
1241
|
// copy: what's stored is the tombstone as 1.39.0 stored it, an empty map whole.
|
|
693
1242
|
yield* serializeSparseOrFail(readModel, { ...tomb }, `${config.label}.write`);
|
|
1243
|
+
// The other projections' bookkeeping, stored as the tombstone stores its own (natively,
|
|
1244
|
+
// a map whole), where `readRow` reads it.
|
|
1245
|
+
for (const [f, v] of Object.entries(carried))
|
|
1246
|
+
tomb[dbName(f)] = v;
|
|
1247
|
+
if (token !== undefined)
|
|
1248
|
+
tomb[ROW_TOKEN] = token;
|
|
694
1249
|
rowItem = yield* marshalOrFail(entityType, `${config.label}.write`, () => toAttributeMap(tomb));
|
|
695
1250
|
}
|
|
696
1251
|
else if (enqueued.length > 0) {
|
|
697
1252
|
const built = yield* validateAndBuildPutItem(readModel, target.value, `${config.label}.write`, { createdAt: DateTime.isDateTime(createdAt) ? DateTime.toUtc(createdAt) : undefined });
|
|
1253
|
+
if (token !== undefined)
|
|
1254
|
+
built.item[ROW_TOKEN] = token;
|
|
698
1255
|
rowItem = toAttributeMap(built.item);
|
|
699
1256
|
}
|
|
700
1257
|
if (rowItem === undefined) {
|
|
@@ -704,45 +1261,122 @@ export const makeEngine = (config) => {
|
|
|
704
1261
|
const op = condition.input === undefined
|
|
705
1262
|
? readModel.create(value)
|
|
706
1263
|
: entityCondition(readModel.put(value), condition.input);
|
|
707
|
-
|
|
1264
|
+
// With a row token the entity writes it, and adds the token's term (without one, the
|
|
1265
|
+
// tombstone's); a `create` for a row read absent never takes a tombstone's place.
|
|
1266
|
+
const run = condition.input === undefined && token === undefined && overRead === undefined && !absent
|
|
708
1267
|
? op.asEffect()
|
|
709
1268
|
: op._builder("model", {
|
|
710
1269
|
condition: op._condition,
|
|
711
1270
|
withVectors: op._withVectors,
|
|
712
1271
|
putKind: op._putKind,
|
|
713
1272
|
createdAt: DateTime.isDateTime(createdAt) ? DateTime.toUtc(createdAt) : undefined,
|
|
1273
|
+
...((token !== undefined || overRead !== undefined || absent) && {
|
|
1274
|
+
projectionWrite: {
|
|
1275
|
+
attributes: token === undefined ? {} : { [ROW_TOKEN]: token },
|
|
1276
|
+
condition: Option.isSome(row) ? term : undefined,
|
|
1277
|
+
expectAbsent: Option.isNone(row),
|
|
1278
|
+
returnOld: returnOld && Option.isSome(row),
|
|
1279
|
+
},
|
|
1280
|
+
}),
|
|
714
1281
|
});
|
|
715
|
-
const written = yield* run.pipe(Effect.catchTag("ConditionalCheckFailed", () => Effect.fail(new LostRace(key
|
|
1282
|
+
const written = yield* run.pipe(Effect.catchTag("ConditionalCheckFailed", (error) => Effect.fail(new LostRace(key,
|
|
1283
|
+
// A `create` for a row read absent: the condition is that it still is.
|
|
1284
|
+
Option.isNone(row)
|
|
1285
|
+
? [guardLabel]
|
|
1286
|
+
: failed(error.current)))));
|
|
716
1287
|
return Option.some(written);
|
|
717
1288
|
}
|
|
718
|
-
const lostRace = (error
|
|
1289
|
+
const lostRace = (error) => Effect.fail(lostRaceOf(error)
|
|
1290
|
+
? new LostRace(key, failed(returnOld ? storedOf(error, false) : undefined))
|
|
1291
|
+
: error);
|
|
1292
|
+
const raw = andRaw(condition.raw, term);
|
|
719
1293
|
const rowPut = {
|
|
720
1294
|
Put: {
|
|
721
1295
|
TableName,
|
|
722
1296
|
Item: rowItem,
|
|
723
|
-
ConditionExpression:
|
|
724
|
-
ExpressionAttributeNames:
|
|
725
|
-
...(Object.keys(
|
|
726
|
-
|
|
727
|
-
: {}),
|
|
1297
|
+
ConditionExpression: raw.expression,
|
|
1298
|
+
ExpressionAttributeNames: raw.names,
|
|
1299
|
+
...(Object.keys(raw.values).length > 0 ? { ExpressionAttributeValues: raw.values } : {}),
|
|
1300
|
+
...(returnOld && { ReturnValuesOnConditionCheckFailure: "ALL_OLD" }),
|
|
728
1301
|
},
|
|
729
1302
|
};
|
|
730
1303
|
if (enqueued.length === 0) {
|
|
731
|
-
yield* client.putItem(rowPut.Put).pipe(Effect.catch((error) => lostRace(error
|
|
1304
|
+
yield* client.putItem(rowPut.Put).pipe(Effect.catch((error) => lostRace(error)));
|
|
1305
|
+
return target;
|
|
732
1306
|
}
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
1307
|
+
// The row and its outbox items in one transaction, read by position (#237): the row's Put
|
|
1308
|
+
// cancelled is a lost race, whatever else was; an item's alone is a key holding another
|
|
1309
|
+
// effect's item (`outboxGuard`). The whole transaction is sent again, those items at their
|
|
1310
|
+
// next stage (`outboxStages`): an item without a mark of the same event replaced, then the
|
|
1311
|
+
// item beside it, at its key followed by `#<mark>` (`outboxItems`), so both effects are
|
|
1312
|
+
// delivered, in order: the key sorts right after the other's and before the next
|
|
1313
|
+
// position's. Nothing is read first, and an item at a free key is written where 1.40.0
|
|
1314
|
+
// wrote it. One held beside too is reported, naming what holds it.
|
|
1315
|
+
const OutboxTable = yield* outboxTable;
|
|
1316
|
+
const keys = outboxKeys();
|
|
1317
|
+
const stages = outboxStages();
|
|
1318
|
+
const reached = new Map();
|
|
1319
|
+
const stageOf = (i) => stages[reached.get(i) ?? 0];
|
|
1320
|
+
while (true) {
|
|
1321
|
+
const items = yield* outboxItems(rowKey, revision ?? 0, enqueued, mark, stageOf);
|
|
1322
|
+
const sent = yield* client
|
|
737
1323
|
.transactWriteItems({
|
|
738
1324
|
TransactItems: [
|
|
739
1325
|
rowPut,
|
|
740
|
-
...items.map((Item) => ({
|
|
1326
|
+
...items.map((Item, i) => ({
|
|
1327
|
+
Put: {
|
|
1328
|
+
TableName: OutboxTable,
|
|
1329
|
+
Item,
|
|
1330
|
+
...outboxGuard(keys.pk, Item, stageOf(i)),
|
|
1331
|
+
...(stageOf(i) === "beside" && {
|
|
1332
|
+
ReturnValuesOnConditionCheckFailure: "ALL_OLD",
|
|
1333
|
+
}),
|
|
1334
|
+
},
|
|
1335
|
+
})),
|
|
741
1336
|
],
|
|
742
1337
|
})
|
|
743
|
-
.pipe(Effect.
|
|
1338
|
+
.pipe(Effect.result);
|
|
1339
|
+
if (Result.isSuccess(sent))
|
|
1340
|
+
return target;
|
|
1341
|
+
const cause = sent.failure?.cause;
|
|
1342
|
+
if (!isAwsTransactionCancelled(cause))
|
|
1343
|
+
return yield* Effect.fail(sent.failure);
|
|
1344
|
+
const reasons = cause.CancellationReasons ?? [];
|
|
1345
|
+
const cancelled = (i) => reasons[i]?.Code === "ConditionalCheckFailed";
|
|
1346
|
+
if (cancelled(0)) {
|
|
1347
|
+
return yield* Effect.fail(new LostRace(key, failed(returnOld ? storedOf(sent.failure, true) : undefined)));
|
|
1348
|
+
}
|
|
1349
|
+
const held = items.flatMap((_, i) => (cancelled(i + 1) && stageOf(i) !== "none" ? [i] : []));
|
|
1350
|
+
if (held.length === 0)
|
|
1351
|
+
return yield* Effect.fail(sent.failure);
|
|
1352
|
+
const again = held.find((i) => stageOf(i) === "beside");
|
|
1353
|
+
if (again !== undefined) {
|
|
1354
|
+
const holder = reasons[again + 1]?.Item;
|
|
1355
|
+
const other = holder?.[OUTBOX_READ_MODEL]?.S;
|
|
1356
|
+
return yield* new ValidationError({
|
|
1357
|
+
entityType,
|
|
1358
|
+
operation: `${config.label}.outbox`,
|
|
1359
|
+
cause: withCause(`[EDD-9145] ${config.label}: read model ${JSON.stringify(entityType)} ` +
|
|
1360
|
+
`(${JSON.stringify(outboxTag)}) found another effect's item at the key of its ` +
|
|
1361
|
+
`outbox item ${again} for revision ${revision ?? 0} of row ` +
|
|
1362
|
+
`(${JSON.stringify(String(rowKey[primary.pk.field]))}, ` +
|
|
1363
|
+
`${JSON.stringify(String(rowKey[primary.sk.field]))}), and the key it writes ` +
|
|
1364
|
+
`beside it, ${JSON.stringify(items[again][keys.sk]?.S)}, which only this ` +
|
|
1365
|
+
`effect writes (${JSON.stringify(items[again][OUTBOX_READ_MODEL]?.S)}), is held ` +
|
|
1366
|
+
"too, by " +
|
|
1367
|
+
(holder === undefined
|
|
1368
|
+
? "an item"
|
|
1369
|
+
: `an item of ${JSON.stringify(holder.__edd_e__?.S ?? "no entity type")}` +
|
|
1370
|
+
(other === undefined
|
|
1371
|
+
? " carrying no mark"
|
|
1372
|
+
: ` marked ${JSON.stringify(other)}`)) +
|
|
1373
|
+
". Nothing was written. The library writes nothing else at that key: was the " +
|
|
1374
|
+
"item written outside the projection?", sent.failure),
|
|
1375
|
+
});
|
|
1376
|
+
}
|
|
1377
|
+
for (const i of held)
|
|
1378
|
+
reached.set(i, (reached.get(i) ?? 0) + 1);
|
|
744
1379
|
}
|
|
745
|
-
return target;
|
|
746
1380
|
});
|
|
747
1381
|
// -------------------------------------------------------------------------
|
|
748
1382
|
// Apply
|
|
@@ -792,9 +1426,7 @@ export const makeEngine = (config) => {
|
|
|
792
1426
|
? new ConcurrentModification({
|
|
793
1427
|
entityType,
|
|
794
1428
|
key: error.key,
|
|
795
|
-
attributes:
|
|
796
|
-
config.revision?.field ?? config.checkpoints.field,
|
|
797
|
-
],
|
|
1429
|
+
attributes: error.attributes,
|
|
798
1430
|
current: Option.none(),
|
|
799
1431
|
})
|
|
800
1432
|
: error));
|
|
@@ -853,6 +1485,13 @@ export const makeEngine = (config) => {
|
|
|
853
1485
|
const fromScratch = options?.fromScratch === true;
|
|
854
1486
|
const attempt = Effect.gen(function* () {
|
|
855
1487
|
const row = yield* readRow(key);
|
|
1488
|
+
// An attribute this projection keeps that another, which has written the row, keeps in
|
|
1489
|
+
// another role, present on the row, would be read in the wrong one (`[EDD-9144]`). A
|
|
1490
|
+
// rebuild reads none of its old values from the row, so it misreads nothing.
|
|
1491
|
+
const misread = fromScratch ? undefined : sharedMeaning(row);
|
|
1492
|
+
if (misread !== undefined) {
|
|
1493
|
+
return yield* new ValidationError({ entityType, operation: config.label, cause: misread });
|
|
1494
|
+
}
|
|
856
1495
|
const slotRow = fromScratch ? Option.none() : row;
|
|
857
1496
|
/**
|
|
858
1497
|
* Each instance's slot and run, in fold order. `barred` instances read an
|
|
@@ -1036,7 +1675,12 @@ export const makeEngine = (config) => {
|
|
|
1036
1675
|
// Every instance failed: the row fails, with the first failure.
|
|
1037
1676
|
if (active.length === 0 && failed.length > 0)
|
|
1038
1677
|
return yield* Effect.fail(failed[0].error);
|
|
1039
|
-
const { state, removed,
|
|
1678
|
+
const { state, removed, results } = folded;
|
|
1679
|
+
// A rebuild enqueues nothing (#237): it re-derives the row, and never replays side effects.
|
|
1680
|
+
// `effects` still runs in its fold, so the row comes out as the fold that applied the events
|
|
1681
|
+
// made it; what it returns is not written. Without effects the row is written alone, as any
|
|
1682
|
+
// write that enqueues nothing is (`writeRow`).
|
|
1683
|
+
const enqueued = fromScratch ? [] : folded.enqueued;
|
|
1040
1684
|
const instances = (version) => active.map((plan, i) => ({
|
|
1041
1685
|
source: plan.work.source.name,
|
|
1042
1686
|
streamId: plan.work.streamIdStr,
|
|
@@ -1080,11 +1724,14 @@ export const makeEngine = (config) => {
|
|
|
1080
1724
|
if (fromScratch && config.revision !== undefined) {
|
|
1081
1725
|
target[config.revision.field] = nextRevisionOf(row);
|
|
1082
1726
|
}
|
|
1083
|
-
const nextRevision = config.revision === undefined
|
|
1727
|
+
const nextRevision = config.revision === undefined
|
|
1728
|
+
? undefined
|
|
1729
|
+
: ownValue(target, config.revision.field);
|
|
1084
1730
|
let written;
|
|
1085
1731
|
if (Option.isNone(state)) {
|
|
1086
|
-
// A tombstone keeps
|
|
1087
|
-
|
|
1732
|
+
// A tombstone keeps the layout's fields, and the bookkeeping of the other projections that
|
|
1733
|
+
// have written the row (`carriedOf`), so they still recognise what they applied.
|
|
1734
|
+
written = yield* writeRow(key, Option.none(), pick(target), row, enqueued, nextRevision, carriedOf(row));
|
|
1088
1735
|
}
|
|
1089
1736
|
else {
|
|
1090
1737
|
const mapped = config.toItem === undefined
|
|
@@ -1093,7 +1740,39 @@ export const makeEngine = (config) => {
|
|
|
1093
1740
|
...(yield* call("toItem", () => config.toItem(target, config.toItemContext(key, work)))),
|
|
1094
1741
|
...pick(target),
|
|
1095
1742
|
};
|
|
1096
|
-
|
|
1743
|
+
// The bookkeeping of the other projections that have written the row (`carriedOf`), each
|
|
1744
|
+
// value as the entity stores it on a row. Over a tombstone it replaces what `initial` gave
|
|
1745
|
+
// it. Over a live row a change to it is refused (`[EDD-9144]`), and it fills what the write
|
|
1746
|
+
// left out only when the write, with it, stores every attribute the row holds under the
|
|
1747
|
+
// name the row holds it by (`keepsData`): one that drops one drops the others'
|
|
1748
|
+
// checkpoints with it, as 1.40.0 did, so they fold their streams again and put their data
|
|
1749
|
+
// back. A rebuild over a live row carries none: it drops the other projections'
|
|
1750
|
+
// contributions to the state, so they lose their checkpoints too and apply again.
|
|
1751
|
+
let item = mapped;
|
|
1752
|
+
if (Option.isSome(row) && row.value.tombstone) {
|
|
1753
|
+
item = { ...mapped, ...onRow(carriedOf(row)) };
|
|
1754
|
+
}
|
|
1755
|
+
else if (Option.isSome(row) && !fromScratch) {
|
|
1756
|
+
const changed = sharedMeaning(row, mapped);
|
|
1757
|
+
if (changed !== undefined) {
|
|
1758
|
+
return yield* new ValidationError({
|
|
1759
|
+
entityType,
|
|
1760
|
+
operation: config.label,
|
|
1761
|
+
cause: changed,
|
|
1762
|
+
});
|
|
1763
|
+
}
|
|
1764
|
+
const carried = onRow(carriedOf(row));
|
|
1765
|
+
if (Object.keys(carried).length > 0) {
|
|
1766
|
+
const candidate = { ...mapped };
|
|
1767
|
+
for (const [field, value] of Object.entries(carried)) {
|
|
1768
|
+
if (candidate[field] === undefined)
|
|
1769
|
+
candidate[field] = value;
|
|
1770
|
+
}
|
|
1771
|
+
if (yield* keepsData(row.value, candidate))
|
|
1772
|
+
item = candidate;
|
|
1773
|
+
}
|
|
1774
|
+
}
|
|
1775
|
+
written = yield* writeRow(key, Option.some(item), {}, row, enqueued, nextRevision);
|
|
1097
1776
|
}
|
|
1098
1777
|
const versions = new Map(advanced.map((a) => [`${a.source}\u0000${a.streamIdStr}`, a.version]));
|
|
1099
1778
|
return {
|
|
@@ -1109,12 +1788,147 @@ export const makeEngine = (config) => {
|
|
|
1109
1788
|
});
|
|
1110
1789
|
return Effect.andThen(preflight("apply"), withRetry(attempt));
|
|
1111
1790
|
};
|
|
1791
|
+
/**
|
|
1792
|
+
* The bookkeeping of the read model's other projections that have written `row`, as its row
|
|
1793
|
+
* token records them (`rowWriters`, #237), each value present on the row as it reads it: a live
|
|
1794
|
+
* row's decoded, a tombstone's as stored (a tombstone keeps every value natively). None for a
|
|
1795
|
+
* row without a token (written before, or by a program that defines only this projection) or of
|
|
1796
|
+
* a projection this program doesn't define: its names can't be told from another's data. A
|
|
1797
|
+
* writer whose attributes the row no longer holds has nothing here.
|
|
1798
|
+
*/
|
|
1799
|
+
const writtenBy = (row) => {
|
|
1800
|
+
if (Option.isNone(row))
|
|
1801
|
+
return [];
|
|
1802
|
+
const writers = new Set(rowWriters(row.value.token));
|
|
1803
|
+
writers.delete(ownTag);
|
|
1804
|
+
if (writers.size === 0)
|
|
1805
|
+
return [];
|
|
1806
|
+
const values = row.value.tombstone
|
|
1807
|
+
? fromAttributeMap(row.value.item)
|
|
1808
|
+
: row.value.values;
|
|
1809
|
+
const out = [];
|
|
1810
|
+
for (const layout of projectionLayoutsOf(readModel) ?? []) {
|
|
1811
|
+
if (!writers.has(layoutTag(layout)))
|
|
1812
|
+
continue;
|
|
1813
|
+
for (const [field, role] of layout.roles) {
|
|
1814
|
+
const stored = dbName(field);
|
|
1815
|
+
const at = row.value.tombstone ? stored : field;
|
|
1816
|
+
const value = Object.hasOwn(values, at) ? values[at] : undefined;
|
|
1817
|
+
if (value !== undefined)
|
|
1818
|
+
out.push({ layout, field, role, stored, value });
|
|
1819
|
+
}
|
|
1820
|
+
}
|
|
1821
|
+
return out;
|
|
1822
|
+
};
|
|
1823
|
+
/**
|
|
1824
|
+
* `[EDD-9144]` (#237): an attribute holding two meanings on `row`. Another projection that has
|
|
1825
|
+
* written the row (`writtenBy`) keeps it as bookkeeping, and it's on the row, and this
|
|
1826
|
+
* projection keeps it in another role, so each would read the other's value as its own; or,
|
|
1827
|
+
* given `item` (what a write over the live row stores), this write gives it another value than
|
|
1828
|
+
* the row holds without keeping it in that role. The problem, or `undefined`. On rows only one
|
|
1829
|
+
* of them writes nothing is refused: projections writing disjoint rows may give one name
|
|
1830
|
+
* different meanings.
|
|
1831
|
+
*/
|
|
1832
|
+
const sharedMeaning = (row, item) => {
|
|
1833
|
+
for (const { layout, field, role, stored, value: held } of writtenBy(row)) {
|
|
1834
|
+
const mine = ownRoles.get(stored);
|
|
1835
|
+
if (mine?.has(role))
|
|
1836
|
+
continue;
|
|
1837
|
+
if (mine !== undefined) {
|
|
1838
|
+
return (`[EDD-9144] ${config.label}: on read model "${entityType}", "${field}" is ` +
|
|
1839
|
+
`${layout.label}'s ${role} on a row ${layout.label} has written, and this ` +
|
|
1840
|
+
`projection's ${[...mine].join(" and ")}. An attribute holds one meaning on a row two ` +
|
|
1841
|
+
"projections write: give each meaning its own field.");
|
|
1842
|
+
}
|
|
1843
|
+
if (item === undefined || Option.isNone(row) || row.value.tombstone)
|
|
1844
|
+
continue;
|
|
1845
|
+
const value = item[field];
|
|
1846
|
+
if (value === undefined || sameValue(value, held))
|
|
1847
|
+
continue;
|
|
1848
|
+
return (`[EDD-9144] ${config.label}: on read model "${entityType}", this write changes ` +
|
|
1849
|
+
`"${field}", which is ${layout.label}'s ${role}, on a row ${layout.label} has written. ` +
|
|
1850
|
+
"An attribute holds one meaning on a row two projections write: give each meaning its " +
|
|
1851
|
+
"own field.");
|
|
1852
|
+
}
|
|
1853
|
+
return undefined;
|
|
1854
|
+
};
|
|
1855
|
+
/**
|
|
1856
|
+
* The bookkeeping a write over `row` carries for the other projections that have written it
|
|
1857
|
+
* (`writtenBy`), by field: each attribute once, none this projection keeps, each value as the
|
|
1858
|
+
* row reads it. The one function every site carries through: a tombstone stores it as it stores
|
|
1859
|
+
* its own (`writeRow`), natively; a row as the entity stores any value of the field (`onRow`),
|
|
1860
|
+
* renamed, packed or as sparse entries; and each reads back what it wrote.
|
|
1861
|
+
*/
|
|
1862
|
+
const carriedOf = (row) => {
|
|
1863
|
+
const out = {};
|
|
1864
|
+
const seen = new Set();
|
|
1865
|
+
for (const { field, stored, value } of writtenBy(row)) {
|
|
1866
|
+
if (ownRoles.has(stored) || seen.has(stored))
|
|
1867
|
+
continue;
|
|
1868
|
+
seen.add(stored);
|
|
1869
|
+
out[field] = value;
|
|
1870
|
+
}
|
|
1871
|
+
return out;
|
|
1872
|
+
};
|
|
1873
|
+
/**
|
|
1874
|
+
* Carried bookkeeping as a row can hold it: a sparse map without the entries whose keys sparse
|
|
1875
|
+
* storage can't hold (a 1.39.0 tombstone's map holding a key with `#`), which are left off.
|
|
1876
|
+
*/
|
|
1877
|
+
const onRow = (carried) => {
|
|
1878
|
+
const out = {};
|
|
1879
|
+
const holds = (name, value) => {
|
|
1880
|
+
try {
|
|
1881
|
+
readModel._serializeSparseFields({ [name]: value });
|
|
1882
|
+
return true;
|
|
1883
|
+
}
|
|
1884
|
+
catch {
|
|
1885
|
+
return false;
|
|
1886
|
+
}
|
|
1887
|
+
};
|
|
1888
|
+
for (const [field, value] of Object.entries(carried)) {
|
|
1889
|
+
const name = dbName(field);
|
|
1890
|
+
if (holds(name, value)) {
|
|
1891
|
+
out[field] = value;
|
|
1892
|
+
continue;
|
|
1893
|
+
}
|
|
1894
|
+
if (typeof value !== "object" || value === null)
|
|
1895
|
+
continue;
|
|
1896
|
+
const entries = {};
|
|
1897
|
+
for (const [entry, v] of Object.entries(value)) {
|
|
1898
|
+
if (holds(name, { [entry]: v }))
|
|
1899
|
+
entries[entry] = v;
|
|
1900
|
+
}
|
|
1901
|
+
out[field] = entries;
|
|
1902
|
+
}
|
|
1903
|
+
return out;
|
|
1904
|
+
};
|
|
1905
|
+
/**
|
|
1906
|
+
* Whether a write over the live `row` storing `item` keeps every attribute the row holds (#237),
|
|
1907
|
+
* judged on two stored things alone: the row's attribute map as read, and the attribute map the
|
|
1908
|
+
* write's request carries (`validateAndBuildPutItem`, the transaction's own: encoded, renamed, as
|
|
1909
|
+
* sparse entries, packed, then marshalled). Every attribute of the row but its row token must be
|
|
1910
|
+
* there under the same name; its value, and its type, may change. No definition says which
|
|
1911
|
+
* attributes are data: a field another program renames, stores in a sparse map under another
|
|
1912
|
+
* prefix, or doesn't define, is an attribute the write drops. `item` carries the other
|
|
1913
|
+
* projections' bookkeeping (`carriedOf`), so theirs counts as kept only where it lands under the
|
|
1914
|
+
* name the row holds it by. A value that stores nothing drops its attributes, whatever drops it:
|
|
1915
|
+
* an `Option.none()`, an emptied sparse map, an empty set (the marshaller stores none). An item
|
|
1916
|
+
* the entity or the marshaller refuses keeps nothing: the write then fails as it would have. A
|
|
1917
|
+
* projection's row write is always a whole `Put`: nothing is left in place or removed by name.
|
|
1918
|
+
*/
|
|
1919
|
+
const keepsData = (row, item) => Effect.gen(function* () {
|
|
1920
|
+
const built = yield* Effect.option(validateAndBuildPutItem(readModel, item, `${config.label}.write`));
|
|
1921
|
+
if (Option.isNone(built))
|
|
1922
|
+
return false;
|
|
1923
|
+
const written = built.value.marshalled;
|
|
1924
|
+
return Object.keys(row.item).every((name) => Object.hasOwn(written, name) || (name === ROW_TOKEN && row.token !== undefined));
|
|
1925
|
+
});
|
|
1112
1926
|
/** The fields the library owns, re-applied after `toItem`. */
|
|
1113
1927
|
const pick = (target) => {
|
|
1114
1928
|
const out = {};
|
|
1115
1929
|
for (const f of keptFields)
|
|
1116
|
-
if (target
|
|
1117
|
-
out
|
|
1930
|
+
if (ownValue(target, f) !== undefined)
|
|
1931
|
+
setOwn(out, f, ownValue(target, f));
|
|
1118
1932
|
return out;
|
|
1119
1933
|
};
|
|
1120
1934
|
// -------------------------------------------------------------------------
|
|
@@ -1126,13 +1940,21 @@ export const makeEngine = (config) => {
|
|
|
1126
1940
|
* Deliver a row's pending effects in order: claim the head item, deliver it,
|
|
1127
1941
|
* delete it, repeat. A claim another drainer holds stops the drain; a crash
|
|
1128
1942
|
* leaves a claim that expires, so the effect is delivered again.
|
|
1943
|
+
*
|
|
1944
|
+
* Each item is judged as it comes to the head (`outboxOwnership`, #237): another read model's
|
|
1945
|
+
* item at this row key (one keyed by `[shop]` with `north#branch_b1` beside one keyed by
|
|
1946
|
+
* `[shop, branch]`) is passed over, unclaimed, for its own drainer, and the query goes on after
|
|
1947
|
+
* it. A row holding only this read model's items sends the requests 1.40.0 sent.
|
|
1129
1948
|
*/
|
|
1130
1949
|
const drainRaw = (rowPk, rowSk, deliver) => Effect.gen(function* () {
|
|
1131
1950
|
const outbox = config.outbox;
|
|
1132
1951
|
const client = yield* Capacity.client;
|
|
1133
1952
|
const TableName = yield* outboxTable;
|
|
1134
1953
|
const keys = outboxKeys();
|
|
1954
|
+
const whose = outboxOwnership(readModel);
|
|
1135
1955
|
let delivered = 0;
|
|
1956
|
+
// The last item passed over as another read model's: the query goes on after it.
|
|
1957
|
+
let after;
|
|
1136
1958
|
while (true) {
|
|
1137
1959
|
const page = yield* client.query({
|
|
1138
1960
|
TableName,
|
|
@@ -1141,10 +1963,15 @@ export const makeEngine = (config) => {
|
|
|
1141
1963
|
ExpressionAttributeValues: toAttributeMap({ ":pk": rowPk, ":sk": `${rowSk}#outbox#` }),
|
|
1142
1964
|
ConsistentRead: true,
|
|
1143
1965
|
Limit: 1,
|
|
1966
|
+
...(after === undefined ? {} : { ExclusiveStartKey: after }),
|
|
1144
1967
|
});
|
|
1145
1968
|
const head = page.Items?.[0];
|
|
1146
1969
|
if (head === undefined)
|
|
1147
1970
|
return { delivered, undelivered: Option.none() };
|
|
1971
|
+
if (whose(head) === "foreign") {
|
|
1972
|
+
after = { [keys.pk]: head[keys.pk], [keys.sk]: head[keys.sk] };
|
|
1973
|
+
continue;
|
|
1974
|
+
}
|
|
1148
1975
|
const raw = fromAttributeMap(head);
|
|
1149
1976
|
const now = DateTime.toEpochMillis(yield* DateTime.now);
|
|
1150
1977
|
const token = `${now}-${Math.floor((yield* Random.next) * 1e9)}`;
|
|
@@ -1205,7 +2032,12 @@ export const makeEngine = (config) => {
|
|
|
1205
2032
|
const rowKey = composePrimaryKey(readModel, key);
|
|
1206
2033
|
return drainRaw(String(rowKey[primary.pk.field]), String(rowKey[primary.sk.field]), deliver);
|
|
1207
2034
|
};
|
|
1208
|
-
/**
|
|
2035
|
+
/**
|
|
2036
|
+
* Every row of this read model with pending effects, through the outbox's sparse index, drained.
|
|
2037
|
+
* The items another read model's are (`outboxOwnership`) are left to its drainer, here and at a
|
|
2038
|
+
* row key both write (`drainRaw`); an item written before 1.41.0 at a key both write is drained,
|
|
2039
|
+
* as 1.40.0 did.
|
|
2040
|
+
*/
|
|
1209
2041
|
const drainPending = (deliver) => Effect.gen(function* () {
|
|
1210
2042
|
const outbox = config.outbox;
|
|
1211
2043
|
if (outbox.index === undefined) {
|
|
@@ -1217,6 +2049,7 @@ export const makeEngine = (config) => {
|
|
|
1217
2049
|
}
|
|
1218
2050
|
const client = yield* Capacity.client;
|
|
1219
2051
|
const TableName = yield* outboxTable;
|
|
2052
|
+
const whose = outboxOwnership(readModel);
|
|
1220
2053
|
const rows = new Map();
|
|
1221
2054
|
let start;
|
|
1222
2055
|
do {
|
|
@@ -1229,6 +2062,8 @@ export const makeEngine = (config) => {
|
|
|
1229
2062
|
...(start === undefined ? {} : { ExclusiveStartKey: start }),
|
|
1230
2063
|
});
|
|
1231
2064
|
for (const item of page.Items ?? []) {
|
|
2065
|
+
if (whose(item) === "foreign")
|
|
2066
|
+
continue;
|
|
1232
2067
|
const raw = fromAttributeMap(item);
|
|
1233
2068
|
const pk = String(raw[ROW_PK]);
|
|
1234
2069
|
const sk = String(raw[ROW_SK]);
|