forked from aws/aws-cdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
table-v2.ts
976 lines (831 loc) · 31.9 KB
/
table-v2.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
import { Construct } from 'constructs';
import { Billing } from './billing';
import { Capacity } from './capacity';
import { CfnGlobalTable } from './dynamodb.generated';
import { TableEncryptionV2 } from './encryption';
import {
Attribute,
BillingMode,
LocalSecondaryIndexProps,
ProjectionType,
SecondaryIndexProps,
StreamViewType,
TableClass,
} from './shared';
import { ITableV2, TableBaseV2 } from './table-v2-base';
import { PolicyDocument } from '../../aws-iam';
import { IStream } from '../../aws-kinesis';
import { IKey, Key } from '../../aws-kms';
import {
ArnFormat,
CfnTag,
FeatureFlags,
Lazy,
PhysicalName,
RemovalPolicy,
Stack,
TagManager,
TagType,
Token,
} from '../../core';
import * as cxapi from '../../cx-api';
const HASH_KEY_TYPE = 'HASH';
const RANGE_KEY_TYPE = 'RANGE';
const MAX_GSI_COUNT = 20;
const MAX_LSI_COUNT = 5;
const MAX_NON_KEY_ATTRIBUTES = 100;
/**
* Options used to configure global secondary indexes on a replica table.
*/
export interface ReplicaGlobalSecondaryIndexOptions {
/**
* Whether CloudWatch contributor insights is enabled for a specific global secondary
* index on a replica table.
*
* @default - inherited from the primary table
*/
readonly contributorInsights?: boolean;
/**
* The read capacity for a specific global secondary index on a replica table.
*
* Note: This can only be configured if primary table billing is provisioned.
*
* @default - inherited from the primary table
*/
readonly readCapacity?: Capacity;
/**
* The maximum read request units for a specific global secondary index on a replica table.
*
* Note: This can only be configured if primary table billing is PAY_PER_REQUEST.
*
* @default - inherited from the primary table
*/
readonly maxReadRequestUnits?: number;
}
/**
* Properties used to configure a global secondary index.
*/
export interface GlobalSecondaryIndexPropsV2 extends SecondaryIndexProps {
/**
* Partition key attribute definition.
*/
readonly partitionKey: Attribute;
/**
* Sort key attribute definition.
*
* @default - no sort key
*/
readonly sortKey?: Attribute;
/**
* The read capacity.
*
* Note: This can only be configured if the primary table billing is provisioned.
*
* @default - inherited from the primary table.
*/
readonly readCapacity?: Capacity;
/**
* The write capacity.
*
* Note: This can only be configured if the primary table billing is provisioned.
*
* @default - inherited from the primary table.
*/
readonly writeCapacity?: Capacity;
/**
* The maximum read request units.
*
* Note: This can only be configured if the primary table billing is PAY_PER_REQUEST.
*
* @default - inherited from the primary table.
*/
readonly maxReadRequestUnits?: number;
/**
* The maximum write request units.
*
* Note: This can only be configured if the primary table billing is PAY_PER_REQUEST.
*
* @default - inherited from the primary table.
*/
readonly maxWriteRequestUnits?: number;
}
/**
* Options used to configure a DynamoDB table.
*/
export interface TableOptionsV2 {
/**
* Whether CloudWatch contributor insights is enabled.
*
* @default false
*/
readonly contributorInsights?: boolean;
/**
* Whether deletion protection is enabled.
*
* @default false
*/
readonly deletionProtection?: boolean;
/**
* Whether point-in-time recovery is enabled.
*
* @default false
*/
readonly pointInTimeRecovery?: boolean;
/**
* The table class.
*
* @default TableClass.STANDARD
*/
readonly tableClass?: TableClass;
/**
* Kinesis Data Stream to capture item level changes.
*
* @default - no Kinesis Data Stream
*/
readonly kinesisStream?: IStream;
/**
* Tags to be applied to the primary table (default replica table).
*
* @default - no tags
*/
readonly tags?: CfnTag[];
/**
* Resource policy to assign to DynamoDB Table.
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-globaltable-replicaspecification.html#cfn-dynamodb-globaltable-replicaspecification-resourcepolicy
* @default - No resource policy statements are added to the created table.
*/
readonly resourcePolicy?: PolicyDocument;
}
/**
* Properties used to configure a replica table.
*/
export interface ReplicaTableProps extends TableOptionsV2 {
/**
* The region that the replica table will be created in.
*/
readonly region: string;
/**
* The read capacity.
*
* Note: This can only be configured if the primary table billing is provisioned.
*
* @default - inherited from the primary table
*/
readonly readCapacity?: Capacity;
/**
* The maxium read request units.
*
* Note: This can only be configured if the primary table billing is PAY_PER_REQUEST.
*
* @default - inherited from the primary table
*/
readonly maxReadRequestUnits?: number;
/**
* Options used to configure global secondary index properties.
*
* @default - inherited from the primary table
*/
readonly globalSecondaryIndexOptions?: { [indexName: string]: ReplicaGlobalSecondaryIndexOptions };
}
/**
* Properties used to configure a DynamoDB table.
*/
export interface TablePropsV2 extends TableOptionsV2 {
/**
* Partition key attribute definition.
*/
readonly partitionKey: Attribute;
/**
* Sort key attribute definition.
*
* @default - no sort key
*/
readonly sortKey?: Attribute;
/**
* The name of the table.
*
* @default - generated by CloudFormation
*/
readonly tableName?: string;
/**
* The name of the TTL attribute.
*
* @default - TTL is disabled
*/
readonly timeToLiveAttribute?: string;
/**
* When an item in the table is modified, StreamViewType determines what information is
* written to the stream.
*
* @default - streams are disabled if replicas are not configured and this property is
* not specified. If this property is not specified when replicas are configured, then
* NEW_AND_OLD_IMAGES will be the StreamViewType for all replicas
*/
readonly dynamoStream?: StreamViewType;
/**
* The removal policy applied to the table.
*
* @default RemovalPolicy.RETAIN
*/
readonly removalPolicy?: RemovalPolicy;
/**
* The billing mode and capacity settings to apply to the table.
*
* @default Billing.onDemand()
*/
readonly billing?: Billing;
/**
* Replica tables to deploy with the primary table.
*
* Note: Adding replica tables allows you to use your table as a global table. You
* cannot specify a replica table in the region that the primary table will be deployed
* to. Replica tables will only be supported if the stack deployment region is defined.
*
* @default - no replica tables
*/
readonly replicas?: ReplicaTableProps[];
/**
* Global secondary indexes.
*
* Note: You can provide a maximum of 20 global secondary indexes.
*
* @default - no global secondary indexes
*/
readonly globalSecondaryIndexes?: GlobalSecondaryIndexPropsV2[];
/**
* Local secondary indexes.
*
* Note: You can only provide a maximum of 5 local secondary indexes.
*
* @default - no local secondary indexes
*/
readonly localSecondaryIndexes?: LocalSecondaryIndexProps[];
/**
* The server-side encryption.
*
* @default TableEncryptionV2.dynamoOwnedKey()
*/
readonly encryption?: TableEncryptionV2;
}
/**
* Attributes of a DynamoDB table.
*/
export interface TableAttributesV2 {
/**
* The ARN of the table.
*
* Note: You must specify this or the `tableName`.
*
* @default - table arn generated using `tableName` and region of stack
*/
readonly tableArn?: string;
/**
* The name of the table.
*
* Note: You must specify this or the `tableArn`.
*
* @default - table name retrieved from provided `tableArn`
*/
readonly tableName?: string;
/**
* The ID of the table.
*
* @default - no table id
*/
readonly tableId?: string;
/**
* The stream ARN of the table.
*
* @default - no table stream ARN
*/
readonly tableStreamArn?: string;
/**
* KMS encryption key for the table.
*
* @default - no KMS encryption key
*/
readonly encryptionKey?: IKey;
/**
* The name of the global indexes set for the table.
*
* Note: You must set either this property or `localIndexes` if you want permissions
* to be granted for indexes as well as the table itself.
*
* @default - no global indexes
*/
readonly globalIndexes?: string[];
/**
* The name of the local indexes set for the table.
*
* Note: You must set either this property or `globalIndexes` if you want permissions
* to be granted for indexes as well as the table itself.
*
* @default - no local indexes
*/
readonly localIndexes?: string[];
/**
* Whether or not to grant permissions for all indexes of the table.
*
* Note: If false, permissions will only be granted to indexes when `globalIndexes`
* or `localIndexes` is specified.
*
* @default false
*/
readonly grantIndexPermissions?: boolean;
}
/**
* A DynamoDB Table.
*/
export class TableV2 extends TableBaseV2 {
/**
* Creates a Table construct that represents an external table via table name.
*
* @param scope the parent creating construct (usually `this`)
* @param id the construct's name
* @param tableName the table's name
*/
public static fromTableName(scope: Construct, id: string, tableName: string): ITableV2 {
return TableV2.fromTableAttributes(scope, id, { tableName });
}
/**
* Creates a Table construct that represents an external table via table ARN.
*
* @param scope the parent creating construct (usually `this`)
* @param id the construct's name
* @param tableArn the table's ARN
*/
public static fromTableArn(scope: Construct, id: string, tableArn: string): ITableV2 {
return TableV2.fromTableAttributes(scope, id, { tableArn });
}
/**
* Creates a Table construct that represents an external table.
*
* @param scope the parent creating construct (usually `this`)
* @param id the construct's name
* @param attrs attributes of the table
*/
public static fromTableAttributes(scope: Construct, id: string, attrs: TableAttributesV2): ITableV2 {
class Import extends TableBaseV2 {
public readonly tableArn: string;
public readonly tableName: string;
public readonly tableId?: string;
public readonly tableStreamArn?: string;
public readonly encryptionKey?: IKey;
public readonly resourcePolicy?: PolicyDocument;
protected readonly region: string;
protected readonly hasIndex = (attrs.grantIndexPermissions ?? false) ||
(attrs.globalIndexes ?? []).length > 0 ||
(attrs.localIndexes ?? []).length > 0;
public constructor(tableArn: string, tableName: string, tableId?: string, tableStreamArn?: string, resourcePolicy?: PolicyDocument) {
super(scope, id, { environmentFromArn: tableArn });
const resourceRegion = stack.splitArn(tableArn, ArnFormat.SLASH_RESOURCE_NAME).region;
if (!resourceRegion) {
throw new Error('Table ARN must be of the form: arn:<partition>:dynamodb:<region>:<account>:table/<table-name>');
}
this.region = resourceRegion;
this.tableArn = tableArn;
this.tableName = tableName;
this.tableId = tableId;
this.tableStreamArn = tableStreamArn;
this.encryptionKey = attrs.encryptionKey;
this.resourcePolicy = resourcePolicy;
}
}
let tableName: string;
let tableArn: string;
const stack = Stack.of(scope);
if (!attrs.tableArn) {
if (!attrs.tableName) {
throw new Error('At least one of `tableArn` or `tableName` must be provided');
}
tableName = attrs.tableName;
tableArn = stack.formatArn({
service: 'dynamodb',
resource: 'table',
resourceName: tableName,
});
} else {
if (attrs.tableName) {
throw new Error('Only one of `tableArn` or `tableName` can be provided, but not both');
}
tableArn = attrs.tableArn;
const resourceName = stack.splitArn(tableArn, ArnFormat.SLASH_RESOURCE_NAME).resourceName;
if (!resourceName) {
throw new Error('Table ARN must be of the form: arn:<partition>:dynamodb:<region>:<account>:table/<table-name>');
}
tableName = resourceName;
}
return new Import(tableArn, tableName, attrs.tableId, attrs.tableStreamArn);
}
/**
* @attribute
*/
public readonly tableArn: string;
/**
* @attribute
*/
public readonly tableName: string;
/**
* @attribute
*/
public readonly tableStreamArn?: string;
/**
* @attribute
*/
public readonly tableId?: string;
public readonly encryptionKey?: IKey;
/**
* @attribute
*/
public resourcePolicy?: PolicyDocument;
protected readonly region: string;
protected readonly tags: TagManager;
private readonly billingMode: string;
private readonly partitionKey: Attribute;
private readonly hasSortKey: boolean;
private readonly tableOptions: TableOptionsV2;
private readonly encryption?: TableEncryptionV2;
private readonly keySchema: CfnGlobalTable.KeySchemaProperty[] = [];
private readonly attributeDefinitions: CfnGlobalTable.AttributeDefinitionProperty[] = [];
private readonly nonKeyAttributes = new Set<string>();
private readonly readProvisioning?: CfnGlobalTable.ReadProvisionedThroughputSettingsProperty;
private readonly writeProvisioning?: CfnGlobalTable.WriteProvisionedThroughputSettingsProperty;
private readonly maxReadRequestUnits?: number;
private readonly maxWriteRequestUnits?: number;
private readonly replicaTables = new Map<string, ReplicaTableProps>();
private readonly replicaKeys: { [region: string]: IKey } = {};
private readonly replicaTableArns: string[] = [];
private readonly replicaStreamArns: string[] = [];
private readonly globalSecondaryIndexes = new Map<string, CfnGlobalTable.GlobalSecondaryIndexProperty>();
private readonly localSecondaryIndexes = new Map<string, CfnGlobalTable.LocalSecondaryIndexProperty>();
private readonly globalSecondaryIndexReadCapacitys = new Map<string, Capacity>();
private readonly globalSecondaryIndexMaxReadUnits = new Map<string, number>();
public constructor(scope: Construct, id: string, props: TablePropsV2) {
super(scope, id, { physicalName: props.tableName ?? PhysicalName.GENERATE_IF_NEEDED });
this.tableOptions = props;
this.partitionKey = props.partitionKey;
this.hasSortKey = props.sortKey !== undefined;
this.region = this.stack.region;
this.tags = new TagManager(TagType.STANDARD, CfnGlobalTable.CFN_RESOURCE_TYPE_NAME);
this.encryption = props.encryption;
this.encryptionKey = this.encryption?.tableKey;
this.configureReplicaKeys(this.encryption?.replicaKeyArns);
this.addKey(props.partitionKey, HASH_KEY_TYPE);
if (props.sortKey) {
this.addKey(props.sortKey, RANGE_KEY_TYPE);
}
if (props.billing?.mode === BillingMode.PAY_PER_REQUEST || props.billing?.mode === undefined) {
this.maxReadRequestUnits = props.billing?._renderReadCapacity();
this.maxWriteRequestUnits = props.billing?._renderWriteCapacity();
this.billingMode = BillingMode.PAY_PER_REQUEST;
} else {
this.readProvisioning = props.billing?._renderReadCapacity();
this.writeProvisioning = props.billing?._renderWriteCapacity();
this.billingMode = props.billing.mode;
}
props.globalSecondaryIndexes?.forEach(gsi => this.addGlobalSecondaryIndex(gsi));
props.localSecondaryIndexes?.forEach(lsi => this.addLocalSecondaryIndex(lsi));
const resource = new CfnGlobalTable(this, 'Resource', {
tableName: this.physicalName,
keySchema: this.keySchema,
attributeDefinitions: Lazy.any({ produce: () => this.attributeDefinitions }),
replicas: Lazy.any({ produce: () => this.renderReplicaTables() }),
globalSecondaryIndexes: Lazy.any({ produce: () => this.renderGlobalIndexes() }, { omitEmptyArray: true }),
localSecondaryIndexes: Lazy.any({ produce: () => this.renderLocalIndexes() }, { omitEmptyArray: true }),
billingMode: this.billingMode,
writeProvisionedThroughputSettings: this.writeProvisioning,
writeOnDemandThroughputSettings: this.maxWriteRequestUnits
? { maxWriteRequestUnits: this.maxWriteRequestUnits }
: undefined,
streamSpecification: Lazy.any(
{ produce: () => props.dynamoStream ? { streamViewType: props.dynamoStream } : this.renderStreamSpecification() },
),
sseSpecification: this.encryption?._renderSseSpecification(),
timeToLiveSpecification: props.timeToLiveAttribute
? { attributeName: props.timeToLiveAttribute, enabled: true }
: undefined,
});
resource.applyRemovalPolicy(props.removalPolicy);
this.tableArn = this.getResourceArnAttribute(resource.attrArn, {
service: 'dynamodb',
resource: 'table',
resourceName: this.physicalName,
});
this.tableName = this.getResourceNameAttribute(resource.ref);
this.tableId = resource.attrTableId;
this.tableStreamArn = resource.attrStreamArn;
props.replicas?.forEach(replica => this.addReplica(replica));
if (props.tableName) {
this.node.addMetadata('aws:cdk:hasPhysicalName', this.tableName);
}
}
/**
* Add a replica table.
*
* Note: Adding a replica table will allow you to use your table as a global table.
*
* @param props the properties of the replica table to add
*/
public addReplica(props: ReplicaTableProps) {
this.validateReplica(props);
const replicaArn = this.stack.formatArn({
region: props.region,
resource: 'table',
service: 'dynamodb',
resourceName: this.tableName,
});
this.replicaTableArns.push(replicaArn);
const replicaStreamArn = `${replicaArn}/stream/*`;
this.replicaStreamArns.push(replicaStreamArn);
this.replicaTables.set(props.region, props);
}
/**
* Add a global secondary index to the table.
*
* Note: Global secondary indexes will be inherited by all replica tables.
*
* @param props the properties of the global secondary index
*/
public addGlobalSecondaryIndex(props: GlobalSecondaryIndexPropsV2) {
this.validateGlobalSecondaryIndex(props);
const globalSecondaryIndex = this.configureGlobalSecondaryIndex(props);
this.globalSecondaryIndexes.set(props.indexName, globalSecondaryIndex);
}
/**
* Add a local secondary index to the table.
*
* Note: Local secondary indexes will be inherited by all replica tables.
*
* @param props the properties of the local secondary index
*/
public addLocalSecondaryIndex(props: LocalSecondaryIndexProps) {
this.validateLocalSecondaryIndex(props);
const localSecondaryIndex = this.configureLocalSecondaryIndex(props);
this.localSecondaryIndexes.set(props.indexName, localSecondaryIndex);
}
/**
* Retrieve a replica table.
*
* Note: Replica tables are not supported in a region agnostic stack.
*
* @param region the region of the replica table
*/
public replica(region: string): ITableV2 {
if (Token.isUnresolved(this.stack.region)) {
throw new Error('Replica tables are not supported in a region agnostic stack');
}
if (Token.isUnresolved(region)) {
throw new Error('Provided `region` cannot be a token');
}
if (region === this.stack.region) {
return this;
}
if (!this.replicaTables.has(region)) {
throw new Error(`No replica table exists in region ${region}`);
}
const replicaTableArn = this.replicaTableArns.find(arn => arn.includes(region));
const replicaStreamArn = this.replicaStreamArns.find(arn => arn.includes(region));
return TableV2.fromTableAttributes(this, `ReplicaTable${region}`, {
tableArn: replicaTableArn,
encryptionKey: this.replicaKeys[region],
grantIndexPermissions: this.hasIndex,
tableStreamArn: replicaStreamArn,
});
}
private configureReplicaTable(props: ReplicaTableProps): CfnGlobalTable.ReplicaSpecificationProperty {
const pointInTimeRecovery = props.pointInTimeRecovery ?? this.tableOptions.pointInTimeRecovery;
const contributorInsights = props.contributorInsights ?? this.tableOptions.contributorInsights;
/*
* Feature flag set as the following may be a breaking change.
* @see https://github.com/aws/aws-cdk/pull/31097
* @see https://github.com/aws/aws-cdk/blob/main/packages/%40aws-cdk/cx-api/FEATURE_FLAGS.md
*/
const resourcePolicy = FeatureFlags.of(this).isEnabled(cxapi.DYNAMODB_TABLEV2_RESOURCE_POLICY_PER_REPLICA)
? (props.region === this.region ? this.tableOptions.resourcePolicy : props.resourcePolicy) || undefined
: props.resourcePolicy ?? this.tableOptions.resourcePolicy;
const propTags: Record<string, string> = (props.tags ?? []).reduce((p, item) =>
({ ...p, [item.key]: item.value }), {},
);
const tags: CfnTag[] = Object.entries({
...this.tags.tagValues(),
...propTags,
}).map(([k, v]) => ({ key: k, value: v }));
return {
region: props.region,
globalSecondaryIndexes: this.configureReplicaGlobalSecondaryIndexes(props.globalSecondaryIndexOptions),
deletionProtectionEnabled: props.deletionProtection ?? this.tableOptions.deletionProtection,
tableClass: props.tableClass ?? this.tableOptions.tableClass,
sseSpecification: this.encryption?._renderReplicaSseSpecification(this, props.region),
kinesisStreamSpecification: props.kinesisStream
? { streamArn: props.kinesisStream.streamArn }
: undefined,
contributorInsightsSpecification: contributorInsights !== undefined
? { enabled: contributorInsights }
: undefined,
pointInTimeRecoverySpecification: pointInTimeRecovery !== undefined
? { pointInTimeRecoveryEnabled: pointInTimeRecovery }
: undefined,
readProvisionedThroughputSettings: props.readCapacity
? props.readCapacity._renderReadCapacity()
: this.readProvisioning,
tags: tags.length === 0 ? undefined : tags,
readOnDemandThroughputSettings: props.maxReadRequestUnits
? { maxReadRequestUnits: props.maxReadRequestUnits }
: this.maxReadRequestUnits
? { maxReadRequestUnits: this.maxReadRequestUnits }
: undefined,
resourcePolicy: resourcePolicy
? { policyDocument: resourcePolicy }
: undefined,
};
}
private configureGlobalSecondaryIndex(props: GlobalSecondaryIndexPropsV2): CfnGlobalTable.GlobalSecondaryIndexProperty {
const keySchema = this.configureIndexKeySchema(props.partitionKey, props.sortKey);
const projection = this.configureIndexProjection(props);
props.readCapacity && this.globalSecondaryIndexReadCapacitys.set(props.indexName, props.readCapacity);
const writeProvisionedThroughputSettings = props.writeCapacity ? props.writeCapacity._renderWriteCapacity() : this.writeProvisioning;
props.maxReadRequestUnits && this.globalSecondaryIndexMaxReadUnits.set(props.indexName, props.maxReadRequestUnits);
const writeOnDemandThroughputSettings: CfnGlobalTable.WriteOnDemandThroughputSettingsProperty | undefined = props.maxWriteRequestUnits
? { maxWriteRequestUnits: props.maxWriteRequestUnits }
: undefined;
return {
indexName: props.indexName,
keySchema,
projection,
writeProvisionedThroughputSettings,
writeOnDemandThroughputSettings,
};
}
private configureLocalSecondaryIndex(props: LocalSecondaryIndexProps): CfnGlobalTable.LocalSecondaryIndexProperty {
const keySchema = this.configureIndexKeySchema(this.partitionKey, props.sortKey);
const projection = this.configureIndexProjection(props);
return {
indexName: props.indexName,
keySchema,
projection,
};
}
private configureReplicaGlobalSecondaryIndexes(options: { [indexName: string]: ReplicaGlobalSecondaryIndexOptions } = {}) {
this.validateReplicaIndexOptions(options);
const replicaGlobalSecondaryIndexes: CfnGlobalTable.ReplicaGlobalSecondaryIndexSpecificationProperty[] = [];
const indexNamesFromOptions = Object.keys(options);
for (const gsi of this.globalSecondaryIndexes.values()) {
const indexName = gsi.indexName;
let contributorInsights = this.tableOptions.contributorInsights;
let readCapacity = this.globalSecondaryIndexReadCapacitys.get(indexName);
let maxReadRequestUnits = this.globalSecondaryIndexMaxReadUnits.get(indexName);
if (indexNamesFromOptions.includes(indexName)) {
const indexOptions = options[indexName];
contributorInsights = indexOptions.contributorInsights;
readCapacity = indexOptions.readCapacity;
maxReadRequestUnits = indexOptions.maxReadRequestUnits;
}
const readProvisionedThroughputSettings = readCapacity?._renderReadCapacity() ?? this.readProvisioning;
const readOnDemandThroughputSettings: CfnGlobalTable.ReadOnDemandThroughputSettingsProperty | undefined = maxReadRequestUnits
? { maxReadRequestUnits: maxReadRequestUnits }
: undefined;
replicaGlobalSecondaryIndexes.push({
indexName,
readProvisionedThroughputSettings,
readOnDemandThroughputSettings,
contributorInsightsSpecification: contributorInsights !== undefined
? { enabled: contributorInsights }
: undefined,
});
}
return replicaGlobalSecondaryIndexes.length > 0 ? replicaGlobalSecondaryIndexes : undefined;
}
private configureIndexKeySchema(partitionKey: Attribute, sortKey?: Attribute) {
this.addAttributeDefinition(partitionKey);
const indexKeySchema: CfnGlobalTable.KeySchemaProperty[] = [
{ attributeName: partitionKey.name, keyType: HASH_KEY_TYPE },
];
if (sortKey) {
this.addAttributeDefinition(sortKey);
indexKeySchema.push({ attributeName: sortKey.name, keyType: RANGE_KEY_TYPE });
}
return indexKeySchema;
}
private configureIndexProjection(props: SecondaryIndexProps): CfnGlobalTable.ProjectionProperty {
this.validateIndexProjection(props);
props.nonKeyAttributes?.forEach(attr => this.nonKeyAttributes.add(attr));
if (this.nonKeyAttributes.size > MAX_NON_KEY_ATTRIBUTES) {
throw new Error(`The maximum number of 'nonKeyAttributes' across all secondary indexes is ${MAX_NON_KEY_ATTRIBUTES}`);
}
return {
projectionType: props.projectionType ?? ProjectionType.ALL,
nonKeyAttributes: props.nonKeyAttributes ?? undefined,
};
}
private configureReplicaKeys(replicaKeyArns: { [region: string]: string } = {}) {
for (const [region, keyArn] of Object.entries(replicaKeyArns)) {
this.replicaKeys[region] = Key.fromKeyArn(this, `ReplicaKey${region}`, keyArn);
}
}
private renderReplicaTables() {
const replicaTables: CfnGlobalTable.ReplicaSpecificationProperty[] = [];
for (const replicaTable of this.replicaTables.values()) {
replicaTables.push(this.configureReplicaTable(replicaTable));
}
replicaTables.push(this.configureReplicaTable({
region: this.stack.region,
kinesisStream: this.tableOptions.kinesisStream,
tags: this.tableOptions.tags,
}));
return replicaTables;
}
private renderGlobalIndexes() {
const globalSecondaryIndexes: CfnGlobalTable.GlobalSecondaryIndexProperty[] = [];
for (const globalSecondaryIndex of this.globalSecondaryIndexes.values()) {
globalSecondaryIndexes.push(globalSecondaryIndex);
}
return globalSecondaryIndexes;
}
private renderLocalIndexes() {
const localSecondaryIndexes: CfnGlobalTable.LocalSecondaryIndexProperty[] = [];
for (const localSecondaryIndex of this.localSecondaryIndexes.values()) {
localSecondaryIndexes.push(localSecondaryIndex);
}
return localSecondaryIndexes;
}
private renderStreamSpecification(): CfnGlobalTable.StreamSpecificationProperty | undefined {
return this.replicaTables.size > 0 ? { streamViewType: StreamViewType.NEW_AND_OLD_IMAGES } : undefined;
}
private addKey(key: Attribute, keyType: string) {
this.addAttributeDefinition(key);
this.keySchema.push({ attributeName: key.name, keyType });
}
private addAttributeDefinition(attribute: Attribute) {
const { name, type } = attribute;
const existingAttributeDef = this.attributeDefinitions.find(def => def.attributeName === name);
if (existingAttributeDef && existingAttributeDef.attributeType !== type) {
throw new Error(`Unable to specify ${name} as ${type} because it was already defined as ${existingAttributeDef.attributeType}`);
}
if (!existingAttributeDef) {
this.attributeDefinitions.push({ attributeName: name, attributeType: type });
}
}
protected get hasIndex() {
return this.globalSecondaryIndexes.size + this.localSecondaryIndexes.size > 0;
}
private validateIndexName(indexName: string) {
if (this.globalSecondaryIndexes.has(indexName) || this.localSecondaryIndexes.has(indexName)) {
throw new Error(`Duplicate secondary index name, ${indexName}, is not allowed`);
}
}
private validateIndexProjection(props: SecondaryIndexProps) {
if (props.projectionType === ProjectionType.INCLUDE && !props.nonKeyAttributes) {
throw new Error(`Non-key attributes should be specified when using ${ProjectionType.INCLUDE} projection type`);
}
if (props.projectionType !== ProjectionType.INCLUDE && props.nonKeyAttributes) {
throw new Error(`Non-key attributes should not be specified when not using ${ProjectionType.INCLUDE} projection type`);
}
}
private validateReplicaIndexOptions(options: { [indexName: string]: ReplicaGlobalSecondaryIndexOptions }) {
for (const indexName of Object.keys(options)) {
if (!this.globalSecondaryIndexes.has(indexName)) {
throw new Error(`Cannot configure replica global secondary index, ${indexName}, because it is not defined on the primary table`);
}
const replicaGsiOptions = options[indexName];
if (this.billingMode === BillingMode.PAY_PER_REQUEST && replicaGsiOptions.readCapacity) {
throw new Error(`Cannot configure 'readCapacity' for replica global secondary index, ${indexName}, because billing mode is ${BillingMode.PAY_PER_REQUEST}`);
}
}
}
private validateReplica(props: ReplicaTableProps) {
const stackRegion = this.stack.region;
if (Token.isUnresolved(stackRegion)) {
throw new Error('Replica tables are not supported in a region agnostic stack');
}
if (Token.isUnresolved(props.region)) {
throw new Error('Replica table region must not be a token');
}
if (props.region === this.stack.region) {
throw new Error(`You cannot add a replica table in the same region as the primary table - the primary table region is ${this.region}`);
}
if (this.replicaTables.has(props.region)) {
throw new Error(`Duplicate replica table region, ${props.region}, is not allowed`);
}
if (this.billingMode === BillingMode.PAY_PER_REQUEST && props.readCapacity) {
throw new Error(`You cannot provide 'readCapacity' on a replica table when the billing mode is ${BillingMode.PAY_PER_REQUEST}`);
}
}
private validateGlobalSecondaryIndex(props: GlobalSecondaryIndexPropsV2) {
this.validateIndexName(props.indexName);
if (this.globalSecondaryIndexes.size === MAX_GSI_COUNT) {
throw new Error(`You may not provide more than ${MAX_GSI_COUNT} global secondary indexes`);
}
if (this.billingMode === BillingMode.PAY_PER_REQUEST && (props.readCapacity || props.writeCapacity)) {
throw new Error(`You cannot configure 'readCapacity' or 'writeCapacity' on a global secondary index when the billing mode is ${BillingMode.PAY_PER_REQUEST}`);
}
}
private validateLocalSecondaryIndex(props: LocalSecondaryIndexProps) {
this.validateIndexName(props.indexName);
if (!this.hasSortKey) {
throw new Error('The table must have a sort key in order to add a local secondary index');
}
if (this.localSecondaryIndexes.size === MAX_LSI_COUNT) {
throw new Error(`You may not provide more than ${MAX_LSI_COUNT} local secondary indexes`);
}
}
}