@twin.org/entity-storage-connector-dynamodb 0.0.3-next.2 → 0.0.3-next.21

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.
@@ -1,11 +1,12 @@
1
1
  // Copyright 2024 IOTA Stiftung.
2
2
  // SPDX-License-Identifier: Apache-2.0.
3
- import { DynamoDB, QueryCommand, waitUntilTableExists } from "@aws-sdk/client-dynamodb";
4
- import { DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
3
+ import { BatchWriteItemCommand, DynamoDB, QueryCommand, ScanCommand as RawScanCommand, waitUntilTableExists, waitUntilTableNotExists } from "@aws-sdk/client-dynamodb";
4
+ import { BatchWriteCommand, DeleteCommand, DynamoDBDocumentClient, GetCommand, PutCommand, ScanCommand } from "@aws-sdk/lib-dynamodb";
5
5
  import { unmarshall } from "@aws-sdk/util-dynamodb";
6
6
  import { ContextIdHelper, ContextIdStore } from "@twin.org/context";
7
- import { BaseError, Coerce, ComponentFactory, Converter, GeneralError, Guards, Is, ObjectHelper } from "@twin.org/core";
7
+ import { BaseError, Coerce, ComponentFactory, Converter, GeneralError, Guards, HealthStatus, Is, ObjectHelper } from "@twin.org/core";
8
8
  import { ComparisonOperator, EntitySchemaFactory, EntitySchemaHelper, LogicalOperator, SortDirection } from "@twin.org/entity";
9
+ import { EntityStorageHelper } from "@twin.org/entity-storage-models";
9
10
  /**
10
11
  * Class for performing entity storage operations using Dynamo DB.
11
12
  */
@@ -29,6 +30,11 @@ export class DynamoDbEntityStorageConnector {
29
30
  * @internal
30
31
  */
31
32
  static _PARTITION_KEY_VALUE = "root";
33
+ /**
34
+ * The name for the schema.
35
+ * @internal
36
+ */
37
+ _entitySchemaName;
32
38
  /**
33
39
  * The schema for the entity.
34
40
  * @internal
@@ -64,8 +70,9 @@ export class DynamoDbEntityStorageConnector {
64
70
  }
65
71
  Guards.stringValue(DynamoDbEntityStorageConnector.CLASS_NAME, "options.config.region", options.config.region);
66
72
  Guards.stringValue(DynamoDbEntityStorageConnector.CLASS_NAME, "options.config.tableName", options.config.tableName);
67
- this._entitySchema = EntitySchemaFactory.get(options.entitySchema);
68
73
  this._partitionContextIds = options.partitionContextIds;
74
+ this._entitySchemaName = options.entitySchema;
75
+ this._entitySchema = EntitySchemaFactory.get(options.entitySchema);
69
76
  this._primaryKey = EntitySchemaHelper.getPrimaryKey(this._entitySchema);
70
77
  this._config = options.config;
71
78
  this._config.endpoint = Is.stringValue(this._config.endpoint)
@@ -79,6 +86,35 @@ export class DynamoDbEntityStorageConnector {
79
86
  className() {
80
87
  return DynamoDbEntityStorageConnector.CLASS_NAME;
81
88
  }
89
+ /**
90
+ * Returns the health status of the component.
91
+ * @returns The health status of the component.
92
+ */
93
+ async health() {
94
+ try {
95
+ const dbConnection = this.createConnection();
96
+ await dbConnection.describeTable({ TableName: this._config.tableName });
97
+ return [
98
+ {
99
+ source: DynamoDbEntityStorageConnector.CLASS_NAME,
100
+ status: HealthStatus.Ok,
101
+ description: "healthDescription",
102
+ data: { tableName: this._config.tableName }
103
+ }
104
+ ];
105
+ }
106
+ catch {
107
+ return [
108
+ {
109
+ source: DynamoDbEntityStorageConnector.CLASS_NAME,
110
+ status: HealthStatus.Error,
111
+ description: "healthDescription",
112
+ message: "connectionFailed",
113
+ data: { tableName: this._config.tableName }
114
+ }
115
+ ];
116
+ }
117
+ }
82
118
  /**
83
119
  * Get the schema for the entities.
84
120
  * @returns The schema for the entities.
@@ -174,7 +210,7 @@ export class DynamoDbEntityStorageConnector {
174
210
  // Wait for table to exist
175
211
  await waitUntilTableExists({
176
212
  client: dbConnection,
177
- maxWaitTime: 60000
213
+ maxWaitTime: 60
178
214
  }, {
179
215
  TableName: this._config.tableName
180
216
  });
@@ -250,8 +286,12 @@ export class DynamoDbEntityStorageConnector {
250
286
  }
251
287
  });
252
288
  const response = await docClient.send(getCommand);
253
- delete response.Item?.[DynamoDbEntityStorageConnector._PARTITION_KEY];
254
- return response.Item;
289
+ if (response.Item) {
290
+ return EntityStorageHelper.unPrepareEntity(response.Item, [
291
+ DynamoDbEntityStorageConnector._PARTITION_KEY
292
+ ]);
293
+ }
294
+ return undefined;
255
295
  }
256
296
  const finalConditions = {
257
297
  conditions: []
@@ -296,17 +336,21 @@ export class DynamoDbEntityStorageConnector {
296
336
  Guards.object(DynamoDbEntityStorageConnector.CLASS_NAME, "entity", entity);
297
337
  const contextIds = await ContextIdStore.getContextIds();
298
338
  const partitionKey = ContextIdHelper.combinedContextKey(contextIds, this._partitionContextIds);
299
- EntitySchemaHelper.validateEntity(entity, this.getSchema());
300
- const id = entity[this._primaryKey.property];
339
+ const prepared = EntityStorageHelper.prepareEntity(entity, this._entitySchema, partitionKey
340
+ ? [{ property: DynamoDbEntityStorageConnector._PARTITION_KEY, value: partitionKey }]
341
+ : [
342
+ {
343
+ property: DynamoDbEntityStorageConnector._PARTITION_KEY,
344
+ value: DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE
345
+ }
346
+ ], { nullBehavior: "omit" });
347
+ const id = prepared[this._primaryKey.property];
301
348
  try {
302
349
  const docClient = this.createDocClient();
303
350
  const { conditionExpression, attributeNames, attributeValues } = this.buildConditionExpression(conditions);
304
351
  const putCommand = new PutCommand({
305
352
  TableName: this._config.tableName,
306
- Item: {
307
- [DynamoDbEntityStorageConnector._PARTITION_KEY]: partitionKey ?? DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE,
308
- ...entity
309
- },
353
+ Item: prepared,
310
354
  // Only set the condition expression if we have conditions to match
311
355
  // and the primary key exists, otherwise we are creating a new object
312
356
  ConditionExpression: Is.stringValue(conditionExpression)
@@ -331,6 +375,93 @@ export class DynamoDbEntityStorageConnector {
331
375
  }, err);
332
376
  }
333
377
  }
378
+ /**
379
+ * Set multiple entities in a batch.
380
+ * @param entities The entities to set.
381
+ * @returns Nothing.
382
+ */
383
+ async setBatch(entities) {
384
+ Guards.arrayValue(DynamoDbEntityStorageConnector.CLASS_NAME, "entities", entities);
385
+ const contextIds = await ContextIdStore.getContextIds();
386
+ const partitionKey = ContextIdHelper.combinedContextKey(contextIds, this._partitionContextIds);
387
+ const preparedEntities = entities.map(entity => EntityStorageHelper.prepareEntity(entity, this._entitySchema, partitionKey
388
+ ? [{ property: DynamoDbEntityStorageConnector._PARTITION_KEY, value: partitionKey }]
389
+ : [
390
+ {
391
+ property: DynamoDbEntityStorageConnector._PARTITION_KEY,
392
+ value: DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE
393
+ }
394
+ ], { nullBehavior: "omit" }));
395
+ try {
396
+ const docClient = this.createDocClient();
397
+ const chunkSize = 25;
398
+ for (let i = 0; i < preparedEntities.length; i += chunkSize) {
399
+ const chunk = preparedEntities.slice(i, i + chunkSize);
400
+ await docClient.send(new BatchWriteCommand({
401
+ RequestItems: {
402
+ [this._config.tableName]: chunk.map(entity => ({
403
+ PutRequest: {
404
+ Item: entity
405
+ }
406
+ }))
407
+ }
408
+ }));
409
+ }
410
+ }
411
+ catch (err) {
412
+ if (BaseError.isErrorCode(err, "ResourceNotFoundException")) {
413
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "tableDoesNotExist", { tableName: this._config.tableName }, err);
414
+ }
415
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "setBatchFailed", undefined, err);
416
+ }
417
+ }
418
+ /**
419
+ * Empty the entity storage.
420
+ * @returns Nothing.
421
+ */
422
+ async empty() {
423
+ try {
424
+ const contextIds = await ContextIdStore.getContextIds();
425
+ const partitionKey = ContextIdHelper.combinedContextKey(contextIds, this._partitionContextIds);
426
+ const pKey = partitionKey ?? DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE;
427
+ const docClient = this.createDocClient();
428
+ const chunkSize = 25;
429
+ let exclusiveStartKey;
430
+ do {
431
+ const scanResult = await docClient.send(new ScanCommand({
432
+ TableName: this._config.tableName,
433
+ FilterExpression: "#partitionId = :partitionId",
434
+ ExpressionAttributeNames: {
435
+ "#partitionId": DynamoDbEntityStorageConnector._PARTITION_KEY
436
+ },
437
+ ExpressionAttributeValues: {
438
+ ":partitionId": pKey
439
+ },
440
+ ExclusiveStartKey: exclusiveStartKey
441
+ }));
442
+ const items = scanResult.Items ?? [];
443
+ for (let i = 0; i < items.length; i += chunkSize) {
444
+ const chunk = items.slice(i, i + chunkSize);
445
+ await docClient.send(new BatchWriteCommand({
446
+ RequestItems: {
447
+ [this._config.tableName]: chunk.map((item) => ({
448
+ DeleteRequest: {
449
+ Key: {
450
+ [DynamoDbEntityStorageConnector._PARTITION_KEY]: item[DynamoDbEntityStorageConnector._PARTITION_KEY],
451
+ [this._primaryKey.property]: item[this._primaryKey.property]
452
+ }
453
+ }
454
+ }))
455
+ }
456
+ }));
457
+ }
458
+ exclusiveStartKey = scanResult.LastEvaluatedKey;
459
+ } while (exclusiveStartKey);
460
+ }
461
+ catch (err) {
462
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "emptyFailed", undefined, err);
463
+ }
464
+ }
334
465
  /**
335
466
  * Remove the entity.
336
467
  * @param id The id of the entity to remove.
@@ -370,6 +501,77 @@ export class DynamoDbEntityStorageConnector {
370
501
  }, err);
371
502
  }
372
503
  }
504
+ /**
505
+ * Remove multiple entities by their IDs in a batch.
506
+ * @param ids The ids of the entities to remove.
507
+ * @returns Nothing.
508
+ */
509
+ async removeBatch(ids) {
510
+ Guards.arrayValue(DynamoDbEntityStorageConnector.CLASS_NAME, "ids", ids);
511
+ const contextIds = await ContextIdStore.getContextIds();
512
+ const partitionKey = ContextIdHelper.combinedContextKey(contextIds, this._partitionContextIds);
513
+ try {
514
+ const docClient = this.createDocClient();
515
+ const chunkSize = 25;
516
+ const primaryKeyProperty = this._primaryKey.property;
517
+ for (let i = 0; i < ids.length; i += chunkSize) {
518
+ const chunk = ids.slice(i, i + chunkSize);
519
+ await docClient.send(new BatchWriteCommand({
520
+ RequestItems: {
521
+ [this._config.tableName]: chunk.map(id => ({
522
+ DeleteRequest: {
523
+ Key: {
524
+ [primaryKeyProperty]: id,
525
+ [DynamoDbEntityStorageConnector._PARTITION_KEY]: partitionKey ?? DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE
526
+ }
527
+ }
528
+ }))
529
+ }
530
+ }));
531
+ }
532
+ }
533
+ catch (err) {
534
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "removeBatchFailed", undefined, err);
535
+ }
536
+ }
537
+ /**
538
+ * Teardown the entity storage by deleting the underlying table.
539
+ * @param nodeLoggingComponentType The node logging component type.
540
+ * @returns True if the teardown process was successful.
541
+ */
542
+ async teardown(nodeLoggingComponentType) {
543
+ const nodeLogging = ComponentFactory.getIfExists(nodeLoggingComponentType);
544
+ await nodeLogging?.log({
545
+ level: "info",
546
+ source: DynamoDbEntityStorageConnector.CLASS_NAME,
547
+ ts: Date.now(),
548
+ message: "tableDeleting",
549
+ data: { tableName: this._config.tableName }
550
+ });
551
+ try {
552
+ const dbConnection = this.createConnection();
553
+ await dbConnection.deleteTable({ TableName: this._config.tableName });
554
+ await waitUntilTableNotExists({ client: dbConnection, maxWaitTime: 60 }, { TableName: this._config.tableName });
555
+ await nodeLogging?.log({
556
+ level: "info",
557
+ source: DynamoDbEntityStorageConnector.CLASS_NAME,
558
+ ts: Date.now(),
559
+ message: "tableDeleted",
560
+ data: { tableName: this._config.tableName }
561
+ });
562
+ return true;
563
+ }
564
+ catch (err) {
565
+ await nodeLogging?.log({
566
+ level: "error",
567
+ source: DynamoDbEntityStorageConnector.CLASS_NAME,
568
+ ts: Date.now(),
569
+ message: "teardownFailed",
570
+ error: BaseError.fromError(err)
571
+ });
572
+ return false;
573
+ }
574
+ }
373
575
  /**
374
576
  * Find all the entities which match the conditions.
375
577
  * @param conditions The conditions to match for the entities.
@@ -386,15 +588,194 @@ export class DynamoDbEntityStorageConnector {
386
588
  return this.internalQuery(conditions, sortProperties, properties, cursor, limit, undefined, partitionKey);
387
589
  }
388
590
  /**
389
- * Delete the table.
390
- * @returns Nothing.
591
+ * Count all the entities which match the conditions.
592
+ * @param conditions The optional conditions to match for the entities.
593
+ * @returns The total count of entities in the storage.
391
594
  */
392
- async tableDelete() {
595
+ async count(conditions) {
393
596
  try {
597
+ const contextIds = await ContextIdStore.getContextIds();
598
+ const partitionKey = ContextIdHelper.combinedContextKey(contextIds, this._partitionContextIds);
599
+ const attributeNames = {
600
+ "#partitionId": DynamoDbEntityStorageConnector._PARTITION_KEY
601
+ };
602
+ const attributeValues = {
603
+ ":partitionId": {
604
+ S: partitionKey ?? DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE
605
+ }
606
+ };
607
+ const expressions = this.buildQueryParameters("", conditions, attributeNames, attributeValues);
608
+ if (expressions.noResults) {
609
+ return 0;
610
+ }
394
611
  const dbConnection = this.createConnection();
395
- await dbConnection.deleteTable({ TableName: this._config.tableName });
612
+ let total = 0;
613
+ let exclusiveStartKey;
614
+ do {
615
+ const result = await dbConnection.send(new QueryCommand({
616
+ TableName: this._config.tableName,
617
+ Select: "COUNT",
618
+ KeyConditionExpression: "#partitionId = :partitionId",
619
+ FilterExpression: Is.stringValue(expressions.filterCondition)
620
+ ? expressions.filterCondition
621
+ : undefined,
622
+ ExpressionAttributeNames: attributeNames,
623
+ ExpressionAttributeValues: attributeValues,
624
+ ExclusiveStartKey: exclusiveStartKey
625
+ }));
626
+ total += result.Count ?? 0;
627
+ exclusiveStartKey = result.LastEvaluatedKey;
628
+ } while (exclusiveStartKey);
629
+ return total;
630
+ }
631
+ catch (err) {
632
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "countFailed", undefined, err);
633
+ }
634
+ }
635
+ /**
636
+ * Get a unique list of all the context ids from the storage.
637
+ * @returns The list of unique context ids.
638
+ */
639
+ async getPartitionContextIds() {
640
+ if (!Is.arrayValue(this._partitionContextIds)) {
641
+ return [];
642
+ }
643
+ const contextIdsMap = {};
644
+ try {
645
+ const docClient = this.createDocClient();
646
+ let exclusiveStartKey;
647
+ do {
648
+ const scanResult = await docClient.send(new ScanCommand({
649
+ TableName: this._config.tableName,
650
+ ProjectionExpression: "#partitionId",
651
+ ExpressionAttributeNames: {
652
+ "#partitionId": DynamoDbEntityStorageConnector._PARTITION_KEY
653
+ },
654
+ ExclusiveStartKey: exclusiveStartKey
655
+ }));
656
+ for (const item of scanResult.Items ?? []) {
657
+ const partitionId = item[DynamoDbEntityStorageConnector._PARTITION_KEY];
658
+ if (Is.stringValue(partitionId) && !(partitionId in contextIdsMap)) {
659
+ contextIdsMap[partitionId] = ContextIdHelper.shortSplit(this._partitionContextIds ?? [], partitionId);
660
+ }
661
+ }
662
+ exclusiveStartKey = scanResult.LastEvaluatedKey;
663
+ } while (exclusiveStartKey);
664
+ }
665
+ catch (err) {
666
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "getPartitionContextIdsFailed", undefined, err);
667
+ }
668
+ return Object.values(contextIdsMap);
669
+ }
670
+ /**
671
+ * Create the target connector for performing the migration it will use a temporary storage location.
672
+ * @param newEntitySchema The name of the new entity schema to create the connector for.
673
+ * @returns Connector for performing the migration.
674
+ */
675
+ async createTargetConnector(newEntitySchema) {
676
+ // We create a new table for the migration with a unique name to avoid conflicts with the existing table
677
+ // This table will be swapped with the existing table once the migration is finalized.
678
+ const migrationTableName = `${this._config.tableName}Migration${Date.now()}`;
679
+ return new DynamoDbEntityStorageConnector({
680
+ entitySchema: newEntitySchema,
681
+ config: {
682
+ ...this._config,
683
+ tableName: migrationTableName
684
+ },
685
+ partitionContextIds: this._partitionContextIds
686
+ });
687
+ }
688
+ /**
689
+ * Finalize the migration by tearing down the old connector and replacing it with the new one.
690
+ * @param targetConnector The target connector to finalize the migration with.
691
+ * @param options The options to control how the migration is finalized.
692
+ * @param loggingComponentType The logging component type to use for logging during the migration finalization.
693
+ * @returns A promise that resolves when the migration is finalized.
694
+ */
695
+ async finalizeMigration(targetConnector, options, loggingComponentType) {
696
+ // There is no rename operation in DynamoDB so we have to create a new table with the original name and copy the data over
697
+ // Teardown the existing table with the original name to free up the name for the new table
698
+ await this.teardown(loggingComponentType);
699
+ // Create a new connector with the original table name but with the new schema
700
+ // and copy the data from the migration table to the new table using batch operations
701
+ const finalConnector = new DynamoDbEntityStorageConnector({
702
+ entitySchema: targetConnector._entitySchemaName,
703
+ config: this._config,
704
+ partitionContextIds: this._partitionContextIds
705
+ });
706
+ if (await finalConnector.bootstrap(loggingComponentType)) {
707
+ // Since there is no rename, we need to copy the data from the migration table to the new table
708
+ const partitions = await targetConnector.getPartitionContextIds();
709
+ const batchSize = options?.batchSize ?? DynamoDbEntityStorageConnector._DEFAULT_LIMIT;
710
+ await this.bulkCopy(targetConnector, finalConnector, partitions, batchSize);
711
+ await targetConnector.teardown(loggingComponentType);
712
+ return finalConnector;
713
+ }
714
+ throw new GeneralError(DynamoDbEntityStorageConnector.CLASS_NAME, "finalizeMigrationFailedBootstrap", undefined);
715
+ }
716
+ /**
717
+ * Cleanup the migration if a migration fails or needs to be aborted.
718
+ * @param targetConnector The target connector to cleanup the migration with.
719
+ * @param options The options to control how the migration is cleaned up.
720
+ * @param loggingComponentType The optional component type to use for logging the migration progress.
721
+ * @returns A promise that resolves when the migration is cleaned up.
722
+ */
723
+ async cleanupMigration(targetConnector, options, loggingComponentType) {
724
+ // If something failed the only thing to cleanup is the migration table
725
+ await targetConnector?.teardown?.(loggingComponentType);
726
+ }
727
+ /**
728
+ * Copy all entities from sourceConnector to destConnector, paging through each partition.
729
+ * @param sourceConnector The connector to read entities from.
730
+ * @param destConnector The connector to write entities to.
731
+ * @param partitions The partition list returned by getPartitionContextIds.
732
+ * @param batchSize The number of entities to read per page.
733
+ * @internal
734
+ */
735
+ async bulkCopy(sourceConnector, destConnector, partitions, batchSize) {
736
+ let partitionList;
737
+ if (Is.arrayValue(partitions)) {
738
+ partitionList = partitions;
739
+ }
740
+ else if (Is.arrayValue(sourceConnector._partitionContextIds)) {
741
+ partitionList = [];
742
+ }
743
+ else {
744
+ partitionList = [{}];
745
+ }
746
+ const dbConnection = sourceConnector.createConnection();
747
+ const chunkSize = 25;
748
+ for (let i = 0; i < partitionList.length; i++) {
749
+ const partitionKey = ContextIdHelper.combinedContextKey(partitionList[i], sourceConnector._partitionContextIds) ?? DynamoDbEntityStorageConnector._PARTITION_KEY_VALUE;
750
+ let exclusiveStartKey;
751
+ do {
752
+ const { Items: items, LastEvaluatedKey: lastKey } = await dbConnection.send(new QueryCommand({
753
+ TableName: sourceConnector._config.tableName,
754
+ KeyConditionExpression: `#${DynamoDbEntityStorageConnector._PARTITION_KEY} = :${DynamoDbEntityStorageConnector._PARTITION_KEY}`,
755
+ ExpressionAttributeNames: {
756
+ [`#${DynamoDbEntityStorageConnector._PARTITION_KEY}`]: DynamoDbEntityStorageConnector._PARTITION_KEY
757
+ },
758
+ ExpressionAttributeValues: {
759
+ [`:${DynamoDbEntityStorageConnector._PARTITION_KEY}`]: { S: partitionKey }
760
+ },
761
+ Limit: batchSize,
762
+ ExclusiveStartKey: exclusiveStartKey
763
+ }));
764
+ exclusiveStartKey = lastKey;
765
+ if (Is.arrayValue(items)) {
766
+ for (let j = 0; j < items.length; j += chunkSize) {
767
+ const chunk = items.slice(j, j + chunkSize);
768
+ await dbConnection.send(new BatchWriteItemCommand({
769
+ RequestItems: {
770
+ [destConnector._config.tableName]: chunk.map(item => ({
771
+ PutRequest: { Item: item }
772
+ }))
773
+ }
774
+ }));
775
+ }
776
+ }
777
+ } while (exclusiveStartKey);
396
778
  }
397
- catch { }
398
779
  }
399
780
  /**
400
781
  * Create the parameters for a query.
@@ -410,19 +791,79 @@ export class DynamoDbEntityStorageConnector {
410
791
  if (Is.undefined(condition)) {
411
792
  return {
412
793
  keyCondition: "",
413
- filterCondition: ""
794
+ filterCondition: "",
795
+ requiresScan: false
414
796
  };
415
797
  }
416
798
  if ("conditions" in condition) {
417
799
  if (condition.conditions.length === 0) {
418
800
  return {
419
801
  keyCondition: "",
420
- filterCondition: ""
802
+ filterCondition: "",
803
+ requiresScan: false
421
804
  };
422
805
  }
806
+ // Snapshot before the entire group. Used by the AND path to undo
807
+ // surviving siblings' attribute registrations when the AND is dead (#141).
808
+ const preGroupNames = new Set(Object.keys(attributeNames));
809
+ const preGroupValues = new Set(Object.keys(attributeValues));
423
810
  // It's a group of comparisons, so check the individual items and combine with the logical operator
424
- const joinConditions = condition.conditions.map(c => this.buildQueryParameters(objectPath, c, attributeNames, attributeValues, secondaryIndex));
811
+ const joinConditions = condition.conditions.map(c => {
812
+ // Snapshot before each branch. When a branch is dead (noResults),
813
+ // undo its attribute registrations so the final expressions stay
814
+ // consistent — DynamoDB rejects unused ExpressionAttributeNames (#141).
815
+ const preBranchNames = new Set(Object.keys(attributeNames));
816
+ const preBranchValues = new Set(Object.keys(attributeValues));
817
+ const result = this.buildQueryParameters(objectPath, c, attributeNames, attributeValues, secondaryIndex);
818
+ if (result.noResults) {
819
+ for (const key of Object.keys(attributeNames)) {
820
+ if (!preBranchNames.has(key)) {
821
+ delete attributeNames[key];
822
+ }
823
+ }
824
+ for (const key of Object.keys(attributeValues)) {
825
+ if (!preBranchValues.has(key)) {
826
+ delete attributeValues[key];
827
+ }
828
+ }
829
+ }
830
+ return result;
831
+ });
425
832
  const logicalOperator = this.mapConditionalOperator(condition.logicalOperator);
833
+ // DynamoDB does not support OR in KeyConditionExpression, so when the operator
834
+ // is OR we must move all conditions (including key conditions) into FilterExpression.
835
+ if (condition.logicalOperator === LogicalOperator.Or) {
836
+ // OR: only empty if ALL branches are guaranteed empty (e.g. all empty IN lists).
837
+ // If only some are empty they are naturally filtered out of `parts` below,
838
+ // which is correct — false OR x = x (#141).
839
+ if (joinConditions.every(j => j.noResults)) {
840
+ return { keyCondition: "", filterCondition: "", requiresScan: false, noResults: true };
841
+ }
842
+ const parts = joinConditions
843
+ .map(j => {
844
+ // A branch marked noResults (e.g. a dead AND group containing In [])
845
+ // must contribute nothing to the OR — false OR x = x (#141).
846
+ if (j.noResults) {
847
+ return "";
848
+ }
849
+ const subParts = [j.keyCondition.trim(), j.filterCondition.trim()].filter(s => s.length > 0);
850
+ if (subParts.length === 0) {
851
+ return "";
852
+ }
853
+ if (subParts.length === 1) {
854
+ return subParts[0];
855
+ }
856
+ return `(${subParts.join(" AND ")})`;
857
+ })
858
+ .filter(s => s.length > 0);
859
+ const hasKeyConditions = joinConditions.some(j => j.keyCondition.length > 0);
860
+ const filterCondition = parts.join(" OR ");
861
+ return {
862
+ keyCondition: "",
863
+ filterCondition: Is.stringValue(filterCondition) ? ` (${filterCondition}) ` : "",
864
+ requiresScan: hasKeyConditions
865
+ };
866
+ }
426
867
  const keyCondition = joinConditions
427
868
  .filter(j => j.keyCondition.length > 0)
428
869
  .map(j => j.keyCondition)
@@ -431,18 +872,46 @@ export class DynamoDbEntityStorageConnector {
431
872
  .filter(j => j.filterCondition.length > 0)
432
873
  .map(j => j.filterCondition)
433
874
  .join(` ${logicalOperator} `);
875
+ // AND: if any sub-condition is a guaranteed empty result (e.g. empty IN list),
876
+ // the whole AND group is also empty (#141). Restore the attribute maps to the
877
+ // pre-group snapshot so surviving siblings' registrations are also undone —
878
+ // per-branch cleanup above only undoes dead branches, not live ones whose AND
879
+ // partner was dead.
880
+ const noResults = joinConditions.some(j => j.noResults);
881
+ if (noResults) {
882
+ for (const key of Object.keys(attributeNames)) {
883
+ if (!preGroupNames.has(key)) {
884
+ delete attributeNames[key];
885
+ }
886
+ }
887
+ for (const key of Object.keys(attributeValues)) {
888
+ if (!preGroupValues.has(key)) {
889
+ delete attributeValues[key];
890
+ }
891
+ }
892
+ return { keyCondition: "", filterCondition: "", requiresScan: false, noResults: true };
893
+ }
434
894
  return {
435
895
  keyCondition: Is.stringValue(keyCondition) ? ` (${keyCondition}) ` : "",
436
- filterCondition: Is.stringValue(filterCondition) ? ` (${filterCondition}) ` : ""
896
+ filterCondition: Is.stringValue(filterCondition) ? ` (${filterCondition}) ` : "",
897
+ requiresScan: joinConditions.some(j => j.requiresScan)
437
898
  };
438
899
  }
439
900
  const schemaProp = this._entitySchema.properties?.find(p => p.property === condition.property);
901
+ // Empty IN list: DynamoDB has no `IN ()` syntax — short-circuit to empty result (#141).
902
+ if ("comparison" in condition &&
903
+ condition.comparison === ComparisonOperator.In &&
904
+ Is.array(condition.value) &&
905
+ condition.value.length === 0) {
906
+ return { keyCondition: "", filterCondition: "", requiresScan: false, noResults: true };
907
+ }
440
908
  // It's a single value so just create the property comparison for the condition
441
909
  const comparison = this.mapComparisonOperator(objectPath, condition, schemaProp?.type, attributeNames, attributeValues);
442
910
  const isKey = schemaProp?.isPrimary ?? (schemaProp?.isSecondary && schemaProp?.property === secondaryIndex);
443
911
  return {
444
912
  keyCondition: isKey ? comparison : "",
445
- filterCondition: !isKey ? comparison : ""
913
+ filterCondition: !isKey ? comparison : "",
914
+ requiresScan: false
446
915
  };
447
916
  }
448
917
  /**
@@ -464,6 +933,8 @@ export class DynamoDbEntityStorageConnector {
464
933
  prop += comparator.property;
465
934
  let attributeName = this.populateAttributeNames(prop, attributeNames);
466
935
  if (Is.empty(comparator.value)) {
936
+ // With "omit" storage, optional null/undefined fields are absent from the item entirely.
937
+ // attribute_not_exists matches absent attributes; attribute_exists matches present ones.
467
938
  if (comparator.comparison === ComparisonOperator.Equals) {
468
939
  return `attribute_not_exists(${attributeName})`;
469
940
  }
@@ -471,7 +942,13 @@ export class DynamoDbEntityStorageConnector {
471
942
  return `attribute_exists(${attributeName})`;
472
943
  }
473
944
  }
474
- let propName = `:${attributeName.replace(/\./g, "").replace(/#/g, "")}`;
945
+ const basePropName = `:${attributeName.replace(/\./g, "").replace(/#/g, "")}`;
946
+ let propName = basePropName;
947
+ let propSuffix = 0;
948
+ while (!Is.undefined(attributeValues[propName])) {
949
+ propSuffix++;
950
+ propName = `${basePropName}${propSuffix}`;
951
+ }
475
952
  if (Is.array(comparator.value)) {
476
953
  const dbValues = comparator.value.map(v => this.propertyToDbValue(v, type));
477
954
  const arrAttributeNames = [];
@@ -508,7 +985,7 @@ export class DynamoDbEntityStorageConnector {
508
985
  return `contains(${attributeName}, ${propName})`;
509
986
  }
510
987
  else if (comparator.comparison === ComparisonOperator.NotIncludes) {
511
- return `notContains(${attributeName}, ${propName})`;
988
+ return `NOT contains(${attributeName}, ${propName})`;
512
989
  }
513
990
  else if (comparator.comparison === ComparisonOperator.In) {
514
991
  return `${propName} IN ${attributeName}`;
@@ -608,6 +1085,9 @@ export class DynamoDbEntityStorageConnector {
608
1085
  * @internal
609
1086
  */
610
1087
  createConnectionConfig() {
1088
+ const requestHandler = Is.number(this._config.connectionTimeoutMs)
1089
+ ? { requestTimeout: this._config.connectionTimeoutMs }
1090
+ : undefined;
611
1091
  if (Is.stringValue(this._config.secretAccessKey) &&
612
1092
  Is.stringValue(this._config.accessKeyId) &&
613
1093
  this._config.authMode === "credentials") {
@@ -617,12 +1097,16 @@ export class DynamoDbEntityStorageConnector {
617
1097
  secretAccessKey: this._config.secretAccessKey
618
1098
  },
619
1099
  endpoint: this._config.endpoint,
620
- region: this._config.region
1100
+ region: this._config.region,
1101
+ requestHandler,
1102
+ maxAttempts: this._config.maxAttempts
621
1103
  };
622
1104
  }
623
1105
  return {
624
1106
  endpoint: this._config.endpoint,
625
- region: this._config.region
1107
+ region: this._config.region,
1108
+ requestHandler,
1109
+ maxAttempts: this._config.maxAttempts
626
1110
  };
627
1111
  }
628
1112
  /**
@@ -634,8 +1118,9 @@ export class DynamoDbEntityStorageConnector {
634
1118
  async tableExists(tableName) {
635
1119
  try {
636
1120
  const dbConnection = this.createConnection();
637
- await dbConnection.describeTable({ TableName: tableName });
638
- return true;
1121
+ const result = await dbConnection.describeTable({ TableName: tableName });
1122
+ // A table in DELETING state should not be treated as existing
1123
+ return result.Table?.TableStatus !== "DELETING";
639
1124
  }
640
1125
  catch {
641
1126
  return false;
@@ -690,6 +1175,52 @@ export class DynamoDbEntityStorageConnector {
690
1175
  }
691
1176
  };
692
1177
  const expressions = this.buildQueryParameters("", conditions, attributeNames, attributeValues, secondaryIndex);
1178
+ if (expressions.noResults) {
1179
+ return { entities: [], cursor: undefined };
1180
+ }
1181
+ // OR conditions on primary key attributes can't use KeyConditionExpression or
1182
+ // FilterExpression in a QueryCommand — fall back to a full table ScanCommand.
1183
+ if (expressions.requiresScan) {
1184
+ let scanFilter = "#partitionId = :partitionId";
1185
+ if (Is.stringValue(expressions.filterCondition)) {
1186
+ scanFilter += ` AND ${expressions.filterCondition.trim()}`;
1187
+ }
1188
+ const dbConnection = this.createConnection();
1189
+ const matchingItems = [];
1190
+ let scanStartKey = Is.empty(cursor)
1191
+ ? undefined
1192
+ : ObjectHelper.fromBytes(Converter.base64ToBytes(cursor));
1193
+ do {
1194
+ const scanResult = await dbConnection.send(new RawScanCommand({
1195
+ TableName: this._config.tableName,
1196
+ FilterExpression: scanFilter,
1197
+ ExpressionAttributeNames: attributeNames,
1198
+ ExpressionAttributeValues: attributeValues,
1199
+ ProjectionExpression: properties?.map(p => p).join(", "),
1200
+ ExclusiveStartKey: scanStartKey
1201
+ }));
1202
+ matchingItems.push(...(scanResult.Items ?? []));
1203
+ scanStartKey = scanResult.LastEvaluatedKey;
1204
+ } while (!Is.empty(scanStartKey));
1205
+ const hasMore = matchingItems.length > returnSize;
1206
+ const returnedRawItems = hasMore ? matchingItems.slice(0, returnSize) : matchingItems;
1207
+ let resultCursor;
1208
+ if (hasMore) {
1209
+ const lastRawItem = returnedRawItems[returnedRawItems.length - 1];
1210
+ const syntheticKey = {
1211
+ [DynamoDbEntityStorageConnector._PARTITION_KEY]: lastRawItem[DynamoDbEntityStorageConnector._PARTITION_KEY],
1212
+ [this._primaryKey.property]: lastRawItem[this._primaryKey.property]
1213
+ };
1214
+ resultCursor = Converter.bytesToBase64(ObjectHelper.toBytes(syntheticKey));
1215
+ }
1216
+ const scanEntities = returnedRawItems.map(item => {
1217
+ const unmarshalled = unmarshall(item);
1218
+ return EntityStorageHelper.unPrepareEntity(unmarshalled, [
1219
+ DynamoDbEntityStorageConnector._PARTITION_KEY
1220
+ ]);
1221
+ });
1222
+ return { entities: scanEntities, cursor: resultCursor };
1223
+ }
693
1224
  let keyExpression = "#partitionId = :partitionId";
694
1225
  if (expressions.keyCondition.length > 0) {
695
1226
  keyExpression += ` AND ${expressions.keyCondition}`;
@@ -704,7 +1235,7 @@ export class DynamoDbEntityStorageConnector {
704
1235
  ExpressionAttributeNames: attributeNames,
705
1236
  ExpressionAttributeValues: attributeValues,
706
1237
  ProjectionExpression: properties?.map(p => p).join(", "),
707
- Limit: returnSize,
1238
+ Limit: returnSize + 1,
708
1239
  ScanIndexForward: scanAscending,
709
1240
  ExclusiveStartKey: Is.empty(cursor)
710
1241
  ? undefined
@@ -712,20 +1243,28 @@ export class DynamoDbEntityStorageConnector {
712
1243
  });
713
1244
  const connection = this.createDocClient();
714
1245
  const results = await connection.send(query);
715
- let entities = [];
716
- if (Is.arrayValue(results.Items)) {
717
- entities = results.Items.map(item => {
718
- const unmarshalled = unmarshall(item);
719
- delete unmarshalled[DynamoDbEntityStorageConnector._PARTITION_KEY];
720
- return unmarshalled;
721
- });
1246
+ const rawItems = results.Items ?? [];
1247
+ const hasMore = rawItems.length > returnSize;
1248
+ const returnedRawItems = hasMore ? rawItems.slice(0, returnSize) : rawItems;
1249
+ let resultCursor;
1250
+ if (hasMore) {
1251
+ const lastRawItem = returnedRawItems[returnedRawItems.length - 1];
1252
+ const syntheticKey = {
1253
+ [DynamoDbEntityStorageConnector._PARTITION_KEY]: lastRawItem[DynamoDbEntityStorageConnector._PARTITION_KEY],
1254
+ [this._primaryKey.property]: lastRawItem[this._primaryKey.property]
1255
+ };
1256
+ if (Is.stringValue(secondaryIndex)) {
1257
+ syntheticKey[secondaryIndex] = lastRawItem[secondaryIndex];
1258
+ }
1259
+ resultCursor = Converter.bytesToBase64(ObjectHelper.toBytes(syntheticKey));
722
1260
  }
723
- return {
724
- entities,
725
- cursor: Is.empty(results.LastEvaluatedKey)
726
- ? undefined
727
- : Converter.bytesToBase64(ObjectHelper.toBytes(results.LastEvaluatedKey))
728
- };
1261
+ const entities = returnedRawItems.map(item => {
1262
+ const unmarshalled = unmarshall(item);
1263
+ return EntityStorageHelper.unPrepareEntity(unmarshalled, [
1264
+ DynamoDbEntityStorageConnector._PARTITION_KEY
1265
+ ]);
1266
+ });
1267
+ return { entities, cursor: resultCursor };
729
1268
  }
730
1269
  catch (err) {
731
1270
  if (BaseError.isErrorCode(err, "ResourceNotFoundException")) {