effect-dynamodb 1.43.0 → 1.45.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 (64) hide show
  1. package/dist/Aggregate.d.ts +88 -13
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +613 -280
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/Batch.js +3 -0
  6. package/dist/Batch.js.map +1 -1
  7. package/dist/BlobGc.d.ts +2 -2
  8. package/dist/BlobGc.d.ts.map +1 -1
  9. package/dist/Collection.d.ts.map +1 -1
  10. package/dist/Collection.js +75 -16
  11. package/dist/Collection.js.map +1 -1
  12. package/dist/DynamoClient.d.ts +1 -1
  13. package/dist/DynamoClient.d.ts.map +1 -1
  14. package/dist/DynamoClient.js +59 -4
  15. package/dist/DynamoClient.js.map +1 -1
  16. package/dist/Entity.d.ts +23 -4
  17. package/dist/Entity.d.ts.map +1 -1
  18. package/dist/Entity.js +493 -220
  19. package/dist/Entity.js.map +1 -1
  20. package/dist/Query.d.ts +33 -1
  21. package/dist/Query.d.ts.map +1 -1
  22. package/dist/Query.js +70 -8
  23. package/dist/Query.js.map +1 -1
  24. package/dist/Table.d.ts.map +1 -1
  25. package/dist/Table.js +4 -1
  26. package/dist/Table.js.map +1 -1
  27. package/dist/Transaction.js +2 -1
  28. package/dist/Transaction.js.map +1 -1
  29. package/dist/index.d.ts +2 -1
  30. package/dist/index.d.ts.map +1 -1
  31. package/dist/index.js +1 -0
  32. package/dist/index.js.map +1 -1
  33. package/dist/internal/AggregateWrite.d.ts +130 -0
  34. package/dist/internal/AggregateWrite.d.ts.map +1 -0
  35. package/dist/internal/AggregateWrite.js +341 -0
  36. package/dist/internal/AggregateWrite.js.map +1 -0
  37. package/dist/internal/EntityOps.d.ts.map +1 -1
  38. package/dist/internal/EntityOps.js +38 -9
  39. package/dist/internal/EntityOps.js.map +1 -1
  40. package/dist/internal/ExpressionLimits.d.ts +22 -3
  41. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  42. package/dist/internal/ExpressionLimits.js +46 -7
  43. package/dist/internal/ExpressionLimits.js.map +1 -1
  44. package/dist/internal/ItemSize.d.ts +7 -1
  45. package/dist/internal/ItemSize.d.ts.map +1 -1
  46. package/dist/internal/ItemSize.js +13 -5
  47. package/dist/internal/ItemSize.js.map +1 -1
  48. package/dist/internal/ProjectionEngine.d.ts +5 -0
  49. package/dist/internal/ProjectionEngine.d.ts.map +1 -1
  50. package/dist/internal/ProjectionEngine.js +28 -20
  51. package/dist/internal/ProjectionEngine.js.map +1 -1
  52. package/dist/internal/TransactPlan.d.ts +18 -1
  53. package/dist/internal/TransactPlan.d.ts.map +1 -1
  54. package/dist/internal/TransactPlan.js +45 -7
  55. package/dist/internal/TransactPlan.js.map +1 -1
  56. package/dist/internal/TransactWriteOps.d.ts +1 -1
  57. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  58. package/dist/internal/TransactWriteOps.js +159 -130
  59. package/dist/internal/TransactWriteOps.js.map +1 -1
  60. package/dist/internal/TransactableOps.d.ts +3 -3
  61. package/dist/internal/TransactableOps.d.ts.map +1 -1
  62. package/dist/internal/TransactableOps.js +14 -3
  63. package/dist/internal/TransactableOps.js.map +1 -1
  64. package/package.json +2 -2
package/dist/Entity.js CHANGED
@@ -31,7 +31,7 @@ import { givenZoneReading, staleZonesOf, } from "@effect-dynamodb/schema/interna
31
31
  import * as KeyComposer from "@effect-dynamodb/schema/KeyComposer.js";
32
32
  import { normalizeGsiConfig } from "@effect-dynamodb/schema/KeyComposer.js";
33
33
  import { deriveSourceText } from "@effect-dynamodb/schema/VectorIndex.js";
34
- import { Cause, Clock, Context, Data, DateTime, Effect, Equal, Exit, Option, Schema, SchemaAST, SchemaIssue, Stream, } from "effect";
34
+ import { Cause, Clock, Context, Data, DateTime, Effect, Equal, Exit, Option, Result, Schema, SchemaAST, SchemaIssue, Stream, } from "effect";
35
35
  import { SecureRandom } from "effect/crypto";
36
36
  import { BlobStore } from "./BlobStore.js";
37
37
  import { attributeValueEquals } from "./internal/AttributeValueEquals.js";
@@ -60,7 +60,7 @@ import { KEY_MAX, KEY_TOP, keyJustBelow } from "./internal/RangePlanner.js";
60
60
  import * as Rekey from "./internal/Rekey.js";
61
61
  import { asRead, notReadBack, readBackOf, readBackRefusal, } from "./internal/RoundTrip.js";
62
62
  import { andRaw, capturedServices, composeKeysOrFail, freshIncarnationToken, generateTimestampPrimitive, hasProjectionTombstones, INCARNATION_TOKEN, isProjectionTombstone, KEY_TEXT, marshalOrFail, OUTBOX_CLAIM, OUTBOX_CLAIMED_UNTIL, OUTBOX_ROW_PK, OUTBOX_ROW_SK, overTombstone, UNSENTINELED_DEFAULTS, } from "./internal/TransactableOps.js";
63
- import { planWrite } from "./internal/TransactPlan.js";
63
+ import { conditionCheckItem, planWrite } from "./internal/TransactPlan.js";
64
64
  import { batchEntries, diagnosedValidationError, diagnoseFailure, isItemSizeRejection, keyAttributesOf, storedTypeName, targetsFor, transactItemTarget, withCause, } from "./internal/WriteDiagnosis.js";
65
65
  import { decodeSparseFields, encodeSparseFields, fromAttributeMap, fromAttributeValue, hasNoStoredForm, isEmptySet, protoEntryAt, toAttributeMap, toAttributeValue, UnstorableValue, unstorableIn, } from "./Marshaller.js";
66
66
  import * as Query from "./Query.js";
@@ -1728,6 +1728,15 @@ const makeImpl = (config, precomputedData) => {
1728
1728
  }
1729
1729
  return ownSchemaFor.own;
1730
1730
  };
1731
+ /**
1732
+ * `[EDD-9181]` when an index declared `shards: { layouts: "provided" }` has no table in the
1733
+ * context this operation runs in (#287): checked as a write starts, so nothing is sent, whether
1734
+ * or not the write would compose that index. A bound operation runs in its binding's context,
1735
+ * which `DynamoClient.make` checked. Nothing to check, and nothing read, for an entity with no
1736
+ * provided index.
1737
+ */
1738
+ const providedShards = KeyComposer.hasProvidedShards(data.initialIndexes);
1739
+ const requireShardTables = (where) => KeyComposer.requireShardTables(where, schema, entityType, data.initialIndexes);
1731
1740
  /** {@link ownSchema} for an update: the composites its `payload` gives are its own. */
1732
1741
  const ownPayload = (payload) => ownSchema((site) => site.attr !== undefined && site.attr in payload);
1733
1742
  /**
@@ -4856,6 +4865,25 @@ const makeImpl = (config, precomputedData) => {
4856
4865
  };
4857
4866
  /** The item at a key, strongly consistent: the read a read-then-write op starts with. */
4858
4867
  const readCurrent = (tableName, marshalledKey) => Effect.flatMap(Capacity.client, (client) => client.getItem({ TableName: tableName, Key: marshalledKey, ConsistentRead: true }));
4868
+ /**
4869
+ * The row an update finds at its key: `undefined` for none, and for a projection tombstone
4870
+ * (#154), a removed row that every read by key reports as absent. An update of it is an update
4871
+ * of a missing row, by every path (#132).
4872
+ */
4873
+ const liveRow = (row) => row !== undefined && isProjectionTombstone(row, entityType) ? undefined : row;
4874
+ /**
4875
+ * The condition that the row an update writes exists, under `pkName`: `attribute_exists` of its
4876
+ * partition key, and, on a read model whose rows may be projection tombstones, that it isn't one
4877
+ * (#132). The term is free when it holds, and every other entity sends what it did.
4878
+ */
4879
+ const rowExists = (names, values, pkName) => {
4880
+ names[pkName] = config.indexes.primary.pk.field;
4881
+ if (!hasProjectionTombstones(self))
4882
+ return `attribute_exists(${pkName})`;
4883
+ names["#eddLive"] = "__edd_e__";
4884
+ values[":eddTomb"] = { S: `${entityType}#tombstone` };
4885
+ return `attribute_exists(${pkName}) AND #eddLive <> :eddTomb`;
4886
+ };
4859
4887
  /** Fill a `ConcurrentModification`'s `current` with the stored item, decoded. */
4860
4888
  const withCurrentItem = (effect, stored) => effect.pipe(Effect.catchIf((e) => e instanceof ConcurrentModification, (e) => Effect.gen(function* () {
4861
4889
  const item = stored();
@@ -6219,6 +6247,8 @@ const makeImpl = (config, precomputedData) => {
6219
6247
  keyFields,
6220
6248
  refAttribute: refSet.attribute,
6221
6249
  refData: refSet.value,
6250
+ heldAttribute: gsiPkField,
6251
+ heldValue: { S: gsiPkValue },
6222
6252
  });
6223
6253
  }
6224
6254
  exclusiveStartKey = queryResult.LastEvaluatedKey;
@@ -6227,58 +6257,88 @@ const makeImpl = (config, precomputedData) => {
6227
6257
  }
6228
6258
  if (allUpdateOps.length === 0)
6229
6259
  return;
6260
+ /**
6261
+ * A target's update: its ref SET, conditioned on the target still naming the source (#132).
6262
+ * The index the targets were found through is eventually consistent, so a target deleted or
6263
+ * pointed at another source since may still be listed: unconditioned, the update would
6264
+ * create a key-only item at a deleted target's key (one no read decodes, blocking a later
6265
+ * `create` there), or write this source's data into a target that no longer names it.
6266
+ * Refused, the target is no longer this source's, and is skipped.
6267
+ */
6268
+ const cascadeUpdate = (op) => ({
6269
+ TableName: op.tableName,
6270
+ Key: op.key,
6271
+ UpdateExpression: "SET #ref = :refData",
6272
+ ConditionExpression: "#held = :held",
6273
+ ExpressionAttributeNames: { "#ref": op.refAttribute, "#held": op.heldAttribute },
6274
+ ExpressionAttributeValues: { ":refData": op.refData, ":held": op.heldValue },
6275
+ });
6230
6276
  if (mode === "transactional") {
6231
6277
  // Transactional mode — one atomic transaction. DynamoDB's limits (100
6232
6278
  // items, 4 MB, item size, sort keys) are not pre-checked (#144): a
6233
6279
  // rejection is diagnosed and reported as a cascade that wrote nothing.
6234
- const cascadeItems = allUpdateOps.map((op) => ({
6235
- Update: {
6236
- TableName: op.tableName,
6237
- Key: op.key,
6238
- UpdateExpression: "SET #ref = :refData",
6239
- ExpressionAttributeNames: { "#ref": op.refAttribute },
6240
- ExpressionAttributeValues: { ":refData": op.refData },
6241
- },
6242
- }));
6243
- yield* client.transactWriteItems({ TransactItems: [...cascadeItems] }).pipe(diagnoseFailure({
6244
- sent: () => ({
6245
- _tag: "Transaction",
6246
- items: cascadeItems,
6247
- targets: () => cascadeItems.map((item, index) => {
6248
- const op = allUpdateOps[index];
6249
- return transactItemTarget(item, op.tableName, op.keyFields, op.entityType, `the cascade update of ${op.entityType} (item ${index})`);
6250
- }),
6251
- }),
6252
- keys: () => ({
6253
- partition: [...new Set(allUpdateOps.map((op) => op.keyFields[0]))],
6254
- sort: [...new Set(allUpdateOps.map((op) => op.keyFields[1]))],
6255
- }),
6256
- rewrite: (diagnosis, original) => new CascadePartialFailure({
6257
- sourceEntity: sourceEntityType,
6258
- sourceId: sourceIdValue,
6259
- succeeded: 0,
6260
- failed: allUpdateOps.length,
6261
- errors: [
6262
- diagnosedValidationError(diagnosis, original, {
6263
- operation: "cascade",
6264
- entityType: sourceEntityType,
6280
+ // A target refused by its condition (#132) left the source since the query: it is
6281
+ // dropped, and the rest sent again, up to `GUARDED_PUT_ATTEMPTS` sends in all.
6282
+ let pending = allUpdateOps;
6283
+ for (let send = 1; pending.length > 0; send++) {
6284
+ const sentOps = pending;
6285
+ const cascadeItems = sentOps.map((op) => ({
6286
+ Update: cascadeUpdate(op),
6287
+ }));
6288
+ const sent = yield* Effect.result(client.transactWriteItems({ TransactItems: [...cascadeItems] }).pipe(diagnoseFailure({
6289
+ sent: () => ({
6290
+ _tag: "Transaction",
6291
+ items: cascadeItems,
6292
+ targets: () => cascadeItems.map((item, index) => {
6293
+ const op = sentOps[index];
6294
+ return transactItemTarget(item, op.tableName, op.keyFields, op.entityType, `the cascade update of ${op.entityType} (item ${index})`);
6265
6295
  }),
6266
- ],
6267
- }),
6268
- }));
6296
+ }),
6297
+ keys: () => ({
6298
+ partition: [...new Set(sentOps.map((op) => op.keyFields[0]))],
6299
+ sort: [...new Set(sentOps.map((op) => op.keyFields[1]))],
6300
+ }),
6301
+ rewrite: (diagnosis, original) => new CascadePartialFailure({
6302
+ sourceEntity: sourceEntityType,
6303
+ sourceId: sourceIdValue,
6304
+ succeeded: 0,
6305
+ failed: sentOps.length,
6306
+ errors: [
6307
+ diagnosedValidationError(diagnosis, original, {
6308
+ operation: "cascade",
6309
+ entityType: sourceEntityType,
6310
+ }),
6311
+ ],
6312
+ }),
6313
+ })));
6314
+ if (Result.isSuccess(sent))
6315
+ return;
6316
+ const error = sent.failure;
6317
+ const reasons = error._tag === "CascadePartialFailure" || !isAwsTransactionCancelled(error.cause)
6318
+ ? undefined
6319
+ : error.cause.CancellationReasons;
6320
+ const refused = new Set((reasons ?? []).flatMap((reason, index) => reason?.Code === "ConditionalCheckFailed" ? [index] : []));
6321
+ // Cancelled for another reason, or once the sends run out: a cascade that wrote nothing.
6322
+ if (refused.size === 0)
6323
+ return yield* error;
6324
+ pending = sentOps.filter((_, index) => !refused.has(index));
6325
+ if (send >= GUARDED_PUT_ATTEMPTS && pending.length > 0) {
6326
+ return yield* new CascadePartialFailure({
6327
+ sourceEntity: sourceEntityType,
6328
+ sourceId: sourceIdValue,
6329
+ succeeded: 0,
6330
+ failed: pending.length,
6331
+ errors: [error],
6332
+ });
6333
+ }
6334
+ }
6269
6335
  }
6270
6336
  else {
6271
6337
  // Eventual mode — concurrent updates with partial failure tracking
6272
6338
  let succeeded = 0;
6273
6339
  const errors = [];
6274
6340
  const updateEffects = allUpdateOps.map((op) => {
6275
- const update = {
6276
- TableName: op.tableName,
6277
- Key: op.key,
6278
- UpdateExpression: "SET #ref = :refData",
6279
- ExpressionAttributeNames: { "#ref": op.refAttribute },
6280
- ExpressionAttributeValues: { ":refData": op.refData },
6281
- };
6341
+ const update = cascadeUpdate(op);
6282
6342
  return client.updateItem(update).pipe(
6283
6343
  // An item the cascade grows past 400 KB is named in `errors`.
6284
6344
  diagnoseFailure({
@@ -6294,7 +6354,10 @@ const makeImpl = (config, precomputedData) => {
6294
6354
  }),
6295
6355
  }), Effect.tap(() => Effect.sync(() => {
6296
6356
  succeeded++;
6297
- })), Effect.catch((err) => Effect.sync(() => {
6357
+ })),
6358
+ // Refused (#132): the target was deleted, or no longer names this source, since the
6359
+ // query found it. It isn't this source's: skipped, neither succeeded nor failed.
6360
+ Effect.catchIf((err) => err._tag !== "ValidationError" && isAwsConditionalCheckFailed(err.cause), () => Effect.void), Effect.catch((err) => Effect.sync(() => {
6298
6361
  errors.push(err);
6299
6362
  })));
6300
6363
  });
@@ -7070,7 +7133,7 @@ const makeImpl = (config, precomputedData) => {
7070
7133
  return checked;
7071
7134
  });
7072
7135
  /** An update from what {@link prepareUpdate} decided: its reads and its write. */
7073
- const runPreparedUpdate = (key, prepared, mode,
7136
+ const runPreparedUpdate = (prepared, mode,
7074
7137
  /**
7075
7138
  * The item as already read — consistently — by the caller (`upsert`, a transaction's plan).
7076
7139
  * Used instead of reading it again: the write is guarded on it either way. An update that
@@ -7104,7 +7167,7 @@ const makeImpl = (config, precomputedData) => {
7104
7167
  // --- Retain path: read-then-transact ---
7105
7168
  // Read current item (needed to create snapshot of pre-update state)
7106
7169
  const currentResult = preRead !== undefined ? { Item: preRead } : yield* readCurrent(tableName, marshalledKey);
7107
- if (!currentResult.Item) {
7170
+ if (!currentResult.Item || isProjectionTombstone(currentResult.Item, entityType)) {
7108
7171
  return yield* missingItem();
7109
7172
  }
7110
7173
  const currentRaw = fromAttributeMap(currentResult.Item);
@@ -7851,7 +7914,7 @@ const makeImpl = (config, precomputedData) => {
7851
7914
  let casRead;
7852
7915
  if (isRetainEnabled() || needsBothImages) {
7853
7916
  const current = yield* readCurrent(tableName, marshalledKey);
7854
- if (!current.Item) {
7917
+ if (!current.Item || isProjectionTombstone(current.Item, entityType)) {
7855
7918
  return yield* missingItem();
7856
7919
  }
7857
7920
  yield* checkVersion(current.Item, "update");
@@ -7928,7 +7991,7 @@ const makeImpl = (config, precomputedData) => {
7928
7991
  if (plainWrite &&
7929
7992
  immutables.some((asserted) => asserted.packed || asserted.offloaded !== undefined)) {
7930
7993
  const stored = yield* readCurrent(tableName, marshalledKey);
7931
- if (stored.Item === undefined) {
7994
+ if (!stored.Item || isProjectionTombstone(stored.Item, entityType)) {
7932
7995
  return yield* createsOnMissing
7933
7996
  ? new MissingForCreate({ input: createInput() })
7934
7997
  : missingItem();
@@ -8531,16 +8594,32 @@ const makeImpl = (config, precomputedData) => {
8531
8594
  addClauses.length > 0 ||
8532
8595
  deleteClauses.length > 0;
8533
8596
  const rv = uState.returnValues ?? "allNew";
8534
- if (!hasAnyUpdate) {
8535
- // Nothing to update: nothing written, so nothing "updated"; the
8536
- // whole-item modes are the current item.
8597
+ // Nothing to update (#132): nothing is written, but the op still establishes what its write
8598
+ // would have: the row exists (`ItemNotFound`, `patch`'s `ConditionalCheckFailed`), and its
8599
+ // condition holds. Existence alone is read, consistently, in every return mode; a condition
8600
+ // is sent in the update's own request with no `UpdateExpression`, which changes nothing. In a
8601
+ // transaction's plan the read is held to the commit by a `ConditionCheck` (`planned`), and
8602
+ // the request is recorded as one (`planWrite`).
8603
+ const noOp = !hasAnyUpdate;
8604
+ /**
8605
+ * A no-op's result: nothing "updated"; the whole-item modes, the row. `row`: the row it read,
8606
+ * or its request returned; `"held"`, its request's condition proved the row there and it
8607
+ * asked for nothing back.
8608
+ */
8609
+ const noOpResult = (row) => Effect.gen(function* () {
8610
+ if (row === undefined || (row !== "held" && liveRow(row) === undefined)) {
8611
+ return yield* missingItem();
8612
+ }
8537
8613
  if (rv === "none")
8538
8614
  return undefined;
8539
8615
  if (rv === "updatedOld" || rv === "updatedNew") {
8540
8616
  return yield* decodePartial(undefined, new Set(), mode);
8541
8617
  }
8542
- return yield* get(key)._run(mode);
8543
- }
8618
+ // A whole-item mode always asks its request for the row.
8619
+ if (row === "held")
8620
+ return yield* Effect.die(new Error("a no-op returned no row"));
8621
+ return yield* decodeAs(fromAttributeMap(row), row, mode);
8622
+ });
8544
8623
  // Compose UpdateExpression from all clause types
8545
8624
  const expressionParts = [];
8546
8625
  if (setClauses.length > 0)
@@ -8554,6 +8633,8 @@ const makeImpl = (config, precomputedData) => {
8554
8633
  const updateExpression = expressionParts.join(" ");
8555
8634
  // Build condition expression — combine optimistic lock + user condition
8556
8635
  const condParts = [];
8636
+ /** How many of `condParts` restate an immutable value (`#immN = :immN`). */
8637
+ let immutableTerms = 0;
8557
8638
  if (evExpected !== undefined && systemFields.version) {
8558
8639
  condParts.push(versionIs(evExpected, names, values, "#condVer", ":expectedVer"));
8559
8640
  }
@@ -8581,9 +8662,9 @@ const makeImpl = (config, precomputedData) => {
8581
8662
  names[`#imm${i}`] = attr;
8582
8663
  values[`:imm${i}`] = value;
8583
8664
  condParts.push(`#imm${i} = :imm${i}`);
8665
+ immutableTerms++;
8584
8666
  }
8585
- names["#exists"] = config.indexes.primary.pk.field;
8586
- condParts.push("attribute_exists(#exists)");
8667
+ condParts.push(rowExists(names, values, "#exists"));
8587
8668
  // A `pathIfNotExists` operand a check refuses is written only where its path is absent:
8588
8669
  // the write requires the path, and a refusal returning an item without it is that
8589
8670
  // operand's (`fallbackRefusal`, #236). None: the request is as it was.
@@ -8599,6 +8680,27 @@ const makeImpl = (config, precomputedData) => {
8599
8680
  if (incarnation !== undefined)
8600
8681
  condParts.push(incarnation);
8601
8682
  }
8683
+ if (noOp) {
8684
+ // Required in a no-op's request whatever else it asserts: an `UpdateItem` with no
8685
+ // `UpdateExpression` creates a key-only item at a missing key.
8686
+ if (!plainWrite)
8687
+ condParts.push(rowExists(names, values, "#exists"));
8688
+ // Asserting nothing but existence, and restated immutable values: the row is read (or
8689
+ // was), consistently, and the values are compared with it, as the refusal of the same
8690
+ // update with a payload compares them (`immutableMismatch`).
8691
+ if (condParts.length === 1 + immutableTerms) {
8692
+ const row = liveRow(held ?? (yield* readCurrent(tableName, marshalledKey)).Item);
8693
+ const immutableChange = row !== undefined ? immutableMismatch(immutables, row) : undefined;
8694
+ if (immutableChange !== undefined) {
8695
+ return yield* new ValidationError({
8696
+ entityType,
8697
+ operation: "update",
8698
+ cause: immutableChange,
8699
+ });
8700
+ }
8701
+ return yield* noOpResult(row);
8702
+ }
8703
+ }
8602
8704
  // Sent as built: a condition over DynamoDB's expression limits is
8603
8705
  // DynamoDB's to reject, and is diagnosed naming the caller's part (#144).
8604
8706
  const conditionExpression = condParts.length > 0 ? condParts.join(" AND ") : undefined;
@@ -8711,18 +8813,23 @@ const makeImpl = (config, precomputedData) => {
8711
8813
  // The image the mode returns; `none` asks for nothing unless a
8712
8814
  // cascade needs the new item.
8713
8815
  const wantsOld = casRead === undefined && (rv === "allOld" || rv === "updatedOld");
8714
- const returned = wantsOld
8715
- ? "ALL_OLD"
8716
- : rv === "none" && !uState.cascade && casRead === undefined
8717
- ? "NONE"
8718
- : "ALL_NEW";
8816
+ const returned = noOp
8817
+ ? // A no-op's item, unchanged: returned only to the whole-item modes, and never cascaded.
8818
+ rv === "allNew" || rv === "allOld"
8819
+ ? "ALL_NEW"
8820
+ : "NONE"
8821
+ : wantsOld
8822
+ ? "ALL_OLD"
8823
+ : rv === "none" && !uState.cascade && casRead === undefined
8824
+ ? "NONE"
8825
+ : "ALL_NEW";
8719
8826
  // DynamoDB rejects an empty `ExpressionAttributeValues` map. When
8720
8827
  // the UpdateExpression is REMOVE-only (e.g. clearMap with no other
8721
8828
  // combinators), `values` may be empty — omit the property entirely.
8722
8829
  const updateInput = {
8723
8830
  TableName: tableName,
8724
8831
  Key: marshalledKey,
8725
- UpdateExpression: updateExpression,
8832
+ ...(!noOp && { UpdateExpression: updateExpression }),
8726
8833
  ExpressionAttributeNames: names,
8727
8834
  ExpressionAttributeValues: Object.keys(values).length > 0 ? values : undefined,
8728
8835
  ConditionExpression: conditionExpression,
@@ -8736,9 +8843,10 @@ const makeImpl = (config, precomputedData) => {
8736
8843
  // item (it must exist), a restated immutable value, the
8737
8844
  // version CAS, or the user's condition.
8738
8845
  if (isAwsConditionalCheckFailed(err.cause)) {
8739
- const stored = err.cause.Item;
8846
+ const stored = liveRow(err.cause.Item);
8740
8847
  if (stored === undefined && !uState.patch) {
8741
- return createsOnMissing
8848
+ // A no-op never creates: its payload names nothing to create from.
8849
+ return createsOnMissing && !noOp
8742
8850
  ? new MissingForCreate({ input: createInput() })
8743
8851
  : new ItemNotFound({ entityType, key: encodedKey });
8744
8852
  }
@@ -8780,6 +8888,10 @@ const makeImpl = (config, precomputedData) => {
8780
8888
  !pathOpsPresent &&
8781
8889
  !forceReadMerge &&
8782
8890
  isItemSizeRejection(err), () => Effect.fail(new OffloadSizeRetry())), diagnoseItemWrite("update", { Update: updateInput }, () => uc?.expression));
8891
+ // The no-op's condition held: nothing changed, so nothing cascades.
8892
+ if (noOp) {
8893
+ return yield* noOpResult(returned === "NONE" ? "held" : result.Attributes);
8894
+ }
8783
8895
  // A cascade never meets an old-image mode here: that combination is
8784
8896
  // routed to the read-then-write branch, or read first (`casRead`).
8785
8897
  const newImage = wantsOld ? undefined : result.Attributes;
@@ -8791,7 +8903,7 @@ const makeImpl = (config, precomputedData) => {
8791
8903
  /** See {@link runPreparedUpdate}. */
8792
8904
  preRead,
8793
8905
  /** See {@link runPreparedUpdate}. */
8794
- forceReadMerge = false) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(key, prepared, mode, preRead, forceReadMerge));
8906
+ forceReadMerge = false) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(prepared, mode, preRead, forceReadMerge));
8795
8907
  /**
8796
8908
  * {@link runUpdate}, re-run once on the read-merge branch when its standard
8797
8909
  * `UpdateItem` was rejected for item size under an item budget (#179,
@@ -8815,7 +8927,7 @@ const makeImpl = (config, precomputedData) => {
8815
8927
  held) => {
8816
8928
  const once = () => prepared === undefined
8817
8929
  ? runUpdateSized(key, mode, requested, held)
8818
- : sizedUpdate((force) => runPreparedUpdate(key, prepared, mode, held, force));
8930
+ : sizedUpdate((force) => runPreparedUpdate(prepared, mode, held, force));
8819
8931
  // A form race (#238): the row's renamed sparse map changed form between the update's read and
8820
8932
  // its write. Read again and written again, as a guarded put is; once every attempt raced, the
8821
8933
  // race is reported naming the map. A row handed in (a transaction's plan) is never re-read here:
@@ -8885,7 +8997,8 @@ const makeImpl = (config, precomputedData) => {
8885
8997
  Key: ownKey,
8886
8998
  ConsistentRead: true,
8887
8999
  });
8888
- if (read.Item === undefined) {
9000
+ // A projection tombstone is a removed row: missing, as every read by key reports it.
9001
+ if (read.Item === undefined || isProjectionTombstone(read.Item, entityType)) {
8889
9002
  ;
8890
9003
  ({ items, ownRow } = yield* plan({ rowMissing: true }));
8891
9004
  }
@@ -8919,6 +9032,26 @@ const makeImpl = (config, precomputedData) => {
8919
9032
  }
8920
9033
  const pkField = config.indexes.primary.pk.field;
8921
9034
  const skField = config.indexes.primary.sk.field;
9035
+ // An update with nothing to set writes nothing, and found its row with a consistent read
9036
+ // (#132). Standalone, that read IS the op's answer; in a transaction, the row could be
9037
+ // deleted before the commit, so the read is held to it: a `ConditionCheck` that the row
9038
+ // still exists, judged below as the op's main item (a refusal is a lost race, planned again,
9039
+ // which then finds the row missing). A no-op that asserts a condition recorded its own check.
9040
+ if (items.length === 0 && ownRow !== undefined) {
9041
+ const { name: tableName } = yield* tableTag;
9042
+ const names = {};
9043
+ const values = {};
9044
+ items = [
9045
+ conditionCheckItem({
9046
+ TableName: tableName,
9047
+ Key: ownKey,
9048
+ ConditionExpression: rowExists(names, values, "#pk"),
9049
+ ExpressionAttributeNames: names,
9050
+ ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9051
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9052
+ }),
9053
+ ];
9054
+ }
8922
9055
  const isOwn = (row) => {
8923
9056
  if (row === undefined)
8924
9057
  return false;
@@ -8944,7 +9077,10 @@ const makeImpl = (config, precomputedData) => {
8944
9077
  const sentinelPrefix = `${entityType}._unique.`;
8945
9078
  const versionPrefix = DynamoSchema.composeVersionKeyPrefix(schema, entityType);
8946
9079
  const roles = items.map((item) => {
8947
- if (isOwn(item.Put?.Item) || isOwn(item.Update?.Key) || isOwn(item.Delete?.Key)) {
9080
+ if (isOwn(item.Put?.Item) ||
9081
+ isOwn(item.Update?.Key) ||
9082
+ isOwn(item.Delete?.Key) ||
9083
+ isOwn(item.ConditionCheck?.Key)) {
8948
9084
  return { _tag: "main" };
8949
9085
  }
8950
9086
  // A retain snapshot: in the row's partition, at a version key.
@@ -8990,7 +9126,7 @@ const makeImpl = (config, precomputedData) => {
8990
9126
  // every write carrying it asks (`internal/FormGuard.ts`, #238); its
8991
9127
  // attribute is no input of the rest.
8992
9128
  const mainItem = items[roles.findIndex((role) => role._tag === "main")];
8993
- const guarded = mainItem?.Update ?? mainItem?.Put ?? mainItem?.Delete;
9129
+ const guarded = mainItem?.Update ?? mainItem?.Put ?? mainItem?.Delete ?? mainItem?.ConditionCheck;
8994
9130
  const conditionAttrs = [
8995
9131
  ...new Set((guarded?.ConditionExpression?.match(/#[A-Za-z0-9_]+/g) ?? []).flatMap((token) => {
8996
9132
  const attr = guarded?.ExpressionAttributeNames?.[token];
@@ -9052,12 +9188,12 @@ const makeImpl = (config, precomputedData) => {
9052
9188
  return ownRow === undefined
9053
9189
  ? lostRace(undefined)
9054
9190
  : { _tag: "Fail", error: historyConflict(role.version, operation) };
9055
- case "main":
9056
- main =
9057
- reason.Item === undefined
9058
- ? "absent"
9059
- : reason.Item;
9191
+ case "main": {
9192
+ // A projection tombstone there is the row removed: absent, as a read reports it.
9193
+ const stored = liveRow(reason.Item);
9194
+ main = stored === undefined ? "absent" : stored;
9060
9195
  break;
9196
+ }
9061
9197
  case "side":
9062
9198
  sideFailed = true;
9063
9199
  }
@@ -9101,11 +9237,100 @@ const makeImpl = (config, precomputedData) => {
9101
9237
  // `.keepRefs()`'s guard is the caller's: a row holding another ref fails it, unchanged.
9102
9238
  callerCondition: uState.condition !== undefined || prepared.kept !== undefined,
9103
9239
  expectedVersion: uState.expectedVersion,
9104
- refuse: (row) => fallbackRefusal(prepared.operands.fallbacks, row),
9240
+ // A restated immutable value the row doesn't hold is refused as standalone refuses it
9241
+ // (`ValidationError`), never sent and retried as a lost race.
9242
+ refuse: (row) => {
9243
+ const immutableChange = immutableMismatch(prepared.immutables, row);
9244
+ return immutableChange !== undefined
9245
+ ? new ValidationError({ entityType, operation: "update", cause: immutableChange })
9246
+ : fallbackRefusal(prepared.operands.fallbacks, row);
9247
+ },
9105
9248
  });
9106
9249
  // ---------------------------------------------------------------------------
9107
9250
  // delete operation
9108
9251
  // ---------------------------------------------------------------------------
9252
+ /**
9253
+ * The parts of the transaction a read-first delete sends (#133), for the item at `primaryKey`:
9254
+ * the main `Delete`'s condition (its guard on the row as read, ANDed with the caller's), the
9255
+ * owned sentinels' releases, and how a cancellation of it reads. `delete` sends them for an
9256
+ * entity with `unique`, retain or soft delete, and `purge` for a unique entity's live row
9257
+ * (#132), so the two can't drift.
9258
+ */
9259
+ const hardDeleteParts = ({ encodedKey, primaryKey, userCondition, }) => {
9260
+ const primary = config.indexes.primary;
9261
+ /** The guard ANDed with the user's condition, for the main Delete. */
9262
+ const guardedDeleteCondition = (guard) => {
9263
+ const values = { ...guard.values, ...userCondition?.values };
9264
+ return {
9265
+ ConditionExpression: userCondition
9266
+ ? `${guard.expression} AND (${userCondition.expression})`
9267
+ : guard.expression,
9268
+ ExpressionAttributeNames: { ...guard.names, ...userCondition?.names },
9269
+ ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9270
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9271
+ };
9272
+ };
9273
+ /**
9274
+ * Run a guarded delete transaction: index 0 is the main Delete, the
9275
+ * only conditioned item, so its rejection is read from the stored
9276
+ * item (ALL_OLD) — gone, raced, or the user's condition.
9277
+ */
9278
+ const guardedDelete = (write, read, inputs, snapshotAt, releases) => {
9279
+ let rejected;
9280
+ const reject = (stored) => {
9281
+ rejected = stored;
9282
+ // Deleted since the read: with nothing asserted, read it again —
9283
+ // a delete of a missing item reports what such a delete does.
9284
+ if (stored === undefined && userCondition === undefined) {
9285
+ return new DeletedConcurrently();
9286
+ }
9287
+ return deleteRejection(encodedKey, read, inputs, stored, userCondition !== undefined);
9288
+ };
9289
+ return withCurrentItem(write.pipe(Effect.mapError((err) => {
9290
+ if (isAwsTransactionCancelled(err.cause)) {
9291
+ const main = err.cause.CancellationReasons?.[0];
9292
+ if (main?.Code === "ConditionalCheckFailed")
9293
+ return reject(main.Item);
9294
+ if (snapshotAt !== undefined &&
9295
+ err.cause.CancellationReasons?.[snapshotAt.index]?.Code === "ConditionalCheckFailed") {
9296
+ return historyConflict(snapshotAt.version, "delete");
9297
+ }
9298
+ for (const { index, constraintName } of releases) {
9299
+ if (err.cause.CancellationReasons?.[index]?.Code === "ConditionalCheckFailed") {
9300
+ return releaseRaced(encodedKey, constraintName);
9301
+ }
9302
+ }
9303
+ }
9304
+ if (isAwsConditionalCheckFailed(err.cause))
9305
+ return reject(err.cause.Item);
9306
+ return err;
9307
+ })), () => rejected);
9308
+ };
9309
+ /**
9310
+ * Append a release for each sentinel the stored item `raw` holds AND
9311
+ * owns (#133) — composed from its domain view, since the stored row is
9312
+ * attribute-keyed and the constraint is not (#127) — returning where
9313
+ * each landed, so a release that lost a race can be reported.
9314
+ */
9315
+ const ownedReleases = (table, raw, into) => Effect.gen(function* () {
9316
+ const rawDomain = toDomainView(raw);
9317
+ const held = [];
9318
+ for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
9319
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain, readSentinelValue);
9320
+ if (!sentinel)
9321
+ continue;
9322
+ held.push({ ...sentinel.key, constraintName });
9323
+ }
9324
+ const owner = { pk: primaryKey[primary.pk.field], sk: primaryKey[primary.sk.field] };
9325
+ const releases = [];
9326
+ for (const sentinel of yield* ownedSentinels(table, held, owner)) {
9327
+ releases.push({ index: into.length, constraintName: sentinel.constraintName });
9328
+ into.push(sentinelRelease(table, sentinel, owner));
9329
+ }
9330
+ return releases;
9331
+ });
9332
+ return { guardedDeleteCondition, guardedDelete, ownedReleases };
9333
+ };
9109
9334
  const del = (key) => new EntityDeleteImpl((opts) => Effect.gen(function* () {
9110
9335
  const client = yield* Capacity.client;
9111
9336
  const tc = yield* tableTag;
@@ -9188,77 +9413,10 @@ const makeImpl = (config, precomputedData) => {
9188
9413
  }
9189
9414
  return err;
9190
9415
  };
9191
- /** The guard ANDed with the user's condition, for the main Delete. */
9192
- const guardedDeleteCondition = (guard) => {
9193
- const values = { ...guard.values, ...userCondition?.values };
9194
- return {
9195
- ConditionExpression: userCondition
9196
- ? `${guard.expression} AND (${userCondition.expression})`
9197
- : guard.expression,
9198
- ExpressionAttributeNames: { ...guard.names, ...userCondition?.names },
9199
- ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9200
- ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9201
- };
9202
- };
9203
- /**
9204
- * Run a guarded delete transaction: index 0 is the main Delete, the
9205
- * only conditioned item, so its rejection is read from the stored
9206
- * item (ALL_OLD) — gone, raced, or the user's condition.
9207
- */
9208
- const guardedDelete = (write, read, inputs, snapshotAt, releases) => {
9209
- let rejected;
9210
- const reject = (stored) => {
9211
- rejected = stored;
9212
- // Deleted since the read: with nothing asserted, read it again —
9213
- // a delete of a missing item reports what such a delete does.
9214
- if (stored === undefined && userCondition === undefined) {
9215
- return new DeletedConcurrently();
9216
- }
9217
- return deleteRejection(encodedKey, read, inputs, stored, userCondition !== undefined);
9218
- };
9219
- return withCurrentItem(write.pipe(Effect.mapError((err) => {
9220
- if (isAwsTransactionCancelled(err.cause)) {
9221
- const main = err.cause.CancellationReasons?.[0];
9222
- if (main?.Code === "ConditionalCheckFailed")
9223
- return reject(main.Item);
9224
- if (snapshotAt !== undefined &&
9225
- err.cause.CancellationReasons?.[snapshotAt.index]?.Code ===
9226
- "ConditionalCheckFailed") {
9227
- return historyConflict(snapshotAt.version, "delete");
9228
- }
9229
- for (const { index, constraintName } of releases) {
9230
- if (err.cause.CancellationReasons?.[index]?.Code === "ConditionalCheckFailed") {
9231
- return releaseRaced(encodedKey, constraintName);
9232
- }
9233
- }
9234
- }
9235
- if (isAwsConditionalCheckFailed(err.cause))
9236
- return reject(err.cause.Item);
9237
- return err;
9238
- })), () => rejected);
9239
- };
9240
- /**
9241
- * Append a release for each sentinel the stored item `raw` holds AND
9242
- * owns (#133) — composed from its domain view, since the stored row is
9243
- * attribute-keyed and the constraint is not (#127) — returning where
9244
- * each landed, so a release that lost a race can be reported.
9245
- */
9246
- const ownedReleases = (table, raw, into) => Effect.gen(function* () {
9247
- const rawDomain = toDomainView(raw);
9248
- const held = [];
9249
- for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
9250
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain, readSentinelValue);
9251
- if (!sentinel)
9252
- continue;
9253
- held.push({ ...sentinel.key, constraintName });
9254
- }
9255
- const owner = { pk: primaryKey[primary.pk.field], sk: primaryKey[primary.sk.field] };
9256
- const releases = [];
9257
- for (const sentinel of yield* ownedSentinels(table, held, owner)) {
9258
- releases.push({ index: into.length, constraintName: sentinel.constraintName });
9259
- into.push(sentinelRelease(table, sentinel, owner));
9260
- }
9261
- return releases;
9416
+ const { guardedDeleteCondition, guardedDelete, ownedReleases } = hardDeleteParts({
9417
+ encodedKey: encodedKey,
9418
+ primaryKey,
9419
+ userCondition,
9262
9420
  });
9263
9421
  if (isSoftDeleteEnabled() || hasUniqueConstraints || isRetainEnabled()) {
9264
9422
  const readFirst = Effect.gen(function* () {
@@ -10902,7 +11060,14 @@ const makeImpl = (config, precomputedData) => {
10902
11060
  // The public `append`: the core as the named operation (consumed capacity, #174).
10903
11061
  const append = (input, givenCondition, skipFollowUp = false, removeAttrs,
10904
11062
  // Internal: the bound builder's `.offloaded()` modes for `current` (#179).
10905
- offloadModes) => Capacity.operation("Entity.append", { target: entityType }, withReadModes(self, offloadModes, BlobLedger.rootIf(data.offload !== undefined, appendCore(input, givenCondition, skipFollowUp, removeAttrs))));
11063
+ offloadModes) => Capacity.operation("Entity.append", { target: entityType }, withReadModes(self, offloadModes, BlobLedger.rootIf(data.offload !== undefined,
11064
+ // A missing provided shard table (#287) is `EDD-9181` before the append reads or writes.
11065
+ providedShards
11066
+ ? Effect.suspend(() => {
11067
+ requireShardTables("Entity.append");
11068
+ return appendCore(input, givenCondition, skipFollowUp, removeAttrs);
11069
+ })
11070
+ : appendCore(input, givenCondition, skipFollowUp, removeAttrs))));
10906
11071
  const historyQuery = (key) => {
10907
11072
  if (!timeSeriesConfig) {
10908
11073
  throw new Error(`[EDD-9010] Entity "${entityType}": .history() requires timeSeries config on the entity.`);
@@ -10957,15 +11122,20 @@ const makeImpl = (config, precomputedData) => {
10957
11122
  // The bound definition: a Z-order half carries its layout (#171).
10958
11123
  const indexDef = data.initialIndexes[indexName] ?? config.indexes[indexName];
10959
11124
  const zorder = KeyComposer.isZOrderHalf(indexDef.sk);
11125
+ const provided = KeyComposer.hasProvidedShards({ [indexName]: indexDef });
10960
11126
  const indexQuery = (rawPk) => {
10961
11127
  // Normalise composites to their key form before composing — same rule
10962
11128
  // and same function the write path uses (see `CompositeCodec`). They are
10963
11129
  // the caller's DOMAIN values: the key `put` wrote for one is the key form
10964
11130
  // of the value it stores.
10965
11131
  const pkKeyForm = domainKeyForm(rawPk, indexDef.pk.composite, indexDef.sk.composite);
10966
- // One partition, or a sharded index's several (#183).
10967
- const read = KeyComposer.composeReadPartitions(schema, entityType, indexDef, pkKeyForm);
10968
- const pkValue = read.partitions[0];
11132
+ // One partition, or a sharded index's several (#183). An index whose table is supplied at
11133
+ // run time (#287) composes them when a terminal runs, from the `ShardLayouts` of its
11134
+ // context: the query is built before that is known.
11135
+ const read = provided
11136
+ ? undefined
11137
+ : KeyComposer.composeReadPartitions(schema, entityType, indexDef, pkKeyForm);
11138
+ const pkValue = read?.partitions[0] ?? "";
10969
11139
  // A Z-order sort key has no text prefix: its prefix composites and
10970
11140
  // dimensions are bounded through `.within()` on the typed accessor, never
10971
11141
  // passed as accessor composites (EDD-9093).
@@ -11000,7 +11170,9 @@ const makeImpl = (config, precomputedData) => {
11000
11170
  ],
11001
11171
  // DynamoDB's rejection of the key condition (#144) names the accessor.
11002
11172
  keyConditionDiagnosis: { operation: "query", label: `${entityType}.query.${indexName}` },
11003
- }).pipe((made) => Query.fanOut(made, read));
11173
+ }).pipe((made) => read !== undefined
11174
+ ? Query.fanOut(made, read)
11175
+ : Query.fanOutDeferred(made, () => Query.orRefusal({ name: "Entity.query", target: entityType }, () => KeyComposer.composeReadPartitions(schema, entityType, indexDef, pkKeyForm), (refusal) => refusal)));
11004
11176
  // `composeSortKeyCondition`: a partial prefix stops on a segment boundary,
11005
11177
  // or it matches sibling values that merely start with the supplied one
11006
11178
  // (`status_done` also matching `status_done_archived`, issue #115), and on a
@@ -11226,6 +11398,11 @@ const makeImpl = (config, precomputedData) => {
11226
11398
  // restore operation
11227
11399
  // ---------------------------------------------------------------------------
11228
11400
  const restore = (key) => new EntityGetImpl((mode, _opts) => Effect.gen(function* () {
11401
+ // A restore writes the row's keys again: a missing provided shard table (#287) is
11402
+ // `EDD-9181` before it reads, whether or not this row composes that index. It is
11403
+ // get-shaped, so no write's own check runs for it.
11404
+ if (providedShards)
11405
+ requireShardTables("Entity.restore");
11229
11406
  const client = yield* Capacity.client;
11230
11407
  const tc = yield* tableTag;
11231
11408
  const tableName = tc.name;
@@ -11451,7 +11628,6 @@ const makeImpl = (config, precomputedData) => {
11451
11628
  const primary = config.indexes.primary;
11452
11629
  const pkValue = KeyComposer.composePk(schema, entityType, primary, keyForm(encodedKey));
11453
11630
  const liveSk = liveSkOf(encodedKey);
11454
- const allItems = [];
11455
11631
  const history = historyKeyOptions(liveSk);
11456
11632
  /**
11457
11633
  * Whether a row of the partition is this item's (#133). Only this
@@ -11512,90 +11688,183 @@ const makeImpl = (config, precomputedData) => {
11512
11688
  offloadedAttributeNames.forEach((attr, i) => {
11513
11689
  projected[`#o${i}`] = attr;
11514
11690
  });
11515
- let exclusiveStartKey;
11516
- do {
11517
- const result = yield* client.query({
11518
- TableName: tableName,
11519
- KeyConditionExpression: "#pk = :pk",
11520
- ExpressionAttributeNames: {
11521
- "#pk": primary.pk.field,
11522
- "#sk": primary.sk.field,
11523
- ...projected,
11524
- },
11525
- ExpressionAttributeValues: { ":pk": toAttributeValue(pkValue) },
11526
- ProjectionExpression: ["#pk", "#sk", ...Object.keys(projected)].join(", "),
11527
- ExclusiveStartKey: exclusiveStartKey,
11528
- });
11529
- allItems.push(...(result.Items ?? []).filter(belongsToItem));
11530
- exclusiveStartKey = result.LastEvaluatedKey;
11531
- } while (exclusiveStartKey);
11532
- // The unique sentinels the item holds — live, or soft-deleted with
11533
- // `preserveUnique` — and owns (#133): a sentinel of a value the item
11534
- // holds without owning its reservation belongs to another item.
11535
- if (config.unique && Object.keys(config.unique).length > 0) {
11536
- const owner = { pk: pkValue, sk: liveSk };
11537
- const holders = [];
11538
- const mainResult = yield* client.getItem({
11539
- TableName: tableName,
11540
- Key: toAttributeMap({ [primary.pk.field]: owner.pk, [primary.sk.field]: owner.sk }),
11541
- ConsistentRead: true,
11542
- });
11543
- if (mainResult.Item)
11544
- holders.push(mainResult.Item);
11545
- // Every soft-deleted incarnation (each kept its reservations).
11546
- const deletedPrefix = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
11547
- let deletedStart;
11691
+ const hasUniqueConstraints = config.unique !== undefined && Object.keys(config.unique).length > 0;
11692
+ const owner = { pk: pkValue, sk: liveSk };
11693
+ const liveKey = toAttributeMap({
11694
+ [primary.pk.field]: owner.pk,
11695
+ [primary.sk.field]: owner.sk,
11696
+ });
11697
+ const isLiveRow = (row) => row[primary.pk.field]?.S === pkValue && row[primary.sk.field]?.S === liveSk;
11698
+ /**
11699
+ * One attempt: read the item's rows, and with `unique`, delete the live row and the
11700
+ * sentinels it owns in one transaction guarded on the row as read — the one `delete`
11701
+ * sends (#132). A batch delete carries no condition, so a concurrent update moving a
11702
+ * unique value after the read would otherwise leave the new value's sentinel reserving
11703
+ * for a row the batch then deletes. A lost race fails the attempt, and the purge starts
11704
+ * again from the query. Returns every row read, and whether the transaction deleted the
11705
+ * live row.
11706
+ *
11707
+ * The live row is read before the partition query: on a versioned entity its guard then
11708
+ * covers every row the query can see, since a write landing after the read moves the
11709
+ * version and refuses the transaction. Read after the query, a write in between was
11710
+ * guarded against while the rows it added (its snapshot) were missed.
11711
+ */
11712
+ const attempt = Effect.gen(function* () {
11713
+ const mainResult = hasUniqueConstraints
11714
+ ? yield* client.getItem({ TableName: tableName, Key: liveKey, ConsistentRead: true })
11715
+ : undefined;
11716
+ let liveDeleted = false;
11717
+ const allItems = [];
11718
+ let exclusiveStartKey;
11548
11719
  do {
11549
- const deletedResult = yield* client.query({
11720
+ // Consistent (#132): a purge straight after the item's last write sees every row
11721
+ // that write left — a new live row, a fresh snapshot — and deletes it.
11722
+ const result = yield* client.query({
11550
11723
  TableName: tableName,
11551
- KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
11724
+ KeyConditionExpression: "#pk = :pk",
11552
11725
  ExpressionAttributeNames: {
11553
11726
  "#pk": primary.pk.field,
11554
11727
  "#sk": primary.sk.field,
11728
+ ...projected,
11555
11729
  },
11556
- ExpressionAttributeValues: {
11557
- ":pk": toAttributeValue(pkValue),
11558
- ":skPrefix": toAttributeValue(deletedPrefix),
11559
- },
11730
+ ExpressionAttributeValues: { ":pk": toAttributeValue(pkValue) },
11731
+ ProjectionExpression: ["#pk", "#sk", ...Object.keys(projected)].join(", "),
11560
11732
  ConsistentRead: true,
11561
- ExclusiveStartKey: deletedStart,
11733
+ ExclusiveStartKey: exclusiveStartKey,
11562
11734
  });
11563
- holders.push(...(deletedResult.Items ?? []).filter(belongsToItem));
11564
- deletedStart = deletedResult.LastEvaluatedKey;
11565
- } while (deletedStart !== undefined);
11566
- // Sparse — fields that were unset never had a sentinel. The stored
11567
- // row is attribute-keyed, the constraint is not (#127).
11568
- const held = new Map();
11569
- for (const holder of holders) {
11570
- const holderDomain = toDomainView(fromAttributeMap(holder));
11571
- for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
11572
- const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain, readSentinelValue);
11573
- if (!sentinel)
11574
- continue;
11575
- held.set(`${sentinel.key.pk}\u0000${sentinel.key.sk}`, sentinel.key);
11735
+ allItems.push(...(result.Items ?? []).filter(belongsToItem));
11736
+ exclusiveStartKey = result.LastEvaluatedKey;
11737
+ } while (exclusiveStartKey);
11738
+ // The unique sentinels the item holds — live, or soft-deleted with
11739
+ // `preserveUnique` — and owns (#133): a sentinel of a value the item
11740
+ // holds without owning its reservation belongs to another item.
11741
+ if (hasUniqueConstraints) {
11742
+ // The live row, with the sentinels it owns, in `delete`'s guarded transaction.
11743
+ if (mainResult?.Item) {
11744
+ const live = mainResult.Item;
11745
+ const parts = hardDeleteParts({
11746
+ encodedKey: encodedKey,
11747
+ primaryKey: { [primary.pk.field]: owner.pk, [primary.sk.field]: owner.sk },
11748
+ userCondition: undefined,
11749
+ });
11750
+ const hardGuard = deleteGuard(live, [
11751
+ ...new Set(Object.values(config.unique).flatMap((def) => resolveUniqueFields(def).map(compositeAttribute))),
11752
+ ], undefined);
11753
+ const transactItems = [
11754
+ {
11755
+ Delete: {
11756
+ TableName: tableName,
11757
+ Key: liveKey,
11758
+ ...parts.guardedDeleteCondition(hardGuard),
11759
+ },
11760
+ },
11761
+ ];
11762
+ const releases = yield* parts.ownedReleases(tableName, fromAttributeMap(live), transactItems);
11763
+ yield* parts
11764
+ .guardedDelete(client.transactWriteItems({ TransactItems: transactItems }), live, hardGuard.inputs, undefined, releases)
11765
+ .pipe(
11766
+ // A delete of stored keys meets no size limit; wrapped for uniformity (#144).
11767
+ diagnoseFailure({
11768
+ sent: () => ({
11769
+ _tag: "Transaction",
11770
+ items: transactItems,
11771
+ targets: () => targetsFor(transactItems, entityKeyFields(), entityType, (index) => index === 0 ? "the item" : `item ${index} of the purge transaction`),
11772
+ }),
11773
+ keys: entityKeys,
11774
+ rewrite: (diagnosis, original) => diagnosedValidationError(diagnosis, original, {
11775
+ operation: "purge",
11776
+ entityType,
11777
+ }),
11778
+ }));
11779
+ liveDeleted = true;
11780
+ }
11781
+ // Every soft-deleted incarnation (each kept its reservations).
11782
+ const holders = [];
11783
+ const deletedPrefix = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
11784
+ let deletedStart;
11785
+ do {
11786
+ const deletedResult = yield* client.query({
11787
+ TableName: tableName,
11788
+ KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
11789
+ ExpressionAttributeNames: {
11790
+ "#pk": primary.pk.field,
11791
+ "#sk": primary.sk.field,
11792
+ },
11793
+ ExpressionAttributeValues: {
11794
+ ":pk": toAttributeValue(pkValue),
11795
+ ":skPrefix": toAttributeValue(deletedPrefix),
11796
+ },
11797
+ ConsistentRead: true,
11798
+ ExclusiveStartKey: deletedStart,
11799
+ });
11800
+ holders.push(...(deletedResult.Items ?? []).filter(belongsToItem));
11801
+ deletedStart = deletedResult.LastEvaluatedKey;
11802
+ } while (deletedStart !== undefined);
11803
+ // Sparse — fields that were unset never had a sentinel. The stored
11804
+ // row is attribute-keyed, the constraint is not (#127).
11805
+ const held = new Map();
11806
+ for (const holder of holders) {
11807
+ const holderDomain = toDomainView(fromAttributeMap(holder));
11808
+ for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
11809
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain, readSentinelValue);
11810
+ if (!sentinel)
11811
+ continue;
11812
+ held.set(`${sentinel.key.pk}\u0000${sentinel.key.sk}`, sentinel.key);
11813
+ }
11814
+ }
11815
+ // Released one by one, each only while still this item's: a batch
11816
+ // delete cannot carry the ownership condition. A tombstone's
11817
+ // reservation that the live row shared went with it above.
11818
+ for (const sentinel of yield* ownedSentinels(tableName, [...held.values()], owner)) {
11819
+ const release = sentinelRelease(tableName, sentinel, owner);
11820
+ yield* client.deleteItem(release.Delete).pipe(Effect.catchIf((err) => isAwsConditionalCheckFailed(err.cause), () => Effect.void),
11821
+ // A delete of a stored key cannot meet a size limit; wrapped
11822
+ // for uniformity (#144), so it passes through in practice.
11823
+ diagnoseItemWrite("purge", release));
11576
11824
  }
11577
11825
  }
11578
- // Released one by one, each only while still this item's: a batch
11579
- // delete cannot carry the ownership condition.
11580
- for (const sentinel of yield* ownedSentinels(tableName, [...held.values()], owner)) {
11581
- const release = sentinelRelease(tableName, sentinel, owner);
11582
- yield* client.deleteItem(release.Delete).pipe(Effect.catchIf((err) => isAwsConditionalCheckFailed(err.cause), () => Effect.void),
11583
- // A delete of a stored key cannot meet a size limit; wrapped
11584
- // for uniformity (#144), so it passes through in practice.
11585
- diagnoseItemWrite("purge", release));
11586
- }
11587
- }
11826
+ return { allItems, liveDeleted };
11827
+ });
11828
+ // A lost race on the live row is retried from the query, as a read-first delete is;
11829
+ // purge refuses a `.condition()`, so it always is. Once every attempt has lost, it is
11830
+ // what such a delete reports — a row deleted concurrently each time, a change.
11831
+ const { allItems, liveDeleted } = yield* attempt.pipe(Effect.retry({
11832
+ times: GUARDED_PUT_ATTEMPTS - 1,
11833
+ while: (e) => e instanceof OptimisticLockError ||
11834
+ e instanceof ConcurrentModification ||
11835
+ e instanceof DeletedConcurrently,
11836
+ }), Effect.catchIf((e) => e instanceof DeletedConcurrently ||
11837
+ e instanceof ItemNotFound ||
11838
+ e instanceof ConditionalCheckFailed, () => Effect.fail(new ConcurrentModification({
11839
+ entityType,
11840
+ key: encodedKey,
11841
+ attributes: [],
11842
+ current: Option.none(),
11843
+ }))));
11844
+ // With `unique`, the live row went in the transaction: the batch never deletes it, so a
11845
+ // row created after the attempt's read keeps its sentinels with it.
11846
+ const batchItems = hasUniqueConstraints
11847
+ ? allItems.filter((row) => !isLiveRow(row))
11848
+ : allItems;
11588
11849
  // Batch delete in chunks of 25. `UnprocessedItems` are retried with
11589
11850
  // `Batch.write`'s backoff; what the purge had deleted is always
11590
11851
  // stated exactly, whether a request is rejected or retries run out. By count alone: 25
11591
11852
  // stored keys (at most 2048 + 1024 bytes each, so at most about 0.5 MB as JSON) can't
11592
11853
  // reach the 16 MB request limit.
11854
+ // The live row the transaction deleted is one of the partition's items, and counted;
11855
+ // the reservations it released are in other partitions, and named.
11856
+ const inTransaction = liveDeleted ? 1 : 0;
11857
+ const partitionItems = batchItems.length + inTransaction;
11593
11858
  let deleted = 0;
11594
- const deletedSoFar = () => deleted === 0
11859
+ const deletedSoFar = () => deleted + inTransaction === 0
11595
11860
  ? "the purge had deleted none of the partition's items"
11596
- : `the purge had already deleted ${deleted} of the partition's ${allItems.length} items`;
11597
- for (let i = 0; i < allItems.length; i += 25) {
11598
- const chunk = allItems.slice(i, i + 25);
11861
+ : `the purge had already deleted ${deleted + inTransaction} of the partition's ` +
11862
+ `${partitionItems} items` +
11863
+ (liveDeleted
11864
+ ? ", the live item among them, with the reservations of its unique values"
11865
+ : "");
11866
+ for (let i = 0; i < batchItems.length; i += 25) {
11867
+ const chunk = batchItems.slice(i, i + 25);
11599
11868
  let requestItems = {
11600
11869
  [tableName]: chunk.map((item) => ({
11601
11870
  DeleteRequest: {
@@ -11643,7 +11912,7 @@ const makeImpl = (config, precomputedData) => {
11643
11912
  if (retries > MAX_RETRIES) {
11644
11913
  return yield* new DynamoError({
11645
11914
  operation: "BatchWriteItem",
11646
- cause: new Error(`purge: ${remaining} of the partition's ${allItems.length} items were still ` +
11915
+ cause: new Error(`purge: ${remaining} of the partition's ${partitionItems} items were still ` +
11647
11916
  `unprocessed after ${MAX_RETRIES} retries; ${deletedSoFar()}. The rest ` +
11648
11917
  "were not deleted: purge again to finish."),
11649
11918
  });
@@ -12622,7 +12891,9 @@ const makeImpl = (config, precomputedData) => {
12622
12891
  if (stored !== undefined) {
12623
12892
  const text = composing(() => KeyComposer.composeStoredPk(schema, entityType, index, rowKeyForm));
12624
12893
  if (text === undefined) {
12625
- if (!KeyComposer.isCurrentShardLayout(schema, entityType, index, stored)) {
12894
+ // Judged against the row's resolved layout (#287): its value's, or for a row
12895
+ // with a hole in its partition key, the default's or any agreeing entry's.
12896
+ if (!KeyComposer.isCurrentShardLayout(schema, entityType, index, stored, rowKeyForm)) {
12626
12897
  uncomposable.push(name);
12627
12898
  }
12628
12899
  }
@@ -14876,6 +15147,8 @@ const makeImpl = (config, precomputedData) => {
14876
15147
  _fillDecodingDefaults: fillDecodingDefaults,
14877
15148
  _encodeInput: (input, operation) => Effect.flatMap(prepareInput(input, operation), (prepared) => encodeForWrite(schemas.inputSchema, prepared, operation, operation)),
14878
15149
  _ownSchema: () => ownSchema(),
15150
+ _compileShardTable: data.compileShardTable,
15151
+ _requireShardTables: providedShards ? requireShardTables : undefined,
14879
15152
  _composeUniqueSentinels: (under, record) => composeUniqueSentinels(under, record),
14880
15153
  _unsentineledDefaults: unsentineledDefaults,
14881
15154
  _planPut: planPut,