effect-dynamodb 1.43.0 → 1.44.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 (39) hide show
  1. package/dist/Aggregate.d.ts +88 -13
  2. package/dist/Aggregate.d.ts.map +1 -1
  3. package/dist/Aggregate.js +604 -278
  4. package/dist/Aggregate.js.map +1 -1
  5. package/dist/BlobGc.d.ts +2 -2
  6. package/dist/BlobGc.d.ts.map +1 -1
  7. package/dist/DynamoClient.d.ts +1 -1
  8. package/dist/DynamoClient.d.ts.map +1 -1
  9. package/dist/DynamoClient.js.map +1 -1
  10. package/dist/Entity.d.ts +12 -4
  11. package/dist/Entity.d.ts.map +1 -1
  12. package/dist/Entity.js +455 -214
  13. package/dist/Entity.js.map +1 -1
  14. package/dist/Transaction.js +2 -1
  15. package/dist/Transaction.js.map +1 -1
  16. package/dist/index.d.ts +1 -1
  17. package/dist/index.d.ts.map +1 -1
  18. package/dist/index.js.map +1 -1
  19. package/dist/internal/AggregateWrite.d.ts +130 -0
  20. package/dist/internal/AggregateWrite.d.ts.map +1 -0
  21. package/dist/internal/AggregateWrite.js +341 -0
  22. package/dist/internal/AggregateWrite.js.map +1 -0
  23. package/dist/internal/ExpressionLimits.d.ts +22 -3
  24. package/dist/internal/ExpressionLimits.d.ts.map +1 -1
  25. package/dist/internal/ExpressionLimits.js +46 -7
  26. package/dist/internal/ExpressionLimits.js.map +1 -1
  27. package/dist/internal/ItemSize.d.ts +7 -1
  28. package/dist/internal/ItemSize.d.ts.map +1 -1
  29. package/dist/internal/ItemSize.js +13 -5
  30. package/dist/internal/ItemSize.js.map +1 -1
  31. package/dist/internal/TransactPlan.d.ts +18 -1
  32. package/dist/internal/TransactPlan.d.ts.map +1 -1
  33. package/dist/internal/TransactPlan.js +45 -7
  34. package/dist/internal/TransactPlan.js.map +1 -1
  35. package/dist/internal/TransactWriteOps.d.ts +1 -1
  36. package/dist/internal/TransactWriteOps.d.ts.map +1 -1
  37. package/dist/internal/TransactWriteOps.js +8 -8
  38. package/dist/internal/TransactWriteOps.js.map +1 -1
  39. 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";
@@ -4856,6 +4856,25 @@ const makeImpl = (config, precomputedData) => {
4856
4856
  };
4857
4857
  /** The item at a key, strongly consistent: the read a read-then-write op starts with. */
4858
4858
  const readCurrent = (tableName, marshalledKey) => Effect.flatMap(Capacity.client, (client) => client.getItem({ TableName: tableName, Key: marshalledKey, ConsistentRead: true }));
4859
+ /**
4860
+ * The row an update finds at its key: `undefined` for none, and for a projection tombstone
4861
+ * (#154), a removed row that every read by key reports as absent. An update of it is an update
4862
+ * of a missing row, by every path (#132).
4863
+ */
4864
+ const liveRow = (row) => row !== undefined && isProjectionTombstone(row, entityType) ? undefined : row;
4865
+ /**
4866
+ * The condition that the row an update writes exists, under `pkName`: `attribute_exists` of its
4867
+ * partition key, and, on a read model whose rows may be projection tombstones, that it isn't one
4868
+ * (#132). The term is free when it holds, and every other entity sends what it did.
4869
+ */
4870
+ const rowExists = (names, values, pkName) => {
4871
+ names[pkName] = config.indexes.primary.pk.field;
4872
+ if (!hasProjectionTombstones(self))
4873
+ return `attribute_exists(${pkName})`;
4874
+ names["#eddLive"] = "__edd_e__";
4875
+ values[":eddTomb"] = { S: `${entityType}#tombstone` };
4876
+ return `attribute_exists(${pkName}) AND #eddLive <> :eddTomb`;
4877
+ };
4859
4878
  /** Fill a `ConcurrentModification`'s `current` with the stored item, decoded. */
4860
4879
  const withCurrentItem = (effect, stored) => effect.pipe(Effect.catchIf((e) => e instanceof ConcurrentModification, (e) => Effect.gen(function* () {
4861
4880
  const item = stored();
@@ -6219,6 +6238,8 @@ const makeImpl = (config, precomputedData) => {
6219
6238
  keyFields,
6220
6239
  refAttribute: refSet.attribute,
6221
6240
  refData: refSet.value,
6241
+ heldAttribute: gsiPkField,
6242
+ heldValue: { S: gsiPkValue },
6222
6243
  });
6223
6244
  }
6224
6245
  exclusiveStartKey = queryResult.LastEvaluatedKey;
@@ -6227,58 +6248,88 @@ const makeImpl = (config, precomputedData) => {
6227
6248
  }
6228
6249
  if (allUpdateOps.length === 0)
6229
6250
  return;
6251
+ /**
6252
+ * A target's update: its ref SET, conditioned on the target still naming the source (#132).
6253
+ * The index the targets were found through is eventually consistent, so a target deleted or
6254
+ * pointed at another source since may still be listed: unconditioned, the update would
6255
+ * create a key-only item at a deleted target's key (one no read decodes, blocking a later
6256
+ * `create` there), or write this source's data into a target that no longer names it.
6257
+ * Refused, the target is no longer this source's, and is skipped.
6258
+ */
6259
+ const cascadeUpdate = (op) => ({
6260
+ TableName: op.tableName,
6261
+ Key: op.key,
6262
+ UpdateExpression: "SET #ref = :refData",
6263
+ ConditionExpression: "#held = :held",
6264
+ ExpressionAttributeNames: { "#ref": op.refAttribute, "#held": op.heldAttribute },
6265
+ ExpressionAttributeValues: { ":refData": op.refData, ":held": op.heldValue },
6266
+ });
6230
6267
  if (mode === "transactional") {
6231
6268
  // Transactional mode — one atomic transaction. DynamoDB's limits (100
6232
6269
  // items, 4 MB, item size, sort keys) are not pre-checked (#144): a
6233
6270
  // 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,
6271
+ // A target refused by its condition (#132) left the source since the query: it is
6272
+ // dropped, and the rest sent again, up to `GUARDED_PUT_ATTEMPTS` sends in all.
6273
+ let pending = allUpdateOps;
6274
+ for (let send = 1; pending.length > 0; send++) {
6275
+ const sentOps = pending;
6276
+ const cascadeItems = sentOps.map((op) => ({
6277
+ Update: cascadeUpdate(op),
6278
+ }));
6279
+ const sent = yield* Effect.result(client.transactWriteItems({ TransactItems: [...cascadeItems] }).pipe(diagnoseFailure({
6280
+ sent: () => ({
6281
+ _tag: "Transaction",
6282
+ items: cascadeItems,
6283
+ targets: () => cascadeItems.map((item, index) => {
6284
+ const op = sentOps[index];
6285
+ return transactItemTarget(item, op.tableName, op.keyFields, op.entityType, `the cascade update of ${op.entityType} (item ${index})`);
6265
6286
  }),
6266
- ],
6267
- }),
6268
- }));
6287
+ }),
6288
+ keys: () => ({
6289
+ partition: [...new Set(sentOps.map((op) => op.keyFields[0]))],
6290
+ sort: [...new Set(sentOps.map((op) => op.keyFields[1]))],
6291
+ }),
6292
+ rewrite: (diagnosis, original) => new CascadePartialFailure({
6293
+ sourceEntity: sourceEntityType,
6294
+ sourceId: sourceIdValue,
6295
+ succeeded: 0,
6296
+ failed: sentOps.length,
6297
+ errors: [
6298
+ diagnosedValidationError(diagnosis, original, {
6299
+ operation: "cascade",
6300
+ entityType: sourceEntityType,
6301
+ }),
6302
+ ],
6303
+ }),
6304
+ })));
6305
+ if (Result.isSuccess(sent))
6306
+ return;
6307
+ const error = sent.failure;
6308
+ const reasons = error._tag === "CascadePartialFailure" || !isAwsTransactionCancelled(error.cause)
6309
+ ? undefined
6310
+ : error.cause.CancellationReasons;
6311
+ const refused = new Set((reasons ?? []).flatMap((reason, index) => reason?.Code === "ConditionalCheckFailed" ? [index] : []));
6312
+ // Cancelled for another reason, or once the sends run out: a cascade that wrote nothing.
6313
+ if (refused.size === 0)
6314
+ return yield* error;
6315
+ pending = sentOps.filter((_, index) => !refused.has(index));
6316
+ if (send >= GUARDED_PUT_ATTEMPTS && pending.length > 0) {
6317
+ return yield* new CascadePartialFailure({
6318
+ sourceEntity: sourceEntityType,
6319
+ sourceId: sourceIdValue,
6320
+ succeeded: 0,
6321
+ failed: pending.length,
6322
+ errors: [error],
6323
+ });
6324
+ }
6325
+ }
6269
6326
  }
6270
6327
  else {
6271
6328
  // Eventual mode — concurrent updates with partial failure tracking
6272
6329
  let succeeded = 0;
6273
6330
  const errors = [];
6274
6331
  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
- };
6332
+ const update = cascadeUpdate(op);
6282
6333
  return client.updateItem(update).pipe(
6283
6334
  // An item the cascade grows past 400 KB is named in `errors`.
6284
6335
  diagnoseFailure({
@@ -6294,7 +6345,10 @@ const makeImpl = (config, precomputedData) => {
6294
6345
  }),
6295
6346
  }), Effect.tap(() => Effect.sync(() => {
6296
6347
  succeeded++;
6297
- })), Effect.catch((err) => Effect.sync(() => {
6348
+ })),
6349
+ // Refused (#132): the target was deleted, or no longer names this source, since the
6350
+ // query found it. It isn't this source's: skipped, neither succeeded nor failed.
6351
+ Effect.catchIf((err) => err._tag !== "ValidationError" && isAwsConditionalCheckFailed(err.cause), () => Effect.void), Effect.catch((err) => Effect.sync(() => {
6298
6352
  errors.push(err);
6299
6353
  })));
6300
6354
  });
@@ -7070,7 +7124,7 @@ const makeImpl = (config, precomputedData) => {
7070
7124
  return checked;
7071
7125
  });
7072
7126
  /** An update from what {@link prepareUpdate} decided: its reads and its write. */
7073
- const runPreparedUpdate = (key, prepared, mode,
7127
+ const runPreparedUpdate = (prepared, mode,
7074
7128
  /**
7075
7129
  * The item as already read — consistently — by the caller (`upsert`, a transaction's plan).
7076
7130
  * Used instead of reading it again: the write is guarded on it either way. An update that
@@ -7104,7 +7158,7 @@ const makeImpl = (config, precomputedData) => {
7104
7158
  // --- Retain path: read-then-transact ---
7105
7159
  // Read current item (needed to create snapshot of pre-update state)
7106
7160
  const currentResult = preRead !== undefined ? { Item: preRead } : yield* readCurrent(tableName, marshalledKey);
7107
- if (!currentResult.Item) {
7161
+ if (!currentResult.Item || isProjectionTombstone(currentResult.Item, entityType)) {
7108
7162
  return yield* missingItem();
7109
7163
  }
7110
7164
  const currentRaw = fromAttributeMap(currentResult.Item);
@@ -7851,7 +7905,7 @@ const makeImpl = (config, precomputedData) => {
7851
7905
  let casRead;
7852
7906
  if (isRetainEnabled() || needsBothImages) {
7853
7907
  const current = yield* readCurrent(tableName, marshalledKey);
7854
- if (!current.Item) {
7908
+ if (!current.Item || isProjectionTombstone(current.Item, entityType)) {
7855
7909
  return yield* missingItem();
7856
7910
  }
7857
7911
  yield* checkVersion(current.Item, "update");
@@ -7928,7 +7982,7 @@ const makeImpl = (config, precomputedData) => {
7928
7982
  if (plainWrite &&
7929
7983
  immutables.some((asserted) => asserted.packed || asserted.offloaded !== undefined)) {
7930
7984
  const stored = yield* readCurrent(tableName, marshalledKey);
7931
- if (stored.Item === undefined) {
7985
+ if (!stored.Item || isProjectionTombstone(stored.Item, entityType)) {
7932
7986
  return yield* createsOnMissing
7933
7987
  ? new MissingForCreate({ input: createInput() })
7934
7988
  : missingItem();
@@ -8531,16 +8585,32 @@ const makeImpl = (config, precomputedData) => {
8531
8585
  addClauses.length > 0 ||
8532
8586
  deleteClauses.length > 0;
8533
8587
  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.
8588
+ // Nothing to update (#132): nothing is written, but the op still establishes what its write
8589
+ // would have: the row exists (`ItemNotFound`, `patch`'s `ConditionalCheckFailed`), and its
8590
+ // condition holds. Existence alone is read, consistently, in every return mode; a condition
8591
+ // is sent in the update's own request with no `UpdateExpression`, which changes nothing. In a
8592
+ // transaction's plan the read is held to the commit by a `ConditionCheck` (`planned`), and
8593
+ // the request is recorded as one (`planWrite`).
8594
+ const noOp = !hasAnyUpdate;
8595
+ /**
8596
+ * A no-op's result: nothing "updated"; the whole-item modes, the row. `row`: the row it read,
8597
+ * or its request returned; `"held"`, its request's condition proved the row there and it
8598
+ * asked for nothing back.
8599
+ */
8600
+ const noOpResult = (row) => Effect.gen(function* () {
8601
+ if (row === undefined || (row !== "held" && liveRow(row) === undefined)) {
8602
+ return yield* missingItem();
8603
+ }
8537
8604
  if (rv === "none")
8538
8605
  return undefined;
8539
8606
  if (rv === "updatedOld" || rv === "updatedNew") {
8540
8607
  return yield* decodePartial(undefined, new Set(), mode);
8541
8608
  }
8542
- return yield* get(key)._run(mode);
8543
- }
8609
+ // A whole-item mode always asks its request for the row.
8610
+ if (row === "held")
8611
+ return yield* Effect.die(new Error("a no-op returned no row"));
8612
+ return yield* decodeAs(fromAttributeMap(row), row, mode);
8613
+ });
8544
8614
  // Compose UpdateExpression from all clause types
8545
8615
  const expressionParts = [];
8546
8616
  if (setClauses.length > 0)
@@ -8554,6 +8624,8 @@ const makeImpl = (config, precomputedData) => {
8554
8624
  const updateExpression = expressionParts.join(" ");
8555
8625
  // Build condition expression — combine optimistic lock + user condition
8556
8626
  const condParts = [];
8627
+ /** How many of `condParts` restate an immutable value (`#immN = :immN`). */
8628
+ let immutableTerms = 0;
8557
8629
  if (evExpected !== undefined && systemFields.version) {
8558
8630
  condParts.push(versionIs(evExpected, names, values, "#condVer", ":expectedVer"));
8559
8631
  }
@@ -8581,9 +8653,9 @@ const makeImpl = (config, precomputedData) => {
8581
8653
  names[`#imm${i}`] = attr;
8582
8654
  values[`:imm${i}`] = value;
8583
8655
  condParts.push(`#imm${i} = :imm${i}`);
8656
+ immutableTerms++;
8584
8657
  }
8585
- names["#exists"] = config.indexes.primary.pk.field;
8586
- condParts.push("attribute_exists(#exists)");
8658
+ condParts.push(rowExists(names, values, "#exists"));
8587
8659
  // A `pathIfNotExists` operand a check refuses is written only where its path is absent:
8588
8660
  // the write requires the path, and a refusal returning an item without it is that
8589
8661
  // operand's (`fallbackRefusal`, #236). None: the request is as it was.
@@ -8599,6 +8671,27 @@ const makeImpl = (config, precomputedData) => {
8599
8671
  if (incarnation !== undefined)
8600
8672
  condParts.push(incarnation);
8601
8673
  }
8674
+ if (noOp) {
8675
+ // Required in a no-op's request whatever else it asserts: an `UpdateItem` with no
8676
+ // `UpdateExpression` creates a key-only item at a missing key.
8677
+ if (!plainWrite)
8678
+ condParts.push(rowExists(names, values, "#exists"));
8679
+ // Asserting nothing but existence, and restated immutable values: the row is read (or
8680
+ // was), consistently, and the values are compared with it, as the refusal of the same
8681
+ // update with a payload compares them (`immutableMismatch`).
8682
+ if (condParts.length === 1 + immutableTerms) {
8683
+ const row = liveRow(held ?? (yield* readCurrent(tableName, marshalledKey)).Item);
8684
+ const immutableChange = row !== undefined ? immutableMismatch(immutables, row) : undefined;
8685
+ if (immutableChange !== undefined) {
8686
+ return yield* new ValidationError({
8687
+ entityType,
8688
+ operation: "update",
8689
+ cause: immutableChange,
8690
+ });
8691
+ }
8692
+ return yield* noOpResult(row);
8693
+ }
8694
+ }
8602
8695
  // Sent as built: a condition over DynamoDB's expression limits is
8603
8696
  // DynamoDB's to reject, and is diagnosed naming the caller's part (#144).
8604
8697
  const conditionExpression = condParts.length > 0 ? condParts.join(" AND ") : undefined;
@@ -8711,18 +8804,23 @@ const makeImpl = (config, precomputedData) => {
8711
8804
  // The image the mode returns; `none` asks for nothing unless a
8712
8805
  // cascade needs the new item.
8713
8806
  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";
8807
+ const returned = noOp
8808
+ ? // A no-op's item, unchanged: returned only to the whole-item modes, and never cascaded.
8809
+ rv === "allNew" || rv === "allOld"
8810
+ ? "ALL_NEW"
8811
+ : "NONE"
8812
+ : wantsOld
8813
+ ? "ALL_OLD"
8814
+ : rv === "none" && !uState.cascade && casRead === undefined
8815
+ ? "NONE"
8816
+ : "ALL_NEW";
8719
8817
  // DynamoDB rejects an empty `ExpressionAttributeValues` map. When
8720
8818
  // the UpdateExpression is REMOVE-only (e.g. clearMap with no other
8721
8819
  // combinators), `values` may be empty — omit the property entirely.
8722
8820
  const updateInput = {
8723
8821
  TableName: tableName,
8724
8822
  Key: marshalledKey,
8725
- UpdateExpression: updateExpression,
8823
+ ...(!noOp && { UpdateExpression: updateExpression }),
8726
8824
  ExpressionAttributeNames: names,
8727
8825
  ExpressionAttributeValues: Object.keys(values).length > 0 ? values : undefined,
8728
8826
  ConditionExpression: conditionExpression,
@@ -8736,9 +8834,10 @@ const makeImpl = (config, precomputedData) => {
8736
8834
  // item (it must exist), a restated immutable value, the
8737
8835
  // version CAS, or the user's condition.
8738
8836
  if (isAwsConditionalCheckFailed(err.cause)) {
8739
- const stored = err.cause.Item;
8837
+ const stored = liveRow(err.cause.Item);
8740
8838
  if (stored === undefined && !uState.patch) {
8741
- return createsOnMissing
8839
+ // A no-op never creates: its payload names nothing to create from.
8840
+ return createsOnMissing && !noOp
8742
8841
  ? new MissingForCreate({ input: createInput() })
8743
8842
  : new ItemNotFound({ entityType, key: encodedKey });
8744
8843
  }
@@ -8780,6 +8879,10 @@ const makeImpl = (config, precomputedData) => {
8780
8879
  !pathOpsPresent &&
8781
8880
  !forceReadMerge &&
8782
8881
  isItemSizeRejection(err), () => Effect.fail(new OffloadSizeRetry())), diagnoseItemWrite("update", { Update: updateInput }, () => uc?.expression));
8882
+ // The no-op's condition held: nothing changed, so nothing cascades.
8883
+ if (noOp) {
8884
+ return yield* noOpResult(returned === "NONE" ? "held" : result.Attributes);
8885
+ }
8783
8886
  // A cascade never meets an old-image mode here: that combination is
8784
8887
  // routed to the read-then-write branch, or read first (`casRead`).
8785
8888
  const newImage = wantsOld ? undefined : result.Attributes;
@@ -8791,7 +8894,7 @@ const makeImpl = (config, precomputedData) => {
8791
8894
  /** See {@link runPreparedUpdate}. */
8792
8895
  preRead,
8793
8896
  /** See {@link runPreparedUpdate}. */
8794
- forceReadMerge = false) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(key, prepared, mode, preRead, forceReadMerge));
8897
+ forceReadMerge = false) => Effect.flatMap(prepareUpdate(key, requested), (prepared) => runPreparedUpdate(prepared, mode, preRead, forceReadMerge));
8795
8898
  /**
8796
8899
  * {@link runUpdate}, re-run once on the read-merge branch when its standard
8797
8900
  * `UpdateItem` was rejected for item size under an item budget (#179,
@@ -8815,7 +8918,7 @@ const makeImpl = (config, precomputedData) => {
8815
8918
  held) => {
8816
8919
  const once = () => prepared === undefined
8817
8920
  ? runUpdateSized(key, mode, requested, held)
8818
- : sizedUpdate((force) => runPreparedUpdate(key, prepared, mode, held, force));
8921
+ : sizedUpdate((force) => runPreparedUpdate(prepared, mode, held, force));
8819
8922
  // A form race (#238): the row's renamed sparse map changed form between the update's read and
8820
8923
  // its write. Read again and written again, as a guarded put is; once every attempt raced, the
8821
8924
  // race is reported naming the map. A row handed in (a transaction's plan) is never re-read here:
@@ -8885,7 +8988,8 @@ const makeImpl = (config, precomputedData) => {
8885
8988
  Key: ownKey,
8886
8989
  ConsistentRead: true,
8887
8990
  });
8888
- if (read.Item === undefined) {
8991
+ // A projection tombstone is a removed row: missing, as every read by key reports it.
8992
+ if (read.Item === undefined || isProjectionTombstone(read.Item, entityType)) {
8889
8993
  ;
8890
8994
  ({ items, ownRow } = yield* plan({ rowMissing: true }));
8891
8995
  }
@@ -8919,6 +9023,26 @@ const makeImpl = (config, precomputedData) => {
8919
9023
  }
8920
9024
  const pkField = config.indexes.primary.pk.field;
8921
9025
  const skField = config.indexes.primary.sk.field;
9026
+ // An update with nothing to set writes nothing, and found its row with a consistent read
9027
+ // (#132). Standalone, that read IS the op's answer; in a transaction, the row could be
9028
+ // deleted before the commit, so the read is held to it: a `ConditionCheck` that the row
9029
+ // still exists, judged below as the op's main item (a refusal is a lost race, planned again,
9030
+ // which then finds the row missing). A no-op that asserts a condition recorded its own check.
9031
+ if (items.length === 0 && ownRow !== undefined) {
9032
+ const { name: tableName } = yield* tableTag;
9033
+ const names = {};
9034
+ const values = {};
9035
+ items = [
9036
+ conditionCheckItem({
9037
+ TableName: tableName,
9038
+ Key: ownKey,
9039
+ ConditionExpression: rowExists(names, values, "#pk"),
9040
+ ExpressionAttributeNames: names,
9041
+ ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9042
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9043
+ }),
9044
+ ];
9045
+ }
8922
9046
  const isOwn = (row) => {
8923
9047
  if (row === undefined)
8924
9048
  return false;
@@ -8944,7 +9068,10 @@ const makeImpl = (config, precomputedData) => {
8944
9068
  const sentinelPrefix = `${entityType}._unique.`;
8945
9069
  const versionPrefix = DynamoSchema.composeVersionKeyPrefix(schema, entityType);
8946
9070
  const roles = items.map((item) => {
8947
- if (isOwn(item.Put?.Item) || isOwn(item.Update?.Key) || isOwn(item.Delete?.Key)) {
9071
+ if (isOwn(item.Put?.Item) ||
9072
+ isOwn(item.Update?.Key) ||
9073
+ isOwn(item.Delete?.Key) ||
9074
+ isOwn(item.ConditionCheck?.Key)) {
8948
9075
  return { _tag: "main" };
8949
9076
  }
8950
9077
  // A retain snapshot: in the row's partition, at a version key.
@@ -8990,7 +9117,7 @@ const makeImpl = (config, precomputedData) => {
8990
9117
  // every write carrying it asks (`internal/FormGuard.ts`, #238); its
8991
9118
  // attribute is no input of the rest.
8992
9119
  const mainItem = items[roles.findIndex((role) => role._tag === "main")];
8993
- const guarded = mainItem?.Update ?? mainItem?.Put ?? mainItem?.Delete;
9120
+ const guarded = mainItem?.Update ?? mainItem?.Put ?? mainItem?.Delete ?? mainItem?.ConditionCheck;
8994
9121
  const conditionAttrs = [
8995
9122
  ...new Set((guarded?.ConditionExpression?.match(/#[A-Za-z0-9_]+/g) ?? []).flatMap((token) => {
8996
9123
  const attr = guarded?.ExpressionAttributeNames?.[token];
@@ -9052,12 +9179,12 @@ const makeImpl = (config, precomputedData) => {
9052
9179
  return ownRow === undefined
9053
9180
  ? lostRace(undefined)
9054
9181
  : { _tag: "Fail", error: historyConflict(role.version, operation) };
9055
- case "main":
9056
- main =
9057
- reason.Item === undefined
9058
- ? "absent"
9059
- : reason.Item;
9182
+ case "main": {
9183
+ // A projection tombstone there is the row removed: absent, as a read reports it.
9184
+ const stored = liveRow(reason.Item);
9185
+ main = stored === undefined ? "absent" : stored;
9060
9186
  break;
9187
+ }
9061
9188
  case "side":
9062
9189
  sideFailed = true;
9063
9190
  }
@@ -9101,11 +9228,100 @@ const makeImpl = (config, precomputedData) => {
9101
9228
  // `.keepRefs()`'s guard is the caller's: a row holding another ref fails it, unchanged.
9102
9229
  callerCondition: uState.condition !== undefined || prepared.kept !== undefined,
9103
9230
  expectedVersion: uState.expectedVersion,
9104
- refuse: (row) => fallbackRefusal(prepared.operands.fallbacks, row),
9231
+ // A restated immutable value the row doesn't hold is refused as standalone refuses it
9232
+ // (`ValidationError`), never sent and retried as a lost race.
9233
+ refuse: (row) => {
9234
+ const immutableChange = immutableMismatch(prepared.immutables, row);
9235
+ return immutableChange !== undefined
9236
+ ? new ValidationError({ entityType, operation: "update", cause: immutableChange })
9237
+ : fallbackRefusal(prepared.operands.fallbacks, row);
9238
+ },
9105
9239
  });
9106
9240
  // ---------------------------------------------------------------------------
9107
9241
  // delete operation
9108
9242
  // ---------------------------------------------------------------------------
9243
+ /**
9244
+ * The parts of the transaction a read-first delete sends (#133), for the item at `primaryKey`:
9245
+ * the main `Delete`'s condition (its guard on the row as read, ANDed with the caller's), the
9246
+ * owned sentinels' releases, and how a cancellation of it reads. `delete` sends them for an
9247
+ * entity with `unique`, retain or soft delete, and `purge` for a unique entity's live row
9248
+ * (#132), so the two can't drift.
9249
+ */
9250
+ const hardDeleteParts = ({ encodedKey, primaryKey, userCondition, }) => {
9251
+ const primary = config.indexes.primary;
9252
+ /** The guard ANDed with the user's condition, for the main Delete. */
9253
+ const guardedDeleteCondition = (guard) => {
9254
+ const values = { ...guard.values, ...userCondition?.values };
9255
+ return {
9256
+ ConditionExpression: userCondition
9257
+ ? `${guard.expression} AND (${userCondition.expression})`
9258
+ : guard.expression,
9259
+ ExpressionAttributeNames: { ...guard.names, ...userCondition?.names },
9260
+ ...(Object.keys(values).length > 0 && { ExpressionAttributeValues: values }),
9261
+ ReturnValuesOnConditionCheckFailure: "ALL_OLD",
9262
+ };
9263
+ };
9264
+ /**
9265
+ * Run a guarded delete transaction: index 0 is the main Delete, the
9266
+ * only conditioned item, so its rejection is read from the stored
9267
+ * item (ALL_OLD) — gone, raced, or the user's condition.
9268
+ */
9269
+ const guardedDelete = (write, read, inputs, snapshotAt, releases) => {
9270
+ let rejected;
9271
+ const reject = (stored) => {
9272
+ rejected = stored;
9273
+ // Deleted since the read: with nothing asserted, read it again —
9274
+ // a delete of a missing item reports what such a delete does.
9275
+ if (stored === undefined && userCondition === undefined) {
9276
+ return new DeletedConcurrently();
9277
+ }
9278
+ return deleteRejection(encodedKey, read, inputs, stored, userCondition !== undefined);
9279
+ };
9280
+ return withCurrentItem(write.pipe(Effect.mapError((err) => {
9281
+ if (isAwsTransactionCancelled(err.cause)) {
9282
+ const main = err.cause.CancellationReasons?.[0];
9283
+ if (main?.Code === "ConditionalCheckFailed")
9284
+ return reject(main.Item);
9285
+ if (snapshotAt !== undefined &&
9286
+ err.cause.CancellationReasons?.[snapshotAt.index]?.Code === "ConditionalCheckFailed") {
9287
+ return historyConflict(snapshotAt.version, "delete");
9288
+ }
9289
+ for (const { index, constraintName } of releases) {
9290
+ if (err.cause.CancellationReasons?.[index]?.Code === "ConditionalCheckFailed") {
9291
+ return releaseRaced(encodedKey, constraintName);
9292
+ }
9293
+ }
9294
+ }
9295
+ if (isAwsConditionalCheckFailed(err.cause))
9296
+ return reject(err.cause.Item);
9297
+ return err;
9298
+ })), () => rejected);
9299
+ };
9300
+ /**
9301
+ * Append a release for each sentinel the stored item `raw` holds AND
9302
+ * owns (#133) — composed from its domain view, since the stored row is
9303
+ * attribute-keyed and the constraint is not (#127) — returning where
9304
+ * each landed, so a release that lost a race can be reported.
9305
+ */
9306
+ const ownedReleases = (table, raw, into) => Effect.gen(function* () {
9307
+ const rawDomain = toDomainView(raw);
9308
+ const held = [];
9309
+ for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
9310
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, rawDomain, readSentinelValue);
9311
+ if (!sentinel)
9312
+ continue;
9313
+ held.push({ ...sentinel.key, constraintName });
9314
+ }
9315
+ const owner = { pk: primaryKey[primary.pk.field], sk: primaryKey[primary.sk.field] };
9316
+ const releases = [];
9317
+ for (const sentinel of yield* ownedSentinels(table, held, owner)) {
9318
+ releases.push({ index: into.length, constraintName: sentinel.constraintName });
9319
+ into.push(sentinelRelease(table, sentinel, owner));
9320
+ }
9321
+ return releases;
9322
+ });
9323
+ return { guardedDeleteCondition, guardedDelete, ownedReleases };
9324
+ };
9109
9325
  const del = (key) => new EntityDeleteImpl((opts) => Effect.gen(function* () {
9110
9326
  const client = yield* Capacity.client;
9111
9327
  const tc = yield* tableTag;
@@ -9188,77 +9404,10 @@ const makeImpl = (config, precomputedData) => {
9188
9404
  }
9189
9405
  return err;
9190
9406
  };
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;
9407
+ const { guardedDeleteCondition, guardedDelete, ownedReleases } = hardDeleteParts({
9408
+ encodedKey: encodedKey,
9409
+ primaryKey,
9410
+ userCondition,
9262
9411
  });
9263
9412
  if (isSoftDeleteEnabled() || hasUniqueConstraints || isRetainEnabled()) {
9264
9413
  const readFirst = Effect.gen(function* () {
@@ -11451,7 +11600,6 @@ const makeImpl = (config, precomputedData) => {
11451
11600
  const primary = config.indexes.primary;
11452
11601
  const pkValue = KeyComposer.composePk(schema, entityType, primary, keyForm(encodedKey));
11453
11602
  const liveSk = liveSkOf(encodedKey);
11454
- const allItems = [];
11455
11603
  const history = historyKeyOptions(liveSk);
11456
11604
  /**
11457
11605
  * Whether a row of the partition is this item's (#133). Only this
@@ -11512,90 +11660,183 @@ const makeImpl = (config, precomputedData) => {
11512
11660
  offloadedAttributeNames.forEach((attr, i) => {
11513
11661
  projected[`#o${i}`] = attr;
11514
11662
  });
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;
11663
+ const hasUniqueConstraints = config.unique !== undefined && Object.keys(config.unique).length > 0;
11664
+ const owner = { pk: pkValue, sk: liveSk };
11665
+ const liveKey = toAttributeMap({
11666
+ [primary.pk.field]: owner.pk,
11667
+ [primary.sk.field]: owner.sk,
11668
+ });
11669
+ const isLiveRow = (row) => row[primary.pk.field]?.S === pkValue && row[primary.sk.field]?.S === liveSk;
11670
+ /**
11671
+ * One attempt: read the item's rows, and with `unique`, delete the live row and the
11672
+ * sentinels it owns in one transaction guarded on the row as read — the one `delete`
11673
+ * sends (#132). A batch delete carries no condition, so a concurrent update moving a
11674
+ * unique value after the read would otherwise leave the new value's sentinel reserving
11675
+ * for a row the batch then deletes. A lost race fails the attempt, and the purge starts
11676
+ * again from the query. Returns every row read, and whether the transaction deleted the
11677
+ * live row.
11678
+ *
11679
+ * The live row is read before the partition query: on a versioned entity its guard then
11680
+ * covers every row the query can see, since a write landing after the read moves the
11681
+ * version and refuses the transaction. Read after the query, a write in between was
11682
+ * guarded against while the rows it added (its snapshot) were missed.
11683
+ */
11684
+ const attempt = Effect.gen(function* () {
11685
+ const mainResult = hasUniqueConstraints
11686
+ ? yield* client.getItem({ TableName: tableName, Key: liveKey, ConsistentRead: true })
11687
+ : undefined;
11688
+ let liveDeleted = false;
11689
+ const allItems = [];
11690
+ let exclusiveStartKey;
11548
11691
  do {
11549
- const deletedResult = yield* client.query({
11692
+ // Consistent (#132): a purge straight after the item's last write sees every row
11693
+ // that write left — a new live row, a fresh snapshot — and deletes it.
11694
+ const result = yield* client.query({
11550
11695
  TableName: tableName,
11551
- KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
11696
+ KeyConditionExpression: "#pk = :pk",
11552
11697
  ExpressionAttributeNames: {
11553
11698
  "#pk": primary.pk.field,
11554
11699
  "#sk": primary.sk.field,
11700
+ ...projected,
11555
11701
  },
11556
- ExpressionAttributeValues: {
11557
- ":pk": toAttributeValue(pkValue),
11558
- ":skPrefix": toAttributeValue(deletedPrefix),
11559
- },
11702
+ ExpressionAttributeValues: { ":pk": toAttributeValue(pkValue) },
11703
+ ProjectionExpression: ["#pk", "#sk", ...Object.keys(projected)].join(", "),
11560
11704
  ConsistentRead: true,
11561
- ExclusiveStartKey: deletedStart,
11705
+ ExclusiveStartKey: exclusiveStartKey,
11562
11706
  });
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);
11707
+ allItems.push(...(result.Items ?? []).filter(belongsToItem));
11708
+ exclusiveStartKey = result.LastEvaluatedKey;
11709
+ } while (exclusiveStartKey);
11710
+ // The unique sentinels the item holds — live, or soft-deleted with
11711
+ // `preserveUnique` — and owns (#133): a sentinel of a value the item
11712
+ // holds without owning its reservation belongs to another item.
11713
+ if (hasUniqueConstraints) {
11714
+ // The live row, with the sentinels it owns, in `delete`'s guarded transaction.
11715
+ if (mainResult?.Item) {
11716
+ const live = mainResult.Item;
11717
+ const parts = hardDeleteParts({
11718
+ encodedKey: encodedKey,
11719
+ primaryKey: { [primary.pk.field]: owner.pk, [primary.sk.field]: owner.sk },
11720
+ userCondition: undefined,
11721
+ });
11722
+ const hardGuard = deleteGuard(live, [
11723
+ ...new Set(Object.values(config.unique).flatMap((def) => resolveUniqueFields(def).map(compositeAttribute))),
11724
+ ], undefined);
11725
+ const transactItems = [
11726
+ {
11727
+ Delete: {
11728
+ TableName: tableName,
11729
+ Key: liveKey,
11730
+ ...parts.guardedDeleteCondition(hardGuard),
11731
+ },
11732
+ },
11733
+ ];
11734
+ const releases = yield* parts.ownedReleases(tableName, fromAttributeMap(live), transactItems);
11735
+ yield* parts
11736
+ .guardedDelete(client.transactWriteItems({ TransactItems: transactItems }), live, hardGuard.inputs, undefined, releases)
11737
+ .pipe(
11738
+ // A delete of stored keys meets no size limit; wrapped for uniformity (#144).
11739
+ diagnoseFailure({
11740
+ sent: () => ({
11741
+ _tag: "Transaction",
11742
+ items: transactItems,
11743
+ targets: () => targetsFor(transactItems, entityKeyFields(), entityType, (index) => index === 0 ? "the item" : `item ${index} of the purge transaction`),
11744
+ }),
11745
+ keys: entityKeys,
11746
+ rewrite: (diagnosis, original) => diagnosedValidationError(diagnosis, original, {
11747
+ operation: "purge",
11748
+ entityType,
11749
+ }),
11750
+ }));
11751
+ liveDeleted = true;
11752
+ }
11753
+ // Every soft-deleted incarnation (each kept its reservations).
11754
+ const holders = [];
11755
+ const deletedPrefix = DynamoSchema.composeDeletedKeyPrefix(schema, entityType);
11756
+ let deletedStart;
11757
+ do {
11758
+ const deletedResult = yield* client.query({
11759
+ TableName: tableName,
11760
+ KeyConditionExpression: "#pk = :pk AND begins_with(#sk, :skPrefix)",
11761
+ ExpressionAttributeNames: {
11762
+ "#pk": primary.pk.field,
11763
+ "#sk": primary.sk.field,
11764
+ },
11765
+ ExpressionAttributeValues: {
11766
+ ":pk": toAttributeValue(pkValue),
11767
+ ":skPrefix": toAttributeValue(deletedPrefix),
11768
+ },
11769
+ ConsistentRead: true,
11770
+ ExclusiveStartKey: deletedStart,
11771
+ });
11772
+ holders.push(...(deletedResult.Items ?? []).filter(belongsToItem));
11773
+ deletedStart = deletedResult.LastEvaluatedKey;
11774
+ } while (deletedStart !== undefined);
11775
+ // Sparse — fields that were unset never had a sentinel. The stored
11776
+ // row is attribute-keyed, the constraint is not (#127).
11777
+ const held = new Map();
11778
+ for (const holder of holders) {
11779
+ const holderDomain = toDomainView(fromAttributeMap(holder));
11780
+ for (const [constraintName, constraintDef] of Object.entries(config.unique)) {
11781
+ const sentinel = composeUniqueSentinel(schema, entityType, constraintName, constraintDef, holderDomain, readSentinelValue);
11782
+ if (!sentinel)
11783
+ continue;
11784
+ held.set(`${sentinel.key.pk}\u0000${sentinel.key.sk}`, sentinel.key);
11785
+ }
11786
+ }
11787
+ // Released one by one, each only while still this item's: a batch
11788
+ // delete cannot carry the ownership condition. A tombstone's
11789
+ // reservation that the live row shared went with it above.
11790
+ for (const sentinel of yield* ownedSentinels(tableName, [...held.values()], owner)) {
11791
+ const release = sentinelRelease(tableName, sentinel, owner);
11792
+ yield* client.deleteItem(release.Delete).pipe(Effect.catchIf((err) => isAwsConditionalCheckFailed(err.cause), () => Effect.void),
11793
+ // A delete of a stored key cannot meet a size limit; wrapped
11794
+ // for uniformity (#144), so it passes through in practice.
11795
+ diagnoseItemWrite("purge", release));
11576
11796
  }
11577
11797
  }
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
- }
11798
+ return { allItems, liveDeleted };
11799
+ });
11800
+ // A lost race on the live row is retried from the query, as a read-first delete is;
11801
+ // purge refuses a `.condition()`, so it always is. Once every attempt has lost, it is
11802
+ // what such a delete reports — a row deleted concurrently each time, a change.
11803
+ const { allItems, liveDeleted } = yield* attempt.pipe(Effect.retry({
11804
+ times: GUARDED_PUT_ATTEMPTS - 1,
11805
+ while: (e) => e instanceof OptimisticLockError ||
11806
+ e instanceof ConcurrentModification ||
11807
+ e instanceof DeletedConcurrently,
11808
+ }), Effect.catchIf((e) => e instanceof DeletedConcurrently ||
11809
+ e instanceof ItemNotFound ||
11810
+ e instanceof ConditionalCheckFailed, () => Effect.fail(new ConcurrentModification({
11811
+ entityType,
11812
+ key: encodedKey,
11813
+ attributes: [],
11814
+ current: Option.none(),
11815
+ }))));
11816
+ // With `unique`, the live row went in the transaction: the batch never deletes it, so a
11817
+ // row created after the attempt's read keeps its sentinels with it.
11818
+ const batchItems = hasUniqueConstraints
11819
+ ? allItems.filter((row) => !isLiveRow(row))
11820
+ : allItems;
11588
11821
  // Batch delete in chunks of 25. `UnprocessedItems` are retried with
11589
11822
  // `Batch.write`'s backoff; what the purge had deleted is always
11590
11823
  // stated exactly, whether a request is rejected or retries run out. By count alone: 25
11591
11824
  // stored keys (at most 2048 + 1024 bytes each, so at most about 0.5 MB as JSON) can't
11592
11825
  // reach the 16 MB request limit.
11826
+ // The live row the transaction deleted is one of the partition's items, and counted;
11827
+ // the reservations it released are in other partitions, and named.
11828
+ const inTransaction = liveDeleted ? 1 : 0;
11829
+ const partitionItems = batchItems.length + inTransaction;
11593
11830
  let deleted = 0;
11594
- const deletedSoFar = () => deleted === 0
11831
+ const deletedSoFar = () => deleted + inTransaction === 0
11595
11832
  ? "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);
11833
+ : `the purge had already deleted ${deleted + inTransaction} of the partition's ` +
11834
+ `${partitionItems} items` +
11835
+ (liveDeleted
11836
+ ? ", the live item among them, with the reservations of its unique values"
11837
+ : "");
11838
+ for (let i = 0; i < batchItems.length; i += 25) {
11839
+ const chunk = batchItems.slice(i, i + 25);
11599
11840
  let requestItems = {
11600
11841
  [tableName]: chunk.map((item) => ({
11601
11842
  DeleteRequest: {
@@ -11643,7 +11884,7 @@ const makeImpl = (config, precomputedData) => {
11643
11884
  if (retries > MAX_RETRIES) {
11644
11885
  return yield* new DynamoError({
11645
11886
  operation: "BatchWriteItem",
11646
- cause: new Error(`purge: ${remaining} of the partition's ${allItems.length} items were still ` +
11887
+ cause: new Error(`purge: ${remaining} of the partition's ${partitionItems} items were still ` +
11647
11888
  `unprocessed after ${MAX_RETRIES} retries; ${deletedSoFar()}. The rest ` +
11648
11889
  "were not deleted: purge again to finish."),
11649
11890
  });