-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
table.ts
927 lines (808 loc) · 30 KB
/
table.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
import * as appscaling from '@aws-cdk/aws-applicationautoscaling';
import * as iam from '@aws-cdk/aws-iam';
import { Aws, Construct, IResource, Lazy, RemovalPolicy, Resource, Stack } from '@aws-cdk/core';
import { CfnTable } from './dynamodb.generated';
import { EnableScalingProps, IScalableTableAttribute } from './scalable-attribute-api';
import { ScalableTableAttribute } from './scalable-table-attribute';
const HASH_KEY_TYPE = 'HASH';
const RANGE_KEY_TYPE = 'RANGE';
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-secondary-indexes
const MAX_LOCAL_SECONDARY_INDEX_COUNT = 5;
const READ_DATA_ACTIONS = [
'dynamodb:BatchGetItem',
'dynamodb:GetRecords',
'dynamodb:GetShardIterator',
'dynamodb:Query',
'dynamodb:GetItem',
'dynamodb:Scan'
];
const READ_STREAM_DATA_ACTIONS = [
"dynamodb:DescribeStream",
"dynamodb:GetRecords",
"dynamodb:GetShardIterator",
];
const WRITE_DATA_ACTIONS = [
'dynamodb:BatchWriteItem',
'dynamodb:PutItem',
'dynamodb:UpdateItem',
'dynamodb:DeleteItem'
];
export interface Attribute {
/**
* The name of an attribute.
*/
readonly name: string;
/**
* The data type of an attribute.
*/
readonly type: AttributeType;
}
export interface TableOptions {
/**
* Partition key attribute definition.
*/
readonly partitionKey: Attribute;
/**
* Table sort key attribute definition.
*
* @default no sort key
*/
readonly sortKey?: Attribute;
/**
* The read capacity for the table. Careful if you add Global Secondary Indexes, as
* those will share the table's provisioned throughput.
*
* Can only be provided if billingMode is Provisioned.
*
* @default 5
*/
readonly readCapacity?: number;
/**
* The write capacity for the table. Careful if you add Global Secondary Indexes, as
* those will share the table's provisioned throughput.
*
* Can only be provided if billingMode is Provisioned.
*
* @default 5
*/
readonly writeCapacity?: number;
/**
* Specify how you are charged for read and write throughput and how you manage capacity.
* @default Provisioned
*/
readonly billingMode?: BillingMode;
/**
* Whether point-in-time recovery is enabled.
* @default - point-in-time recovery is disabled
*/
readonly pointInTimeRecovery?: boolean;
/**
* Whether server-side encryption with an AWS managed customer master key is enabled.
* @default - server-side encryption is enabled with an AWS owned customer master key
*/
readonly serverSideEncryption?: boolean;
/**
* The name of 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 for this table.
*
* @default - streams are disabled
*/
readonly stream?: StreamViewType;
/**
* The removal policy to apply to the DynamoDB Table.
*
* @default RemovalPolicy.RETAIN
*/
readonly removalPolicy?: RemovalPolicy;
}
export interface TableProps extends TableOptions {
/**
* Enforces a particular physical table name.
* @default <generated>
*/
readonly tableName?: string;
}
export interface SecondaryIndexProps {
/**
* The name of the secondary index.
*/
readonly indexName: string;
/**
* The set of attributes that are projected into the secondary index.
* @default ALL
*/
readonly projectionType?: ProjectionType;
/**
* The non-key attributes that are projected into the secondary index.
* @default - No additional attributes
*/
readonly nonKeyAttributes?: string[];
}
export interface GlobalSecondaryIndexProps extends SecondaryIndexProps {
/**
* The attribute of a partition key for the global secondary index.
*/
readonly partitionKey: Attribute;
/**
* The attribute of a sort key for the global secondary index.
* @default - No sort key
*/
readonly sortKey?: Attribute;
/**
* The read capacity for the global secondary index.
*
* Can only be provided if table billingMode is Provisioned or undefined.
*
* @default 5
*/
readonly readCapacity?: number;
/**
* The write capacity for the global secondary index.
*
* Can only be provided if table billingMode is Provisioned or undefined.
*
* @default 5
*/
readonly writeCapacity?: number;
}
export interface LocalSecondaryIndexProps extends SecondaryIndexProps {
/**
* The attribute of a sort key for the local secondary index.
*/
readonly sortKey: Attribute;
}
/**
* An interface that represents a DynamoDB Table - either created with the CDK, or an existing one.
*/
export interface ITable extends IResource {
/**
* Arn of the dynamodb table.
*
* @attribute
*/
readonly tableArn: string;
/**
* Table name of the dynamodb table.
*
* @attribute
*/
readonly tableName: string;
/**
* Permits an IAM principal all data read operations from this table:
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan.
* @param grantee The principal to grant access to
*/
grantReadData(grantee: iam.IGrantable): iam.Grant;
/**
* Permits an IAM Principal to list streams attached to current dynamodb table.
*
* @param grantee The principal (no-op if undefined)
*/
grantTableListStreams(grantee: iam.IGrantable): iam.Grant;
/**
* Permits an IAM principal all stream data read operations for this
* table's stream:
* DescribeStream, GetRecords, GetShardIterator, ListStreams.
* @param grantee The principal to grant access to
*/
grantStreamRead(grantee: iam.IGrantable): iam.Grant;
/**
* Permits an IAM principal all data write operations to this table:
* BatchWriteItem, PutItem, UpdateItem, DeleteItem.
* @param grantee The principal to grant access to
*/
grantWriteData(grantee: iam.IGrantable): iam.Grant;
/**
* Permits an IAM principal to all data read/write operations to this table.
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan,
* BatchWriteItem, PutItem, UpdateItem, DeleteItem
* @param grantee The principal to grant access to
*/
grantReadWriteData(grantee: iam.IGrantable): iam.Grant;
}
/**
* Reference to a dynamodb table.
*/
export interface TableAttributes {
/**
* The ARN of the dynamodb table.
* One of this, or {@link tabeName}, is required.
*
* @default no table arn
*/
readonly tableArn?: string;
/**
* The table name of the dynamodb table.
* One of this, or {@link tabeArn}, is required.
*
* @default no table name
*/
readonly tableName?: string;
}
abstract class TableBase extends Resource implements ITable {
/**
* @attribute
*/
public abstract readonly tableArn: string;
/**
* @attribute
*/
public abstract readonly tableName: string;
/**
* Adds an IAM policy statement associated with this table to an IAM
* principal's policy.
* @param grantee The principal (no-op if undefined)
* @param actions The set of actions to allow (i.e. "dynamodb:PutItem", "dynamodb:GetItem", ...)
*/
public grant(grantee: iam.IGrantable, ...actions: string[]): iam.Grant {
return iam.Grant.addToPrincipal({
grantee,
actions,
resourceArns: [
this.tableArn,
Lazy.stringValue({ produce: () => this.hasIndex ? `${this.tableArn}/index/*` : Aws.NO_VALUE })
],
scope: this,
});
}
/**
* Permits an IAM principal all data read operations from this table:
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan.
* @param grantee The principal to grant access to
*/
public grantReadData(grantee: iam.IGrantable): iam.Grant {
return this.grant(grantee, ...READ_DATA_ACTIONS);
}
/**
* Permits an IAM Principal to list streams attached to current dynamodb table.
*
* @param _grantee The principal (no-op if undefined)
*/
public abstract grantTableListStreams(_grantee: iam.IGrantable): iam.Grant;
/**
* Permits an IAM principal all stream data read operations for this
* table's stream:
* DescribeStream, GetRecords, GetShardIterator, ListStreams.
* @param grantee The principal to grant access to
*/
public abstract grantStreamRead(grantee: iam.IGrantable): iam.Grant;
/**
* Permits an IAM principal all data write operations to this table:
* BatchWriteItem, PutItem, UpdateItem, DeleteItem.
* @param grantee The principal to grant access to
*/
public grantWriteData(grantee: iam.IGrantable): iam.Grant {
return this.grant(grantee, ...WRITE_DATA_ACTIONS);
}
/**
* Permits an IAM principal to all data read/write operations to this table.
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan,
* BatchWriteItem, PutItem, UpdateItem, DeleteItem
* @param grantee The principal to grant access to
*/
public grantReadWriteData(grantee: iam.IGrantable): iam.Grant {
return this.grant(grantee, ...READ_DATA_ACTIONS, ...WRITE_DATA_ACTIONS);
}
/**
* Permits all DynamoDB operations ("dynamodb:*") to an IAM principal.
* @param grantee The principal to grant access to
*/
public grantFullAccess(grantee: iam.IGrantable) {
return this.grant(grantee, 'dynamodb:*');
}
protected abstract get hasIndex(): boolean;
}
/**
* Provides a DynamoDB table.
*/
export class Table extends TableBase {
/**
* Permits an IAM Principal to list all DynamoDB Streams.
* @deprecated Use {@link #grantTableListStreams} for more granular permission
* @param grantee The principal (no-op if undefined)
*/
public static grantListStreams(grantee: iam.IGrantable): iam.Grant {
return iam.Grant.addToPrincipal({
grantee,
actions: ['dynamodb:ListStreams'],
resourceArns: ['*'],
});
}
/**
* 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): ITable {
return Table.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): ITable {
return Table.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 A `TableAttributes` object.
*/
public static fromTableAttributes(scope: Construct, id: string, attrs: TableAttributes): ITable {
class Import extends TableBase {
public readonly tableName: string;
public readonly tableArn: string;
constructor(_scope: Construct, _id: string, _tableArn: string, _tableName: string) {
super(_scope, _id);
this.tableArn = _tableArn;
this.tableName = _tableName;
}
protected get hasIndex(): boolean {
return false;
}
public grantTableListStreams(_grantee: iam.IGrantable): iam.Grant {
throw new Error("Method not implemented.");
}
public grantStreamRead(_grantee: iam.IGrantable): iam.Grant {
throw new Error("Method not implemented.");
}
}
let tableName: string;
let tableArn: string;
const stack = Stack.of(scope);
if (!attrs.tableName) {
if (!attrs.tableArn) { throw new Error('One of tableName or tableArn is required!'); }
tableArn = attrs.tableArn;
const maybeTableName = stack.parseArn(attrs.tableArn).resourceName;
if (!maybeTableName) { throw new Error('ARN for DynamoDB table must be in the form: ...'); }
tableName = maybeTableName;
} else {
if (attrs.tableArn) { throw new Error("Only one of tableArn or tableName can be provided"); }
tableName = attrs.tableName;
tableArn = stack.formatArn({
service: 'dynamodb',
resource: 'table',
resourceName: attrs.tableName,
});
}
return new Import(scope, id, tableArn, tableName);
}
/**
* @attribute
*/
public readonly tableArn: string;
/**
* @attribute
*/
public readonly tableName: string;
/**
* @attribute
*/
public readonly tableStreamArn: string | undefined;
private readonly table: CfnTable;
private readonly keySchema = new Array<CfnTable.KeySchemaProperty>();
private readonly attributeDefinitions = new Array<CfnTable.AttributeDefinitionProperty>();
private readonly globalSecondaryIndexes = new Array<CfnTable.GlobalSecondaryIndexProperty>();
private readonly localSecondaryIndexes = new Array<CfnTable.LocalSecondaryIndexProperty>();
private readonly secondaryIndexNames: string[] = [];
private readonly nonKeyAttributes: string[] = [];
private readonly tablePartitionKey: Attribute;
private readonly tableSortKey?: Attribute;
private readonly billingMode: BillingMode;
private readonly tableScaling: ScalableAttributePair = {};
private readonly indexScaling = new Map<string, ScalableAttributePair>();
private readonly scalingRole: iam.IRole;
constructor(scope: Construct, id: string, props: TableProps) {
super(scope, id, {
physicalName: props.tableName,
});
this.billingMode = props.billingMode || BillingMode.PROVISIONED;
this.validateProvisioning(props);
this.table = new CfnTable(this, 'Resource', {
tableName: this.physicalName,
keySchema: this.keySchema,
attributeDefinitions: this.attributeDefinitions,
globalSecondaryIndexes: Lazy.anyValue({ produce: () => this.globalSecondaryIndexes }, { omitEmptyArray: true }),
localSecondaryIndexes: Lazy.anyValue({ produce: () => this.localSecondaryIndexes }, { omitEmptyArray: true }),
pointInTimeRecoverySpecification: props.pointInTimeRecovery ? { pointInTimeRecoveryEnabled: props.pointInTimeRecovery } : undefined,
billingMode: this.billingMode === BillingMode.PAY_PER_REQUEST ? this.billingMode : undefined,
provisionedThroughput: props.billingMode === BillingMode.PAY_PER_REQUEST ? undefined : {
readCapacityUnits: props.readCapacity || 5,
writeCapacityUnits: props.writeCapacity || 5
},
sseSpecification: props.serverSideEncryption ? { sseEnabled: props.serverSideEncryption } : undefined,
streamSpecification: props.stream ? { streamViewType: props.stream } : undefined,
timeToLiveSpecification: props.timeToLiveAttribute ? { attributeName: props.timeToLiveAttribute, enabled: true } : undefined
});
this.table.applyRemovalPolicy(props.removalPolicy);
if (props.tableName) { this.node.addMetadata('aws:cdk:hasPhysicalName', props.tableName); }
this.tableArn = this.getResourceArnAttribute(this.table.attrArn, {
service: 'dynamodb',
resource: 'table',
resourceName: this.physicalName,
});
this.tableName = this.getResourceNameAttribute(this.table.ref);
this.tableStreamArn = props.stream ? this.table.attrStreamArn : undefined;
this.scalingRole = this.makeScalingRole();
this.addKey(props.partitionKey, HASH_KEY_TYPE);
this.tablePartitionKey = props.partitionKey;
if (props.sortKey) {
this.addKey(props.sortKey, RANGE_KEY_TYPE);
this.tableSortKey = props.sortKey;
}
}
/**
* Adds an IAM policy statement associated with this table's stream to an
* IAM principal's policy.
* @param grantee The principal (no-op if undefined)
* @param actions The set of actions to allow (i.e. "dynamodb:DescribeStream", "dynamodb:GetRecords", ...)
*/
public grantStream(grantee: iam.IGrantable, ...actions: string[]): iam.Grant {
if (!this.tableStreamArn) {
throw new Error(`DynamoDB Streams must be enabled on the table ${this.node.path}`);
}
return iam.Grant.addToPrincipal({
grantee,
actions,
resourceArns: [this.tableStreamArn],
scope: this,
});
}
/**
* Permits an IAM Principal to list streams attached to current dynamodb table.
*
* @param grantee The principal (no-op if undefined)
*/
public grantTableListStreams(grantee: iam.IGrantable): iam.Grant {
if (!this.tableStreamArn) {
throw new Error(`DynamoDB Streams must be enabled on the table ${this.node.path}`);
}
return iam.Grant.addToPrincipal({
grantee,
actions: ['dynamodb:ListStreams'],
resourceArns: [
Lazy.stringValue({ produce: () => `${this.tableArn}/stream/*` })
],
});
}
/**
* Permits an IAM principal all stream data read operations for this
* table's stream:
* DescribeStream, GetRecords, GetShardIterator, ListStreams.
* @param grantee The principal to grant access to
*/
public grantStreamRead(grantee: iam.IGrantable): iam.Grant {
this.grantTableListStreams(grantee);
return this.grantStream(grantee, ...READ_STREAM_DATA_ACTIONS);
}
/**
* Add a global secondary index of table.
*
* @param props the property of global secondary index
*/
public addGlobalSecondaryIndex(props: GlobalSecondaryIndexProps) {
this.validateProvisioning(props);
this.validateIndexName(props.indexName);
// build key schema and projection for index
const gsiKeySchema = this.buildIndexKeySchema(props.partitionKey, props.sortKey);
const gsiProjection = this.buildIndexProjection(props);
this.secondaryIndexNames.push(props.indexName);
this.globalSecondaryIndexes.push({
indexName: props.indexName,
keySchema: gsiKeySchema,
projection: gsiProjection,
provisionedThroughput: this.billingMode === BillingMode.PAY_PER_REQUEST ? undefined : {
readCapacityUnits: props.readCapacity || 5,
writeCapacityUnits: props.writeCapacity || 5
}
});
this.indexScaling.set(props.indexName, {});
}
/**
* Add a local secondary index of table.
*
* @param props the property of local secondary index
*/
public addLocalSecondaryIndex(props: LocalSecondaryIndexProps) {
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-secondary-indexes
if (this.localSecondaryIndexes.length >= MAX_LOCAL_SECONDARY_INDEX_COUNT) {
throw new RangeError(`a maximum number of local secondary index per table is ${MAX_LOCAL_SECONDARY_INDEX_COUNT}`);
}
this.validateIndexName(props.indexName);
// build key schema and projection for index
const lsiKeySchema = this.buildIndexKeySchema(this.tablePartitionKey, props.sortKey);
const lsiProjection = this.buildIndexProjection(props);
this.secondaryIndexNames.push(props.indexName);
this.localSecondaryIndexes.push({
indexName: props.indexName,
keySchema: lsiKeySchema,
projection: lsiProjection
});
}
/**
* Enable read capacity scaling for this table
*
* @returns An object to configure additional AutoScaling settings
*/
public autoScaleReadCapacity(props: EnableScalingProps): IScalableTableAttribute {
if (this.tableScaling.scalableReadAttribute) {
throw new Error('Read AutoScaling already enabled for this table');
}
if (this.billingMode === BillingMode.PAY_PER_REQUEST) {
throw new Error('AutoScaling is not available for tables with PAY_PER_REQUEST billing mode');
}
return this.tableScaling.scalableReadAttribute = new ScalableTableAttribute(this, 'ReadScaling', {
serviceNamespace: appscaling.ServiceNamespace.DYNAMODB,
resourceId: `table/${this.tableName}`,
dimension: 'dynamodb:table:ReadCapacityUnits',
role: this.scalingRole,
...props
});
}
/**
* Enable write capacity scaling for this table
*
* @returns An object to configure additional AutoScaling settings for this attribute
*/
public autoScaleWriteCapacity(props: EnableScalingProps): IScalableTableAttribute {
if (this.tableScaling.scalableWriteAttribute) {
throw new Error('Write AutoScaling already enabled for this table');
}
if (this.billingMode === BillingMode.PAY_PER_REQUEST) {
throw new Error('AutoScaling is not available for tables with PAY_PER_REQUEST billing mode');
}
return this.tableScaling.scalableWriteAttribute = new ScalableTableAttribute(this, 'WriteScaling', {
serviceNamespace: appscaling.ServiceNamespace.DYNAMODB,
resourceId: `table/${this.tableName}`,
dimension: 'dynamodb:table:WriteCapacityUnits',
role: this.scalingRole,
...props,
});
}
/**
* Enable read capacity scaling for the given GSI
*
* @returns An object to configure additional AutoScaling settings for this attribute
*/
public autoScaleGlobalSecondaryIndexReadCapacity(indexName: string, props: EnableScalingProps): IScalableTableAttribute {
if (this.billingMode === BillingMode.PAY_PER_REQUEST) {
throw new Error('AutoScaling is not available for tables with PAY_PER_REQUEST billing mode');
}
const attributePair = this.indexScaling.get(indexName);
if (!attributePair) {
throw new Error(`No global secondary index with name ${indexName}`);
}
if (attributePair.scalableReadAttribute) {
throw new Error('Read AutoScaling already enabled for this index');
}
return attributePair.scalableReadAttribute = new ScalableTableAttribute(this, `${indexName}ReadScaling`, {
serviceNamespace: appscaling.ServiceNamespace.DYNAMODB,
resourceId: `table/${this.tableName}/index/${indexName}`,
dimension: 'dynamodb:index:ReadCapacityUnits',
role: this.scalingRole,
...props
});
}
/**
* Enable write capacity scaling for the given GSI
*
* @returns An object to configure additional AutoScaling settings for this attribute
*/
public autoScaleGlobalSecondaryIndexWriteCapacity(indexName: string, props: EnableScalingProps): IScalableTableAttribute {
if (this.billingMode === BillingMode.PAY_PER_REQUEST) {
throw new Error('AutoScaling is not available for tables with PAY_PER_REQUEST billing mode');
}
const attributePair = this.indexScaling.get(indexName);
if (!attributePair) {
throw new Error(`No global secondary index with name ${indexName}`);
}
if (attributePair.scalableWriteAttribute) {
throw new Error('Write AutoScaling already enabled for this index');
}
return attributePair.scalableWriteAttribute = new ScalableTableAttribute(this, `${indexName}WriteScaling`, {
serviceNamespace: appscaling.ServiceNamespace.DYNAMODB,
resourceId: `table/${this.tableName}/index/${indexName}`,
dimension: 'dynamodb:index:WriteCapacityUnits',
role: this.scalingRole,
...props
});
}
/**
* Validate the table construct.
*
* @returns an array of validation error message
*/
protected validate(): string[] {
const errors = new Array<string>();
if (!this.tablePartitionKey) {
errors.push('a partition key must be specified');
}
if (this.localSecondaryIndexes.length > 0 && !this.tableSortKey) {
errors.push('a sort key of the table must be specified to add local secondary indexes');
}
return errors;
}
/**
* Validate read and write capacity are not specified for on-demand tables (billing mode PAY_PER_REQUEST).
*
* @param props read and write capacity properties
*/
private validateProvisioning(props: { readCapacity?: number, writeCapacity?: number }): void {
if (this.billingMode === BillingMode.PAY_PER_REQUEST) {
if (props.readCapacity !== undefined || props.writeCapacity !== undefined) {
throw new Error('you cannot provision read and write capacity for a table with PAY_PER_REQUEST billing mode');
}
}
}
/**
* Validate index name to check if a duplicate name already exists.
*
* @param indexName a name of global or local secondary index
*/
private validateIndexName(indexName: string) {
if (this.secondaryIndexNames.includes(indexName)) {
// a duplicate index name causes validation exception, status code 400, while trying to create CFN stack
throw new Error(`a duplicate index name, ${indexName}, is not allowed`);
}
this.secondaryIndexNames.push(indexName);
}
/**
* Validate non-key attributes by checking limits within secondary index, which may vary in future.
*
* @param nonKeyAttributes a list of non-key attribute names
*/
private validateNonKeyAttributes(nonKeyAttributes: string[]) {
if (this.nonKeyAttributes.length + nonKeyAttributes.length > 20) {
// https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Limits.html#limits-secondary-indexes
throw new RangeError('a maximum number of nonKeyAttributes across all of secondary indexes is 20');
}
// store all non-key attributes
this.nonKeyAttributes.push(...nonKeyAttributes);
// throw error if key attribute is part of non-key attributes
this.attributeDefinitions.forEach(keyAttribute => {
if (typeof keyAttribute.attributeName === 'string' && this.nonKeyAttributes.includes(keyAttribute.attributeName)) {
throw new Error(`a key attribute, ${keyAttribute.attributeName}, is part of a list of non-key attributes, ${this.nonKeyAttributes}` +
', which is not allowed since all key attributes are added automatically and this configuration causes stack creation failure');
}
});
}
private buildIndexKeySchema(partitionKey: Attribute, sortKey?: Attribute): CfnTable.KeySchemaProperty[] {
this.registerAttribute(partitionKey);
const indexKeySchema: CfnTable.KeySchemaProperty[] = [
{ attributeName: partitionKey.name, keyType: HASH_KEY_TYPE }
];
if (sortKey) {
this.registerAttribute(sortKey);
indexKeySchema.push({ attributeName: sortKey.name, keyType: RANGE_KEY_TYPE });
}
return indexKeySchema;
}
private buildIndexProjection(props: SecondaryIndexProps): CfnTable.ProjectionProperty {
if (props.projectionType === ProjectionType.INCLUDE && !props.nonKeyAttributes) {
// https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-dynamodb-projectionobject.html
throw new Error(`non-key attributes should be specified when using ${ProjectionType.INCLUDE} projection type`);
}
if (props.projectionType !== ProjectionType.INCLUDE && props.nonKeyAttributes) {
// this combination causes validation exception, status code 400, while trying to create CFN stack
throw new Error(`non-key attributes should not be specified when not using ${ProjectionType.INCLUDE} projection type`);
}
if (props.nonKeyAttributes) {
this.validateNonKeyAttributes(props.nonKeyAttributes);
}
return {
projectionType: props.projectionType ? props.projectionType : ProjectionType.ALL,
nonKeyAttributes: props.nonKeyAttributes ? props.nonKeyAttributes : undefined
};
}
private findKey(keyType: string) {
return this.keySchema.find(prop => prop.keyType === keyType);
}
private addKey(attribute: Attribute, keyType: string) {
const existingProp = this.findKey(keyType);
if (existingProp) {
throw new Error(`Unable to set ${attribute.name} as a ${keyType} key, because ${existingProp.attributeName} is a ${keyType} key`);
}
this.registerAttribute(attribute);
this.keySchema.push({
attributeName: attribute.name,
keyType
});
return this;
}
/**
* Register the key attribute of table or secondary index to assemble attribute definitions of TableResourceProps.
*
* @param attribute the key attribute of table or secondary index
*/
private registerAttribute(attribute: Attribute) {
const name = attribute.name;
const type = attribute.type;
const existingDef = this.attributeDefinitions.find(def => def.attributeName === name);
if (existingDef && existingDef.attributeType !== type) {
throw new Error(`Unable to specify ${name} as ${type} because it was already defined as ${existingDef.attributeType}`);
}
if (!existingDef) {
this.attributeDefinitions.push({
attributeName: name,
attributeType: type
});
}
}
/**
* Return the role that will be used for AutoScaling
*/
private makeScalingRole(): iam.IRole {
// Use a Service Linked Role.
// https://docs.aws.amazon.com/autoscaling/application/userguide/application-auto-scaling-service-linked-roles.html
return iam.Role.fromRoleArn(this, 'ScalingRole', Stack.of(this).formatArn({
service: 'iam',
region: '',
resource: 'role/aws-service-role/dynamodb.application-autoscaling.amazonaws.com',
resourceName: 'AWSServiceRoleForApplicationAutoScaling_DynamoDBTable'
}));
}
/**
* Whether this table has indexes
*/
protected get hasIndex(): boolean {
return this.globalSecondaryIndexes.length + this.localSecondaryIndexes.length > 0;
}
}
export enum AttributeType {
BINARY = 'B',
NUMBER = 'N',
STRING = 'S',
}
/**
* DyanmoDB's Read/Write capacity modes.
*/
export enum BillingMode {
/**
* Pay only for what you use. You don't configure Read/Write capacity units.
*/
PAY_PER_REQUEST = 'PAY_PER_REQUEST',
/**
* Explicitly specified Read/Write capacity units.
*/
PROVISIONED = 'PROVISIONED',
}
export enum ProjectionType {
KEYS_ONLY = 'KEYS_ONLY',
INCLUDE = 'INCLUDE',
ALL = 'ALL'
}
/**
* When an item in the table is modified, StreamViewType determines what information
* is written to the stream for this table.
*
* @see https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_StreamSpecification.html
*/
export enum StreamViewType {
/** The entire item, as it appears after it was modified, is written to the stream. */
NEW_IMAGE = 'NEW_IMAGE',
/** The entire item, as it appeared before it was modified, is written to the stream. */
OLD_IMAGE = 'OLD_IMAGE',
/** Both the new and the old item images of the item are written to the stream. */
NEW_AND_OLD_IMAGES = 'NEW_AND_OLD_IMAGES',
/** Only the key attributes of the modified item are written to the stream. */
KEYS_ONLY = 'KEYS_ONLY'
}
/**
* Just a convenient way to keep track of both attributes
*/
interface ScalableAttributePair {
scalableReadAttribute?: ScalableTableAttribute;
scalableWriteAttribute?: ScalableTableAttribute;
}