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
@@ -12,23 +12,24 @@ import { Compression, make as makeCompressionRegistry, } from "@effect-dynamodb/
12
12
  import * as DynamoSchema from "@effect-dynamodb/schema/DynamoSchema.js";
13
13
  import { Embedder } from "@effect-dynamodb/schema/Embedder.js";
14
14
  import { DynamoError, DynamoValidationError, InternalServerError, isAwsInternalServerError, isAwsResourceNotFound, isAwsThrottling, isAwsValidationError, ResourceNotFoundError, ThrottlingError, ValidationError, } from "@effect-dynamodb/schema/Errors.js";
15
- import { compositeKeyFormKind, keyFormValueKind, makeCompositeKeyForm, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
15
+ import { compositeKeyFormKind, keyFormValueKind, keyFormValueKindOf, makeCompositeDomainKeyForm, makeCompositeKeyForm, refuseInexact, toCompositeKeyRecord, } from "@effect-dynamodb/schema/internal/CompositeCodec.js";
16
16
  import { makeDefaultCrypto } from "@effect-dynamodb/schema/internal/DefaultCrypto.js";
17
- import * as KeyText136 from "@effect-dynamodb/schema/internal/KeyText136.js";
18
17
  import { getSchemaFields } from "@effect-dynamodb/schema/internal/SchemaAccessors.js";
19
18
  import * as ZOrderCurve from "@effect-dynamodb/schema/internal/ZOrderCurve.js";
20
19
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
21
20
  import { Config, Context, DateTime, Duration, Effect, Layer, Option, SchemaAST, } from "effect";
22
21
  import { SecureRandom } from "effect/crypto";
23
- import { bind as aggregateBind } from "./Aggregate.js";
22
+ import { bind as aggregateBind, ownershipConflict } from "./Aggregate.js";
24
23
  import { bind as entityBind, fromDefinition as entityFromDefinition } from "./Entity.js";
25
24
  import { BoundQueryImpl, collectionNaming, entityNaming, } from "./internal/BoundQuery.js";
26
25
  import { makeBoundVectorQuery, } from "./internal/BoundVectorQuery.js";
27
26
  import * as Capacity from "./internal/Capacity.js";
27
+ import { acquireSdkClient, readClientOptions, } from "./internal/ClientOptions.js";
28
28
  import { redactCredentialRefusal } from "./internal/CredentialRefusal.js";
29
29
  import { createConditionOps, ExprTag } from "./internal/Expr.js";
30
30
  import { codecRequirements, collectionPackedQueryOptions, entityPackedQueryOptions, unregisteredCodecError, } from "./internal/Packed.js";
31
31
  import { createPathBuilder } from "./internal/PathBuilder.js";
32
+ import { physicalTableName, refuseSharedOutboxKeySpace, remoteOutboxesOf, sharedOutboxKeySpace, } from "./internal/ProjectionEngine.js";
32
33
  import { canonicalJson, compareUtf8, compositePlanner, keyJustBelow, zorderPlanner, } from "./internal/RangePlanner.js";
33
34
  import * as Rekey from "./internal/Rekey.js";
34
35
  import { diagnoseFailure, explainDiagnosis, withCause, } from "./internal/WriteDiagnosis.js";
@@ -42,15 +43,15 @@ import { mergeVectorIndexes, definition as tableDefinition, toVectorIndexSpec }
42
43
  * code point representable in a 3-byte UTF-8 sequence, which sorts above every
43
44
  * character DynamoDB key composition emits for the following segment.
44
45
  */
45
- const SK_MAX_SENTINEL = "￿";
46
+ const SK_MAX_SENTINEL = KeyComposer.SORT_KEY_MAX;
46
47
  /**
47
48
  * A composite value's key text as key composition writes it: serialized,
48
- * cased and escaped (`KeyComposer.serializeSortKeyValue`), so it sorts as the
49
+ * cased and escaped (`KeyComposer.keyValueText`), so it sorts as the
49
50
  * cased value does.
50
51
  */
51
- const valueText = (casing, keyForm) => KeyComposer.serializeSortKeyValue(keyForm, casing);
52
+ const valueText = (schema, casing, keyForm) => KeyComposer.keyValueText(schema, keyForm, casing);
52
53
  /** A sort key composite's segment as key composition writes it: `<name>_<value>`, cased. */
53
- export const compositeSegment = (casing, field, keyForm) => `${DynamoSchema.applyCasing(field, casing)}_${valueText(casing, keyForm)}`;
54
+ export const compositeSegment = (schema, casing, field, keyForm) => `${DynamoSchema.applyCasing(field, casing)}_${valueText(schema, casing, keyForm)}`;
54
55
  /** `bound` with each operand mapped — into its key form, say. */
55
56
  const mapBound = (bound, f) => {
56
57
  if ("eq" in bound)
@@ -72,9 +73,9 @@ const mapBound = (bound, f) => {
72
73
  * forms. Escaped key text sorts as the cased value, so this is the order the
73
74
  * key condition reads in.
74
75
  */
75
- const boundHolds = (casing, bound, keyForm) => {
76
- const text = valueText(casing, keyForm);
77
- const against = (operand) => compareUtf8(text, valueText(casing, operand));
76
+ const boundHolds = (schema, casing, bound, keyForm) => {
77
+ const text = valueText(schema, casing, keyForm);
78
+ const against = (operand) => compareUtf8(text, valueText(schema, casing, operand));
78
79
  if ("eq" in bound)
79
80
  return against(bound.eq) === 0;
80
81
  if ("lt" in bound)
@@ -91,7 +92,7 @@ const boundHolds = (casing, bound, keyForm) => {
91
92
  const operand = bound.beginsWith;
92
93
  return typeof operand === "number" || typeof operand === "bigint"
93
94
  ? against(operand) === 0
94
- : text.startsWith(valueText(casing, operand));
95
+ : text.startsWith(valueText(schema, casing, operand));
95
96
  };
96
97
  /**
97
98
  * @internal Compose a bound on sort key composite `field` into a key condition, the
@@ -107,7 +108,7 @@ const boundHolds = (casing, bound, keyForm) => {
107
108
  * the `<name>_` prefix, the casing and the escaping.
108
109
  *
109
110
  * The condition is exact: a composite's key text is escaped
110
- * (`KeyComposer.sortKeyText`), so it sorts as its value, and the delimiter
111
+ * (`KeyComposer.keyText`), so it sorts as its value, and the delimiter
111
112
  * that follows it sorts below every character it holds — a value's subtree
112
113
  * (`v#…`) sorts after `v` itself and before every greater value (`v%20x`,
113
114
  * `v0`), whatever characters the values hold (#171).
@@ -125,7 +126,7 @@ export const composeRangeUnder = (index, prefixText, field, bound, options) => {
125
126
  // `composeSortKeyPrefix` stops at the first missing composite.
126
127
  const compose = (value) => value === undefined || value === null
127
128
  ? prefixText.slice(0, -1)
128
- : `${prefixText}${compositeSegment(index.casing, field, value)}`;
129
+ : `${prefixText}${compositeSegment(index.schema, index.casing, field, value)}`;
129
130
  /**
130
131
  * `begins_with` operand matching exactly the keys whose composite equals
131
132
  * `value`: it stops on a segment boundary rather than leaking into sibling
@@ -160,7 +161,11 @@ export const composeRangeUnder = (index, prefixText, field, bound, options) => {
160
161
  return { beginsWith: compose(operand) };
161
162
  }
162
163
  if ("eq" in bound) {
163
- return index.isLast ? { eq: compose(bound.eq) } : { beginsWith: subtreeBeginsWith(bound.eq) };
164
+ if (index.isLast)
165
+ return { eq: compose(bound.eq) };
166
+ return index.secondary
167
+ ? KeyComposer.pinCondition(index.schema, compose(bound.eq))
168
+ : { beginsWith: subtreeBeginsWith(bound.eq) };
164
169
  }
165
170
  if ("between" in bound) {
166
171
  return { between: [compose(bound.between[0]), upper(bound.between[1])] };
@@ -210,7 +215,7 @@ export const composeIntervalUnder = (index, prefixText, field, lower, upper) =>
210
215
  throw new Error("[internal] A .within() range bound has no end.");
211
216
  return under(one);
212
217
  }
213
- const operand = (bound) => valueText(index.casing, Object.values(bound)[0]);
218
+ const operand = (bound) => valueText(index.schema, index.casing, Object.values(bound)[0]);
214
219
  const order = compareUtf8(operand(lower), operand(upper));
215
220
  if (order > 0 || (order === 0 && ("gt" in lower || "lt" in upper)))
216
221
  return undefined;
@@ -300,7 +305,7 @@ const combineRowChecks = (checks) => checks.length === 0
300
305
  * nothing: the query is returned as it is.
301
306
  */
302
307
  const planCompositeWithin = (args) => {
303
- const { entityLike, accessor, indexDef, compositeKeyForm, pinnedKeyForm } = args;
308
+ const { entityLike, accessor, indexDef, domainKeyForm, pinnedKeyForm } = args;
304
309
  const sk = indexDef.sk.composite;
305
310
  const n = sk.length;
306
311
  const p = sk.findIndex((attr) => pinnedKeyForm[attr] === undefined);
@@ -357,8 +362,8 @@ const planCompositeWithin = (args) => {
357
362
  }
358
363
  const expected = kindOf(field);
359
364
  const keyForm = (value) => {
360
- const converted = compositeKeyForm(field, value);
361
- if (expected !== undefined && typeof converted !== expected) {
365
+ const converted = domainKeyForm(field, value);
366
+ if (expected !== undefined && keyFormValueKindOf(converted) !== expected) {
362
367
  return refuse(`the bound on "${field}" is ${JSON.stringify(String(value))} (${typeof value}), but ` +
363
368
  `the composite's key form is a ${expected}.`);
364
369
  }
@@ -391,7 +396,7 @@ const planCompositeWithin = (args) => {
391
396
  return args.query;
392
397
  // -- composition --
393
398
  const casing = KeyComposer.effectiveCasing(entityLike._schema, indexDef);
394
- const segment = (i, keyForm) => compositeSegment(casing, sk[i], keyForm);
399
+ const segment = (i, keyForm) => compositeSegment(entityLike._schema, casing, sk[i], keyForm);
395
400
  const label = (i) => `${DynamoSchema.applyCasing(sk[i], casing)}_`;
396
401
  /**
397
402
  * Bound `i` composed under `prefixText`, clamped to it; `undefined` when no
@@ -399,7 +404,12 @@ const planCompositeWithin = (args) => {
399
404
  */
400
405
  const composeBound = (prefixText, i) => {
401
406
  const bound = bounds.get(i);
402
- const index = { casing, isLast: i === n - 1 };
407
+ const index = {
408
+ schema: entityLike._schema,
409
+ casing,
410
+ isLast: i === n - 1,
411
+ secondary: indexDef.index !== undefined,
412
+ };
403
413
  return bound._tag === "eq"
404
414
  ? composeRangeUnder(index, prefixText, sk[i], { eq: bound.value }, { clampToPrefix: true })
405
415
  : composeIntervalUnder(index, prefixText, sk[i], bound.lower, bound.upper);
@@ -407,10 +417,11 @@ const planCompositeWithin = (args) => {
407
417
  /** Does bound `i` hold for a composite value (key form), compared as key text? */
408
418
  const holds = (i, keyForm) => {
409
419
  const bound = bounds.get(i);
410
- if (bound._tag === "eq")
411
- return boundHolds(casing, { eq: bound.value }, keyForm);
412
- return ((bound.lower === undefined || boundHolds(casing, bound.lower, keyForm)) &&
413
- (bound.upper === undefined || boundHolds(casing, bound.upper, keyForm)));
420
+ if (bound._tag === "eq") {
421
+ return boundHolds(entityLike._schema, casing, { eq: bound.value }, keyForm);
422
+ }
423
+ return ((bound.lower === undefined || boundHolds(entityLike._schema, casing, bound.lower, keyForm)) &&
424
+ (bound.upper === undefined || boundHolds(entityLike._schema, casing, bound.upper, keyForm)));
414
425
  };
415
426
  /**
416
427
  * The key condition under `prefixText` from composite `from`: eq bounds
@@ -434,7 +445,14 @@ const planCompositeWithin = (args) => {
434
445
  checked: [...bounds.keys()].filter((j) => j > i),
435
446
  };
436
447
  }
437
- return { condition: { beginsWith: q }, checked: [...bounds.keys()].filter((j) => j >= i) };
448
+ // The eq bounds end at a value with nothing after it bounded. On a secondary
449
+ // index a row truncated there belongs too (`pinCondition`).
450
+ return {
451
+ condition: indexDef.index === undefined
452
+ ? { beginsWith: q }
453
+ : KeyComposer.pinCondition(entityLike._schema, q.slice(0, -1)),
454
+ checked: [...bounds.keys()].filter((j) => j >= i),
455
+ };
438
456
  };
439
457
  /**
440
458
  * Bounds checked on the raw row (§11): each composite's key text is
@@ -625,13 +643,14 @@ const withinEnds = (value, lower, upper, compare) => {
625
643
  * where it doesn't (numbers stored as strings, zoned dates, a `literals`
626
644
  * selection too large for `IN`) and for hashed prefix values (collisions).
627
645
  *
628
- * Throws `[EDD-9093]` for misuse from untyped code, `[EDD-9050]` for a value
629
- * that doesn't reach key form and `[EDD-9092]` for one no level holds — at
630
- * `.within()`, so every terminal (and `explain`) has a valid box. `{}` plans
631
- * nothing: the query is returned as it is.
646
+ * Throws `[EDD-9093]` for misuse from untyped code and `[EDD-9050]` for a value
647
+ * that doesn't reach key form, at `.within()`, so every terminal (and `explain`)
648
+ * has a valid box. A value no level holds throws `ZOrderValueError` (`[EDD-9092]`),
649
+ * which `.within()` turns into the query's `ValidationError`. `{}` plans nothing:
650
+ * the query is returned as it is.
632
651
  */
633
652
  const planZOrderWithin = (args) => {
634
- const { entityLike, accessor, indexDef, compositeKeyForm } = args;
653
+ const { entityLike, accessor, indexDef, domainKeyForm } = args;
635
654
  const refuse = (why) => {
636
655
  throw new Error(`[EDD-9093] .within() on index "${accessor}" of entity "${entityLike.entityType}": ${why}`);
637
656
  };
@@ -648,10 +667,10 @@ const planZOrderWithin = (args) => {
648
667
  const fields = getSchemaFields(args.encoderSource);
649
668
  /** `value` in the field's key form: `[EDD-9050]` from the encoder, `[EDD-9093]` for the wrong type. */
650
669
  const keyForm = (field, value) => {
651
- const converted = compositeKeyForm(field, value);
670
+ const converted = domainKeyForm(field, value);
652
671
  const schema = fields?.[field];
653
672
  const expected = schema === undefined ? undefined : keyFormValueKind(schema);
654
- if (expected !== undefined && typeof converted !== expected) {
673
+ if (expected !== undefined && keyFormValueKindOf(converted) !== expected) {
655
674
  return refuse(`the bound on "${field}" is ${JSON.stringify(String(value))} (${typeof value}), but ` +
656
675
  `the field's key form is a ${expected}.`);
657
676
  }
@@ -786,22 +805,14 @@ const planZOrderWithin = (args) => {
786
805
  return Array.from({ length: Math.max(0, hi - lo + 1) }, (_, i) => lo + i);
787
806
  };
788
807
  const { box, selections } = (() => {
789
- try {
790
- const quantized = ZOrderCurve.quantizeBounds(layout, Object.fromEntries(dimensions
791
- .filter((dim) => bounded.has(dim.field))
792
- .map((dim) => [dim.field, quantizable(dim)])));
793
- const selected = new Map(dimensions
794
- .filter((dim) => dim.spec.kind === "literals" && bounded.has(dim.field))
795
- .map((dim) => [dim.field, literalSelection(dim, bounded.get(dim.field).keyForm)]));
796
- const none = [...selected.values()].some((members) => members.length === 0);
797
- return { box: none ? "empty" : quantized, selections: selected };
798
- }
799
- catch (error) {
800
- // A value that reaches key form but no level (§3.3): thrown, like EDD-9050.
801
- if (ZOrderCurve.isZOrderValueError(error))
802
- throw new Error(error.message);
803
- throw error;
804
- }
808
+ const quantized = ZOrderCurve.quantizeBounds(layout, Object.fromEntries(dimensions
809
+ .filter((dim) => bounded.has(dim.field))
810
+ .map((dim) => [dim.field, quantizable(dim)])));
811
+ const selected = new Map(dimensions
812
+ .filter((dim) => dim.spec.kind === "literals" && bounded.has(dim.field))
813
+ .map((dim) => [dim.field, literalSelection(dim, bounded.get(dim.field).keyForm)]));
814
+ const none = [...selected.values()].some((members) => members.length === 0);
815
+ return { box: none ? "empty" : quantized, selections: selected };
805
816
  })();
806
817
  // -- exact bounds (§11): a FilterExpression where DynamoDB's order agrees, else row checks --
807
818
  const path = (field) => ({ _tag: "path", segments: [field] });
@@ -913,7 +924,7 @@ const planZOrderWithin = (args) => {
913
924
  }
914
925
  // -- the prefix (§4.3, §7.5) --
915
926
  const casing = KeyComposer.effectiveCasing(entityLike._schema, indexDef);
916
- const textOf = (value) => valueText(casing, value);
927
+ const textOf = (value) => valueText(entityLike._schema, casing, value);
917
928
  const segmentOf = (part) => ZOrderCurve.prefixSegment(textOf(prefixValues.get(part.field)), part.hash);
918
929
  /** A given prefix composite, checked on the cased value — never a hash, which can collide. */
919
930
  const prefixCheck = (part) => {
@@ -980,14 +991,17 @@ const planZOrderWithin = (args) => {
980
991
  });
981
992
  };
982
993
  /**
983
- * The composite key form for an arbitrary entity-like value — the same rule
984
- * `Entity` applies to its own keys (`internal/CompositeCodec.ts`).
994
+ * The key form of a caller's DOMAIN record for an arbitrary entity-like value —
995
+ * the key `put` wrote for those values (`internal/CompositeCodec.ts`,
996
+ * `makeCompositeDomainKeyForm`), as `Entity._domainKeyForm` composes it.
985
997
  */
986
- const entityKeyForm = (entityLike, record) => {
998
+ const entityDomainKeyForm = (entityLike, record) => {
987
999
  const source = (entityLike.schemas?.inputSchema ?? entityLike.model);
988
1000
  if (source === undefined)
989
1001
  return record;
990
- const form = makeCompositeKeyForm(source, (attr, value) => {
1002
+ const form = makeCompositeDomainKeyForm(source, (attr, value, reason) => {
1003
+ if (reason !== undefined)
1004
+ return refuseInexact(`Composite "${attr}"`, value, reason);
991
1005
  throw new Error(`[EDD-9050] Composite "${attr}" could not be put into its key form: ` +
992
1006
  `${JSON.stringify(String(value))} resolves under neither encode nor decode->encode.`);
993
1007
  });
@@ -1054,6 +1068,13 @@ export class DynamoClient extends Context.Service()("@effect-dynamodb/DynamoClie
1054
1068
  * @param config.region - AWS region
1055
1069
  * @param config.endpoint - Optional endpoint override (e.g., for DynamoDB Local)
1056
1070
  * @param config.credentials - Optional static credentials
1071
+ * @param config.requestHandler - Optional HTTP handler, or the options of the
1072
+ * runtime's handler (`{ socketTimeout: 5000 }`), passed to the SDK client.
1073
+ * None is set by default, so without one a connection that stays open and
1074
+ * never answers keeps a call waiting until it is interrupted. A handler you
1075
+ * pass is destroyed with the layer.
1076
+ * @param config.maxAttempts - Optional attempts per request, the first
1077
+ * included, passed to the SDK client (its default is 3)
1057
1078
  * @param config.compressors - Optional compressors for packed storage
1058
1079
  * (`DynamoModel.Packed` with `compression`). When given, the layer also
1059
1080
  * provides the `Compression` service built from them. That reaches whatever
@@ -1074,7 +1095,7 @@ export class DynamoClient extends Context.Service()("@effect-dynamodb/DynamoClie
1074
1095
  * const live = DynamoClient.layer({ region: "us-east-1", compressors: [ZlibCompression.zstd()] })
1075
1096
  * ```
1076
1097
  */
1077
- static layer = (config) => withCompressors(Layer.effect(DynamoClient, buildService(config.region, config.endpoint, config.credentials)), config.compressors);
1098
+ static layer = (config) => withCompressors(Layer.effect(DynamoClient, buildService(config.region, config.endpoint, config.credentials, config)), config.compressors);
1078
1099
  /**
1079
1100
  * Create a live Layer that reads configuration from Effect Config providers
1080
1101
  * (e.g., environment variables, config files).
@@ -1082,6 +1103,12 @@ export class DynamoClient extends Context.Service()("@effect-dynamodb/DynamoClie
1082
1103
  * @param config.region - Config for AWS region
1083
1104
  * @param config.endpoint - Optional Config for endpoint override
1084
1105
  * @param config.credentials - Optional Config for static credentials
1106
+ * @param config.requestHandler - Optional Config for each of the handler's
1107
+ * timeouts (`connectionTimeout`, `socketTimeout`, `requestTimeout`,
1108
+ * `throwOnRequestTimeout`), which an operator tunes per environment, or an
1109
+ * HTTP handler, which is code and is passed as itself. A timeout missing
1110
+ * from the provider stays unset.
1111
+ * @param config.maxAttempts - Optional Config for the attempts per request
1085
1112
  * @param config.compressors - Optional compressors for packed storage; when
1086
1113
  * given, the layer also provides the `Compression` service (see {@link layer}
1087
1114
  * for why a separate `Compression.layer([...])` is the recommended form).
@@ -1092,7 +1119,8 @@ export class DynamoClient extends Context.Service()("@effect-dynamodb/DynamoClie
1092
1119
  const credentials = config.credentials
1093
1120
  ? yield* Config.option(config.credentials)
1094
1121
  : undefined;
1095
- return yield* buildService(region, endpoint && endpoint._tag === "Some" ? endpoint.value : undefined, credentials && credentials._tag === "Some" ? credentials.value : undefined);
1122
+ const options = yield* readClientOptions(config);
1123
+ return yield* buildService(region, endpoint && endpoint._tag === "Some" ? endpoint.value : undefined, credentials && credentials._tag === "Some" ? credentials.value : undefined, options);
1096
1124
  })), config.compressors);
1097
1125
  /**
1098
1126
  * Create a typed client gateway from entities, aggregates, and (optionally) tables.
@@ -1207,6 +1235,15 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1207
1235
  ? Context.add(withEmbedder, Compression, compressionRegistry)
1208
1236
  : withEmbedder;
1209
1237
  const provide = (effect) => Effect.provide(effect, ctx);
1238
+ // A table's TTL attribute is named by its configuration, so an entity that sets it is checked
1239
+ // here, where the table is bound: a row's reader may not take it as a sparse map's entry
1240
+ // (`[EDD-9140]`, as `Entity.make` checks every name the definition supplies).
1241
+ for (const rawEntity of Object.values(config.entities)) {
1242
+ const entityLike = rawEntity;
1243
+ const tableConfig = Option.getOrUndefined(Context.getOption(baseCtx, entityLike._tableTag));
1244
+ if (tableConfig !== undefined)
1245
+ entityLike._refuseTableAttributes?.(tableConfig);
1246
+ }
1210
1247
  // Dimension agreement between the Embedder and every bound vector index is
1211
1248
  // a construction-time invariant — a mismatch would otherwise surface as a
1212
1249
  // per-write failure long after wiring. See `DESIGN.md §14`.
@@ -1266,13 +1303,20 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1266
1303
  // composing keys. The raw model is not equivalent — entity derivation
1267
1304
  // substitutes date/Redacted fields with their wire transforms.
1268
1305
  const encoderSource = entityLike.schemas.inputSchema ?? entityLike.model;
1269
- const compositeKeyForm = makeCompositeKeyForm(encoderSource, (attr, value) => {
1306
+ const unencodable = (attr, value, reason) => {
1307
+ if (reason !== undefined) {
1308
+ return refuseInexact(`Composite "${attr}" on index "${_indexName}" of entity "${entityLike.entityType}"`, value, reason);
1309
+ }
1270
1310
  throw new Error(`[EDD-9050] Composite "${attr}" on index "${_indexName}" of entity ` +
1271
1311
  `"${entityLike.entityType}" could not be encoded to its stored form. The ` +
1272
1312
  `attribute's schema carries an encoding transformation, so the stored key holds ` +
1273
1313
  `the ENCODED value, but ${JSON.stringify(String(value))} encodes under neither ` +
1274
1314
  `encode nor decode->encode. Supply a value of the attribute's own type.`);
1275
- });
1315
+ };
1316
+ const compositeKeyForm = makeCompositeKeyForm(encoderSource, unencodable);
1317
+ // The caller's composites and bounds are DOMAIN values: the key `put` wrote for one is
1318
+ // the key form of the value it stores (`Entity._domainKeyForm`).
1319
+ const domainKeyForm = makeCompositeDomainKeyForm(encoderSource, unencodable);
1276
1320
  // A Z-order sort key (#171) is a binary address: its prefix composites
1277
1321
  // and dimensions are bounded with `.within()`, never pinned by the
1278
1322
  // accessor, which takes the partition key composites only.
@@ -1285,7 +1329,7 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1285
1329
  ? indexDef.sk.zorderHalf.layout
1286
1330
  : undefined;
1287
1331
  const zorderPlans = zorderLayout === undefined ? undefined : makeZOrderPlans(zorderLayout);
1288
- return (rawComposites) => {
1332
+ const accessor = (rawComposites) => {
1289
1333
  if (zorder) {
1290
1334
  const misplaced = indexDef.sk.composite.filter((attr) => rawComposites[attr] !== undefined);
1291
1335
  if (misplaced.length > 0) {
@@ -1296,9 +1340,11 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1296
1340
  }
1297
1341
  }
1298
1342
  validateQueryComposites(_indexName, accessorDef, rawComposites);
1299
- const compositesKeyForm = toCompositeKeyRecord(compositeKeyForm, rawComposites);
1300
- const pkValue = KeyComposer.composePk(entityLike._schema, entityLike.entityType, indexDef, compositesKeyForm);
1301
- const query = Query.make({
1343
+ const compositesKeyForm = toCompositeKeyRecord(domainKeyForm, rawComposites);
1344
+ // One partition, or a sharded index's several (#183).
1345
+ const read = KeyComposer.composeReadPartitions(entityLike._schema, entityLike.entityType, indexDef, compositesKeyForm);
1346
+ const pkValue = read.partitions[0];
1347
+ const unpartitioned = Query.make({
1302
1348
  tableName: "",
1303
1349
  indexName: indexDef.index,
1304
1350
  pkField: indexDef.pk.field,
@@ -1323,33 +1369,19 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1323
1369
  label: `${entityLike.entityType}.${_indexName}`,
1324
1370
  },
1325
1371
  });
1372
+ const query = Query.fanOut(unpartitioned, read);
1326
1373
  // Apply the SK condition from the provided composites
1327
- // (`composeSortKeyCondition`): a partial prefix is a `begins_with`
1328
- // terminated on a segment boundary, or it matches sibling values that
1329
- // merely start with the supplied one (`status_done` also matching
1330
- // `status_done_archived`, issue #115); a complete key is an exact `=`,
1331
- // or `seq: 3` also matches 3.14 and `name: "a"` also matches "ab".
1374
+ // (`composeSortKeyCondition`): a partial prefix stops on a segment
1375
+ // boundary, or it matches sibling values that merely start with the
1376
+ // supplied one (`status_done` also matching `status_done_archived`,
1377
+ // issue #115), and on a secondary index takes the row truncated at it; a
1378
+ // complete key is an exact `=`, or `seq: 3` also matches 3.14 and
1379
+ // `name: "a"` also matches "ab".
1332
1380
  const hasSkComposites = !zorder &&
1333
1381
  indexDef.sk.composite.some((attr) => compositesKeyForm[attr] !== undefined);
1334
1382
  const pinnedQuery = hasSkComposites
1335
- ? Query.where(query, KeyComposer.composeSortKeyCondition(entityLike._schema, entityLike.entityType, 1, indexDef, compositesKeyForm))
1383
+ ? Query.whereUnderPins(query, KeyComposer.composeSortKeyCondition(entityLike._schema, entityLike.entityType, 1, indexDef, compositesKeyForm))
1336
1384
  : query;
1337
- // Rows 1.36 wrote whose key text changed sit under the key 1.36
1338
- // composed for these pins until they move (#171): the query reads it
1339
- // too — the partition key, and the pins' `eq` / `begins_with`. A
1340
- // Z-order index is new in 1.37, so it has no 1.36 rows.
1341
- const pk136 = !zorder && KeyText136.enabled(entityLike._schema)
1342
- ? KeyText136.composePk(entityLike._schema, entityLike.entityType, indexDef, compositesKeyForm)
1343
- : undefined;
1344
- const finalQuery = pk136 === undefined
1345
- ? pinnedQuery
1346
- : Query.alsoRead136(pinnedQuery, {
1347
- pkValue: pk136,
1348
- rows: entityLike._indexRows136?.(indexDef),
1349
- condition: hasSkComposites
1350
- ? KeyText136.composeSortKeyCondition(entityLike._schema, entityLike.entityType, 1, indexDef, compositesKeyForm)
1351
- : undefined,
1352
- });
1353
1385
  const pathBuilder = createPathBuilder();
1354
1386
  const conditionOps = createConditionOps();
1355
1387
  // composeSkCondition — compose the user's `.where()` operand into a full
@@ -1448,42 +1480,17 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1448
1480
  // are equivalent again — stating the real predicate keeps them from
1449
1481
  // drifting apart a second time.
1450
1482
  return composeRangeUnder({
1483
+ schema: entityLike._schema,
1451
1484
  casing: KeyComposer.effectiveCasing(entityLike._schema, indexDef),
1452
1485
  isLast: targetIndex === skComposites.length - 1,
1453
- }, prefixText, targetAttr, mapBound(condition, (value) => compositeKeyForm(targetAttr, value)), { clampToPrefix: pinnedCount > 0 });
1454
- };
1455
- /**
1456
- * The 1.36 key a `.where()` also reads (#171): an `eq` or
1457
- * `beginsWith` extends the pins, so the rows it selects under 1.36's
1458
- * key text are read too. A range bound reads only the current key.
1459
- */
1460
- const where136 = (condition, field) => {
1461
- if (pk136 === undefined || !("eq" in condition || "beginsWith" in condition)) {
1462
- return undefined;
1463
- }
1464
- const pinnedCount = skComposites.findIndex((attr) => compositesKeyForm[attr] === undefined);
1465
- const targetAttr = field !== undefined && skComposites.includes(field)
1466
- ? field
1467
- : skComposites[pinnedCount === -1 ? skComposites.length - 1 : pinnedCount];
1468
- const pinned = {};
1469
- for (const attr of skComposites.slice(0, skComposites.indexOf(targetAttr))) {
1470
- pinned[attr] = compositesKeyForm[attr];
1471
- }
1472
- const operand = (value) => compositeKeyForm(targetAttr, value);
1473
- return {
1474
- pkValue: pk136,
1475
- rows: entityLike._indexRows136?.(indexDef),
1476
- condition: KeyText136.composeBoundCondition(entityLike._schema, entityLike.entityType, 1, indexDef, pinned, targetAttr, "eq" in condition
1477
- ? { eq: operand(condition.eq) }
1478
- : { beginsWith: operand(condition.beginsWith) }),
1479
- };
1486
+ secondary: indexDef.index !== undefined,
1487
+ }, prefixText, targetAttr, mapBound(condition, (value) => domainKeyForm(targetAttr, value)), { clampToPrefix: pinnedCount > 0 });
1480
1488
  };
1481
1489
  const bqConfig = {
1482
1490
  pathBuilder,
1483
1491
  conditionOps,
1484
1492
  provide,
1485
1493
  composeSkCondition,
1486
- where136,
1487
1494
  // A Z-order accessor bounds its dimensions and prefix composites
1488
1495
  // (#171), and takes `.zorder()`.
1489
1496
  ...(zorder
@@ -1495,6 +1502,7 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1495
1502
  indexDef,
1496
1503
  encoderSource,
1497
1504
  compositeKeyForm,
1505
+ domainKeyForm,
1498
1506
  pkValue,
1499
1507
  plans: zorderPlans,
1500
1508
  query: q,
@@ -1509,6 +1517,7 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1509
1517
  indexDef,
1510
1518
  encoderSource,
1511
1519
  compositeKeyForm,
1520
+ domainKeyForm,
1512
1521
  pinnedKeyForm: compositesKeyForm,
1513
1522
  pkValue,
1514
1523
  query: q,
@@ -1520,7 +1529,21 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1520
1529
  ...entityNaming(entityLike._resolveDbName),
1521
1530
  operation: { name: "Entity.query", target: entityLike.entityType, index: _indexName },
1522
1531
  };
1523
- return new BoundQueryImpl(finalQuery, bqConfig);
1532
+ return new BoundQueryImpl(pinnedQuery, bqConfig);
1533
+ };
1534
+ return (rawComposites) => {
1535
+ const operation = {
1536
+ name: "Entity.query",
1537
+ target: entityLike.entityType,
1538
+ index: _indexName,
1539
+ };
1540
+ return Query.orRefusal(operation, () => accessor(rawComposites), (refusal) => new BoundQueryImpl(Query.refused(indexDef.index, refusal), {
1541
+ pathBuilder: createPathBuilder(),
1542
+ conditionOps: createConditionOps(),
1543
+ provide,
1544
+ ...entityNaming(entityLike._resolveDbName),
1545
+ operation,
1546
+ }));
1524
1547
  };
1525
1548
  };
1526
1549
  // 2. Bind entities + build entity query accessors
@@ -1578,7 +1601,7 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1578
1601
  `accessors, \`scan\` and \`reembed\` — rename one of them.`);
1579
1602
  }
1580
1603
  const vqConfig = {
1581
- keyForm: (record) => entityKeyForm(entityLike, record),
1604
+ keyForm: (record) => entityDomainKeyForm(entityLike, record),
1582
1605
  entityType: entityLike.entityType,
1583
1606
  logicalName,
1584
1607
  definition,
@@ -1628,7 +1651,8 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1628
1651
  // bind time instead.
1629
1652
  assertCollectionKeyFormAgreement(collName, members);
1630
1653
  KeyComposer.assertCollectionCasingAgreement(collName, members.map((m) => ({ key: m.entityKey, schema: m.entityLike._schema, index: m.indexDef })));
1631
- boundCollections[collName] = (composites) => {
1654
+ KeyComposer.assertCollectionShardsAgreement(collName, members.map((m) => ({ key: m.entityKey, index: m.indexDef })));
1655
+ const collectionAccessor = (composites) => {
1632
1656
  // Use the first member for PK composition — verified above to agree
1633
1657
  // with every other member.
1634
1658
  const firstMember = members[0];
@@ -1666,13 +1690,14 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1666
1690
  // path use — without it `db.collections.window({ takenAt })` composed a
1667
1691
  // different PK from `db.entities.Readings.byWindow({ takenAt })` and
1668
1692
  // returned nothing.
1669
- const pkValue = KeyComposer.composePk(firstMember.entityLike._schema, firstMember.entityLike.entityType, indexDef, entityKeyForm(firstMember.entityLike, composites));
1693
+ // Members share the partitions, whatever each hashes: never pruned (#183).
1694
+ const read = KeyComposer.composeReadPartitions(firstMember.entityLike._schema, firstMember.entityLike.entityType, indexDef, entityDomainKeyForm(firstMember.entityLike, composites), { prune: false });
1670
1695
  // Always isolated — begins_with on collection SK prefix
1671
1696
  let query = Query.make({
1672
1697
  tableName: "",
1673
1698
  indexName: indexDef.index,
1674
1699
  pkField: indexDef.pk.field,
1675
- pkValue,
1700
+ pkValue: read.partitions[0],
1676
1701
  skField: indexDef.sk.field,
1677
1702
  entityTypes,
1678
1703
  decoder: collDecoder,
@@ -1688,6 +1713,7 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1688
1713
  liveRows: indexDef.index === undefined ? collectionLiveRows(members) : undefined,
1689
1714
  keyConditionDiagnosis: { operation: "query", label: `collection "${collName}"` },
1690
1715
  });
1716
+ query = Query.fanOut(query, read);
1691
1717
  // Add begins_with on collection SK prefix for clustered collections.
1692
1718
  // For isolated collections (default), each entity has its own entity-type
1693
1719
  // SK prefix, so a collection-name begins_with would filter them all out.
@@ -1706,11 +1732,6 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1706
1732
  const skPrefix = `${pre}#${casedNames.join("#")}`;
1707
1733
  query = Query.where(query, { beginsWith: skPrefix });
1708
1734
  }
1709
- // A collection's sort key prefix holds names only, so its 1.36 key
1710
- // differs in the partition key alone — a number composite (#171).
1711
- query = Query.alsoReadPartition136(query, KeyText136.enabled(firstMember.entityLike._schema)
1712
- ? KeyText136.composePk(firstMember.entityLike._schema, firstMember.entityLike.entityType, indexDef, entityKeyForm(firstMember.entityLike, composites))
1713
- : undefined);
1714
1735
  // Wrap in BoundQuery that groups results by entity key
1715
1736
  const pathBuilder = createPathBuilder();
1716
1737
  const conditionOps = createConditionOps();
@@ -1750,6 +1771,70 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1750
1771
  };
1751
1772
  return new BoundQueryImpl(query, bqConfig);
1752
1773
  };
1774
+ boundCollections[collName] = (composites) => {
1775
+ const operation = { name: "Collection.query", target: collName };
1776
+ return Query.orRefusal(operation, () => collectionAccessor(composites), (refusal) => new BoundQueryImpl(Query.refused(members[0].indexDef.index, refusal), {
1777
+ pathBuilder: createPathBuilder(),
1778
+ conditionOps: createConditionOps(),
1779
+ provide,
1780
+ operation,
1781
+ }));
1782
+ };
1783
+ }
1784
+ // An aggregate declaring `ownsRows` takes every row of its types in its partition. Refused when
1785
+ // another member this client can see can write such a row there (DESIGN.md §7 "Which rows in
1786
+ // its partition are an aggregate's"): those its table declares, those the client binds, and
1787
+ // those of every table the client binds, on the same physical table (by table, or by the
1788
+ // name it resolves to here). A writer it doesn't see, here or in another process, isn't checked.
1789
+ const tableNameOf = (table) => {
1790
+ // A table's tag is a function.
1791
+ if (table === null ||
1792
+ (typeof table !== "object" && typeof table !== "function") ||
1793
+ !("key" in table)) {
1794
+ return undefined;
1795
+ }
1796
+ return Option.getOrUndefined(Context.getOption(baseCtx, table))?.name;
1797
+ };
1798
+ // Every entity the client sees: those it binds, then those of every table it binds, named as a
1799
+ // refusal names them. A member may reach the client only as another bound table's.
1800
+ const visible = [
1801
+ ...Object.entries(config.entities),
1802
+ ...Object.entries(config.tables ?? {}).flatMap(([tableKey, table]) => Object.entries(table.entities).map(([key, entity]) => [`${tableKey}.${key}`, entity])),
1803
+ ];
1804
+ // And every aggregate it sees, the same way.
1805
+ const visibleAggregates = [
1806
+ ...Object.entries(config.aggregates ?? {}),
1807
+ ...Object.entries(config.tables ?? {}).flatMap(([tableKey, table]) => Object.entries(table.aggregates ?? {}).map(([key, aggregate]) => [`${tableKey}.${key}`, aggregate])),
1808
+ ];
1809
+ const visibleMembers = [...visible, ...visibleAggregates].map(([name, member]) => ({
1810
+ name,
1811
+ member,
1812
+ }));
1813
+ // The owners checked are the aggregates it sees, from the same list: `rekey` runs the handler of
1814
+ // a table's aggregate the client doesn't bind itself. Each once, by the first name it has.
1815
+ const checked = new Set();
1816
+ for (const [key, aggregate] of visibleAggregates) {
1817
+ if (aggregate._ownsRows !== true)
1818
+ continue;
1819
+ if (checked.has(aggregate))
1820
+ continue;
1821
+ checked.add(aggregate);
1822
+ const own = aggregate._tableTag;
1823
+ const ownName = tableNameOf(own);
1824
+ const conflict = ownershipConflict(aggregate, visibleMembers, (table) => {
1825
+ if (table === own)
1826
+ return true;
1827
+ const keyOf = (t) => t?.key;
1828
+ if (keyOf(table) !== undefined && keyOf(table) === keyOf(own))
1829
+ return true;
1830
+ return ownName !== undefined && tableNameOf(table) === ownName;
1831
+ });
1832
+ if (conflict !== undefined) {
1833
+ throw new Error(`[EDD-9130] Aggregate "${key}" declares \`ownsRows\`, but "${conflict.member}" can write ` +
1834
+ `a row of type "${conflict.type}" into its partition (${conflict.channel}). ` +
1835
+ `\`ownsRows\` would take that row for the aggregate's: leave it off, or keep ` +
1836
+ `"${conflict.member}"'s rows out of the aggregate's partition.`);
1837
+ }
1753
1838
  }
1754
1839
  // 4. Bind aggregates
1755
1840
  const boundAggregates = {};
@@ -1763,39 +1848,83 @@ const makeFromConfig = (config) => Effect.gen(function* () {
1763
1848
  // 5. Build table operations
1764
1849
  const client = yield* DynamoClient;
1765
1850
  const tables = {};
1851
+ // The entities the client sees (`visible`) are where `rekey` finds the outboxes of their
1852
+ // projections. `entities` comes first, so the read models it found before keep their order.
1853
+ const visibleEntities = visible.map(([, entity]) => entity);
1854
+ const named = visible.map(([name, entity]) => [`"${name}"`, entity]);
1855
+ yield* refuseSharedOutboxKeySpace("DynamoClient.make", named);
1766
1856
  // `rekey` (#171) hands each row to the member owning it: the table's
1767
1857
  // entities and aggregates, those the client binds on the same table, and
1768
1858
  // the streams the caller passes (`DynamoClient.make` binds no streams).
1769
- const rekeyFor = (tableName, tagKey, registered) => (options) => {
1770
- const onTable = (member) => member._tableTag?.key === tagKey;
1859
+ const rekeyFor = (tableName, tagKey, registered) => (options) => provide(Effect.gen(function* () {
1860
+ const onTable = (member) => member._tableTag?.key ===
1861
+ tagKey;
1771
1862
  const handlers = new Set();
1772
- for (const member of [
1863
+ const tableMembers = [
1773
1864
  ...registered,
1774
1865
  ...Object.values(config.entities).filter(onTable),
1775
1866
  ...Object.values(config.aggregates ?? {}).filter(onTable),
1776
- ...(options?.streams ?? []),
1777
- ]) {
1867
+ ];
1868
+ for (const member of [...tableMembers, ...(options?.streams ?? [])]) {
1778
1869
  const handler = Rekey.handlerOf(member);
1779
1870
  if (handler !== undefined)
1780
1871
  handlers.add(handler);
1781
1872
  }
1782
- // A projection's outbox on this table, of a read model on another (#171).
1873
+ // The read models whose outboxes are on this table are checked before anything is
1874
+ // sent: `rekey` reads an item's key back by its key space, so two whose keys could be
1875
+ // read as each other's are refused here, where `DynamoClient.make` refuses only those
1876
+ // whose items would overwrite each other in normal operation, and so is a member of
1877
+ // this table that would read a read model's items as its own. Projections are defined
1878
+ // when the program runs them, so one defined after the client was made has its outbox
1879
+ // recorded only now. A run's refusal is the run's `ValidationError`.
1880
+ const shared = yield* sharedOutboxKeySpace("rekey", named, {
1881
+ key: tagKey,
1882
+ name: tableName,
1883
+ members: [...new Set(tableMembers)].map((member) => [
1884
+ named.find(([, entity]) => entity === member)?.[0] ??
1885
+ `"${member.entityType}"`,
1886
+ member,
1887
+ ]),
1888
+ });
1889
+ if (shared !== undefined) {
1890
+ return yield* new ValidationError({
1891
+ entityType: "Table",
1892
+ operation: "rekey",
1893
+ cause: shared,
1894
+ });
1895
+ }
1896
+ // The outboxes on this table of a read model on another (#171): every projection's, so
1897
+ // a second projection of one read model doesn't hide the first's items, named by this
1898
+ // table's service or by another handle on the same physical table. A read model's
1899
+ // projections may have one each, on tables of their own.
1783
1900
  const outboxOf = new Set();
1784
- for (const entity of [...registered, ...Object.values(config.entities)]) {
1785
- const outbox = entity._projectionOutbox;
1786
- if (outbox === undefined || outbox.table.Tag.key !== tagKey || outboxOf.has(entity)) {
1901
+ for (const entity of [...registered, ...visibleEntities]) {
1902
+ if (outboxOf.has(entity))
1787
1903
  continue;
1788
- }
1789
1904
  outboxOf.add(entity);
1905
+ // Their key attributes, once each.
1906
+ const layouts = new Map();
1907
+ for (const outbox of remoteOutboxesOf(entity)) {
1908
+ if (outbox.table.Tag.key !== tagKey &&
1909
+ (yield* physicalTableName(outbox.table.Tag)) !== tableName) {
1910
+ continue;
1911
+ }
1912
+ layouts.set(`${outbox.pk}\u0000${outbox.sk}`, { pk: outbox.pk, sk: outbox.sk });
1913
+ }
1914
+ if (layouts.size === 0)
1915
+ continue;
1916
+ const keys = [...layouts.values()];
1790
1917
  const readModel = entity;
1791
1918
  handlers.add({
1792
1919
  name: readModel.entityType,
1793
1920
  types: [`${readModel.entityType}#outbox`],
1794
- row: (row, ctx) => readModel._rekeyProjectionRow(row, ctx, { pk: outbox.pk, sk: outbox.sk }),
1921
+ // A table has one key schema, so its items are under the layout whose attributes
1922
+ // they hold.
1923
+ row: (row, ctx) => readModel._rekeyProjectionRow(row, ctx, keys.find((key) => row[key.pk]?.S !== undefined && row[key.sk]?.S !== undefined) ?? keys[0]),
1795
1924
  });
1796
1925
  }
1797
- return provide(Rekey.run({ tableName, members: [...handlers], options }));
1798
- };
1926
+ return yield* Rekey.run({ tableName, members: [...handlers], options });
1927
+ }));
1799
1928
  if (config.tables) {
1800
1929
  for (const [tableKey, table] of Object.entries(config.tables)) {
1801
1930
  const tableConfig = yield* table.Tag;
@@ -2129,138 +2258,142 @@ export const classifyError = (operation) => (thrown) => {
2129
2258
  return new DynamoError({ operation, cause });
2130
2259
  };
2131
2260
  /** @internal Build the DynamoClient service implementation from resolved config values. */
2132
- const buildService = (region, endpoint, credentials) => Effect.gen(function* () {
2261
+ const buildService = (region, endpoint, credentials, options) => Effect.gen(function* () {
2133
2262
  const clientConfig = { region };
2134
2263
  if (endpoint !== undefined)
2135
2264
  clientConfig.endpoint = endpoint;
2136
2265
  if (credentials !== undefined)
2137
2266
  clientConfig.credentials = credentials;
2138
- const client = yield* Effect.acquireRelease(Effect.sync(() => new DynamoDBClient(clientConfig)), (c) => Effect.sync(() => c.destroy()));
2267
+ if (options.requestHandler !== undefined)
2268
+ clientConfig.requestHandler = options.requestHandler;
2269
+ if (options.maxAttempts !== undefined)
2270
+ clientConfig.maxAttempts = options.maxAttempts;
2271
+ const client = yield* acquireSdkClient(() => new DynamoDBClient(clientConfig));
2139
2272
  return {
2140
2273
  createTable: (input) => Effect.tryPromise({
2141
- try: () => client.send(new CreateTableCommand(input)),
2274
+ try: (signal) => client.send(new CreateTableCommand(input), { abortSignal: signal }),
2142
2275
  catch: classifyError("CreateTable"),
2143
2276
  }),
2144
2277
  deleteTable: (input) => Effect.tryPromise({
2145
- try: () => client.send(new DeleteTableCommand(input)),
2278
+ try: (signal) => client.send(new DeleteTableCommand(input), { abortSignal: signal }),
2146
2279
  catch: classifyError("DeleteTable"),
2147
2280
  }),
2148
2281
  describeTable: (input) => Effect.tryPromise({
2149
- try: () => client.send(new DescribeTableCommand(input)),
2282
+ try: (signal) => client.send(new DescribeTableCommand(input), { abortSignal: signal }),
2150
2283
  catch: classifyError("DescribeTable"),
2151
2284
  }),
2152
2285
  putItem: (input) => Effect.tryPromise({
2153
- try: () => client.send(new PutItemCommand(input)),
2286
+ try: (signal) => client.send(new PutItemCommand(input), { abortSignal: signal }),
2154
2287
  catch: classifyError("PutItem"),
2155
2288
  }),
2156
2289
  getItem: (input) => Effect.tryPromise({
2157
- try: () => client.send(new GetItemCommand(input)),
2290
+ try: (signal) => client.send(new GetItemCommand(input), { abortSignal: signal }),
2158
2291
  catch: classifyError("GetItem"),
2159
2292
  }),
2160
2293
  deleteItem: (input) => Effect.tryPromise({
2161
- try: () => client.send(new DeleteItemCommand(input)),
2294
+ try: (signal) => client.send(new DeleteItemCommand(input), { abortSignal: signal }),
2162
2295
  catch: classifyError("DeleteItem"),
2163
2296
  }),
2164
2297
  updateItem: (input) => Effect.tryPromise({
2165
- try: () => client.send(new UpdateItemCommand(input)),
2298
+ try: (signal) => client.send(new UpdateItemCommand(input), { abortSignal: signal }),
2166
2299
  catch: classifyError("UpdateItem"),
2167
2300
  }),
2168
2301
  query: (input) => Effect.tryPromise({
2169
- try: () => client.send(new QueryCommand(input)),
2302
+ try: (signal) => client.send(new QueryCommand(input), { abortSignal: signal }),
2170
2303
  catch: classifyError("Query"),
2171
2304
  }),
2172
2305
  scan: (input) => Effect.tryPromise({
2173
- try: () => client.send(new ScanCommand(input)),
2306
+ try: (signal) => client.send(new ScanCommand(input), { abortSignal: signal }),
2174
2307
  catch: classifyError("Scan"),
2175
2308
  }),
2176
2309
  searchVectors: (input) => Effect.tryPromise({
2177
- try: () => client.send(new SearchVectorsCommand(input)),
2310
+ try: (signal) => client.send(new SearchVectorsCommand(input), { abortSignal: signal }),
2178
2311
  catch: classifyError("SearchVectors"),
2179
2312
  }),
2180
2313
  batchGetItem: (input) => Effect.tryPromise({
2181
- try: () => client.send(new BatchGetItemCommand(input)),
2314
+ try: (signal) => client.send(new BatchGetItemCommand(input), { abortSignal: signal }),
2182
2315
  catch: classifyError("BatchGetItem"),
2183
2316
  }),
2184
2317
  batchWriteItem: (input) => Effect.tryPromise({
2185
- try: () => client.send(new BatchWriteItemCommand(input)),
2318
+ try: (signal) => client.send(new BatchWriteItemCommand(input), { abortSignal: signal }),
2186
2319
  catch: classifyError("BatchWriteItem"),
2187
2320
  }),
2188
2321
  transactGetItems: (input) => Effect.tryPromise({
2189
- try: () => client.send(new TransactGetItemsCommand(input)),
2322
+ try: (signal) => client.send(new TransactGetItemsCommand(input), { abortSignal: signal }),
2190
2323
  catch: classifyError("TransactGetItems"),
2191
2324
  }),
2192
2325
  transactWriteItems: (input) => Effect.tryPromise({
2193
- try: () => client.send(new TransactWriteItemsCommand(input)),
2326
+ try: (signal) => client.send(new TransactWriteItemsCommand(input), { abortSignal: signal }),
2194
2327
  catch: classifyError("TransactWriteItems"),
2195
2328
  }),
2196
2329
  // --- Table management ---
2197
2330
  updateTable: (input) => Effect.tryPromise({
2198
- try: () => client.send(new UpdateTableCommand(input)),
2331
+ try: (signal) => client.send(new UpdateTableCommand(input), { abortSignal: signal }),
2199
2332
  catch: classifyError("UpdateTable"),
2200
2333
  }),
2201
2334
  listTables: (input) => Effect.tryPromise({
2202
- try: () => client.send(new ListTablesCommand(input)),
2335
+ try: (signal) => client.send(new ListTablesCommand(input), { abortSignal: signal }),
2203
2336
  catch: classifyError("ListTables"),
2204
2337
  }),
2205
2338
  // --- Backup ---
2206
2339
  createBackup: (input) => Effect.tryPromise({
2207
- try: () => client.send(new CreateBackupCommand(input)),
2340
+ try: (signal) => client.send(new CreateBackupCommand(input), { abortSignal: signal }),
2208
2341
  catch: classifyError("CreateBackup"),
2209
2342
  }),
2210
2343
  deleteBackup: (input) => Effect.tryPromise({
2211
- try: () => client.send(new DeleteBackupCommand(input)),
2344
+ try: (signal) => client.send(new DeleteBackupCommand(input), { abortSignal: signal }),
2212
2345
  catch: classifyError("DeleteBackup"),
2213
2346
  }),
2214
2347
  listBackups: (input) => Effect.tryPromise({
2215
- try: () => client.send(new ListBackupsCommand(input)),
2348
+ try: (signal) => client.send(new ListBackupsCommand(input), { abortSignal: signal }),
2216
2349
  catch: classifyError("ListBackups"),
2217
2350
  }),
2218
2351
  restoreTableFromBackup: (input) => Effect.tryPromise({
2219
- try: () => client.send(new RestoreTableFromBackupCommand(input)),
2352
+ try: (signal) => client.send(new RestoreTableFromBackupCommand(input), { abortSignal: signal }),
2220
2353
  catch: classifyError("RestoreTableFromBackup"),
2221
2354
  }),
2222
2355
  // --- PITR ---
2223
2356
  describeContinuousBackups: (input) => Effect.tryPromise({
2224
- try: () => client.send(new DescribeContinuousBackupsCommand(input)),
2357
+ try: (signal) => client.send(new DescribeContinuousBackupsCommand(input), { abortSignal: signal }),
2225
2358
  catch: classifyError("DescribeContinuousBackups"),
2226
2359
  }),
2227
2360
  updateContinuousBackups: (input) => Effect.tryPromise({
2228
- try: () => client.send(new UpdateContinuousBackupsCommand(input)),
2361
+ try: (signal) => client.send(new UpdateContinuousBackupsCommand(input), { abortSignal: signal }),
2229
2362
  catch: classifyError("UpdateContinuousBackups"),
2230
2363
  }),
2231
2364
  restoreTableToPointInTime: (input) => Effect.tryPromise({
2232
- try: () => client.send(new RestoreTableToPointInTimeCommand(input)),
2365
+ try: (signal) => client.send(new RestoreTableToPointInTimeCommand(input), { abortSignal: signal }),
2233
2366
  catch: classifyError("RestoreTableToPointInTime"),
2234
2367
  }),
2235
2368
  // --- Export ---
2236
2369
  exportTableToPointInTime: (input) => Effect.tryPromise({
2237
- try: () => client.send(new ExportTableToPointInTimeCommand(input)),
2370
+ try: (signal) => client.send(new ExportTableToPointInTimeCommand(input), { abortSignal: signal }),
2238
2371
  catch: classifyError("ExportTableToPointInTime"),
2239
2372
  }),
2240
2373
  describeExport: (input) => Effect.tryPromise({
2241
- try: () => client.send(new DescribeExportCommand(input)),
2374
+ try: (signal) => client.send(new DescribeExportCommand(input), { abortSignal: signal }),
2242
2375
  catch: classifyError("DescribeExport"),
2243
2376
  }),
2244
2377
  // --- TTL ---
2245
2378
  updateTimeToLive: (input) => Effect.tryPromise({
2246
- try: () => client.send(new UpdateTimeToLiveCommand(input)),
2379
+ try: (signal) => client.send(new UpdateTimeToLiveCommand(input), { abortSignal: signal }),
2247
2380
  catch: classifyError("UpdateTimeToLive"),
2248
2381
  }),
2249
2382
  describeTimeToLive: (input) => Effect.tryPromise({
2250
- try: () => client.send(new DescribeTimeToLiveCommand(input)),
2383
+ try: (signal) => client.send(new DescribeTimeToLiveCommand(input), { abortSignal: signal }),
2251
2384
  catch: classifyError("DescribeTimeToLive"),
2252
2385
  }),
2253
2386
  // --- Tags ---
2254
2387
  tagResource: (input) => Effect.tryPromise({
2255
- try: () => client.send(new TagResourceCommand(input)),
2388
+ try: (signal) => client.send(new TagResourceCommand(input), { abortSignal: signal }),
2256
2389
  catch: classifyError("TagResource"),
2257
2390
  }),
2258
2391
  untagResource: (input) => Effect.tryPromise({
2259
- try: () => client.send(new UntagResourceCommand(input)),
2392
+ try: (signal) => client.send(new UntagResourceCommand(input), { abortSignal: signal }),
2260
2393
  catch: classifyError("UntagResource"),
2261
2394
  }),
2262
2395
  listTagsOfResource: (input) => Effect.tryPromise({
2263
- try: () => client.send(new ListTagsOfResourceCommand(input)),
2396
+ try: (signal) => client.send(new ListTagsOfResourceCommand(input), { abortSignal: signal }),
2264
2397
  catch: classifyError("ListTagsOfResource"),
2265
2398
  }),
2266
2399
  };