effect-dynamodb 1.38.0 → 1.40.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (152) hide show
  1. package/dist/Aggregate.d.ts +119 -15
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +2286 -670
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.d.ts +9 -5
  6. package/dist/Batch.d.ts.map +1 -1
  7. package/dist/Batch.js +97 -232
  8. package/dist/Batch.js.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +27 -21
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/ConsumedCapacity.js +1 -1
  13. package/dist/ConsumedCapacity.js.map +1 -1
  14. package/dist/DynamoClient.d.ts +44 -16
  15. package/dist/DynamoClient.d.ts.map +1 -1
  16. package/dist/DynamoClient.js +299 -166
  17. package/dist/DynamoClient.js.map +1 -1
  18. package/dist/Entity.d.ts +94 -104
  19. package/dist/Entity.d.ts.map +1 -1
  20. package/dist/Entity.js +3673 -3022
  21. package/dist/Entity.js.map +1 -1
  22. package/dist/EventStore.d.ts +39 -17
  23. package/dist/EventStore.d.ts.map +1 -1
  24. package/dist/EventStore.js +392 -366
  25. package/dist/EventStore.js.map +1 -1
  26. package/dist/Marshaller.d.ts +39 -9
  27. package/dist/Marshaller.d.ts.map +1 -1
  28. package/dist/Marshaller.js +421 -70
  29. package/dist/Marshaller.js.map +1 -1
  30. package/dist/Query.d.ts +93 -32
  31. package/dist/Query.d.ts.map +1 -1
  32. package/dist/Query.js +550 -83
  33. package/dist/Query.js.map +1 -1
  34. package/dist/StorageEncoding.d.ts +7 -1
  35. package/dist/StorageEncoding.d.ts.map +1 -1
  36. package/dist/StorageEncoding.js +8 -2
  37. package/dist/StorageEncoding.js.map +1 -1
  38. package/dist/Table.d.ts +71 -4
  39. package/dist/Table.d.ts.map +1 -1
  40. package/dist/Table.js +7 -0
  41. package/dist/Table.js.map +1 -1
  42. package/dist/Transaction.d.ts +2 -18
  43. package/dist/Transaction.d.ts.map +1 -1
  44. package/dist/Transaction.js +11 -62
  45. package/dist/Transaction.js.map +1 -1
  46. package/dist/change-feed/ChangeFeed.d.ts +8 -3
  47. package/dist/change-feed/ChangeFeed.d.ts.map +1 -1
  48. package/dist/change-feed/ChangeFeed.js +76 -9
  49. package/dist/change-feed/ChangeFeed.js.map +1 -1
  50. package/dist/change-feed/CheckpointStore.js +1 -1
  51. package/dist/change-feed/CheckpointStore.js.map +1 -1
  52. package/dist/change-feed/DynamoStreamsClient.d.ts +12 -5
  53. package/dist/change-feed/DynamoStreamsClient.d.ts.map +1 -1
  54. package/dist/change-feed/DynamoStreamsClient.js +15 -9
  55. package/dist/change-feed/DynamoStreamsClient.js.map +1 -1
  56. package/dist/index.d.ts +1 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js +1 -1
  59. package/dist/index.js.map +1 -1
  60. package/dist/internal/BoundCrud.d.ts +40 -32
  61. package/dist/internal/BoundCrud.d.ts.map +1 -1
  62. package/dist/internal/BoundCrud.js.map +1 -1
  63. package/dist/internal/BoundQuery.d.ts +12 -9
  64. package/dist/internal/BoundQuery.d.ts.map +1 -1
  65. package/dist/internal/BoundQuery.js +26 -12
  66. package/dist/internal/BoundQuery.js.map +1 -1
  67. package/dist/internal/BoundVectorQuery.d.ts.map +1 -1
  68. package/dist/internal/BoundVectorQuery.js +2 -1
  69. package/dist/internal/BoundVectorQuery.js.map +1 -1
  70. package/dist/internal/Capacity.d.ts +44 -4
  71. package/dist/internal/Capacity.d.ts.map +1 -1
  72. package/dist/internal/Capacity.js +89 -15
  73. package/dist/internal/Capacity.js.map +1 -1
  74. package/dist/internal/ClientOptions.d.ts +72 -0
  75. package/dist/internal/ClientOptions.d.ts.map +1 -0
  76. package/dist/internal/ClientOptions.js +79 -0
  77. package/dist/internal/ClientOptions.js.map +1 -0
  78. package/dist/internal/Cursor.d.ts +28 -14
  79. package/dist/internal/Cursor.d.ts.map +1 -1
  80. package/dist/internal/Cursor.js +37 -12
  81. package/dist/internal/Cursor.js.map +1 -1
  82. package/dist/internal/EntityCombinators.d.ts +22 -7
  83. package/dist/internal/EntityCombinators.d.ts.map +1 -1
  84. package/dist/internal/EntityCombinators.js +6 -2
  85. package/dist/internal/EntityCombinators.js.map +1 -1
  86. package/dist/internal/EntityOps.d.ts +11 -1
  87. package/dist/internal/EntityOps.d.ts.map +1 -1
  88. package/dist/internal/EntityOps.js.map +1 -1
  89. package/dist/internal/EventProjection.d.ts +15 -3
  90. package/dist/internal/EventProjection.d.ts.map +1 -1
  91. package/dist/internal/EventProjection.js +27 -8
  92. package/dist/internal/EventProjection.js.map +1 -1
  93. package/dist/internal/Expr.d.ts.map +1 -1
  94. package/dist/internal/Expr.js +53 -2
  95. package/dist/internal/Expr.js.map +1 -1
  96. package/dist/internal/ExpressionLimits.d.ts +57 -1
  97. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  98. package/dist/internal/ExpressionLimits.js +90 -1
  99. package/dist/internal/ExpressionLimits.js.map +1 -1
  100. package/dist/internal/ItemSize.d.ts +108 -4
  101. package/dist/internal/ItemSize.d.ts.map +1 -1
  102. package/dist/internal/ItemSize.js +190 -3
  103. package/dist/internal/ItemSize.js.map +1 -1
  104. package/dist/internal/MultiProjection.d.ts +7 -2
  105. package/dist/internal/MultiProjection.d.ts.map +1 -1
  106. package/dist/internal/MultiProjection.js +9 -3
  107. package/dist/internal/MultiProjection.js.map +1 -1
  108. package/dist/internal/PathBuilder.d.ts +15 -4
  109. package/dist/internal/PathBuilder.d.ts.map +1 -1
  110. package/dist/internal/PathBuilder.js +20 -10
  111. package/dist/internal/PathBuilder.js.map +1 -1
  112. package/dist/internal/ProjectionEngine.d.ts +78 -18
  113. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  114. package/dist/internal/ProjectionEngine.js +402 -257
  115. package/dist/internal/ProjectionEngine.js.map +1 -1
  116. package/dist/internal/RangePlanner.d.ts +0 -76
  117. package/dist/internal/RangePlanner.d.ts.map +1 -1
  118. package/dist/internal/RangePlanner.js +2 -206
  119. package/dist/internal/RangePlanner.js.map +1 -1
  120. package/dist/internal/Rekey.d.ts +49 -7
  121. package/dist/internal/Rekey.d.ts.map +1 -1
  122. package/dist/internal/Rekey.js +113 -10
  123. package/dist/internal/Rekey.js.map +1 -1
  124. package/dist/internal/RoundTrip.d.ts +36 -0
  125. package/dist/internal/RoundTrip.d.ts.map +1 -0
  126. package/dist/internal/RoundTrip.js +79 -0
  127. package/dist/internal/RoundTrip.js.map +1 -0
  128. package/dist/internal/SentRequest.d.ts +14 -0
  129. package/dist/internal/SentRequest.d.ts.map +1 -0
  130. package/dist/internal/SentRequest.js +31 -0
  131. package/dist/internal/SentRequest.js.map +1 -0
  132. package/dist/internal/ShardMerge.d.ts +83 -0
  133. package/dist/internal/ShardMerge.d.ts.map +1 -0
  134. package/dist/internal/ShardMerge.js +182 -0
  135. package/dist/internal/ShardMerge.js.map +1 -0
  136. package/dist/internal/TransactPlan.d.ts +1 -8
  137. package/dist/internal/TransactPlan.d.ts.map +1 -1
  138. package/dist/internal/TransactPlan.js +2 -9
  139. package/dist/internal/TransactPlan.js.map +1 -1
  140. package/dist/internal/TransactWriteOps.d.ts +75 -24
  141. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  142. package/dist/internal/TransactWriteOps.js +147 -186
  143. package/dist/internal/TransactWriteOps.js.map +1 -1
  144. package/dist/internal/TransactableOps.d.ts +123 -29
  145. package/dist/internal/TransactableOps.d.ts.map +1 -1
  146. package/dist/internal/TransactableOps.js +255 -87
  147. package/dist/internal/TransactableOps.js.map +1 -1
  148. package/dist/internal/WriteDiagnosis.d.ts +31 -3
  149. package/dist/internal/WriteDiagnosis.d.ts.map +1 -1
  150. package/dist/internal/WriteDiagnosis.js +128 -11
  151. package/dist/internal/WriteDiagnosis.js.map +1 -1
  152. package/package.json +4 -2
@@ -16,15 +16,20 @@
16
16
  */
17
17
  import { 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 { readingStreamValues, writingTuplePositions, } from "@effect-dynamodb/schema/internal/EntitySchemas.js";
21
+ import { decodingAsBefore } from "@effect-dynamodb/schema/internal/FailingAsBefore.js";
19
22
  import { getSchemaFields } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
23
+ import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
20
24
  import { DateTime, Duration as Dur, Effect, Option, Random, Result, Schema as S, Schedule, } from "effect";
21
25
  import { decodeMarshalledItem } from "../Entity.js";
22
26
  import { fromAttributeMap, toAttributeMap } from "../Marshaller.js";
23
27
  import { resolveTtlAttributeName } from "../Table.js";
24
28
  import * as Capacity from "./Capacity.js";
25
29
  import { condition as entityCondition } from "./EntityCombinators.js";
26
- import { asReadGuard } from "./ExpressionLimits.js";
27
- 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";
30
+ import { handlerOf } from "./Rekey.js";
31
+ import { notReadBack, readBackOf } from "./RoundTrip.js";
32
+ import { addProjectionLayout, OUTBOX_CLAIM as CLAIM_TOKEN, OUTBOX_CLAIMED_UNTIL as CLAIMED_UNTIL, composePrimaryKey, KEY_TEXT, marshalOrFail, projectionTtlChecked, projectionTtlConflict, OUTBOX_ROW_PK as ROW_PK, OUTBOX_ROW_SK as ROW_SK, serializeSparseOrFail, validateAndBuildPutItem, } from "./TransactableOps.js";
28
33
  // ---------------------------------------------------------------------------
29
34
  // Removal (#154)
30
35
  // ---------------------------------------------------------------------------
@@ -85,7 +90,260 @@ export const modelFields = (model) => {
85
90
  const fields = getSchemaFields(schema);
86
91
  return fields === undefined ? undefined : Object.keys(fields);
87
92
  };
88
- /** @internal */
93
+ /**
94
+ * @internal The outboxes on other tables of the read model's projections (`_projectionOutboxes`,
95
+ * the entries with a `table`): several projections of one read model may each have one. A local
96
+ * outbox is on the read model's own table, where its rows are.
97
+ */
98
+ export const remoteOutboxesOf = (entity) => (entity
99
+ ._projectionOutboxes ?? []).filter((outbox) => outbox.table !== undefined);
100
+ /**
101
+ * @internal The physical name of the table `tag` names, the one requests are sent to:
102
+ * `undefined` when the context doesn't provide it.
103
+ */
104
+ export const physicalTableName = (tag) => Effect.map(Effect.serviceOption(tag), (config) => Option.isSome(config) ? config.value.name : undefined);
105
+ /**
106
+ * What a composite of `model` can be in a key (`KeyComposer.CompositeValues`), by its schema, as
107
+ * one side sees it:
108
+ *
109
+ * - `"written"`, the keys its rows are written under: the key text of its literals (a literal
110
+ * union), of `true` and `false` (a boolean), or a number's or bigint's key text; any other field
111
+ * (a string, a field the model doesn't declare) may hold any text, `#` included.
112
+ * - `"read"`, the keys `rekey`'s reader takes as its rows' (`KeyText136.readIndexKeys`): a number,
113
+ * a bigint or a boolean only as text its value composes again, and a literal composite as any
114
+ * text, which it reads as a string.
115
+ */
116
+ const compositeValues = (model, side) => (composite) => {
117
+ if (model === undefined || model === null)
118
+ return "open";
119
+ const schema = isConfiguredModel(model) ? model.model : model;
120
+ const fields = getSchemaFields(schema);
121
+ if (fields === undefined || !Object.hasOwn(fields, composite))
122
+ return "open";
123
+ const field = fields[composite];
124
+ const literals = keyFormLiterals(field);
125
+ if (side === "written" && literals !== undefined)
126
+ return { values: literals };
127
+ const kind = keyFormValueKind(field);
128
+ if (kind === "number" || kind === "bigint")
129
+ return "number";
130
+ if (kind === "boolean")
131
+ return { values: [true, false] };
132
+ return "open";
133
+ };
134
+ /**
135
+ * The key space an entity's rows are under: the text its primary key's partition and sort keys
136
+ * start with, the composites' labels, and what each composite's value can be, composed by the call
137
+ * its writes make (`KeyComposer.composeKeySpace`): the schema's name and version, the primary
138
+ * collection (or the entity type), under a collection the entity type and its version, and each
139
+ * composite's name. Each value is what its type can compose (`compositeValues`), by `view`:
140
+ *
141
+ * - `"plain"`, the keys its rows are written under with values that hold no `#`: every composite is
142
+ * walked, to the end of the key, under the schema's setting.
143
+ * - `"written"` and `"read"`, the keys `rekey` meets on its table, under any setting: the walk
144
+ * stops at the first composite whose value may hold `#` (`"open"`), and anything follows it.
145
+ *
146
+ * `undefined` for an entity on no table.
147
+ */
148
+ const keySpaceOf = (entity, view) => {
149
+ const member = entity;
150
+ const primary = member.indexes?.primary;
151
+ if (member._schema === undefined || member.entityType === undefined || primary === undefined) {
152
+ return undefined;
153
+ }
154
+ const values = compositeValues(member.model, view === "read" ? "read" : "written");
155
+ try {
156
+ return KeyComposer.composeKeySpace(member._schema, member.entityType, member._entityVersion ?? 1, primary, view === "plain"
157
+ ? (composite) => {
158
+ const of = values(composite);
159
+ return of === "open" ? "text" : of;
160
+ }
161
+ : values, { everyForm: view !== "plain" });
162
+ }
163
+ catch {
164
+ return undefined;
165
+ }
166
+ };
167
+ /**
168
+ * The key space of a read model's outbox items: its rows' partition keys, and its rows' sort keys
169
+ * followed by `#outbox#` (`<rowSk>#outbox#<revision>#<n>`), so any text after a whole sort key.
170
+ */
171
+ const outboxSpaceOf = (space) => {
172
+ const { sk } = space;
173
+ if (sk.open)
174
+ return space;
175
+ const last = sk.after.length - 1;
176
+ return {
177
+ pk: space.pk,
178
+ sk: last < 0
179
+ ? { text: `${sk.text}#outbox#`, after: [], values: [], open: true }
180
+ : { ...sk, after: [...sk.after.slice(0, last), `${sk.after[last]}#outbox#`], open: true },
181
+ };
182
+ };
183
+ /** Whether a key of one key space can be a key of the other, in both halves. */
184
+ const spacesMeet = (a, b) => KeyComposer.keySpacesMeet(a.pk, b.pk) && KeyComposer.keySpacesMeet(a.sk, b.sk);
185
+ /**
186
+ * Whether the outbox items of one entity can be read by `rekey` as the other's, either way round:
187
+ * the keys one's are written under (`"written"`) against the keys the other's reader takes
188
+ * (`"read"`).
189
+ */
190
+ const readAsEachOther = (a, b) => {
191
+ const meet = (writer, reader) => {
192
+ const written = keySpaceOf(writer, "written");
193
+ const read = keySpaceOf(reader, "read");
194
+ return (written !== undefined &&
195
+ read !== undefined &&
196
+ spacesMeet(outboxSpaceOf(written), outboxSpaceOf(read)));
197
+ };
198
+ return meet(a, b) || meet(b, a);
199
+ };
200
+ /**
201
+ * Whether two entities compose every key the same way: one schema (name, version, casing,
202
+ * `escapeKeys`), entity type and version, primary key composites, casing and collection, and each
203
+ * composite of one type. Then either one's reader moves a row as the other's would.
204
+ */
205
+ const sameKeys = (a, b) => {
206
+ const x = a;
207
+ const y = b;
208
+ const px = x.indexes?.primary;
209
+ const py = y.indexes?.primary;
210
+ const sx = x._schema;
211
+ const sy = y._schema;
212
+ if (px === undefined || py === undefined || sx === undefined || sy === undefined)
213
+ return false;
214
+ const fieldsOf = (model) => model === undefined || model === null
215
+ ? undefined
216
+ : getSchemaFields(isConfiguredModel(model) ? model.model : model);
217
+ const fx = fieldsOf(x.model);
218
+ const fy = fieldsOf(y.model);
219
+ const typeOf = (fields, composite) => {
220
+ if (fields === undefined || !Object.hasOwn(fields, composite))
221
+ return undefined;
222
+ const field = fields[composite];
223
+ return JSON.stringify([keyFormValueKind(field), keyFormLiterals(field)]);
224
+ };
225
+ const same = (u, v) => u.length === v.length && u.every((name, i) => name === v[i]);
226
+ return (x.entityType === y.entityType &&
227
+ (x._entityVersion ?? 1) === (y._entityVersion ?? 1) &&
228
+ sx.name === sy.name &&
229
+ sx.version === sy.version &&
230
+ sx.casing === sy.casing &&
231
+ (sx.escapeKeys === true) === (sy.escapeKeys === true) &&
232
+ same(px.pk.composite, py.pk.composite) &&
233
+ same(px.sk.composite, py.sk.composite) &&
234
+ px.casing === py.casing &&
235
+ JSON.stringify(px.collection) === JSON.stringify(py.collection) &&
236
+ px.type === py.type &&
237
+ [...px.pk.composite, ...px.sk.composite].every((composite) => {
238
+ const t = typeOf(fx, composite);
239
+ return t !== undefined && t === typeOf(fy, composite);
240
+ }));
241
+ };
242
+ /**
243
+ * @internal `[EDD-9134]`: among `members` (each named as `site`'s message shows it), a read model
244
+ * whose projection's outbox is on another table, where another read model in the same key space
245
+ * has its outbox too. Tables are compared by the physical name the context resolves (two handles
246
+ * on one table are one table), and by service when one isn't provided. The problem, or `undefined`.
247
+ *
248
+ * Two questions, by `scope`:
249
+ *
250
+ * - `"plain"` (where read models are bound: `DynamoClient.make`, `EventStore.processBatch`): can a
251
+ * key of one be a key of the other with values that hold no `#`, each value what its type can
252
+ * compose? Then their items overwrite each other whenever their values match, in normal
253
+ * operation. Read models whose keys meet only through a value holding `#` bind and run, as on
254
+ * 1.39.0, as do two whose keys part where a value of one can't hold the other's text (a number
255
+ * beside a label).
256
+ * - a table (`rekey` of it): can `rekey` read an item of one as the other's at all, a string value
257
+ * holding `#` included, and a literal composite read as any text, as its reader reads it? Then it
258
+ * couldn't tell whose an item on that table is. Only outboxes on that table are looked at. The
259
+ * table's own members (`scope.members`) are looked at too: an entity claims the outbox items of
260
+ * its entity type on its table (its own projections' outbox there), so one that can read a read
261
+ * model's items as its own would move them by its key. One whose keys are composed exactly as
262
+ * the read model's (`sameKeys`) moves them where the read model would, and isn't refused.
263
+ *
264
+ * Read models that never meet at a site that sees several at once can't be checked: their key
265
+ * spaces must be kept apart by whoever defines them.
266
+ */
267
+ export const sharedOutboxKeySpace = (site, members, scope) => Effect.gen(function* () {
268
+ const plain = scope === "plain";
269
+ // Every table a member's outbox is on, by its physical name.
270
+ const names = new Map();
271
+ for (const [, entity] of members) {
272
+ for (const { table } of remoteOutboxesOf(entity)) {
273
+ if (!names.has(table.Tag.key)) {
274
+ names.set(table.Tag.key, yield* physicalTableName(table.Tag));
275
+ }
276
+ }
277
+ }
278
+ const oneTable = (a, b) => {
279
+ if (a.key === b.key)
280
+ return true;
281
+ const name = names.get(a.key);
282
+ return name !== undefined && name === names.get(b.key);
283
+ };
284
+ const startOf = (space) => `(partition keys starting "${space.pk.text}", sort keys starting "${space.sk.text}": the ` +
285
+ "same schema name and version, primary collection, entity type and first composite)";
286
+ for (const [name, entity] of members) {
287
+ const space = keySpaceOf(entity, plain ? "plain" : "written");
288
+ if (space === undefined)
289
+ continue;
290
+ for (const outbox of remoteOutboxesOf(entity)) {
291
+ const into = outbox.table.Tag;
292
+ if (!plain && into.key !== scope.key && names.get(into.key) !== scope.name)
293
+ continue;
294
+ const physical = names.get(into.key);
295
+ for (const [otherName, other] of members) {
296
+ if (other === entity)
297
+ continue;
298
+ if (!remoteOutboxesOf(other).some((o) => oneTable(o.table.Tag, into)))
299
+ continue;
300
+ if (plain) {
301
+ const otherSpace = keySpaceOf(other, "plain");
302
+ if (otherSpace === undefined ||
303
+ !spacesMeet(outboxSpaceOf(space), outboxSpaceOf(otherSpace))) {
304
+ continue;
305
+ }
306
+ }
307
+ else if (!readAsEachOther(entity, other))
308
+ continue;
309
+ return (`[EDD-9134] ${site}: ${name} writes its projection's outbox items into another ` +
310
+ `table${physical === undefined ? "" : ` ("${physical}")`}, where ${otherName} ` +
311
+ `writes its own under the same key space ${startOf(space)}. ` +
312
+ (plain
313
+ ? "Their items would overwrite each other whenever their keys match, and rekey " +
314
+ "couldn't tell whose an item is. "
315
+ : "rekey reads an item's key back by its key space, and couldn't tell whose an " +
316
+ "item on this table is. ") +
317
+ "Give one of them its own entity type, collection, schema or key composites.");
318
+ }
319
+ if (plain)
320
+ continue;
321
+ // The members of the table being rekeyed that claim this read model's outbox items.
322
+ for (const [memberName, member] of scope.members) {
323
+ if (member === entity)
324
+ continue;
325
+ const claims = handlerOf(member)?.types.includes(`${readModelType(entity)}#outbox`);
326
+ if (claims !== true || sameKeys(member, entity) || !readAsEachOther(entity, member)) {
327
+ continue;
328
+ }
329
+ return (`[EDD-9134] ${site}: ${name} writes its projection's outbox items into another ` +
330
+ `table${physical === undefined ? "" : ` ("${physical}")`}, whose member ` +
331
+ `${memberName} claims the outbox items of its entity type there under the same key ` +
332
+ `space ${startOf(space)}, and composes its keys differently. rekey reads an item's ` +
333
+ "key back by its key space, and couldn't tell whose an item on this table is. Give " +
334
+ "one of them its own entity type, collection, schema or key composites.");
335
+ }
336
+ }
337
+ }
338
+ return undefined;
339
+ });
340
+ /** An entity's type, as its rows' `__edd_e__` names it. */
341
+ const readModelType = (entity) => entity.entityType;
342
+ /**
343
+ * @internal `[EDD-9134]` ({@link sharedOutboxKeySpace}) as a defect, from the sites that define
344
+ * what runs (`DynamoClient.make`, `EventStore.processBatch`), before anything runs.
345
+ */
346
+ export const refuseSharedOutboxKeySpace = (site, members) => Effect.flatMap(sharedOutboxKeySpace(site, members, "plain"), (problem) => problem === undefined ? Effect.void : Effect.die(new Error(problem)));
89
347
  export const makeEngine = (config) => {
90
348
  const { readModel } = config;
91
349
  const entityType = readModel.entityType;
@@ -120,61 +378,73 @@ export const makeEngine = (config) => {
120
378
  }
121
379
  return [...kept];
122
380
  })();
123
- // Resolved when it runs: an entity's table is set when it is registered on
124
- // one, which may come after the projection is defined.
125
- // Rows may be tombstones (#154): the entity's `create` takes one's place,
126
- // keeping these fields — the checkpoints — and the revision one higher.
127
- if (config.removal !== undefined) {
128
- ;
129
- readModel._projectionTombstones = {
130
- kept: keptFields.filter((f) => f !== config.revision?.field),
131
- revision: config.revision?.field,
132
- };
381
+ // Each attribute the projection keeps on a row, with its role: the checkpoints, then the
382
+ // revision, as a tombstone stores them. An attribute in two roles is listed in each, and refused
383
+ // (`[EDD-9133]`, `addProjectionLayout`) when the read model's rows may be tombstones.
384
+ const roles = [];
385
+ const giveRole = (field, role) => {
386
+ if (!roles.some(([named, held]) => named === field && held === role))
387
+ roles.push([field, role]);
388
+ };
389
+ if (config.checkpoints.kind === "scalar")
390
+ giveRole(config.checkpoints.field, "checkpoint");
391
+ else {
392
+ if (config.checkpoints.map !== undefined)
393
+ giveRole(config.checkpoints.map, "checkpoint map");
394
+ for (const f of Object.values(config.checkpoints.fields)) {
395
+ giveRole(f.field, "checkpoint");
396
+ giveRole(f.instanceField, "checkpoint owner");
397
+ }
133
398
  }
134
- // An outbox on another table: that table's `rekey` moves its items (#171).
135
- if (config.outbox?.table !== undefined) {
136
- ;
137
- readModel._projectionOutbox = {
399
+ if (config.revision !== undefined)
400
+ giveRole(config.revision.field, "revision");
401
+ // Recorded beside the layouts of the read model's other projections, whether or not it has
402
+ // `removal`, for the checks of `[EDD-9133]`. Rows may be tombstones (#154) when one has
403
+ // `removal`: the entity's `create` takes one's place, keeping the checkpoints of the projection
404
+ // with `removal` that wrote it, with its revision one higher (`overTombstone`).
405
+ addProjectionLayout(readModel, {
406
+ label: config.label,
407
+ roles,
408
+ removal: config.removal !== undefined,
409
+ ttl: config.removal?.ttl !== undefined,
410
+ });
411
+ // Every projection's outbox, kept on the read model, one entry per distinct layout, the one defined
412
+ // last at the end: a second projection doesn't hide the first's, which stays callable, and one
413
+ // defined again adds nothing. One on another table (`table`) is moved by that table's `rekey`
414
+ // (#171). Wherever it is, an aggregate declaring `ownsRows` is checked against its items at bind
415
+ // (DESIGN.md §7 "Which rows in its partition are an aggregate's"), with the index keys it writes
416
+ // on them.
417
+ if (config.outbox !== undefined) {
418
+ const holder = readModel;
419
+ const layout = {
138
420
  table: config.outbox.table,
139
421
  pk: config.outbox.pk,
140
422
  sk: config.outbox.sk,
423
+ index: config.outbox.index,
141
424
  };
425
+ const same = (other) => other.table?.Tag === layout.table?.Tag &&
426
+ other.pk === layout.pk &&
427
+ other.sk === layout.sk &&
428
+ other.index?.name === layout.index?.name &&
429
+ other.index?.pk === layout.index?.pk &&
430
+ other.index?.sk === layout.index?.sk;
431
+ holder._projectionOutboxes = [
432
+ ...(holder._projectionOutboxes ?? []).filter((other) => !same(other)),
433
+ layout,
434
+ ];
142
435
  }
143
436
  const tableName = Effect.suspend(() => Effect.map(readModel._tableTag, (tc) => tc.name));
144
- /**
145
- * The row, read strongly consistent — raw, so a tombstone reads as one. A
146
- * row 1.36 wrote under a key whose text changed (#171) is read there when
147
- * its current key holds none, as the read model's own reads do: judged by
148
- * its values (`_ownsRow136`; a tombstone, which holds none, by its key and
149
- * `KEY_TEXT`), another value's 1.36 row at the current key is no row, nor
150
- * is that value's current row at the 1.36 key. A row found at its 1.36 key
151
- * carries it (`at136`), so the write moves it.
152
- */
437
+ /** The row, read strongly consistent — raw, so a tombstone reads as one. */
153
438
  const readRow = (key) => Effect.gen(function* () {
154
439
  const client = yield* Capacity.client;
155
440
  const TableName = yield* tableName;
156
- const rowKey = key;
157
- const read = (at) => client
158
- .getItem({ TableName, Key: toAttributeMap(at), ConsistentRead: true })
159
- .pipe(Effect.map((result) => result.Item));
160
- const current = composePrimaryKey(readModel, rowKey);
161
- let item = yield* read(current);
162
- if (item !== undefined && !readModel._ownsRow136(rowKey, current, item))
163
- item = undefined;
164
- let at136;
165
- if (item === undefined) {
166
- const old = readModel._primaryKey136(rowKey);
167
- if (old !== undefined) {
168
- const held = yield* read(old);
169
- if (held !== undefined && readModel._ownsRow136(rowKey, old, held)) {
170
- item = held;
171
- at136 = old;
172
- }
173
- }
174
- }
441
+ const { Item: item } = yield* client.getItem({
442
+ TableName,
443
+ Key: toAttributeMap(composePrimaryKey(readModel, key)),
444
+ ConsistentRead: true,
445
+ });
175
446
  if (item === undefined)
176
447
  return Option.none();
177
- const moving = at136 === undefined ? {} : { at136, stored: item };
178
448
  if (item.__edd_e__?.S === tombstoneMarker(entityType)) {
179
449
  const raw = fromAttributeMap(item);
180
450
  const values = {};
@@ -183,7 +453,7 @@ export const makeEngine = (config) => {
183
453
  if (v !== undefined)
184
454
  values[f] = v;
185
455
  }
186
- return Option.some({ values, tombstone: true, createdAt: undefined, ...moving });
456
+ return Option.some({ values, tombstone: true, createdAt: undefined });
187
457
  }
188
458
  const decoded = (yield* decodeMarshalledItem(readModel, item));
189
459
  let values = decoded;
@@ -197,7 +467,6 @@ export const makeEngine = (config) => {
197
467
  values: readModel._attachPrototype?.(values) ?? values,
198
468
  tombstone: false,
199
469
  createdAt: createdAtField === null ? undefined : decoded[createdAtField],
200
- ...moving,
201
470
  });
202
471
  });
203
472
  /**
@@ -352,9 +621,14 @@ export const makeEngine = (config) => {
352
621
  ? { pk: primary.pk.field, sk: primary.sk.field }
353
622
  : { pk: config.outbox.pk, sk: config.outbox.sk };
354
623
  const pad = (n, width) => String(n).padStart(width, "0");
355
- const outboxItems = (rowKey, revision, enqueued, marked) => Effect.forEach(enqueued, (e, i) => Effect.gen(function* () {
624
+ const outboxReadBack = config.outbox === undefined
625
+ ? undefined
626
+ : readBackOf(config.outbox.schema, () => readingStreamValues(config.outbox.schema));
627
+ const outboxItems = (rowKey, revision, enqueued, mark) => Effect.forEach(enqueued, (e, i) => Effect.gen(function* () {
356
628
  const outbox = config.outbox;
357
- const encoded = yield* S.encodeUnknownEffect(outbox.schema)(e.effect).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.outbox`, cause })));
629
+ const encoded = yield* S.encodeUnknownEffect(writingTuplePositions(outbox.schema))(e.effect).pipe(Effect.tap((wire) => outboxReadBack === undefined
630
+ ? Effect.void
631
+ : outboxReadBack(wire).pipe(Effect.mapError((issue) => notReadBack("The outbox effect", issue)))), Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.outbox`, cause })));
358
632
  const keys = outboxKeys();
359
633
  const rowPk = String(rowKey[primary.pk.field]);
360
634
  const rowSk = String(rowKey[primary.sk.field]);
@@ -370,18 +644,15 @@ export const makeEngine = (config) => {
370
644
  streamId: e.event.streamId,
371
645
  version: e.event.version,
372
646
  eventType: e.event.eventType,
373
- ...(marked && { [KEY_TEXT]: 1 }),
647
+ ...(mark !== undefined && { [KEY_TEXT]: mark }),
374
648
  };
375
649
  if (outbox.index !== undefined) {
376
650
  item[outbox.index.pk] = outboxMarker(entityType);
377
651
  item[outbox.index.sk] = `${rowPk}#${sk}`;
378
652
  }
379
- return toAttributeMap(item);
653
+ return yield* marshalOrFail(entityType, `${config.label}.outbox`, () => toAttributeMap(item));
380
654
  }));
381
- /**
382
- * A lost race, from a single write's or a transaction's failure: the row's
383
- * Put, or — moving it from its 1.36 key — that row's Delete, cancelled.
384
- */
655
+ /** A lost race, from a single write's or a transaction's failure: the row's Put cancelled. */
385
656
  const lostRaceOf = (error, transaction) => {
386
657
  const cause = error?.cause;
387
658
  if (!transaction)
@@ -396,15 +667,11 @@ export const makeEngine = (config) => {
396
667
  const rowKey = composePrimaryKey(readModel, key);
397
668
  const condition = guard(row);
398
669
  const createdAt = Option.isSome(row) ? row.value.createdAt : undefined;
399
- // A tombstone or outbox item holds no values: one under a key whose
400
- // text differs from 1.36's is marked as written under its current key
401
- // (#171, `KEY_TEXT`) — whatever the fallback is set to, since `rekey`
402
- // reads every key — and one under unchanged text is as 1.36 wrote it.
403
- const marked = readModel._primaryKey136(key, true) !== undefined;
404
- // The row's item: the entity's own `put` (no outbox), or built for a
405
- // transaction. A row over a tombstone under a key whose text changed is
406
- // built too: the entity's `put` would judge the tombstone by values it
407
- // doesn't hold, and moves it unmarked from its 1.36 key (#171).
670
+ // A tombstone or outbox item holds no values, so its key alone says which text it is for
671
+ // `rekey` (`KEY_TEXT`): one under the text of `escapeKeys: true`, where that isn't off's, is
672
+ // marked.
673
+ const mark = readModel._keyTextMark(key);
674
+ // The row's item: the entity's own `put` (no outbox), or built for a transaction.
408
675
  let rowItem;
409
676
  if (Option.isNone(target)) {
410
677
  // A tombstone: the key, the kept checkpoint fields, the revision.
@@ -414,25 +681,21 @@ export const makeEngine = (config) => {
414
681
  ...rowKey,
415
682
  __edd_e__: tombstoneMarker(entityType),
416
683
  [REMOVED_AT]: DateTime.formatIso(now),
417
- ...(marked && { [KEY_TEXT]: 1 }),
684
+ ...(mark !== undefined && { [KEY_TEXT]: mark }),
418
685
  };
419
686
  for (const [f, v] of Object.entries(kept))
420
687
  tomb[dbName(f)] = v;
421
688
  if (config.removal?.ttl !== undefined) {
422
689
  tomb[resolveTtlAttributeName(tc)] = Math.floor((DateTime.toEpochMillis(now) + Dur.toMillis(config.removal.ttl)) / 1000);
423
690
  }
424
- rowItem = toAttributeMap(tomb);
691
+ // A sparse-map key is refused as the row's own write refuses it. The check flattens a
692
+ // copy: what's stored is the tombstone as 1.39.0 stored it, an empty map whole.
693
+ yield* serializeSparseOrFail(readModel, { ...tomb }, `${config.label}.write`);
694
+ rowItem = yield* marshalOrFail(entityType, `${config.label}.write`, () => toAttributeMap(tomb));
425
695
  }
426
- else if (enqueued.length > 0 ||
427
- (Option.isSome(row) &&
428
- row.value.tombstone &&
429
- readModel._primaryKey136(key) !== undefined)) {
430
- const built = yield* validateAndBuildPutItem(readModel, target.value, `${config.label}.write`);
431
- const item = { ...built.item };
432
- if (createdAtField !== null && DateTime.isDateTime(createdAt)) {
433
- item[dbName(createdAtField)] = generateTimestampPrimitive(DateTime.toUtc(createdAt), readModel.systemFields.createdAtEncoding);
434
- }
435
- rowItem = toAttributeMap(item);
696
+ else if (enqueued.length > 0) {
697
+ const built = yield* validateAndBuildPutItem(readModel, target.value, `${config.label}.write`, { createdAt: DateTime.isDateTime(createdAt) ? DateTime.toUtc(createdAt) : undefined });
698
+ rowItem = toAttributeMap(built.item);
436
699
  }
437
700
  if (rowItem === undefined) {
438
701
  // The row alone, through the entity: `put` conditioned on the guard
@@ -452,86 +715,29 @@ export const makeEngine = (config) => {
452
715
  const written = yield* run.pipe(Effect.catchTag("ConditionalCheckFailed", () => Effect.fail(new LostRace(key))));
453
716
  return Option.some(written);
454
717
  }
455
- // A row read at its 1.36 key (#171) moves in the same write: put at its
456
- // current key, where nothing may be, and deleted at its 1.36 key only
457
- // while it is as read. Another value's 1.36 row at the current key fails
458
- // a write that expects nothing there: it is moved out of the way, as the
459
- // entity's own writes move it, and the write is read again. So is
460
- // another value's outbox item 1.36 left where one of this write's goes:
461
- // a key that reads back as another value's 1.36 key can hold them, so
462
- // there each Put requires its key empty.
463
- const at136 = Option.isSome(row) ? row.value.at136 : undefined;
464
- const OutboxTable = yield* outboxTable;
465
- const keys = outboxKeys();
466
- const sharedKey = typeof readModel._currentKeyOf136(rowKey) === "object";
467
- const moved = at136 === undefined
468
- ? []
469
- : [
470
- {
471
- Delete: {
472
- TableName,
473
- Key: toAttributeMap(at136),
474
- ...asReadGuard(row.value.stored, primary.pk.field, config.revision === undefined ? [] : [dbName(config.revision.field)]),
475
- },
476
- },
477
- ];
478
- const outboxAt = 1 + moved.length;
479
- const lostRace = (error, transaction) => lostRaceOf(error, transaction)
480
- ? Effect.gen(function* () {
481
- if (Option.isNone(row) || at136 !== undefined) {
482
- yield* readModel._clearAlias136(key, config.label);
483
- }
484
- const reasons = transaction
485
- ? (error.cause
486
- ?.CancellationReasons ?? [])
487
- : [];
488
- for (const reason of reasons.slice(outboxAt)) {
489
- if (reason?.Code === "ConditionalCheckFailed" && reason.Item !== undefined) {
490
- yield* readModel._displaceValueless136(OutboxTable, keys, reason.Item, config.label);
491
- }
492
- }
493
- return yield* Effect.fail(new LostRace(key));
494
- })
495
- : Effect.fail(error);
718
+ const lostRace = (error, transaction) => Effect.fail(lostRaceOf(error, transaction) ? new LostRace(key) : error);
496
719
  const rowPut = {
497
720
  Put: {
498
721
  TableName,
499
722
  Item: rowItem,
500
- ...(at136 === undefined
501
- ? {
502
- ConditionExpression: condition.raw.expression,
503
- ExpressionAttributeNames: condition.raw.names,
504
- ...(Object.keys(condition.raw.values).length > 0
505
- ? { ExpressionAttributeValues: condition.raw.values }
506
- : {}),
507
- }
508
- : {
509
- ConditionExpression: "attribute_not_exists(#g)",
510
- ExpressionAttributeNames: { "#g": primary.pk.field },
511
- }),
723
+ ConditionExpression: condition.raw.expression,
724
+ ExpressionAttributeNames: condition.raw.names,
725
+ ...(Object.keys(condition.raw.values).length > 0
726
+ ? { ExpressionAttributeValues: condition.raw.values }
727
+ : {}),
512
728
  },
513
729
  };
514
- if (enqueued.length === 0 && at136 === undefined) {
730
+ if (enqueued.length === 0) {
515
731
  yield* client.putItem(rowPut.Put).pipe(Effect.catch((error) => lostRace(error, false)));
516
732
  }
517
733
  else {
518
- const items = yield* outboxItems(rowKey, revision ?? 0, enqueued, marked);
734
+ const OutboxTable = yield* outboxTable;
735
+ const items = yield* outboxItems(rowKey, revision ?? 0, enqueued, mark);
519
736
  yield* client
520
737
  .transactWriteItems({
521
738
  TransactItems: [
522
739
  rowPut,
523
- ...moved,
524
- ...items.map((Item) => ({
525
- Put: {
526
- TableName: OutboxTable,
527
- Item,
528
- ...(sharedKey && {
529
- ConditionExpression: "attribute_not_exists(#opk)",
530
- ExpressionAttributeNames: { "#opk": keys.pk },
531
- ReturnValuesOnConditionCheckFailure: "ALL_OLD",
532
- }),
533
- },
534
- })),
740
+ ...items.map((Item) => ({ Put: { TableName: OutboxTable, Item } })),
535
741
  ],
536
742
  })
537
743
  .pipe(Effect.catch((error) => lostRace(error, true)));
@@ -557,6 +763,28 @@ export const makeEngine = (config) => {
557
763
  `${to}: a strongly consistent read did not return them. Was the stream written ` +
558
764
  "outside `append`?",
559
765
  }));
766
+ /**
767
+ * `[EDD-9133]` once the table's TTL attribute is known: an attribute a projection keeps on the
768
+ * read model's rows that is stored as the TTL attribute, which a projection's tombstones set. The
769
+ * two would overwrite each other, and a row could expire. Every entry point that writes a row
770
+ * runs it before it sends anything, whatever the data: `applyRow` for each row, and `catchUp` and
771
+ * `rebuild` first (`operation` names the entry point). The drains write no row and don't run it:
772
+ * a worker providing only its outbox's table delivers as on 1.39.0.
773
+ */
774
+ const preflight = (operation) => Effect.suspend(() =>
775
+ // The table is resolved only when there is something to check.
776
+ !projectionTtlChecked(readModel)
777
+ ? Effect.void
778
+ : Effect.flatMap(readModel._tableTag, (tc) => {
779
+ const problem = projectionTtlConflict(readModel, resolveTtlAttributeName(tc));
780
+ return problem === undefined
781
+ ? Effect.void
782
+ : Effect.fail(new ValidationError({
783
+ entityType,
784
+ operation: `${config.label}.${operation}`,
785
+ cause: problem,
786
+ }));
787
+ }));
560
788
  const withRetry = (attempt) => Effect.retry(attempt, {
561
789
  schedule: config.retry,
562
790
  while: (error) => error instanceof LostRace,
@@ -879,7 +1107,7 @@ export const makeEngine = (config) => {
879
1107
  failed,
880
1108
  };
881
1109
  });
882
- return withRetry(attempt);
1110
+ return Effect.andThen(preflight("apply"), withRetry(attempt));
883
1111
  };
884
1112
  /** The fields the library owns, re-applied after `toItem`. */
885
1113
  const pick = (target) => {
@@ -889,65 +1117,32 @@ export const makeEngine = (config) => {
889
1117
  out[f] = target[f];
890
1118
  return out;
891
1119
  };
1120
+ // -------------------------------------------------------------------------
1121
+ // Outbox drain (#155)
1122
+ // -------------------------------------------------------------------------
1123
+ // A decode that dies on an absent attribute fails as 1.39.0's did (`decodingAsBefore`).
1124
+ const decodeEffect = decodingAsBefore(readingStreamValues(config.outbox?.schema ?? S.Unknown), config.outbox?.schema ?? S.Unknown);
892
1125
  /**
893
1126
  * Deliver a row's pending effects in order: claim the head item, deliver it,
894
1127
  * delete it, repeat. A claim another drainer holds stops the drain; a crash
895
1128
  * leaves a claim that expires, so the effect is delivered again.
896
- *
897
- * `rows` are the keys the row's items are under: its current key, and its
898
- * 1.36 key when its items can still be there (#171). The head is the first
899
- * pending item of them all, by revision and position, so a row's effects
900
- * are delivered in one order wherever they are.
901
1129
  */
902
- const drainRaw = (rows, deliver) => Effect.gen(function* () {
1130
+ const drainRaw = (rowPk, rowSk, deliver) => Effect.gen(function* () {
903
1131
  const outbox = config.outbox;
904
1132
  const client = yield* Capacity.client;
905
1133
  const TableName = yield* outboxTable;
906
1134
  const keys = outboxKeys();
907
- /** The row's first item under `at`. */
908
- const firstAt = (at) => Effect.gen(function* () {
909
- const request = {
1135
+ let delivered = 0;
1136
+ while (true) {
1137
+ const page = yield* client.query({
910
1138
  TableName,
911
1139
  KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :sk)",
912
- ExpressionAttributeNames: {
913
- "#pk": keys.pk,
914
- "#sk": keys.sk,
915
- ...(at.only !== undefined && { "#kt": KEY_TEXT }),
916
- },
917
- ExpressionAttributeValues: toAttributeMap({ ":pk": at.pk, ":sk": `${at.sk}#outbox#` }),
1140
+ ExpressionAttributeNames: { "#pk": keys.pk, "#sk": keys.sk },
1141
+ ExpressionAttributeValues: toAttributeMap({ ":pk": rowPk, ":sk": `${rowSk}#outbox#` }),
918
1142
  ConsistentRead: true,
919
- };
920
- if (at.only === undefined) {
921
- return (yield* client.query({ ...request, Limit: 1 })).Items?.[0];
922
- }
923
- // Read past another row's items under the same key.
924
- let start;
925
- do {
926
- const page = yield* client.query({
927
- ...request,
928
- FilterExpression: at.only === "marked" ? "attribute_exists(#kt)" : "attribute_not_exists(#kt)",
929
- ...(start !== undefined && { ExclusiveStartKey: start }),
930
- });
931
- const first = page.Items?.[0];
932
- if (first !== undefined)
933
- return first;
934
- start = page.LastEvaluatedKey;
935
- } while (start !== undefined);
936
- return undefined;
937
- });
938
- let delivered = 0;
939
- while (true) {
940
- let head;
941
- let headAt = "";
942
- for (const at of rows) {
943
- const first = yield* firstAt(at);
944
- // `#outbox#<revision>#<n>`: fixed widths, so text order is delivery order.
945
- const suffix = first?.[keys.sk]?.S?.slice(at.sk.length) ?? "";
946
- if (first !== undefined && (head === undefined || suffix < headAt)) {
947
- head = first;
948
- headAt = suffix;
949
- }
950
- }
1143
+ Limit: 1,
1144
+ });
1145
+ const head = page.Items?.[0];
951
1146
  if (head === undefined)
952
1147
  return { delivered, undelivered: Option.none() };
953
1148
  const raw = fromAttributeMap(head);
@@ -970,7 +1165,7 @@ export const makeEngine = (config) => {
970
1165
  // Another drainer holds the head: it delivers in order; stop here.
971
1166
  if (!claimed)
972
1167
  return { delivered, undelivered: Option.none() };
973
- const effect = yield* S.decodeUnknownEffect(outbox.schema)(raw.effect).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.drain`, cause })));
1168
+ const effect = yield* decodeEffect(raw.effect).pipe(Effect.mapError((cause) => new ValidationError({ entityType, operation: `${config.label}.drain`, cause })));
974
1169
  const meta = {
975
1170
  source: String(raw.source),
976
1171
  streamId: String(raw.streamId),
@@ -1006,33 +1201,9 @@ export const makeEngine = (config) => {
1006
1201
  delivered++;
1007
1202
  }
1008
1203
  });
1009
- /**
1010
- * Drain the row at `key`: under its current key, and — while the fallback is
1011
- * on (#171) — its 1.36 key, where 1.36 left the items it wrote. A key that
1012
- * can also hold another value's items is read for the row's own: its
1013
- * current key when it reads back as another value's 1.36 key (`foo bar`'s
1014
- * is `foo%20bar`'s) for the marked ones, its 1.36 key when that can be
1015
- * another value's current key (`_spells136`) for the unmarked ones.
1016
- */
1017
1204
  const drain = (key, deliver) => {
1018
- const record = key;
1019
- const rowKey = composePrimaryKey(readModel, record);
1020
- const rows = [
1021
- {
1022
- pk: String(rowKey[primary.pk.field]),
1023
- sk: String(rowKey[primary.sk.field]),
1024
- only: typeof readModel._currentKeyOf136(rowKey) === "object" ? "marked" : undefined,
1025
- },
1026
- ];
1027
- const old = readModel._primaryKey136(record);
1028
- if (old !== undefined) {
1029
- rows.unshift({
1030
- pk: old[primary.pk.field],
1031
- sk: old[primary.sk.field],
1032
- only: readModel._spells136(record) ? "unmarked" : undefined,
1033
- });
1034
- }
1035
- return drainRaw(rows, deliver);
1205
+ const rowKey = composePrimaryKey(readModel, key);
1206
+ return drainRaw(String(rowKey[primary.pk.field]), String(rowKey[primary.sk.field]), deliver);
1036
1207
  };
1037
1208
  /** Every row with pending effects, through the outbox's sparse index, drained. */
1038
1209
  const drainPending = (deliver) => Effect.gen(function* () {
@@ -1046,7 +1217,6 @@ export const makeEngine = (config) => {
1046
1217
  }
1047
1218
  const client = yield* Capacity.client;
1048
1219
  const TableName = yield* outboxTable;
1049
- /** The row keys items name, and whether marked and unmarked items name each. */
1050
1220
  const rows = new Map();
1051
1221
  let start;
1052
1222
  do {
@@ -1062,54 +1232,29 @@ export const makeEngine = (config) => {
1062
1232
  const raw = fromAttributeMap(item);
1063
1233
  const pk = String(raw[ROW_PK]);
1064
1234
  const sk = String(raw[ROW_SK]);
1065
- const id = `${pk}\u0000${sk}`;
1066
- const named = rows.get(id) ?? { pk, sk, marked: false, unmarked: false };
1067
- if (raw[KEY_TEXT] === undefined)
1068
- named.unmarked = true;
1069
- else
1070
- named.marked = true;
1071
- rows.set(id, named);
1235
+ rows.set(`${pk}\u0000${sk}`, [pk, sk]);
1072
1236
  }
1073
1237
  start = page.LastEvaluatedKey;
1074
1238
  } while (start !== undefined);
1075
- // A row's items under its 1.36 key (#171) are drained with those under
1076
- // its current key, in one order: the key an item 1.36 wrote names is
1077
- // read back as 1.36 text (`_currentKeyOf136`) to find where the row is
1078
- // now. When that is another row (`foo%20bar`'s 1.36 key is `foo bar`'s
1079
- // current key), the key's unmarked items are that row's, and its
1080
- // marked ones the row of the key.
1081
- const byRow = new Map();
1082
- const add = (rowPk, rowSk, at) => {
1083
- const id = `${rowPk}\u0000${rowSk}`;
1084
- byRow.set(id, [...(byRow.get(id) ?? []), at]);
1085
- };
1086
- for (const { pk, sk, marked, unmarked } of rows.values()) {
1087
- const placed = readModel._currentKeyOf136({
1088
- [primary.pk.field]: pk,
1089
- [primary.sk.field]: sk,
1090
- });
1091
- if (typeof placed !== "object") {
1092
- add(pk, sk, { pk, sk });
1093
- continue;
1094
- }
1095
- if (unmarked) {
1096
- const current = placed.current;
1097
- add(current[primary.pk.field], current[primary.sk.field], { pk, sk, only: "unmarked" });
1098
- }
1099
- if (marked)
1100
- add(pk, sk, { pk, sk, only: "marked" });
1101
- }
1102
1239
  let delivered = 0;
1103
1240
  const undelivered = [];
1104
- for (const keys of byRow.values()) {
1105
- const result = yield* drainRaw(keys, deliver);
1241
+ for (const [pk, sk] of rows.values()) {
1242
+ const result = yield* drainRaw(pk, sk, deliver);
1106
1243
  delivered += result.delivered;
1107
1244
  if (Option.isSome(result.undelivered))
1108
1245
  undelivered.push(result.undelivered.value);
1109
1246
  }
1110
1247
  return { delivered, undelivered };
1111
1248
  });
1112
- return { readRow, applyRow, drain, drainPending, call };
1249
+ return {
1250
+ readRow,
1251
+ // A key the row can't compose is that row's failure, not the batch's.
1252
+ applyRow: (key, work, options) => Capacity.refusalsFail(`${config.label}.apply`, { target: entityType }, applyRow(key, work, options)),
1253
+ drain,
1254
+ drainPending,
1255
+ preflight,
1256
+ call,
1257
+ };
1113
1258
  };
1114
1259
  /**
1115
1260
  * The default lost-race policy: up to 12 retries after a jittered delay