1import * as elasticache from "@distilled.cloud/aws/elasticache";
2import * as Effect from "effect/Effect";
3import * as Schedule from "effect/Schedule";
4import * as Stream from "effect/Stream";
5import { Unowned } from "../../AdoptPolicy.ts";
6import { isResolved } from "../../Diff.ts";
7import { createPhysicalName } from "../../PhysicalName.ts";
8import * as Provider from "../../Provider.ts";
9import { Resource } from "../../Resource.ts";
10import { createInternalTags, diffTags, hasAlchemyTags } from "../../Tags.ts";
11import type { Providers } from "../Providers.ts";
12import { readElastiCacheTags, sameStringSet, tagsToWire } from "./internal.ts";
13
14export interface SubnetGroupProps {
15 /** Name of the subnet group. Generated deterministically when omitted. */
16 subnetGroupName?: string;
17 /** Human-readable description. */
18 description: string;
19 /** VPC subnet IDs. Use at least two AZs for a highly-available cache. */
20 subnetIds: string[];
21 /** User-defined tags. */
22 tags?: Record<string, string>;
23}
24
25export interface SubnetGroup extends Resource<
26 "AWS.ElastiCache.SubnetGroup",
27 SubnetGroupProps,
28 {
29 subnetGroupName: string;
30 subnetGroupArn: string;
31 description: string | undefined;
32 vpcId: string | undefined;
33 subnetIds: string[];
34 tags: Record<string, string>;
35 },
36 never,
37 Providers
38> {}
39
40/**
41 * A VPC subnet group for provisioned ElastiCache resources.
42 *
43 * ### Creating a Subnet Group
44 * **Example:** Two Availability Zones
45 * ```typescript
46 * const subnets = yield* SubnetGroup("CacheSubnets", {
47 * description: "cache subnets",
48 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
49 * });
50 * ```
51 *
52 * @resource
53 */
54export const SubnetGroup = Resource<SubnetGroup>("AWS.ElastiCache.SubnetGroup");
55
56export const SubnetGroupProvider = () =>
57 Provider.effect(
58 SubnetGroup,
59 Effect.gen(function* () {
60 const toName = (id: string, props: SubnetGroupProps) =>
61 props.subnetGroupName
62 ? Effect.succeed(props.subnetGroupName)
63 : createPhysicalName({ id, maxLength: 40, lowercase: true });
64 const readGroup = Effect.fn(function* (name: string) {
65 const response = yield* elasticache
66 .describeCacheSubnetGroups({ CacheSubnetGroupName: name })
67 .pipe(
68 Effect.catchTag("CacheSubnetGroupNotFoundFault", () =>
69 Effect.succeed(undefined),
70 ),
71 );
72 return response?.CacheSubnetGroups?.[0];
73 });
74 const attrs = Effect.fn(function* (group: elasticache.CacheSubnetGroup) {
75 if (!group.CacheSubnetGroupName || !group.ARN) {
76 return yield* Effect.fail(
77 new Error("ElastiCache subnet group is missing its name or ARN"),
78 );
79 }
80 return {
81 subnetGroupName: group.CacheSubnetGroupName,
82 subnetGroupArn: group.ARN,
83 description: group.CacheSubnetGroupDescription,
84 vpcId: group.VpcId,
85 subnetIds: (group.Subnets ?? [])
86 .map((subnet) => subnet.SubnetIdentifier)
87 .filter((id): id is string => id !== undefined),
88 tags: yield* readElastiCacheTags(group.ARN),
89 };
90 });
91
92 return {
93 stables: ["subnetGroupName", "subnetGroupArn"],
94 diff: Effect.fn(function* ({ id, olds, news }) {
95 if (!isResolved(news)) return undefined;
96 if (
97 (yield* toName(id, olds ?? { description: "", subnetIds: [] })) !==
98 (yield* toName(id, news ?? { description: "", subnetIds: [] }))
99 )
100 return { action: "replace" } as const;
101 }),
102 read: Effect.fn(function* ({ id, olds, output }) {
103 const group = yield* readGroup(
104 output?.subnetGroupName ??
105 (yield* toName(id, olds ?? { description: "", subnetIds: [] })),
106 );
107 if (!group?.ARN) return undefined;
108 const result = yield* attrs(group);
109 return (yield* hasAlchemyTags(id, result.tags))
110 ? result
111 : Unowned(result);
112 }),
113 reconcile: Effect.fn(function* ({ id, news, output, session }) {
114 const props = news!;
115 const name = output?.subnetGroupName ?? (yield* toName(id, props));
116 const desiredTags = {
117 ...(yield* createInternalTags(id)),
118 ...props.tags,
119 };
120 let group = yield* readGroup(name);
121 if (!group) {
122 yield* elasticache
123 .createCacheSubnetGroup({
124 CacheSubnetGroupName: name,
125 CacheSubnetGroupDescription: props.description,
126 SubnetIds: props.subnetIds,
127 Tags: tagsToWire(desiredTags),
128 })
129 .pipe(
130 Effect.catchTag(
131 "CacheSubnetGroupAlreadyExistsFault",
132 () => Effect.void,
133 ),
134 );
135 group = yield* readGroup(name);
136 }
137 if (!group)
138 return yield* Effect.fail(
139 new Error(`Subnet group '${name}' not found after create`),
140 );
141 const observedSubnets = (group.Subnets ?? [])
142 .map((subnet) => subnet.SubnetIdentifier)
143 .filter((id): id is string => id !== undefined);
144 if (
145 group.CacheSubnetGroupDescription !== props.description ||
146 !sameStringSet(observedSubnets, props.subnetIds)
147 ) {
148 group =
149 (yield* elasticache.modifyCacheSubnetGroup({
150 CacheSubnetGroupName: name,
151 CacheSubnetGroupDescription: props.description,
152 SubnetIds: props.subnetIds,
153 })).CacheSubnetGroup ?? group;
154 }
155 if (group.ARN) {
156 const { removed, upsert } = diffTags(
157 yield* readElastiCacheTags(group.ARN),
158 desiredTags,
159 );
160 if (upsert.length)
161 yield* elasticache.addTagsToResource({
162 ResourceName: group.ARN,
163 Tags: upsert,
164 });
165 if (removed.length)
166 yield* elasticache.removeTagsFromResource({
167 ResourceName: group.ARN,
168 TagKeys: removed,
169 });
170 }
171 yield* session.note(name);
172 return yield* attrs(group);
173 }),
174 delete: Effect.fn(function* ({ output }) {
175 yield* elasticache
176 .deleteCacheSubnetGroup({
177 CacheSubnetGroupName: output.subnetGroupName,
178 })
179 .pipe(
180 Effect.catchTag(
181 "CacheSubnetGroupNotFoundFault",
182 () => Effect.void,
183 ),
184 Effect.retry({
185 while: (error) => error._tag === "CacheSubnetGroupInUse",
186 schedule: Schedule.max([
187 Schedule.fixed("5 seconds"),
188 Schedule.recurs(8),
189 ]),
190 }),
191 );
192 }),
193 list: () =>
194 elasticache.describeCacheSubnetGroups.pages({}).pipe(
195 Stream.runCollect,
196 Effect.map((pages) =>
197 Array.from(pages).flatMap((page) => page.CacheSubnetGroups ?? []),
198 ),
199 Effect.flatMap((groups) =>
200 Effect.forEach(
201 groups.filter((group) => group.ARN),
202 attrs,
203 ),
204 ),
205 ),
206 };
207 }),
208 );