effect-dynamodb 1.39.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.
Files changed (190) hide show
  1. package/README.md +1 -1
  2. package/dist/Aggregate.d.ts +138 -16
  3. package/dist/Aggregate.d.ts.map +1 -1
  4. package/dist/Aggregate.js +4298 -725
  5. package/dist/Aggregate.js.map +1 -1
  6. package/dist/Batch.d.ts +9 -5
  7. package/dist/Batch.d.ts.map +1 -1
  8. package/dist/Batch.js +28 -44
  9. package/dist/Batch.js.map +1 -1
  10. package/dist/Collection.d.ts.map +1 -1
  11. package/dist/Collection.js +16 -9
  12. package/dist/Collection.js.map +1 -1
  13. package/dist/ConsumedCapacity.js +1 -1
  14. package/dist/ConsumedCapacity.js.map +1 -1
  15. package/dist/DynamoClient.d.ts +44 -21
  16. package/dist/DynamoClient.d.ts.map +1 -1
  17. package/dist/DynamoClient.js +342 -124
  18. package/dist/DynamoClient.js.map +1 -1
  19. package/dist/Entity.d.ts +246 -41
  20. package/dist/Entity.d.ts.map +1 -1
  21. package/dist/Entity.js +6818 -1166
  22. package/dist/Entity.js.map +1 -1
  23. package/dist/EventStore.d.ts +37 -15
  24. package/dist/EventStore.d.ts.map +1 -1
  25. package/dist/EventStore.js +403 -163
  26. package/dist/EventStore.js.map +1 -1
  27. package/dist/Expression.d.ts.map +1 -1
  28. package/dist/Expression.js +40 -24
  29. package/dist/Expression.js.map +1 -1
  30. package/dist/Marshaller.d.ts +72 -11
  31. package/dist/Marshaller.d.ts.map +1 -1
  32. package/dist/Marshaller.js +625 -71
  33. package/dist/Marshaller.js.map +1 -1
  34. package/dist/Query.d.ts +103 -5
  35. package/dist/Query.d.ts.map +1 -1
  36. package/dist/Query.js +262 -15
  37. package/dist/Query.js.map +1 -1
  38. package/dist/StorageEncoding.d.ts +7 -1
  39. package/dist/StorageEncoding.d.ts.map +1 -1
  40. package/dist/StorageEncoding.js +8 -2
  41. package/dist/StorageEncoding.js.map +1 -1
  42. package/dist/Table.d.ts +338 -16
  43. package/dist/Table.d.ts.map +1 -1
  44. package/dist/Table.js +30 -2
  45. package/dist/Table.js.map +1 -1
  46. package/dist/Transaction.d.ts.map +1 -1
  47. package/dist/Transaction.js +70 -7
  48. package/dist/Transaction.js.map +1 -1
  49. package/dist/VectorSearchEmulation.d.ts.map +1 -1
  50. package/dist/VectorSearchEmulation.js +4 -3
  51. package/dist/VectorSearchEmulation.js.map +1 -1
  52. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  53. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  54. package/dist/change-feed/ChangeFeed.js +76 -9
  55. package/dist/change-feed/ChangeFeed.js.map +1 -1
  56. package/dist/change-feed/CheckpointStore.js +1 -1
  57. package/dist/change-feed/CheckpointStore.js.map +1 -1
  58. package/dist/change-feed/DynamoStreamsClient.d.ts +19 -10
  59. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  60. package/dist/change-feed/DynamoStreamsClient.js +24 -14
  61. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  62. package/dist/index.d.ts +2 -2
  63. package/dist/index.d.ts.map +1 -1
  64. package/dist/index.js +1 -1
  65. package/dist/index.js.map +1 -1
  66. package/dist/internal/BoundCrud.d.ts +78 -32
  67. package/dist/internal/BoundCrud.d.ts.map +1 -1
  68. package/dist/internal/BoundCrud.js +25 -0
  69. package/dist/internal/BoundCrud.js.map +1 -1
  70. package/dist/internal/BoundQuery.d.ts +46 -3
  71. package/dist/internal/BoundQuery.d.ts.map +1 -1
  72. package/dist/internal/BoundQuery.js +402 -37
  73. package/dist/internal/BoundQuery.js.map +1 -1
  74. package/dist/internal/BoundVectorQuery.d.ts +6 -0
  75. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  76. package/dist/internal/BoundVectorQuery.js +7 -4
  77. package/dist/internal/BoundVectorQuery.js.map +1 -1
  78. package/dist/internal/Capacity.d.ts +46 -5
  79. package/dist/internal/Capacity.d.ts.map +1 -1
  80. package/dist/internal/Capacity.js +177 -26
  81. package/dist/internal/Capacity.js.map +1 -1
  82. package/dist/internal/ClientOptions.d.ts +144 -0
  83. package/dist/internal/ClientOptions.d.ts.map +1 -0
  84. package/dist/internal/ClientOptions.js +290 -0
  85. package/dist/internal/ClientOptions.js.map +1 -0
  86. package/dist/internal/ConditionHolds.d.ts +29 -0
  87. package/dist/internal/ConditionHolds.d.ts.map +1 -0
  88. package/dist/internal/ConditionHolds.js +453 -0
  89. package/dist/internal/ConditionHolds.js.map +1 -0
  90. package/dist/internal/Cursor.d.ts +19 -10
  91. package/dist/internal/Cursor.d.ts.map +1 -1
  92. package/dist/internal/Cursor.js +25 -10
  93. package/dist/internal/Cursor.js.map +1 -1
  94. package/dist/internal/Digest.d.ts +20 -0
  95. package/dist/internal/Digest.d.ts.map +1 -0
  96. package/dist/internal/Digest.js +106 -0
  97. package/dist/internal/Digest.js.map +1 -0
  98. package/dist/internal/DynamoArithmetic.d.ts +33 -0
  99. package/dist/internal/DynamoArithmetic.d.ts.map +1 -0
  100. package/dist/internal/DynamoArithmetic.js +112 -0
  101. package/dist/internal/DynamoArithmetic.js.map +1 -0
  102. package/dist/internal/EntityCombinators.d.ts +23 -8
  103. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  104. package/dist/internal/EntityCombinators.js +6 -2
  105. package/dist/internal/EntityCombinators.js.map +1 -1
  106. package/dist/internal/EntityOps.d.ts +69 -8
  107. package/dist/internal/EntityOps.d.ts.map +1 -1
  108. package/dist/internal/EntityOps.js.map +1 -1
  109. package/dist/internal/EventProjection.d.ts +18 -4
  110. package/dist/internal/EventProjection.d.ts.map +1 -1
  111. package/dist/internal/EventProjection.js +36 -8
  112. package/dist/internal/EventProjection.js.map +1 -1
  113. package/dist/internal/Expr.d.ts +72 -2
  114. package/dist/internal/Expr.d.ts.map +1 -1
  115. package/dist/internal/Expr.js +264 -5
  116. package/dist/internal/Expr.js.map +1 -1
  117. package/dist/internal/ExpressionLimits.d.ts +57 -1
  118. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  119. package/dist/internal/ExpressionLimits.js +97 -4
  120. package/dist/internal/ExpressionLimits.js.map +1 -1
  121. package/dist/internal/FormGuard.d.ts +52 -0
  122. package/dist/internal/FormGuard.d.ts.map +1 -0
  123. package/dist/internal/FormGuard.js +83 -0
  124. package/dist/internal/FormGuard.js.map +1 -0
  125. package/dist/internal/Hydrate.d.ts.map +1 -1
  126. package/dist/internal/Hydrate.js +2 -1
  127. package/dist/internal/Hydrate.js.map +1 -1
  128. package/dist/internal/InputForm.d.ts +24 -0
  129. package/dist/internal/InputForm.d.ts.map +1 -0
  130. package/dist/internal/InputForm.js +44 -0
  131. package/dist/internal/InputForm.js.map +1 -0
  132. package/dist/internal/InsertStatement.d.ts +15 -0
  133. package/dist/internal/InsertStatement.d.ts.map +1 -0
  134. package/dist/internal/InsertStatement.js +18 -0
  135. package/dist/internal/InsertStatement.js.map +1 -0
  136. package/dist/internal/ItemSize.d.ts +108 -4
  137. package/dist/internal/ItemSize.d.ts.map +1 -1
  138. package/dist/internal/ItemSize.js +190 -3
  139. package/dist/internal/ItemSize.js.map +1 -1
  140. package/dist/internal/MultiProjection.d.ts +7 -2
  141. package/dist/internal/MultiProjection.d.ts.map +1 -1
  142. package/dist/internal/MultiProjection.js +18 -12
  143. package/dist/internal/MultiProjection.js.map +1 -1
  144. package/dist/internal/OperandReaders.d.ts +36 -0
  145. package/dist/internal/OperandReaders.d.ts.map +1 -0
  146. package/dist/internal/OperandReaders.js +176 -0
  147. package/dist/internal/OperandReaders.js.map +1 -0
  148. package/dist/internal/Packed.d.ts.map +1 -1
  149. package/dist/internal/Packed.js +11 -10
  150. package/dist/internal/Packed.js.map +1 -1
  151. package/dist/internal/PathBuilder.d.ts +57 -8
  152. package/dist/internal/PathBuilder.d.ts.map +1 -1
  153. package/dist/internal/PathBuilder.js +98 -24
  154. package/dist/internal/PathBuilder.js.map +1 -1
  155. package/dist/internal/ProjectionEngine.d.ts +196 -3
  156. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  157. package/dist/internal/ProjectionEngine.js +1251 -86
  158. package/dist/internal/ProjectionEngine.js.map +1 -1
  159. package/dist/internal/Rekey.d.ts +187 -21
  160. package/dist/internal/Rekey.d.ts.map +1 -1
  161. package/dist/internal/Rekey.js +1349 -63
  162. package/dist/internal/Rekey.js.map +1 -1
  163. package/dist/internal/ReturnedItem.d.ts +23 -0
  164. package/dist/internal/ReturnedItem.d.ts.map +1 -0
  165. package/dist/internal/ReturnedItem.js +39 -0
  166. package/dist/internal/ReturnedItem.js.map +1 -0
  167. package/dist/internal/RoundTrip.d.ts +45 -0
  168. package/dist/internal/RoundTrip.d.ts.map +1 -0
  169. package/dist/internal/RoundTrip.js +106 -0
  170. package/dist/internal/RoundTrip.js.map +1 -0
  171. package/dist/internal/SentRequest.d.ts +14 -0
  172. package/dist/internal/SentRequest.d.ts.map +1 -0
  173. package/dist/internal/SentRequest.js +31 -0
  174. package/dist/internal/SentRequest.js.map +1 -0
  175. package/dist/internal/TransactPlan.d.ts.map +1 -1
  176. package/dist/internal/TransactPlan.js +4 -0
  177. package/dist/internal/TransactPlan.js.map +1 -1
  178. package/dist/internal/TransactWriteOps.d.ts +70 -15
  179. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  180. package/dist/internal/TransactWriteOps.js +166 -112
  181. package/dist/internal/TransactWriteOps.js.map +1 -1
  182. package/dist/internal/TransactableOps.d.ts +230 -27
  183. package/dist/internal/TransactableOps.d.ts.map +1 -1
  184. package/dist/internal/TransactableOps.js +549 -92
  185. package/dist/internal/TransactableOps.js.map +1 -1
  186. package/dist/internal/WriteDiagnosis.d.ts +66 -3
  187. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  188. package/dist/internal/WriteDiagnosis.js +261 -15
  189. package/dist/internal/WriteDiagnosis.js.map +1 -1
  190. package/package.json +5 -5
@@ -14,16 +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
+ import { keyFormLiterals, keyFormValueKind, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
20
+ import { isSelfDateSchema, optionalField, readingStreamValues, resolveFieldEncoding, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
21
+ import { decodingAsBefore } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
22
+ import { ownValue, setOwn } from "@effect-dynamodb/schema/internal/OwnNames.js";
19
23
  import { getSchemaFields } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
20
- import { DateTime, Duration as Dur, Effect, Option, Random, Result, Schema as S, Schedule, } from "effect";
24
+ import { fnv1a64 } from "@effect-dynamodb/schema/internal/ZOrderCurve.js";
25
+ import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
26
+ import { DateTime, Duration as Dur, Effect, Equal, Option, Random, Result, Schema as S, Schedule, } from "effect";
21
27
  import { decodeMarshalledItem } from "../Entity.js";
22
28
  import { fromAttributeMap, toAttributeMap } from "../Marshaller.js";
23
29
  import { resolveTtlAttributeName } from "../Table.js";
30
+ import { attributeValueEquals } from "./AttributeValueEquals.js";
24
31
  import * as Capacity from "./Capacity.js";
25
32
  import { condition as entityCondition } from "./EntityCombinators.js";
26
- import { OUTBOX_CLAIM as CLAIM_TOKEN, OUTBOX_CLAIMED_UNTIL as CLAIMED_UNTIL, composePrimaryKey, generateTimestampPrimitive, KEY_TEXT, OUTBOX_ROW_PK as ROW_PK, OUTBOX_ROW_SK as ROW_SK, validateAndBuildPutItem, } from "./TransactableOps.js";
33
+ import { handlerOf } from "./Rekey.js";
34
+ import { notReadBack, readBackOf } from "./RoundTrip.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";
27
37
  // ---------------------------------------------------------------------------
28
38
  // Removal (#154)
29
39
  // ---------------------------------------------------------------------------
@@ -59,18 +69,33 @@ export const tombstoneMarker = (entityType) => `${entityType}#tombstone`;
59
69
  export const outboxMarker = (entityType) => `${entityType}#outbox`;
60
70
  /** Attribute names the engine owns on tombstones and outbox items. */
61
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
+ };
62
81
  /** The engine's own lost-race signal. */
63
82
  class LostRace {
64
83
  key;
65
- constructor(key) {
84
+ attributes;
85
+ /** `attributes`: the attributes whose change failed the write's condition (#237). */
86
+ constructor(key, attributes) {
66
87
  this.key = key;
88
+ this.attributes = attributes;
67
89
  }
68
90
  }
69
91
  // ---------------------------------------------------------------------------
70
92
  // The engine
71
93
  // ---------------------------------------------------------------------------
72
- /** A key's identity: its fields, sorted, as JSON. */
73
- export const keyId = (key) => JSON.stringify(Object.entries(key).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)));
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));
74
99
  /** `K | Option<K>` → `Option<K>`. */
75
100
  export const addressed = (key) => Option.isOption(key) ? key : Option.some(key);
76
101
  /** A map checkpoint's key. */
@@ -84,7 +109,563 @@ export const modelFields = (model) => {
84
109
  const fields = getSchemaFields(schema);
85
110
  return fields === undefined ? undefined : Object.keys(fields);
86
111
  };
87
- /** @internal */
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
+ };
140
+ /**
141
+ * @internal The outboxes on other tables of the read model's projections (`_projectionOutboxes`,
142
+ * the entries with a `table`): several projections of one read model may each have one. A local
143
+ * outbox is on the read model's own table, where its rows are.
144
+ */
145
+ export const remoteOutboxesOf = (entity) => (entity
146
+ ._projectionOutboxes ?? []).filter((outbox) => outbox.table !== undefined);
147
+ /**
148
+ * @internal The physical name of the table `tag` names, the one requests are sent to:
149
+ * `undefined` when the context doesn't provide it.
150
+ */
151
+ export const physicalTableName = (tag) => Effect.map(Effect.serviceOption(tag), (config) => Option.isSome(config) ? config.value.name : undefined);
152
+ /**
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.
175
+ */
176
+ const compositeValues = (model, dates = true) => (composite) => {
177
+ if (model === undefined || model === null)
178
+ return "open";
179
+ const schema = isConfiguredModel(model) ? model.model : model;
180
+ const fields = getSchemaFields(schema);
181
+ if (fields === undefined || !Object.hasOwn(fields, composite))
182
+ return "open";
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
+ }
197
+ const literals = keyFormLiterals(field);
198
+ if (literals !== undefined)
199
+ return { values: literals };
200
+ const kind = keyFormValueKind(field);
201
+ if (kind === "number" || kind === "bigint")
202
+ return "number";
203
+ if (kind === "boolean")
204
+ return { values: [true, false] };
205
+ return "open";
206
+ };
207
+ /**
208
+ * The key space an entity's rows are under: the text its primary key's partition and sort keys
209
+ * start with, the composites' labels, and what each composite's value can be, composed by the call
210
+ * its writes make (`KeyComposer.composeKeySpace`): the schema's name and version, the primary
211
+ * collection (or the entity type), under a collection the entity type and its version, and each
212
+ * composite's name. Each value is what its type can compose (`compositeValues`), by `view`:
213
+ *
214
+ * - `"plain"`, the keys its rows are written under with values that hold no `#`: every composite is
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.
219
+ *
220
+ * `undefined` for an entity on no table.
221
+ */
222
+ const keySpaceOf = (entity, view) => {
223
+ const member = entity;
224
+ const primary = member.indexes?.primary;
225
+ if (member._schema === undefined || member.entityType === undefined || primary === undefined) {
226
+ return undefined;
227
+ }
228
+ const values = compositeValues(member.model, view !== "plain140");
229
+ const plain = view === "plain" || view === "plain140";
230
+ try {
231
+ return KeyComposer.composeKeySpace(member._schema, member.entityType, member._entityVersion ?? 1, primary, plain
232
+ ? (composite) => {
233
+ const of = values(composite);
234
+ return of === "open" ? "text" : of;
235
+ }
236
+ : values, { everyForm: !plain, walkOpen: !plain });
237
+ }
238
+ catch {
239
+ return undefined;
240
+ }
241
+ };
242
+ /**
243
+ * The key space of a read model's outbox items: its rows' partition keys, and its rows' sort keys
244
+ * followed by `#outbox#` (`<rowSk>#outbox#<revision>#<n>`), so any text after a whole sort key.
245
+ */
246
+ const outboxSpaceOf = (space) => {
247
+ const { sk } = space;
248
+ if (sk.open)
249
+ return space;
250
+ const last = sk.after.length - 1;
251
+ return {
252
+ pk: space.pk,
253
+ sk: last < 0
254
+ ? { text: `${sk.text}#outbox#`, after: [], values: [], open: true }
255
+ : { ...sk, after: [...sk.after.slice(0, last), `${sk.after[last]}#outbox#`], open: true },
256
+ };
257
+ };
258
+ /** Whether a key of one key space can be a key of the other, in both halves. */
259
+ const spacesMeet = (a, b) => KeyComposer.keySpacesMeet(a.pk, b.pk) && KeyComposer.keySpacesMeet(a.sk, b.sk);
260
+ /**
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.
268
+ */
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));
274
+ };
275
+ if (meet("plain"))
276
+ return true;
277
+ return meet("plain140") && meet("owned");
278
+ };
279
+ /**
280
+ * Whether two entities compose every key the same way: one schema (name, version, casing,
281
+ * `escapeKeys`), entity type and version, primary key composites, casing and collection, and each
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.
287
+ */
288
+ const sameKeys = (a, b) => {
289
+ const x = a;
290
+ const y = b;
291
+ const px = x.indexes?.primary;
292
+ const py = y.indexes?.primary;
293
+ const sx = x._schema;
294
+ const sy = y._schema;
295
+ if (px === undefined || py === undefined || sx === undefined || sy === undefined)
296
+ return false;
297
+ const fieldsOf = (model) => model === undefined || model === null
298
+ ? undefined
299
+ : getSchemaFields(isConfiguredModel(model) ? model.model : model);
300
+ const fx = fieldsOf(x.model);
301
+ const fy = fieldsOf(y.model);
302
+ const typeOf = (fields, composite) => {
303
+ if (fields === undefined || !Object.hasOwn(fields, composite))
304
+ return undefined;
305
+ const field = fields[composite];
306
+ const kind = keyFormValueKind(field);
307
+ return kind !== undefined ? kind : JSON.stringify([kind, keyFormLiterals(field)]);
308
+ };
309
+ const same = (u, v) => u.length === v.length && u.every((name, i) => name === v[i]);
310
+ return (x.entityType === y.entityType &&
311
+ (x._entityVersion ?? 1) === (y._entityVersion ?? 1) &&
312
+ sx.name === sy.name &&
313
+ sx.version === sy.version &&
314
+ sx.casing === sy.casing &&
315
+ (sx.escapeKeys === true) === (sy.escapeKeys === true) &&
316
+ same(px.pk.composite, py.pk.composite) &&
317
+ same(px.sk.composite, py.sk.composite) &&
318
+ px.casing === py.casing &&
319
+ JSON.stringify(px.collection) === JSON.stringify(py.collection) &&
320
+ px.type === py.type &&
321
+ [...px.pk.composite, ...px.sk.composite].every((composite) => {
322
+ const t = typeOf(fx, composite);
323
+ return t !== undefined && t === typeOf(fy, composite);
324
+ }));
325
+ };
326
+ /**
327
+ * @internal `[EDD-9134]`: among `members` (each named as `site`'s message shows it), a read model
328
+ * whose projection's outbox is on another table, where another read model in the same key space
329
+ * has its outbox too. Tables are compared by the physical name the context resolves (two handles
330
+ * on one table are one table), and by service when one isn't provided. The problem, or `undefined`.
331
+ *
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`:
339
+ *
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
345
+ * the read model's (`sameKeys`) moves them where the read model would, and isn't refused.
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
+ *
350
+ * Read models that never meet at a site that sees several at once can't be checked: their key
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.
353
+ */
354
+ export const sharedOutboxKeySpace = (site, given, scope) => Effect.gen(function* () {
355
+ const plain = scope === "plain";
356
+ const members = given.filter(([, entity]) => typeof entity === "object" && entity !== null);
357
+ // Every table a member's outbox is on, by its physical name.
358
+ const names = new Map();
359
+ for (const [, entity] of members) {
360
+ for (const { table } of remoteOutboxesOf(entity)) {
361
+ if (!names.has(table.Tag.key)) {
362
+ names.set(table.Tag.key, yield* physicalTableName(table.Tag));
363
+ }
364
+ }
365
+ }
366
+ const oneTable = (a, b) => {
367
+ if (a.key === b.key)
368
+ return true;
369
+ const name = names.get(a.key);
370
+ return name !== undefined && name === names.get(b.key);
371
+ };
372
+ const startOf = (space) => `(partition keys starting "${space.pk.text}", sort keys starting "${space.sk.text}": the ` +
373
+ "same schema name and version, primary collection, entity type and first composite)";
374
+ for (const [name, entity] of members) {
375
+ const space = keySpaceOf(entity, "plain");
376
+ if (space === undefined)
377
+ continue;
378
+ for (const outbox of remoteOutboxesOf(entity)) {
379
+ const into = outbox.table.Tag;
380
+ if (!plain && into.key !== scope.key && names.get(into.key) !== scope.name)
381
+ continue;
382
+ const physical = names.get(into.key);
383
+ for (const [otherName, other] of members) {
384
+ if (other === entity)
385
+ continue;
386
+ if (!remoteOutboxesOf(other).some((o) => oneTable(o.table.Tag, into)))
387
+ continue;
388
+ if (!overwriteEachOther(entity, other))
389
+ continue;
390
+ return (`[EDD-9134] ${site}: ${name} writes its projection's outbox items into another ` +
391
+ `table${physical === undefined ? "" : ` ("${physical}")`}, where ${otherName} ` +
392
+ `writes its own under the same key space ${startOf(space)}. ` +
393
+ "Their items would overwrite each other whenever their keys match, and rekey " +
394
+ "couldn't tell whose an item is. " +
395
+ "Give one of them its own entity type, collection, schema or key composites.");
396
+ }
397
+ if (plain)
398
+ continue;
399
+ // The members of the table being rekeyed that claim this read model's outbox items.
400
+ for (const [memberName, member] of scope.members) {
401
+ if (member === entity)
402
+ continue;
403
+ const claims = handlerOf(member)?.types.includes(`${readModelType(entity)}#outbox`);
404
+ if (claims !== true || sameKeys(member, entity) || !overwriteEachOther(entity, member)) {
405
+ continue;
406
+ }
407
+ return (`[EDD-9134] ${site}: ${name} writes its projection's outbox items into another ` +
408
+ `table${physical === undefined ? "" : ` ("${physical}")`}, whose member ` +
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.");
413
+ }
414
+ }
415
+ }
416
+ return undefined;
417
+ });
418
+ /** An entity's type, as its rows' `__edd_e__` names it. */
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
+ });
664
+ /**
665
+ * @internal `[EDD-9134]` ({@link sharedOutboxKeySpace}) as a defect, from the sites that define
666
+ * what runs (`DynamoClient.make`, `EventStore.processBatch`), before anything runs.
667
+ */
668
+ export const refuseSharedOutboxKeySpace = (site, members) => Effect.flatMap(sharedOutboxKeySpace(site, members, "plain"), (problem) => problem === undefined ? Effect.void : Effect.die(new Error(problem)));
88
669
  export const makeEngine = (config) => {
89
670
  const { readModel } = config;
90
671
  const entityType = readModel.entityType;
@@ -119,31 +700,96 @@ export const makeEngine = (config) => {
119
700
  }
120
701
  return [...kept];
121
702
  })();
122
- // Resolved when it runs: an entity's table is set when it is registered on
123
- // one, which may come after the projection is defined.
124
- // Rows may be tombstones (#154): the entity's `create` takes one's place,
125
- // keeping these fields — the checkpoints — and the revision one higher.
126
- if (config.removal !== undefined) {
127
- ;
128
- readModel._projectionTombstones = {
129
- kept: keptFields.filter((f) => f !== config.revision?.field),
130
- revision: config.revision?.field,
131
- };
703
+ // Each attribute the projection keeps on a row, with its role: the checkpoints, then the
704
+ // revision, as a tombstone stores them. An attribute in two roles is listed in each, and refused
705
+ // (`[EDD-9133]`, `addProjectionLayout`) when the read model's rows may be tombstones.
706
+ const roles = [];
707
+ const giveRole = (field, role) => {
708
+ if (!roles.some(([named, held]) => named === field && held === role))
709
+ roles.push([field, role]);
710
+ };
711
+ if (config.checkpoints.kind === "scalar")
712
+ giveRole(config.checkpoints.field, "checkpoint");
713
+ else {
714
+ if (config.checkpoints.map !== undefined)
715
+ giveRole(config.checkpoints.map, "checkpoint map");
716
+ for (const f of Object.values(config.checkpoints.fields)) {
717
+ giveRole(f.field, "checkpoint");
718
+ giveRole(f.instanceField, "checkpoint owner");
719
+ }
132
720
  }
133
- // An outbox on another table: that table's `rekey` moves its items (#171).
134
- if (config.outbox?.table !== undefined) {
135
- ;
136
- readModel._projectionOutbox = {
721
+ if (config.revision !== undefined)
722
+ giveRole(config.revision.field, "revision");
723
+ // Recorded beside the layouts of the read model's other projections, whether or not it has
724
+ // `removal`, for the checks of `[EDD-9133]`. Rows may be tombstones (#154) when one has
725
+ // `removal`: the entity's `create` takes one's place, keeping the checkpoints of the projection
726
+ // with `removal` that wrote it, with its revision one higher (`overTombstone`).
727
+ const ownLayout = {
728
+ label: config.label,
729
+ roles,
730
+ removal: config.removal !== undefined,
731
+ ttl: config.removal?.ttl !== undefined,
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
+ }
745
+ // Every projection's outbox, kept on the read model, one entry per distinct layout, the one defined
746
+ // last at the end: a second projection doesn't hide the first's, which stays callable, and one
747
+ // defined again adds nothing. One on another table (`table`) is moved by that table's `rekey`
748
+ // (#171). Wherever it is, an aggregate declaring `ownsRows` is checked against its items at bind
749
+ // (DESIGN.md §7 "Which rows in its partition are an aggregate's"), with the index keys it writes
750
+ // on them.
751
+ if (config.outbox !== undefined) {
752
+ const holder = readModel;
753
+ const layout = {
137
754
  table: config.outbox.table,
138
755
  pk: config.outbox.pk,
139
756
  sk: config.outbox.sk,
757
+ index: config.outbox.index,
140
758
  };
759
+ const same = (other) => other.table?.Tag === layout.table?.Tag &&
760
+ other.pk === layout.pk &&
761
+ other.sk === layout.sk &&
762
+ other.index?.name === layout.index?.name &&
763
+ other.index?.pk === layout.index?.pk &&
764
+ other.index?.sk === layout.index?.sk;
765
+ holder._projectionOutboxes = [
766
+ ...(holder._projectionOutboxes ?? []).filter((other) => !same(other)),
767
+ layout,
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);
141
781
  }
142
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))));
143
788
  /** The row, read strongly consistent — raw, so a tombstone reads as one. */
144
789
  const readRow = (key) => Effect.gen(function* () {
145
790
  const client = yield* Capacity.client;
146
791
  const TableName = yield* tableName;
792
+ const inUse = yield* tokenInUse;
147
793
  const { Item: item } = yield* client.getItem({
148
794
  TableName,
149
795
  Key: toAttributeMap(composePrimaryKey(readModel, key)),
@@ -151,28 +797,31 @@ export const makeEngine = (config) => {
151
797
  });
152
798
  if (item === undefined)
153
799
  return Option.none();
800
+ const token = inUse && Object.hasOwn(item, ROW_TOKEN) ? item[ROW_TOKEN] : undefined;
154
801
  if (item.__edd_e__?.S === tombstoneMarker(entityType)) {
155
802
  const raw = fromAttributeMap(item);
156
803
  const values = {};
157
804
  for (const f of keptFields) {
158
- const v = raw[dbName(f)];
805
+ const v = ownValue(raw, dbName(f));
159
806
  if (v !== undefined)
160
807
  values[f] = v;
161
808
  }
162
- return Option.some({ values, tombstone: true, createdAt: undefined });
809
+ return Option.some({ values, tombstone: true, createdAt: undefined, item, token });
163
810
  }
164
811
  const decoded = (yield* decodeMarshalledItem(readModel, item));
165
812
  let values = decoded;
166
813
  if (fields !== undefined) {
167
814
  values = {};
168
815
  for (const f of fields)
169
- if (decoded[f] !== undefined)
170
- values[f] = decoded[f];
816
+ if (ownValue(decoded, f) !== undefined)
817
+ values[f] = ownValue(decoded, f);
171
818
  }
172
819
  return Option.some({
173
820
  values: readModel._attachPrototype?.(values) ?? values,
174
821
  tombstone: false,
175
- createdAt: createdAtField === null ? undefined : decoded[createdAtField],
822
+ createdAt: createdAtField === null ? undefined : ownValue(decoded, createdAtField),
823
+ item,
824
+ token,
176
825
  });
177
826
  });
178
827
  /**
@@ -185,20 +834,20 @@ export const makeEngine = (config) => {
185
834
  const values = Option.isSome(row) ? row.value.values : undefined;
186
835
  const layout = config.checkpoints;
187
836
  if (layout.kind === "scalar") {
188
- const v = values?.[layout.field];
837
+ const v = ownValue(values, layout.field);
189
838
  return { kind: "scalar", at: v === undefined ? 0 : Number(v) - layout.offset };
190
839
  }
191
840
  const mapped = layout.fields[source];
192
841
  const fromMap = () => {
193
- const map = (values?.[layout.map] ?? {});
842
+ const map = (ownValue(values, layout.map) ?? {});
194
843
  const v = map[instanceKey(source, streamIdStr)];
195
844
  return { kind: "map", at: v === undefined ? 0 : Number(v) };
196
845
  };
197
846
  if (mapped === undefined)
198
847
  return fromMap();
199
- const stored = values?.[mapped.instanceField];
848
+ const stored = ownValue(values, mapped.instanceField);
200
849
  const owner = claimed.get(source) ?? (stored === null || stored === "" ? undefined : stored);
201
- const scalar = values?.[mapped.field];
850
+ const scalar = ownValue(values, mapped.field);
202
851
  const at = scalar === undefined ? 0 : Number(scalar) - mapped.offset;
203
852
  // No owner recorded: a new row, or a legacy one — adopted by this instance.
204
853
  if (owner === undefined && !adopt)
@@ -220,7 +869,7 @@ export const makeEngine = (config) => {
220
869
  const revisionOf = (row) => {
221
870
  if (config.revision === undefined || Option.isNone(row))
222
871
  return undefined;
223
- const v = row.value.values[config.revision.field];
872
+ const v = ownValue(row.value.values, config.revision.field);
224
873
  return v === undefined ? undefined : Number(v);
225
874
  };
226
875
  /** The revision the next write stores: one higher, or `initial` for a row without one. */
@@ -239,15 +888,16 @@ export const makeEngine = (config) => {
239
888
  else {
240
889
  // Carry every field the layout owns over from the row, then advance.
241
890
  for (const f of Object.values(layout.fields)) {
242
- if (target[f.field] === undefined && previous?.[f.field] !== undefined)
243
- target[f.field] = previous[f.field];
244
- if (target[f.instanceField] === undefined && previous?.[f.instanceField] !== undefined) {
245
- target[f.instanceField] = previous[f.instanceField];
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);
246
896
  }
247
897
  }
248
898
  const map = layout.map === undefined
249
899
  ? {}
250
- : { ...(previous?.[layout.map] ?? {}) };
900
+ : { ...(ownValue(previous, layout.map) ?? {}) };
251
901
  for (const a of advanced) {
252
902
  if (a.slot.kind === "field") {
253
903
  const mapped = layout.fields[a.source];
@@ -259,7 +909,7 @@ export const makeEngine = (config) => {
259
909
  }
260
910
  // An empty map stays absent on a row that had none.
261
911
  if (layout.map !== undefined &&
262
- (Object.keys(map).length > 0 || previous?.[layout.map] !== undefined))
912
+ (Object.keys(map).length > 0 || ownValue(previous, layout.map) !== undefined))
263
913
  target[layout.map] = map;
264
914
  }
265
915
  if (config.revision !== undefined)
@@ -295,7 +945,7 @@ export const makeEngine = (config) => {
295
945
  },
296
946
  };
297
947
  }
298
- const stored = row.value.values[layout.field];
948
+ const stored = ownValue(row.value.values, layout.field);
299
949
  // A row written before the projection: no checkpoint yet.
300
950
  if (stored === undefined) {
301
951
  return {
@@ -327,19 +977,55 @@ export const makeEngine = (config) => {
327
977
  ? { pk: primary.pk.field, sk: primary.sk.field }
328
978
  : { pk: config.outbox.pk, sk: config.outbox.sk };
329
979
  const pad = (n, width) => String(n).padStart(width, "0");
330
- const outboxItems = (rowKey, revision, enqueued, mark) => Effect.forEach(enqueued, (e, i) => Effect.gen(function* () {
980
+ const outboxReadBack = config.outbox === undefined
981
+ ? undefined
982
+ : readBackOf(config.outbox.schema, () => readingStreamValues(config.outbox.schema));
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* () {
331
1005
  const outbox = config.outbox;
332
- const encoded = yield* S.encodeUnknownEffect(outbox.schema)(e.effect).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.outbox`, cause })));
1006
+ const encoded = yield* S.encodeUnknownEffect(writingTuplePositions(outbox.schema))(e.effect).pipe(Effect.tap((wire) => outboxReadBack === undefined
1007
+ ? Effect.void
1008
+ : outboxReadBack(wire).pipe(Effect.mapError((issue) => notReadBack("The outbox effect", issue)))), Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.outbox`, cause })));
333
1009
  const keys = outboxKeys();
334
1010
  const rowPk = String(rowKey[primary.pk.field]);
335
1011
  const rowSk = String(rowKey[primary.sk.field]);
336
- const sk = `${rowSk}#outbox#${pad(revision, 12)}#${pad(i, 4)}`;
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;
337
1022
  const item = {
338
1023
  [keys.pk]: rowPk,
339
1024
  [keys.sk]: sk,
340
1025
  __edd_e__: outboxMarker(entityType),
341
1026
  [ROW_PK]: rowPk,
342
1027
  [ROW_SK]: rowSk,
1028
+ ...(marked !== undefined && { [OUTBOX_READ_MODEL]: marked }),
343
1029
  effect: encoded,
344
1030
  source: e.source,
345
1031
  streamId: e.event.streamId,
@@ -351,22 +1037,184 @@ export const makeEngine = (config) => {
351
1037
  item[outbox.index.pk] = outboxMarker(entityType);
352
1038
  item[outbox.index.sk] = `${rowPk}#${sk}`;
353
1039
  }
354
- return toAttributeMap(item);
1040
+ return yield* marshalOrFail(entityType, `${config.label}.outbox`, () => toAttributeMap(item));
355
1041
  }));
356
- /** A lost race, from a single write's or a transaction's failure: the row's Put cancelled. */
357
- const lostRaceOf = (error, transaction) => {
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) => {
358
1049
  const cause = error?.cause;
359
- if (!transaction)
360
- return isAwsConditionalCheckFailed(cause);
361
- return (isAwsTransactionCancelled(cause) &&
362
- (cause.CancellationReasons ?? []).some((reason) => reason?.Code === "ConditionalCheckFailed"));
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;
363
1172
  };
364
1173
  /** The row (or tombstone) and any outbox items, written as one conditional unit. */
365
- const writeRow = (key, target, kept, row, enqueued, revision) => Effect.gen(function* () {
1174
+ const writeRow = (key, target, kept, row, enqueued, revision, carried = {}) => Effect.gen(function* () {
366
1175
  const client = yield* Capacity.client;
367
1176
  const TableName = yield* tableName;
368
1177
  const rowKey = composePrimaryKey(readModel, key);
369
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);
370
1218
  const createdAt = Option.isSome(row) ? row.value.createdAt : undefined;
371
1219
  // A tombstone or outbox item holds no values, so its key alone says which text it is for
372
1220
  // `rekey` (`KEY_TEXT`): one under the text of `escapeKeys: true`, where that isn't off's, is
@@ -389,15 +1237,22 @@ export const makeEngine = (config) => {
389
1237
  if (config.removal?.ttl !== undefined) {
390
1238
  tomb[resolveTtlAttributeName(tc)] = Math.floor((DateTime.toEpochMillis(now) + Dur.toMillis(config.removal.ttl)) / 1000);
391
1239
  }
392
- rowItem = toAttributeMap(tomb);
1240
+ // A sparse-map key is refused as the row's own write refuses it. The check flattens a
1241
+ // copy: what's stored is the tombstone as 1.39.0 stored it, an empty map whole.
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;
1249
+ rowItem = yield* marshalOrFail(entityType, `${config.label}.write`, () => toAttributeMap(tomb));
393
1250
  }
394
1251
  else if (enqueued.length > 0) {
395
- const built = yield* validateAndBuildPutItem(readModel, target.value, `${config.label}.write`);
396
- const item = { ...built.item };
397
- if (createdAtField !== null && DateTime.isDateTime(createdAt)) {
398
- item[dbName(createdAtField)] = generateTimestampPrimitive(DateTime.toUtc(createdAt), readModel.systemFields.createdAtEncoding);
399
- }
400
- rowItem = toAttributeMap(item);
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;
1255
+ rowItem = toAttributeMap(built.item);
401
1256
  }
402
1257
  if (rowItem === undefined) {
403
1258
  // The row alone, through the entity: `put` conditioned on the guard
@@ -406,45 +1261,122 @@ export const makeEngine = (config) => {
406
1261
  const op = condition.input === undefined
407
1262
  ? readModel.create(value)
408
1263
  : entityCondition(readModel.put(value), condition.input);
409
- const run = condition.input === undefined
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
410
1267
  ? op.asEffect()
411
1268
  : op._builder("model", {
412
1269
  condition: op._condition,
413
1270
  withVectors: op._withVectors,
414
1271
  putKind: op._putKind,
415
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
+ }),
416
1281
  });
417
- 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)))));
418
1287
  return Option.some(written);
419
1288
  }
420
- const lostRace = (error, transaction) => Effect.fail(lostRaceOf(error, transaction) ? new LostRace(key) : 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);
421
1293
  const rowPut = {
422
1294
  Put: {
423
1295
  TableName,
424
1296
  Item: rowItem,
425
- ConditionExpression: condition.raw.expression,
426
- ExpressionAttributeNames: condition.raw.names,
427
- ...(Object.keys(condition.raw.values).length > 0
428
- ? { ExpressionAttributeValues: condition.raw.values }
429
- : {}),
1297
+ ConditionExpression: raw.expression,
1298
+ ExpressionAttributeNames: raw.names,
1299
+ ...(Object.keys(raw.values).length > 0 ? { ExpressionAttributeValues: raw.values } : {}),
1300
+ ...(returnOld && { ReturnValuesOnConditionCheckFailure: "ALL_OLD" }),
430
1301
  },
431
1302
  };
432
1303
  if (enqueued.length === 0) {
433
- yield* client.putItem(rowPut.Put).pipe(Effect.catch((error) => lostRace(error, false)));
1304
+ yield* client.putItem(rowPut.Put).pipe(Effect.catch((error) => lostRace(error)));
1305
+ return target;
434
1306
  }
435
- else {
436
- const OutboxTable = yield* outboxTable;
437
- const items = yield* outboxItems(rowKey, revision ?? 0, enqueued, mark);
438
- yield* client
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
439
1323
  .transactWriteItems({
440
1324
  TransactItems: [
441
1325
  rowPut,
442
- ...items.map((Item) => ({ Put: { TableName: OutboxTable, 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
+ })),
443
1336
  ],
444
1337
  })
445
- .pipe(Effect.catch((error) => lostRace(error, true)));
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);
446
1379
  }
447
- return target;
448
1380
  });
449
1381
  // -------------------------------------------------------------------------
450
1382
  // Apply
@@ -465,6 +1397,28 @@ export const makeEngine = (config) => {
465
1397
  `${to}: a strongly consistent read did not return them. Was the stream written ` +
466
1398
  "outside `append`?",
467
1399
  }));
1400
+ /**
1401
+ * `[EDD-9133]` once the table's TTL attribute is known: an attribute a projection keeps on the
1402
+ * read model's rows that is stored as the TTL attribute, which a projection's tombstones set. The
1403
+ * two would overwrite each other, and a row could expire. Every entry point that writes a row
1404
+ * runs it before it sends anything, whatever the data: `applyRow` for each row, and `catchUp` and
1405
+ * `rebuild` first (`operation` names the entry point). The drains write no row and don't run it:
1406
+ * a worker providing only its outbox's table delivers as on 1.39.0.
1407
+ */
1408
+ const preflight = (operation) => Effect.suspend(() =>
1409
+ // The table is resolved only when there is something to check.
1410
+ !projectionTtlChecked(readModel)
1411
+ ? Effect.void
1412
+ : Effect.flatMap(readModel._tableTag, (tc) => {
1413
+ const problem = projectionTtlConflict(readModel, resolveTtlAttributeName(tc));
1414
+ return problem === undefined
1415
+ ? Effect.void
1416
+ : Effect.fail(new ValidationError({
1417
+ entityType,
1418
+ operation: `${config.label}.${operation}`,
1419
+ cause: problem,
1420
+ }));
1421
+ }));
468
1422
  const withRetry = (attempt) => Effect.retry(attempt, {
469
1423
  schedule: config.retry,
470
1424
  while: (error) => error instanceof LostRace,
@@ -472,9 +1426,7 @@ export const makeEngine = (config) => {
472
1426
  ? new ConcurrentModification({
473
1427
  entityType,
474
1428
  key: error.key,
475
- attributes: [
476
- config.revision?.field ?? config.checkpoints.field,
477
- ],
1429
+ attributes: error.attributes,
478
1430
  current: Option.none(),
479
1431
  })
480
1432
  : error));
@@ -533,6 +1485,13 @@ export const makeEngine = (config) => {
533
1485
  const fromScratch = options?.fromScratch === true;
534
1486
  const attempt = Effect.gen(function* () {
535
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
+ }
536
1495
  const slotRow = fromScratch ? Option.none() : row;
537
1496
  /**
538
1497
  * Each instance's slot and run, in fold order. `barred` instances read an
@@ -716,7 +1675,12 @@ export const makeEngine = (config) => {
716
1675
  // Every instance failed: the row fails, with the first failure.
717
1676
  if (active.length === 0 && failed.length > 0)
718
1677
  return yield* Effect.fail(failed[0].error);
719
- const { state, removed, enqueued, results } = folded;
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;
720
1684
  const instances = (version) => active.map((plan, i) => ({
721
1685
  source: plan.work.source.name,
722
1686
  streamId: plan.work.streamIdStr,
@@ -760,11 +1724,14 @@ export const makeEngine = (config) => {
760
1724
  if (fromScratch && config.revision !== undefined) {
761
1725
  target[config.revision.field] = nextRevisionOf(row);
762
1726
  }
763
- const nextRevision = config.revision === undefined ? undefined : target[config.revision.field];
1727
+ const nextRevision = config.revision === undefined
1728
+ ? undefined
1729
+ : ownValue(target, config.revision.field);
764
1730
  let written;
765
1731
  if (Option.isNone(state)) {
766
- // A tombstone keeps exactly the layout's fields.
767
- written = yield* writeRow(key, Option.none(), pick(target), row, enqueued, nextRevision);
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));
768
1735
  }
769
1736
  else {
770
1737
  const mapped = config.toItem === undefined
@@ -773,7 +1740,39 @@ export const makeEngine = (config) => {
773
1740
  ...(yield* call("toItem", () => config.toItem(target, config.toItemContext(key, work)))),
774
1741
  ...pick(target),
775
1742
  };
776
- written = yield* writeRow(key, Option.some(mapped), {}, row, enqueued, nextRevision);
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);
777
1776
  }
778
1777
  const versions = new Map(advanced.map((a) => [`${a.source}\u0000${a.streamIdStr}`, a.version]));
779
1778
  return {
@@ -787,30 +1786,175 @@ export const makeEngine = (config) => {
787
1786
  failed,
788
1787
  };
789
1788
  });
790
- return withRetry(attempt);
1789
+ return Effect.andThen(preflight("apply"), withRetry(attempt));
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;
791
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
+ });
792
1926
  /** The fields the library owns, re-applied after `toItem`. */
793
1927
  const pick = (target) => {
794
1928
  const out = {};
795
1929
  for (const f of keptFields)
796
- if (target[f] !== undefined)
797
- out[f] = target[f];
1930
+ if (ownValue(target, f) !== undefined)
1931
+ setOwn(out, f, ownValue(target, f));
798
1932
  return out;
799
1933
  };
800
1934
  // -------------------------------------------------------------------------
801
1935
  // Outbox drain (#155)
802
1936
  // -------------------------------------------------------------------------
1937
+ // A decode that dies on an absent attribute fails as 1.39.0's did (`decodingAsBefore`).
1938
+ const decodeEffect = decodingAsBefore(readingStreamValues(config.outbox?.schema ?? S.Unknown), config.outbox?.schema ?? S.Unknown);
803
1939
  /**
804
1940
  * Deliver a row's pending effects in order: claim the head item, deliver it,
805
1941
  * delete it, repeat. A claim another drainer holds stops the drain; a crash
806
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.
807
1948
  */
808
1949
  const drainRaw = (rowPk, rowSk, deliver) => Effect.gen(function* () {
809
1950
  const outbox = config.outbox;
810
1951
  const client = yield* Capacity.client;
811
1952
  const TableName = yield* outboxTable;
812
1953
  const keys = outboxKeys();
1954
+ const whose = outboxOwnership(readModel);
813
1955
  let delivered = 0;
1956
+ // The last item passed over as another read model's: the query goes on after it.
1957
+ let after;
814
1958
  while (true) {
815
1959
  const page = yield* client.query({
816
1960
  TableName,
@@ -819,10 +1963,15 @@ export const makeEngine = (config) => {
819
1963
  ExpressionAttributeValues: toAttributeMap({ ":pk": rowPk, ":sk": `${rowSk}#outbox#` }),
820
1964
  ConsistentRead: true,
821
1965
  Limit: 1,
1966
+ ...(after === undefined ? {} : { ExclusiveStartKey: after }),
822
1967
  });
823
1968
  const head = page.Items?.[0];
824
1969
  if (head === undefined)
825
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
+ }
826
1975
  const raw = fromAttributeMap(head);
827
1976
  const now = DateTime.toEpochMillis(yield* DateTime.now);
828
1977
  const token = `${now}-${Math.floor((yield* Random.next) * 1e9)}`;
@@ -843,7 +1992,7 @@ export const makeEngine = (config) => {
843
1992
  // Another drainer holds the head: it delivers in order; stop here.
844
1993
  if (!claimed)
845
1994
  return { delivered, undelivered: Option.none() };
846
- const effect = yield* S.decodeUnknownEffect(outbox.schema)(raw.effect).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.drain`, cause })));
1995
+ const effect = yield* decodeEffect(raw.effect).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.drain`, cause })));
847
1996
  const meta = {
848
1997
  source: String(raw.source),
849
1998
  streamId: String(raw.streamId),
@@ -883,7 +2032,12 @@ export const makeEngine = (config) => {
883
2032
  const rowKey = composePrimaryKey(readModel, key);
884
2033
  return drainRaw(String(rowKey[primary.pk.field]), String(rowKey[primary.sk.field]), deliver);
885
2034
  };
886
- /** Every row with pending effects, through the outbox's sparse index, drained. */
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
+ */
887
2041
  const drainPending = (deliver) => Effect.gen(function* () {
888
2042
  const outbox = config.outbox;
889
2043
  if (outbox.index === undefined) {
@@ -895,6 +2049,7 @@ export const makeEngine = (config) => {
895
2049
  }
896
2050
  const client = yield* Capacity.client;
897
2051
  const TableName = yield* outboxTable;
2052
+ const whose = outboxOwnership(readModel);
898
2053
  const rows = new Map();
899
2054
  let start;
900
2055
  do {
@@ -907,6 +2062,8 @@ export const makeEngine = (config) => {
907
2062
  ...(start === undefined ? {} : { ExclusiveStartKey: start }),
908
2063
  });
909
2064
  for (const item of page.Items ?? []) {
2065
+ if (whose(item) === "foreign")
2066
+ continue;
910
2067
  const raw = fromAttributeMap(item);
911
2068
  const pk = String(raw[ROW_PK]);
912
2069
  const sk = String(raw[ROW_SK]);
@@ -924,7 +2081,15 @@ export const makeEngine = (config) => {
924
2081
  }
925
2082
  return { delivered, undelivered };
926
2083
  });
927
- return { readRow, applyRow, drain, drainPending, call };
2084
+ return {
2085
+ readRow,
2086
+ // A key the row can't compose is that row's failure, not the batch's.
2087
+ applyRow: (key, work, options) => Capacity.refusalsFail(`${config.label}.apply`, { target: entityType }, applyRow(key, work, options)),
2088
+ drain,
2089
+ drainPending,
2090
+ preflight,
2091
+ call,
2092
+ };
928
2093
  };
929
2094
  /**
930
2095
  * The default lost-race policy: up to 12 retries after a jittered delay