Repository navigation
Expand file tree
/
Copy pathTable.ts
More file actions
2279 lines (2139 loc) · 92.5 KB
/
Copy pathTable.ts
File metadata and controls
2279 lines (2139 loc) · 92.5 KB
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 cloudwatch from "@distilled.cloud/aws/cloudwatch";
import type * as DynamoDB from "@distilled.cloud/aws/dynamodb";
import type { TimeToLiveSpecification } from "@distilled.cloud/aws/dynamodb";
import * as dynamodb from "@distilled.cloud/aws/dynamodb";
import { Unowned } from "alchemy/AdoptPolicy";
import { havePropsChanged, isResolved } from "alchemy/Diff";
import type { Input } from "alchemy/Input";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { createInternalTags, createTagsList, diffTags, hasAlchemyTags } from "alchemy/Tags";
import { toWireDays } from "alchemy/Util/Duration";
import type * as lambda from "aws-lambda";
import * as Data from "effect/Data";
import type * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as Stream from "effect/Stream";
import type { AccountID } from "../Environment.ts";
import type { Providers } from "../Providers.ts";
import type { RegionID } from "../Region.ts";
export class TableUnexpectedResponse extends Data.TaggedError("TableUnexpectedResponse")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export type TableName = string;
export type TableArn = `arn:aws:dynamodb:${RegionID}:${AccountID}:table/${TableName}`;
export type TableRecord<Data> = Omit<lambda.DynamoDBRecord, "dynamodb"> & {
dynamodb: Omit<lambda.StreamRecord, "NewImage" | "OldImage"> & {
NewImage?: Data;
OldImage?: Data;
};
};
export type TableEvent<Data> = Omit<lambda.DynamoDBStreamEvent, "Records"> & {
Records: TableRecord<Data>[];
};
export type ScalarAttributeType = "S" | "N" | "B";
export interface PointInTimeRecoverySpecification {
/**
* Whether point-in-time recovery (continuous backups) is enabled for the
* table.
*/
pointInTimeRecoveryEnabled: boolean;
/**
* How far back the table can be restored, e.g. `"7 days"` or
* `Duration.days(7)`. Rounded to whole days on the wire (1–35 days).
* @default 35 days
*/
recoveryPeriod?: Duration.Input;
}
export interface KinesisStreamingDestination {
/**
* ARN of the destination Kinesis Data Stream. The stream must be ACTIVE
* when the destination is enabled (deploy the `AWS.Kinesis.Stream`
* resource in the same stack and pass `stream.streamArn`).
*/
streamArn: string;
/**
* Precision of the approximate creation timestamp stamped on records
* delivered to the Kinesis stream. Changing this on an ACTIVE destination
* updates it in place, but the UPDATING→ACTIVE transition can take several
* minutes.
* @default "MILLISECOND"
*/
approximateCreationDateTimePrecision?: DynamoDB.ApproximateCreationDateTimePrecision;
}
/**
* One or more attribute names forming an index key. DynamoDB's wire format
* flattens both key segments into a single ordered `KeySchema` list, but
* semantically a key is two ordered segments — this type captures one of
* them. Order is significant: partition attributes are hashed together in
* declaration order, and sort attributes are queried left-to-right.
*/
export type IndexKey = string | string[];
export interface LocalSecondaryIndexProps {
/**
* Name of the index, unique within the table.
*/
indexName: string;
/**
* Sort key attribute name. An LSI always shares the table's partition
* key, so only the sort key is declared; multi-attribute keys are not
* supported on LSIs.
*/
sortKey: string;
/**
* Attributes projected from the table into the index.
*/
projection: DynamoDB.Projection;
}
export interface GlobalSecondaryIndexProps {
/**
* Name of the index, unique within the table.
*/
indexName: string;
/**
* Partition key attribute name(s). Up to four attributes may be listed;
* they are hashed together in declaration order and every one must be
* specified with an equality condition when querying the index.
*/
partitionKey: IndexKey;
/**
* Optional sort key attribute name(s). Up to four attributes may be
* listed; items sort by each attribute in declaration order and queries
* narrow them left-to-right (no gaps, inequality last).
*/
sortKey?: IndexKey;
/**
* Attributes projected from the table into the index.
*/
projection: DynamoDB.Projection;
provisionedThroughput?: DynamoDB.ProvisionedThroughput;
onDemandThroughput?: DynamoDB.OnDemandThroughput;
warmThroughput?: DynamoDB.WarmThroughput;
}
export type TableProps = {
/**
* Name of the table. If omitted, Alchemy generates a deterministic physical
* name from the stack, stage, and logical ID, suffixed with the instance ID
* so replacements can create the successor table before deleting the old one.
*
* Changing this property replaces the table. If the name is hard-coded,
* replacement-triggering changes (key schema, attribute types, LSIs, GSI
* key changes) delete the old table first and then recreate it under the
* same name, since DynamoDB table names are unique per account/region.
*/
tableName?: string;
/**
* Partition key attribute name for the table.
*
* Base-table primary keys are always a single partition attribute plus an
* optional single sort attribute — DynamoDB supports multi-attribute keys
* only on global secondary indexes (see `globalSecondaryIndexes`).
*/
partitionKey: string;
/**
* Optional sort key attribute name for the table.
*/
sortKey?: string;
/**
* Attribute definitions used by the primary key and any secondary indexes.
*/
attributes: Record<string, ScalarAttributeType>;
/**
* Local secondary indexes, created with the table. An LSI always shares
* the table's partition key and declares a single sort key. Changing this
* property replaces the table.
*/
localSecondaryIndexes?: LocalSecondaryIndexProps[];
/**
* Global secondary indexes. GSIs support multi-attribute keys: up to four
* partition attributes (hashed together as the composite partition key)
* and up to four sort attributes (sorted and queried left-to-right).
* Attribute order is significant — reordering defines a different index
* and replaces the table. Every key attribute must appear in `attributes`.
*/
globalSecondaryIndexes?: GlobalSecondaryIndexProps[];
billingMode?: DynamoDB.BillingMode;
deletionProtectionEnabled?: boolean;
onDemandThroughput?: DynamoDB.OnDemandThroughput;
/**
* Enables point-in-time recovery (continuous backups) and optionally sets
* the recovery window via `recoveryPeriod` (a `Duration.Input`, rounded to
* whole days on the wire).
*/
pointInTimeRecoverySpecification?: PointInTimeRecoverySpecification;
provisionedThroughput?: DynamoDB.ProvisionedThroughput;
sseSpecification?: DynamoDB.SSESpecification;
tags?: Record<string, string>;
timeToLiveSpecification?: DynamoDB.TimeToLiveSpecification;
warmThroughput?: DynamoDB.WarmThroughput;
tableClass?: DynamoDB.TableClass;
/**
* Resource-based IAM policy document (JSON string) attached to the table.
* Grants cross-account or scoped-principal access to the table and its
* indexes. Removing the property deletes the policy.
*/
resourcePolicy?: string;
/**
* Streams change data capture records to the given Kinesis Data Stream.
* Changing the stream disables the old destination before enabling the
* new one; removing the property disables streaming.
*/
kinesisStreamingDestination?: KinesisStreamingDestination;
/**
* Enables CloudWatch Contributor Insights (table-level rule) for the
* table, surfacing the most-accessed and most-throttled keys.
* @default false
*/
contributorInsightsEnabled?: boolean;
};
export type TableBinding = {
streamSpecification?: DynamoDB.StreamSpecification;
};
export interface Table extends Resource<
"AWS.DynamoDB.Table",
TableProps,
{
/** The unique ID AWS assigns to the table. */
tableId: string;
/** The physical name of the table. */
tableName: TableName;
/** The ARN of the table. */
tableArn: TableArn;
/** The AWS region the table lives in. */
region: RegionID;
/** The partition (hash) key attribute name. */
partitionKey: string;
/** The sort (range) key attribute name, if defined. */
sortKey: string | undefined;
/** ARN of the most recent DynamoDB stream (when streams are enabled). */
latestStreamArn: string | undefined;
/** The current stream configuration (when streams are enabled). */
streamSpecification: DynamoDB.StreamSpecification | undefined;
/** Descriptions of the table's local secondary indexes. */
localSecondaryIndexes: DynamoDB.LocalSecondaryIndexDescription[] | undefined;
/** Descriptions of the table's global secondary indexes. */
globalSecondaryIndexes: DynamoDB.GlobalSecondaryIndexDescription[] | undefined;
/** The point-in-time recovery status of the table. */
pointInTimeRecoveryDescription: DynamoDB.PointInTimeRecoveryDescription | undefined;
/** The tags attached to the table. */
tags: Record<string, string> | undefined;
/**
* Billing mode, as observed on the table. Lets `alchemy drift` detect
* out-of-band changes.
*/
billingMode?: DynamoDB.BillingMode;
/**
* Table-level provisioned capacity (PROVISIONED tables only), as
* observed. Lets `alchemy drift` detect out-of-band changes.
*/
provisionedThroughput?: {
ReadCapacityUnits?: number;
WriteCapacityUnits?: number;
};
/**
* Table-level on-demand maximums, observed when `onDemandThroughput` is
* set. Lets `alchemy drift` detect out-of-band changes.
*/
onDemandThroughput?: DynamoDB.OnDemandThroughput;
/**
* Whether deletion protection is enabled, as observed. Lets
* `alchemy drift` detect out-of-band changes.
*/
deletionProtectionEnabled?: boolean;
/**
* KMS server-side encryption, as observed (`undefined` when the table
* uses the default AWS owned key). Lets `alchemy drift` detect
* out-of-band changes.
*/
sseDescription?: {
sseType?: string;
kmsMasterKeyArn?: string;
};
/**
* Table class, as observed. Lets `alchemy drift` detect out-of-band
* changes.
*/
tableClass?: DynamoDB.TableClass;
/**
* Time-to-live attribute when TTL is enabled, as observed. Lets
* `alchemy drift` detect out-of-band changes.
*/
timeToLiveAttributeName?: string;
/**
* Resource-based policy document attached to the table (canonical JSON),
* as observed. Lets `alchemy drift` detect out-of-band changes.
*/
resourcePolicy?: string;
/**
* Active Kinesis streaming destinations, as observed. Lets
* `alchemy drift` detect out-of-band changes.
*/
kinesisStreamingDestinations?: {
streamArn: string;
approximateCreationDateTimePrecision: string;
}[];
/**
* Whether Contributor Insights is enabled, as observed. Lets
* `alchemy drift` detect out-of-band changes.
*/
contributorInsightsEnabled?: boolean;
},
TableBinding,
Providers
> {}
/**
* An Amazon DynamoDB table with optional indexes, PITR, TTL, and stream-aware
* binding support.
*
* `Table` owns the lifecycle of the physical table while the binding contract
* allows runtime-specific integrations such as Lambda table event sources to
* request stream configuration without forcing a circular input prop.
* ### Creating Tables
* **Example:** Basic Table
* ```typescript
* import * as DynamoDB from "@alchemy.run/aws/DynamoDB";
*
* const table = yield* DynamoDB.Table("UsersTable", {
* partitionKey: "pk",
* attributes: {
* pk: "S",
* },
* });
* ```
*
* **Example:** Table with Sort Key and TTL
* ```typescript
* const table = yield* DynamoDB.Table("SessionsTable", {
* partitionKey: "userId",
* sortKey: "sessionId",
* attributes: {
* userId: "S",
* sessionId: "S",
* expiresAt: "N",
* },
* timeToLiveSpecification: {
* Enabled: true,
* AttributeName: "expiresAt",
* },
* });
* ```
*
* **Example:** Table with Global Secondary Index
* ```typescript
* const table = yield* DynamoDB.Table("OrdersTable", {
* partitionKey: "pk",
* sortKey: "sk",
* attributes: {
* pk: "S",
* sk: "S",
* gsi1pk: "S",
* gsi1sk: "S",
* },
* globalSecondaryIndexes: [{
* indexName: "GSI1",
* partitionKey: "gsi1pk",
* sortKey: "gsi1sk",
* projection: { ProjectionType: "ALL" },
* }],
* });
* ```
*
* **Example:** Multi-Attribute GSI Keys
* GSI partition and sort keys may be composed of up to four attributes each,
* indexing natural domain attributes directly instead of synthetic
* concatenated keys. Partition attributes are hashed together (queries must
* specify all of them with equality); sort attributes are queried
* left-to-right in declaration order.
* ```typescript
* const matches = yield* DynamoDB.Table("TournamentMatches", {
* partitionKey: "matchId",
* attributes: {
* matchId: "S",
* tournamentId: "S",
* region: "S",
* round: "S",
* },
* globalSecondaryIndexes: [{
* indexName: "TournamentRegionIndex",
* partitionKey: ["tournamentId", "region"],
* sortKey: ["round", "matchId"],
* projection: { ProjectionType: "ALL" },
* }],
* });
*
* // init
* const query = yield* AWS.DynamoDB.Query(matches);
*
* // runtime: query with every partition attribute, then narrow the sort
* // attributes left-to-right
* const response = yield* query({
* IndexName: "TournamentRegionIndex",
* KeyConditionExpression:
* "tournamentId = :t AND #r = :r AND round = :round",
* ExpressionAttributeNames: { "#r": "region" },
* ExpressionAttributeValues: {
* ":t": { S: "WINTER2024" },
* ":r": { S: "NA-EAST" },
* ":round": { S: "SEMIFINALS" },
* },
* });
* ```
*
* ### Runtime Operations
* Bind DynamoDB operations in the init phase and use them in runtime
* handlers. Bindings inject the table name and grant scoped IAM
* permissions automatically.
*
* **Example:** Read and write items
* ```typescript
* // init
* const getItem = yield* AWS.DynamoDB.GetItem(table);
* const putItem = yield* AWS.DynamoDB.PutItem(table);
*
* return {
* fetch: Effect.gen(function* () {
* // runtime
* yield* putItem({
* Item: { pk: { S: "user#123" }, name: { S: "Alice" } },
* });
* const result = yield* getItem({
* Key: { pk: { S: "user#123" } },
* });
* return yield* HttpServerResponse.json(result.Item);
* }),
* };
* ```
*
* **Example:** Read and write items from a Cloudflare Worker
*
* The `*Http` layers also run on a Cloudflare Worker. Alchemy creates an
* IAM user, access key, and least-privilege role for the Worker, binds the
* key onto it, and signs each request with the assumed role in the table's
* region. The Stack needs both provider sets:
* `Layer.mergeAll(Cloudflare.providers(), AWS.providers())`.
* ```typescript
* export default class Api extends Cloudflare.Worker<Api>()(
* "Api",
* { main: import.meta.url },
* Effect.gen(function* () {
* const table = yield* AWS.DynamoDB.Table("Links", {
* partitionKey: "id",
* attributes: { id: "S" },
* });
* const getItem = yield* AWS.DynamoDB.GetItem(table);
* const putItem = yield* AWS.DynamoDB.PutItem(table);
* return {
* fetch: Effect.gen(function* () {
* yield* putItem({ Item: { id: { S: "a" }, url: { S: "https://alchemy.run" } } });
* const { Item } = yield* getItem({ Key: { id: { S: "a" } } });
* return yield* HttpServerResponse.json(Item);
* }).pipe(Effect.orDie),
* };
* }).pipe(
* Effect.provide(
* Layer.mergeAll(AWS.DynamoDB.GetItemHttp, AWS.DynamoDB.PutItemHttp),
* ),
* ),
* ) {}
* ```
*
* ### Table Features
* **Example:** Resource Policy
* ```typescript
* const table = yield* DynamoDB.Table("SharedTable", {
* partitionKey: "pk",
* attributes: { pk: "S" },
* resourcePolicy: JSON.stringify({
* Version: "2012-10-17",
* Statement: [{
* Effect: "Allow",
* Principal: { AWS: "arn:aws:iam::111122223333:root" },
* Action: ["dynamodb:GetItem", "dynamodb:Query"],
* Resource: "*",
* }],
* }),
* });
* ```
*
* **Example:** Kinesis Streaming Destination
* ```typescript
* import * as Kinesis from "@alchemy.run/aws/Kinesis";
*
* const stream = yield* Kinesis.Stream("CdcStream", {});
* const table = yield* DynamoDB.Table("CdcTable", {
* partitionKey: "pk",
* attributes: { pk: "S" },
* kinesisStreamingDestination: {
* streamArn: stream.streamArn,
* approximateCreationDateTimePrecision: "MICROSECOND",
* },
* });
* ```
*
* **Example:** Contributor Insights
* ```typescript
* const table = yield* DynamoDB.Table("HotKeyTable", {
* partitionKey: "pk",
* attributes: { pk: "S" },
* contributorInsightsEnabled: true,
* });
* ```
*
* ### DynamoDB Streams
* Process change data capture events from a DynamoDB table using a
* Lambda event source mapping. The stream is enabled automatically
* through the binding contract.
*
* **Example:** Process table changes
* ```typescript
* // init
* yield* DynamoDB.consumeTableChanges(
* table,
* { streamViewType: "NEW_AND_OLD_IMAGES" },
* Effect.fn(function* (event) {
* for (const record of event.Records) {
* yield* Effect.log(`${record.eventName}: ${JSON.stringify(record.dynamodb)}`);
* }
* }),
* );
* ```
*
* @resource
*/
export const Table = Resource<Table>("AWS.DynamoDB.Table");
export const TableProvider = () =>
Provider.effect(
Table,
Effect.gen(function* () {
const createTableName = (id: string, props: Input.ResolveProps<TableProps>) =>
Effect.gen(function* () {
return (
props.tableName ??
(yield* createPhysicalName({
id,
// see: https://docs.aws.amazon.com/amazondynamodb/latest/APIReference/API_TableDescription.html#DDB-Type-TableDescription-TableName
maxLength: 255,
}))
);
});
const toKeySchema = (props: Input.ResolveProps<TableProps>) => [
{
AttributeName: props.partitionKey,
KeyType: "HASH" as const,
},
...(props.sortKey
? [
{
AttributeName: props.sortKey,
KeyType: "RANGE" as const,
},
]
: []),
];
const toKeyAttributeNames = (key: IndexKey | undefined) =>
key === undefined ? [] : typeof key === "string" ? [key] : key;
// AWS's wire format flattens an index key into one ordered KeySchema
// list and validates that all HASH elements precede all RANGE
// elements; deriving the list from the two typed segments makes the
// invalid orderings unrepresentable in props.
const toIndexKeySchema = (
partitionKey: IndexKey,
sortKey: IndexKey | undefined,
): DynamoDB.KeySchemaElement[] => [
...toKeyAttributeNames(partitionKey).map((name) => ({
AttributeName: name,
KeyType: "HASH" as const,
})),
...toKeyAttributeNames(sortKey).map((name) => ({
AttributeName: name,
KeyType: "RANGE" as const,
})),
];
// Pre-typed-props state may persist index props in the legacy wire
// shape ({ IndexName, KeySchema, ... }). Tolerate it when converting
// `olds` so upgrading alchemy never plans a spurious table
// replacement over a shape-only difference.
const isLegacyWireIndex = (index: unknown): index is DynamoDB.GlobalSecondaryIndex =>
typeof index === "object" && index !== null && "KeySchema" in index;
const toWireGlobalSecondaryIndex = (
index: GlobalSecondaryIndexProps,
): DynamoDB.GlobalSecondaryIndex =>
isLegacyWireIndex(index)
? index
: {
IndexName: index.indexName,
KeySchema: toIndexKeySchema(index.partitionKey, index.sortKey),
Projection: index.projection,
ProvisionedThroughput: index.provisionedThroughput,
OnDemandThroughput: index.onDemandThroughput,
WarmThroughput: index.warmThroughput,
};
const toWireLocalSecondaryIndex = (
tablePartitionKey: string,
index: LocalSecondaryIndexProps,
): DynamoDB.LocalSecondaryIndex =>
isLegacyWireIndex(index)
? index
: {
IndexName: index.indexName,
KeySchema: toIndexKeySchema(tablePartitionKey, index.sortKey),
Projection: index.projection,
};
const toWireGlobalSecondaryIndexes = (
indexes: readonly GlobalSecondaryIndexProps[] | undefined,
) =>
indexes === undefined || indexes.length === 0
? undefined
: indexes.map(toWireGlobalSecondaryIndex);
const toWireLocalSecondaryIndexes = (
tablePartitionKey: string,
indexes: readonly LocalSecondaryIndexProps[] | undefined,
) =>
indexes === undefined || indexes.length === 0
? undefined
: indexes.map((index) => toWireLocalSecondaryIndex(tablePartitionKey, index));
const toAttributeDefinitions = (attrs: Record<string, ScalarAttributeType>) =>
Object.entries(attrs)
.map(([name, type]) => ({
AttributeName: name,
AttributeType: type,
}))
.sort((a, b) => a.AttributeName.localeCompare(b.AttributeName));
const adoptExistingTable = (tableName: string) =>
// The engine has cleared us via `read` (foreign-tagged tables are
// surfaced as `Unowned`). On a race between read and create, just
// describe the existing table and continue.
dynamodb.describeTable({ TableName: tableName }).pipe(Effect.map((r) => r.Table!));
const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
return {
...(yield* createInternalTags(id)),
...tags,
};
});
const normalizeStreamSpecification = (
streamSpecification: DynamoDB.StreamSpecification | undefined,
) =>
streamSpecification?.StreamEnabled === true
? ({
StreamEnabled: true,
StreamViewType: streamSpecification.StreamViewType,
} satisfies DynamoDB.StreamSpecification)
: undefined;
const resolveStreamSpecification = (
bindings: ReadonlyArray<TableBinding | { data?: TableBinding }>,
) =>
Effect.gen(function* () {
const requested = bindings
.flatMap((binding) =>
(binding as { data?: TableBinding }).data?.streamSpecification?.StreamEnabled === true
? [
normalizeStreamSpecification(
(binding as { data?: TableBinding }).data?.streamSpecification,
),
]
: (binding as TableBinding).streamSpecification?.StreamEnabled === true
? [normalizeStreamSpecification((binding as TableBinding).streamSpecification)]
: [],
)
.filter((spec) => spec !== undefined);
if (requested.length === 0) {
return undefined;
}
const [first, ...rest] = requested;
if (!first?.StreamViewType) {
return yield* new MissingStreamViewType();
}
for (const spec of rest) {
if (spec.StreamViewType !== first.StreamViewType) {
return yield* new ConflictingStreamViewTypes({
requested: requested.map((item) => item.StreamViewType),
});
}
}
return first;
});
const isRetryableControlPlaneError = (error: { _tag?: string }) =>
error._tag === "InternalServerError" ||
error._tag === "LimitExceededException" ||
error._tag === "ResourceInUseException" ||
error._tag === "ResourceNotFoundException" ||
// Throttling: DynamoDB's control-plane API limits are low and the
// blanket SDK retry (10 attempts) is easily exhausted when the whole
// suite hammers create/update/describe concurrently. Give it the
// provider's much larger budget too.
error._tag === "ThrottlingException" ||
error._tag === "ProvisionedThroughputExceededException" ||
error._tag === "RequestLimitExceeded";
const waitForControlPlaneConvergence = Schedule.max([
Schedule.fixed("1 second"),
Schedule.recurs(120),
]);
const waitForTableActivationConvergence = Schedule.max([
Schedule.fixed("10 seconds"),
Schedule.recurs(180),
]);
const waitForGlobalSecondaryIndexesConvergence = Schedule.max([
Schedule.fixed("10 seconds"),
Schedule.recurs(180),
]);
const waitForDeletionConvergence = Schedule.max([
Schedule.fixed("1 second"),
Schedule.recurs(90),
]);
const formatPollingElapsed = (elapsedSeconds: number) => `${elapsedSeconds}s elapsed`;
const formatGlobalSecondaryIndexStatuses = (
indexes: readonly DynamoDB.GlobalSecondaryIndexDescription[] | undefined,
) =>
JSON.stringify(
(indexes ?? []).map((index) => ({
name: index.IndexName,
status: index.IndexStatus,
backfilling: index.Backfilling,
})),
);
const updateTimeToLive = (
tableName: string,
timeToLiveSpecification: TimeToLiveSpecification,
) =>
dynamodb
.updateTimeToLive({
TableName: tableName,
TimeToLiveSpecification: timeToLiveSpecification!,
})
.pipe(
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(100), Schedule.recurs(30)]),
}),
);
const updateContinuousBackups = (
tableName: string,
pointInTimeRecoverySpecification: DynamoDB.PointInTimeRecoverySpecification,
) =>
dynamodb
.updateContinuousBackups({
TableName: tableName,
PointInTimeRecoverySpecification: pointInTimeRecoverySpecification,
})
.pipe(
Effect.retry({
while: (e) =>
e._tag === "ContinuousBackupsUnavailableException" ||
isRetryableControlPlaneError(e),
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(30)]),
}),
);
// Resource policies are compared as canonicalized JSON so formatting
// differences between what the user wrote and what AWS stores don't
// cause phantom putResourcePolicy calls on every reconcile.
const canonicalPolicyDocument = (policy: string | undefined) => {
if (policy === undefined) return undefined;
try {
return JSON.stringify(JSON.parse(policy));
} catch {
return policy;
}
};
const readTableResourcePolicy = (tableArn: string) =>
dynamodb.getResourcePolicy({ ResourceArn: tableArn }).pipe(
Effect.map((response) => response.Policy),
Effect.catchTag("PolicyNotFoundException", () => Effect.undefined),
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(15)]),
}),
);
const putTableResourcePolicy = (tableArn: string, policy: string) =>
dynamodb.putResourcePolicy({ ResourceArn: tableArn, Policy: policy }).pipe(
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(15)]),
}),
);
const deleteTableResourcePolicy = (tableArn: string) =>
dynamodb.deleteResourcePolicy({ ResourceArn: tableArn }).pipe(
Effect.catchTag("PolicyNotFoundException", () => Effect.void),
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(15)]),
}),
);
const isKinesisDestinationTransitioning = (
destination: DynamoDB.KinesisDataStreamDestination,
) =>
destination.DestinationStatus === "ENABLING" ||
destination.DestinationStatus === "DISABLING" ||
destination.DestinationStatus === "UPDATING";
// Kinesis streaming destinations transition ENABLING→ACTIVE and
// DISABLING→DISABLED within seconds, but a precision change
// (UPDATING→ACTIVE) takes multiple minutes; poll bounded to 8 minutes.
const waitForKinesisDestinationsConvergence = Schedule.max([
Schedule.fixed("5 seconds"),
Schedule.recurs(96),
]);
const waitForKinesisDestinationsSettled = (
session: {
note: (message: string) => Effect.Effect<void, never, never>;
},
tableName: string,
) => {
let elapsedSeconds = 0;
return Effect.gen(function* () {
const response = yield* dynamodb.describeKinesisStreamingDestination({
TableName: tableName,
});
const destinations = response.KinesisDataStreamDestinations ?? [];
if (destinations.some(isKinesisDestinationTransitioning)) {
return yield* new KinesisDestinationNotSettled();
}
return destinations;
}).pipe(
Effect.retry({
while: (error) =>
error._tag === "KinesisDestinationNotSettled" || isRetryableControlPlaneError(error),
schedule: waitForKinesisDestinationsConvergence.pipe(
Schedule.tap(({ attempt }) => {
elapsedSeconds = (attempt + 1) * 5;
return session.note(
`DynamoDB Table provider: waiting for Kinesis streaming destinations on ${tableName} to settle (${formatPollingElapsed(elapsedSeconds)})`,
);
}),
),
}),
);
};
const disableKinesisDestination = (tableName: string, streamArn: string) =>
dynamodb
.disableKinesisStreamingDestination({
TableName: tableName,
StreamArn: streamArn,
})
.pipe(
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(15)]),
}),
);
const enableKinesisDestination = (
tableName: string,
destination: KinesisStreamingDestination,
) =>
dynamodb
.enableKinesisStreamingDestination({
TableName: tableName,
StreamArn: destination.streamArn,
EnableKinesisStreamingConfiguration:
destination.approximateCreationDateTimePrecision !== undefined
? {
ApproximateCreationDateTimePrecision:
destination.approximateCreationDateTimePrecision,
}
: undefined,
})
.pipe(
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(15)]),
}),
);
const updateKinesisDestinationPrecision = (
tableName: string,
destination: KinesisStreamingDestination,
) =>
dynamodb
.updateKinesisStreamingDestination({
TableName: tableName,
StreamArn: destination.streamArn,
UpdateKinesisStreamingConfiguration: {
ApproximateCreationDateTimePrecision:
destination.approximateCreationDateTimePrecision,
},
})
.pipe(
Effect.retry({
while: isRetryableControlPlaneError,
schedule: Schedule.max([Schedule.exponential(250), Schedule.recurs(15)]),
}),
);
// Contributor Insights transitions ENABLING→ENABLED / DISABLING→DISABLED
// within seconds, but UpdateContributorInsights rejects a DISABLE while
// the status is still ENABLING — wait for a settled status before
// diffing observed against desired.
const waitForContributorInsightsSettled = (
session: {
note: (message: string) => Effect.Effect<void, never, never>;
},
tableName: string,
) =>
Effect.gen(function* () {
const response = yield* dynamodb.describeContributorInsights({
TableName: tableName,
});
const status = response.ContributorInsightsStatus ?? "DISABLED";
if (status === "ENABLING" || status === "DISABLING") {
return yield* new ContributorInsightsNotSettled();
}
return status;
}).pipe(
Effect.retry({
while: (error) =>
error._tag === "ContributorInsightsNotSettled" || isRetryableControlPlaneError(error),
schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(45)]).pipe(
Schedule.tap(({ attempt }) =>
session.note(
`DynamoDB Table provider: waiting for Contributor Insights on ${tableName} to settle (${formatPollingElapsed((attempt + 1) * 2)})`,
),
),
),
}),
);
// Enabling Contributor Insights makes DynamoDB create CloudWatch rules
// named `DynamoDBContributorInsights-{PKC|PKT}-<tableName>-<timestamp>`
// in the customer's account. Those rules can ONLY be removed by
// DynamoDB's own asynchronous cleanup, which runs when an
// UpdateContributorInsights DISABLE completes — CloudWatch's
// DeleteInsightRules/PutInsightRule reject them with AccessDenied even
// for account admins, and deleting the table aborts the cleanup and
// strands the rules forever (recoverable only via AWS support). The
// delete lifecycle therefore observes the rules and holds off
// deleteTable until DynamoDB's cleanup has actually removed them.
const listContributorInsightsRules = (tableName: string) =>
cloudwatch.describeInsightRules.pages({}).pipe(
Stream.runFold(
() => [] as string[],
(acc, page) => [
...acc,
...(page.InsightRules ?? [])
.map((rule) => rule.Name)
.filter(
(name): name is string =>
name !== undefined &&
name.startsWith("DynamoDBContributorInsights-") &&
name.includes(`-${tableName}-`),
),
],
),
);
const waitForContributorInsightsRulesDeleted = (
session: {
note: (message: string) => Effect.Effect<void, never, never>;
},
tableName: string,
) =>
Effect.gen(function* () {
const remaining = yield* listContributorInsightsRules(tableName);
if (remaining.length > 0) {
return yield* new ContributorInsightsNotSettled();
}
}).pipe(
Effect.retry({
while: (error) =>
error._tag === "ContributorInsightsNotSettled" || isRetryableControlPlaneError(error),
schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]).pipe(
Schedule.tap(({ attempt }) =>
session.note(
`DynamoDB Table provider: waiting for Contributor Insights rules of ${tableName} to be cleaned up (${formatPollingElapsed((attempt + 1) * 2)})`,
),
),
),
}),
// Rules from a PREVIOUS enable session whose cleanup was already
// aborted (e.g. by an out-of-band table deletion) can never be
// removed by anyone but AWS support — don't wedge the delete on