-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
table.ts
1861 lines (1625 loc) · 63.4 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
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
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import * as appscaling from '@aws-cdk/aws-applicationautoscaling';
import * as cloudwatch from '@aws-cdk/aws-cloudwatch';
import * as iam from '@aws-cdk/aws-iam';
import * as kinesis from '@aws-cdk/aws-kinesis';
import * as kms from '@aws-cdk/aws-kms';
import {
ArnFormat,
Aws, CfnCondition, CfnCustomResource, CfnResource, CustomResource, Duration,
Fn, IResource, Lazy, Names, RemovalPolicy, Resource, Stack, Token,
} from '@aws-cdk/core';
import { Construct } from 'constructs';
import { DynamoDBMetrics } from './dynamodb-canned-metrics.generated';
import { CfnTable, CfnTableProps } from './dynamodb.generated';
import * as perms from './perms';
import { ReplicaProvider } from './replica-provider';
import { EnableScalingProps, IScalableTableAttribute } from './scalable-attribute-api';
import { ScalableTableAttribute } from './scalable-table-attribute';
// keep this import separate from other imports to reduce chance for merge conflicts with v2-main
// eslint-disable-next-line no-duplicate-imports, import/order
import { Construct as CoreConstruct } from '@aws-cdk/core';
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;
/**
* Options for configuring a system errors metric that considers multiple operations.
*/
export interface SystemErrorsForOperationsMetricOptions extends cloudwatch.MetricOptions {
/**
* The operations to apply the metric to.
*
* @default - All operations available by DynamoDB tables will be considered.
*/
readonly operations?: Operation[];
}
/**
* Supported DynamoDB table operations.
*/
export enum Operation {
/** GetItem */
GET_ITEM = 'GetItem',
/** BatchGetItem */
BATCH_GET_ITEM = 'BatchGetItem',
/** Scan */
SCAN = 'Scan',
/** Query */
QUERY = 'Query',
/** GetRecords */
GET_RECORDS = 'GetRecords',
/** PutItem */
PUT_ITEM = 'PutItem',
/** DeleteItem */
DELETE_ITEM = 'DeleteItem',
/** UpdateItem */
UPDATE_ITEM = 'UpdateItem',
/** BatchWriteItem */
BATCH_WRITE_ITEM = 'BatchWriteItem',
/** TransactWriteItems */
TRANSACT_WRITE_ITEMS = 'TransactWriteItems',
/** TransactGetItems */
TRANSACT_GET_ITEMS = 'TransactGetItems',
/** ExecuteTransaction */
EXECUTE_TRANSACTION = 'ExecuteTransaction',
/** BatchExecuteStatement */
BATCH_EXECUTE_STATEMENT = 'BatchExecuteStatement',
/** ExecuteStatement */
EXECUTE_STATEMENT = 'ExecuteStatement',
}
/**
* Represents an attribute for describing the key schema for the table
* and indexes.
*/
export interface Attribute {
/**
* The name of an attribute.
*/
readonly name: string;
/**
* The data type of an attribute.
*/
readonly type: AttributeType;
}
/**
* What kind of server-side encryption to apply to this table.
*/
export enum TableEncryption {
/**
* Server-side KMS encryption with a master key owned by AWS.
*/
DEFAULT = 'AWS_OWNED',
/**
* Server-side KMS encryption with a customer master key managed by customer.
* If `encryptionKey` is specified, this key will be used, otherwise, one will be defined.
*
* > **NOTE**: if `encryptionKey` is not specified and the `Table` construct creates
* > a KMS key for you, the key will be created with default permissions. If you are using
* > CDKv2, these permissions will be sufficient to enable the key for use with DynamoDB tables.
* > If you are using CDKv1, make sure the feature flag `@aws-cdk/aws-kms:defaultKeyPolicies`
* > is set to `true` in your `cdk.json`.
*/
CUSTOMER_MANAGED = 'CUSTOMER_MANAGED',
/**
* Server-side KMS encryption with a master key managed by AWS.
*/
AWS_MANAGED = 'AWS_MANAGED',
}
/**
* Represents the table schema attributes.
*/
export interface SchemaOptions {
/**
* Partition key attribute definition.
*/
readonly partitionKey: Attribute;
/**
* Sort key attribute definition.
*
* @default no sort key
*/
readonly sortKey?: Attribute;
}
/**
* Properties of a DynamoDB Table
*
* Use {@link TableProps} for all table properties
*/
export interface TableOptions extends SchemaOptions {
/**
* 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 if `replicationRegions` is not specified, PAY_PER_REQUEST otherwise
*/
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.
*
* This property cannot be set if `encryption` and/or `encryptionKey` is set.
*
* @default - server-side encryption is enabled with an AWS owned customer master key
*
* @deprecated This property is deprecated. In order to obtain the same behavior as
* enabling this, set the `encryption` property to `TableEncryption.AWS_MANAGED` instead.
*/
readonly serverSideEncryption?: boolean;
/**
* Specify the table class.
* @default STANDARD
*/
readonly tableClass?: TableClass;
/**
* Whether server-side encryption with an AWS managed customer master key is enabled.
*
* This property cannot be set if `serverSideEncryption` is set.
*
* > **NOTE**: if you set this to `CUSTOMER_MANAGED` and `encryptionKey` is not
* > specified, the key that the Tablet generates for you will be created with
* > default permissions. If you are using CDKv2, these permissions will be
* > sufficient to enable the key for use with DynamoDB tables. If you are
* > using CDKv1, make sure the feature flag
* > `@aws-cdk/aws-kms:defaultKeyPolicies` is set to `true` in your `cdk.json`.
*
* @default - server-side encryption is enabled with an AWS owned customer master key
*/
readonly encryption?: TableEncryption;
/**
* External KMS key to use for table encryption.
*
* This property can only be set if `encryption` is set to `TableEncryption.CUSTOMER_MANAGED`.
*
* @default - If `encryption` is set to `TableEncryption.CUSTOMER_MANAGED` and this
* property is undefined, a new KMS key will be created and associated with this table.
*/
readonly encryptionKey?: kms.IKey;
/**
* 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 unless `replicationRegions` is specified
*/
readonly stream?: StreamViewType;
/**
* The removal policy to apply to the DynamoDB Table.
*
* @default RemovalPolicy.RETAIN
*/
readonly removalPolicy?: RemovalPolicy;
/**
* Regions where replica tables will be created
*
* @default - no replica tables are created
*/
readonly replicationRegions?: string[];
/**
* The timeout for a table replication operation in a single region.
*
* @default Duration.minutes(30)
*/
readonly replicationTimeout?: Duration;
/**
* Indicates whether CloudFormation stack waits for replication to finish.
* If set to false, the CloudFormation resource will mark the resource as
* created and replication will be completed asynchronously. This property is
* ignored if replicationRegions property is not set.
*
* DO NOT UNSET this property if adding/removing multiple replicationRegions
* in one deployment, as CloudFormation only supports one region replication
* at a time. CDK overcomes this limitation by waiting for replication to
* finish before starting new replicationRegion.
*
* @see https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-dynamodb-globaltable.html#cfn-dynamodb-globaltable-replicas
* @default true
*/
readonly waitForReplicationToFinish?: boolean;
/**
* Whether CloudWatch contributor insights is enabled.
*
* @default false
*/
readonly contributorInsightsEnabled?: boolean;
}
/**
* Properties for a DynamoDB Table
*/
export interface TableProps extends TableOptions {
/**
* Enforces a particular physical table name.
* @default <generated>
*/
readonly tableName?: string;
/**
* Kinesis Data Stream to capture item-level changes for the table.
*
* @default - no Kinesis Data Stream
*/
readonly kinesisStream?: kinesis.IStream;
}
/**
* Properties for a secondary index
*/
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[];
}
/**
* Properties for a global secondary index
*/
export interface GlobalSecondaryIndexProps extends SecondaryIndexProps, SchemaOptions {
/**
* 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;
}
/**
* Properties for a local secondary index
*/
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;
/**
* ARN of the table's stream, if there is one.
*
* @attribute
*/
readonly tableStreamArn?: string;
/**
*
* Optional KMS encryption key associated with this table.
*/
readonly encryptionKey?: kms.IKey;
/**
* Adds an IAM policy statement associated with this table to an IAM
* principal's policy.
*
* If `encryptionKey` is present, appropriate grants to the key needs to be added
* separately using the `table.encryptionKey.grant*` methods.
*
* @param grantee The principal (no-op if undefined)
* @param actions The set of actions to allow (i.e. "dynamodb:PutItem", "dynamodb:GetItem", ...)
*/
grant(grantee: iam.IGrantable, ...actions: string[]): iam.Grant;
/**
* Adds an IAM policy statement associated with this table's stream to an
* IAM principal's policy.
*
* If `encryptionKey` is present, appropriate grants to the key needs to be added
* separately using the `table.encryptionKey.grant*` methods.
*
* @param grantee The principal (no-op if undefined)
* @param actions The set of actions to allow (i.e. "dynamodb:DescribeStream", "dynamodb:GetRecords", ...)
*/
grantStream(grantee: iam.IGrantable, ...actions: string[]): iam.Grant;
/**
* Permits an IAM principal all data read operations from this table:
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @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.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @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.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @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
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
grantReadWriteData(grantee: iam.IGrantable): iam.Grant;
/**
* Permits all DynamoDB operations ("dynamodb:*") to an IAM principal.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
grantFullAccess(grantee: iam.IGrantable): iam.Grant;
/**
* Metric for the number of Errors executing all Lambdas
*/
metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for the consumed read capacity units
*
* @param props properties of a metric
*/
metricConsumedReadCapacityUnits(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for the consumed write capacity units
*
* @param props properties of a metric
*/
metricConsumedWriteCapacityUnits(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for the system errors
*
* @param props properties of a metric
*
* @deprecated use `metricSystemErrorsForOperations`
*/
metricSystemErrors(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for the system errors this table
*
* @param props properties of a metric
*
*/
metricSystemErrorsForOperations(props?: SystemErrorsForOperationsMetricOptions): cloudwatch.IMetric;
/**
* Metric for the user errors
*
* @param props properties of a metric
*/
metricUserErrors(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for the conditional check failed requests
*
* @param props properties of a metric
*/
metricConditionalCheckFailedRequests(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for throttled requests
*
* @param props properties of a metric
*
*/
metricThrottledRequests(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
/**
* Metric for the successful request latency
*
* @param props properties of a metric
*
*/
metricSuccessfulRequestLatency(props?: cloudwatch.MetricOptions): cloudwatch.Metric;
}
/**
* Reference to a dynamodb table.
*/
export interface TableAttributes {
/**
* The ARN of the dynamodb table.
* One of this, or {@link tableName}, is required.
*
* @default - no table arn
*/
readonly tableArn?: string;
/**
* The table name of the dynamodb table.
* One of this, or {@link tableArn}, is required.
*
* @default - no table name
*/
readonly tableName?: string;
/**
* The ARN of the table's stream.
*
* @default - no table stream
*/
readonly tableStreamArn?: string;
/**
* KMS encryption key, if this table uses a customer-managed encryption key.
*
* @default - no key
*/
readonly encryptionKey?: kms.IKey;
/**
* The name of the global indexes set for this Table.
* Note that you need to set either this property,
* or {@link localIndexes},
* if you want methods like grantReadData()
* to grant permissions for indexes as well as the table itself.
*
* @default - no global indexes
*/
readonly globalIndexes?: string[];
/**
* The name of the local indexes set for this Table.
* Note that you need to set either this property,
* or {@link globalIndexes},
* if you want methods like grantReadData()
* to grant permissions for indexes as well as the table itself.
*
* @default - no local indexes
*/
readonly localIndexes?: string[];
}
abstract class TableBase extends Resource implements ITable {
/**
* @attribute
*/
public abstract readonly tableArn: string;
/**
* @attribute
*/
public abstract readonly tableName: string;
/**
* @attribute
*/
public abstract readonly tableStreamArn?: string;
/**
* KMS encryption key, if this table uses a customer-managed encryption key.
*/
public abstract readonly encryptionKey?: kms.IKey;
protected readonly regionalArns = new Array<string>();
/**
* Adds an IAM policy statement associated with this table to an IAM
* principal's policy.
*
* If `encryptionKey` is present, appropriate grants to the key needs to be added
* separately using the `table.encryptionKey.grant*` methods.
*
* @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.string({ produce: () => this.hasIndex ? `${this.tableArn}/index/*` : Aws.NO_VALUE }),
...this.regionalArns,
...this.regionalArns.map(arn => Lazy.string({
produce: () => this.hasIndex ? `${arn}/index/*` : Aws.NO_VALUE,
})),
],
scope: this,
});
}
/**
* Adds an IAM policy statement associated with this table's stream to an
* IAM principal's policy.
*
* If `encryptionKey` is present, appropriate grants to the key needs to be added
* separately using the `table.encryptionKey.grant*` methods.
*
* @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 all data read operations from this table:
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan, DescribeTable.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
public grantReadData(grantee: iam.IGrantable): iam.Grant {
const tableActions = perms.READ_DATA_ACTIONS.concat(perms.DESCRIBE_TABLE);
return this.combinedGrant(grantee, { keyActions: perms.KEY_READ_ACTIONS, tableActions });
}
/**
* 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: ['*'],
});
}
/**
* Permits an IAM principal all stream data read operations for this
* table's stream:
* DescribeStream, GetRecords, GetShardIterator, ListStreams.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
public grantStreamRead(grantee: iam.IGrantable): iam.Grant {
this.grantTableListStreams(grantee);
return this.combinedGrant(grantee, { keyActions: perms.KEY_READ_ACTIONS, streamActions: perms.READ_STREAM_DATA_ACTIONS });
}
/**
* Permits an IAM principal all data write operations to this table:
* BatchWriteItem, PutItem, UpdateItem, DeleteItem, DescribeTable.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
public grantWriteData(grantee: iam.IGrantable): iam.Grant {
const tableActions = perms.WRITE_DATA_ACTIONS.concat(perms.DESCRIBE_TABLE);
const keyActions = perms.KEY_READ_ACTIONS.concat(perms.KEY_WRITE_ACTIONS);
return this.combinedGrant(grantee, { keyActions, tableActions });
}
/**
* Permits an IAM principal to all data read/write operations to this table.
* BatchGetItem, GetRecords, GetShardIterator, Query, GetItem, Scan,
* BatchWriteItem, PutItem, UpdateItem, DeleteItem, DescribeTable
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
public grantReadWriteData(grantee: iam.IGrantable): iam.Grant {
const tableActions = perms.READ_DATA_ACTIONS.concat(perms.WRITE_DATA_ACTIONS).concat(perms.DESCRIBE_TABLE);
const keyActions = perms.KEY_READ_ACTIONS.concat(perms.KEY_WRITE_ACTIONS);
return this.combinedGrant(grantee, { keyActions, tableActions });
}
/**
* Permits all DynamoDB operations ("dynamodb:*") to an IAM principal.
*
* Appropriate grants will also be added to the customer-managed KMS key
* if one was configured.
*
* @param grantee The principal to grant access to
*/
public grantFullAccess(grantee: iam.IGrantable) {
const keyActions = perms.KEY_READ_ACTIONS.concat(perms.KEY_WRITE_ACTIONS);
return this.combinedGrant(grantee, { keyActions, tableActions: ['dynamodb:*'] });
}
/**
* Return the given named metric for this Table
*
* By default, the metric will be calculated as a sum over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metric(metricName: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
namespace: 'AWS/DynamoDB',
metricName,
dimensionsMap: {
TableName: this.tableName,
},
...props,
}).attachTo(this);
}
/**
* Metric for the consumed read capacity units this table
*
* By default, the metric will be calculated as a sum over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metricConsumedReadCapacityUnits(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(DynamoDBMetrics.consumedReadCapacityUnitsSum, props);
}
/**
* Metric for the consumed write capacity units this table
*
* By default, the metric will be calculated as a sum over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metricConsumedWriteCapacityUnits(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.cannedMetric(DynamoDBMetrics.consumedWriteCapacityUnitsSum, props);
}
/**
* Metric for the system errors this table
*
* @deprecated use `metricSystemErrorsForOperations`.
*/
public metricSystemErrors(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
if (!props?.dimensions?.Operation && !props?.dimensionsMap?.Operation) {
// 'Operation' must be passed because its an operational metric.
throw new Error("'Operation' dimension must be passed for the 'SystemErrors' metric.");
}
const dimensionsMap = {
TableName: this.tableName,
...props?.dimensions ?? {},
...props?.dimensionsMap ?? {},
};
return this.metric('SystemErrors', { statistic: 'sum', ...props, dimensionsMap });
}
/**
* Metric for the user errors. Note that this metric reports user errors across all
* the tables in the account and region the table resides in.
*
* By default, the metric will be calculated as a sum over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metricUserErrors(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
if (props?.dimensions) {
throw new Error("'dimensions' is not supported for the 'UserErrors' metric");
}
// overriding 'dimensions' here because this metric is an account metric.
// see 'UserErrors' in https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/metrics-dimensions.html
return this.metric('UserErrors', { statistic: 'sum', ...props, dimensionsMap: {} });
}
/**
* Metric for the conditional check failed requests this table
*
* By default, the metric will be calculated as a sum over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metricConditionalCheckFailedRequests(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metric('ConditionalCheckFailedRequests', { statistic: 'sum', ...props });
}
/**
* How many requests are throttled on this table
*
* Default: sum over 5 minutes
*
* @deprecated Do not use this function. It returns an invalid metric. Use `metricThrottledRequestsForOperation` instead.
*/
public metricThrottledRequests(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return this.metric('ThrottledRequests', { statistic: 'sum', ...props });
}
/**
* How many requests are throttled on this table, for the given operation
*
* Default: sum over 5 minutes
*/
public metricThrottledRequestsForOperation(operation: string, props?: cloudwatch.MetricOptions): cloudwatch.Metric {
return new cloudwatch.Metric({
...DynamoDBMetrics.throttledRequestsSum({ Operation: operation, TableName: this.tableName }),
...props,
}).attachTo(this);
}
/**
* Metric for the successful request latency this table.
*
* By default, the metric will be calculated as an average over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metricSuccessfulRequestLatency(props?: cloudwatch.MetricOptions): cloudwatch.Metric {
if (!props?.dimensions?.Operation && !props?.dimensionsMap?.Operation) {
throw new Error("'Operation' dimension must be passed for the 'SuccessfulRequestLatency' metric.");
}
const dimensionsMap = {
TableName: this.tableName,
Operation: props.dimensionsMap?.Operation ?? props.dimensions?.Operation,
};
return new cloudwatch.Metric({
...DynamoDBMetrics.successfulRequestLatencyAverage(dimensionsMap),
...props,
dimensionsMap,
}).attachTo(this);
}
/**
* Metric for the system errors this table.
*
* This will sum errors across all possible operations.
* Note that by default, each individual metric will be calculated as a sum over a period of 5 minutes.
* You can customize this by using the `statistic` and `period` properties.
*/
public metricSystemErrorsForOperations(props?: SystemErrorsForOperationsMetricOptions): cloudwatch.IMetric {
if (props?.dimensions?.Operation) {
throw new Error("The Operation dimension is not supported. Use the 'operations' property.");
}
const operations = props?.operations ?? Object.values(Operation);
const values = this.createMetricsForOperations('SystemErrors', operations, { statistic: 'sum', ...props });
const sum = new cloudwatch.MathExpression({
expression: `${Object.keys(values).join(' + ')}`,
usingMetrics: { ...values },
color: props?.color,
label: 'Sum of errors across all operations',
period: props?.period,
});
return sum;
}
/**
* Create a map of metrics that can be used in a math expression.
*
* Using the return value of this function as the `usingMetrics` property in `cloudwatch.MathExpression` allows you to
* use the keys of this map as metric names inside you expression.
*
* @param metricName The metric name.
* @param operations The list of operations to create metrics for.
* @param props Properties for the individual metrics.
* @param metricNameMapper Mapper function to allow controlling the individual metric name per operation.
*/
private createMetricsForOperations(metricName: string, operations: Operation[],
props?: cloudwatch.MetricOptions, metricNameMapper?: (op: Operation) => string): Record<string, cloudwatch.IMetric> {
const metrics: Record<string, cloudwatch.IMetric> = {};
const mapper = metricNameMapper ?? (op => op.toLowerCase());
if (props?.dimensions?.Operation) {
throw new Error('Invalid properties. Operation dimension is not supported when calculating operational metrics');
}
for (const operation of operations) {
const metric = this.metric(metricName, {
...props,
dimensionsMap: {
TableName: this.tableName,
Operation: operation,
...props?.dimensions,
},
});
const operationMetricName = mapper(operation);
const firstChar = operationMetricName.charAt(0);
if (firstChar === firstChar.toUpperCase()) {
// https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/using-metric-math.html#metric-math-syntax
throw new Error(`Mapper generated an illegal operation metric name: ${operationMetricName}. Must start with a lowercase letter`);
}
metrics[operationMetricName] = metric;
}
return metrics;
}
protected abstract get hasIndex(): boolean;
/**
* Adds an IAM policy statement associated with this table to an IAM
* principal's policy.
* @param grantee The principal (no-op if undefined)
* @param opts Options for keyActions, tableActions and streamActions
*/
private combinedGrant(
grantee: iam.IGrantable,
opts: { keyActions?: string[], tableActions?: string[], streamActions?: string[] },
): iam.Grant {
if (opts.tableActions) {
const resources = [this.tableArn,
Lazy.string({ produce: () => this.hasIndex ? `${this.tableArn}/index/*` : Aws.NO_VALUE }),
...this.regionalArns,
...this.regionalArns.map(arn => Lazy.string({
produce: () => this.hasIndex ? `${arn}/index/*` : Aws.NO_VALUE,
}))];
const ret = iam.Grant.addToPrincipal({
grantee,
actions: opts.tableActions,
resourceArns: resources,
scope: this,
});
if (this.encryptionKey && opts.keyActions) {