@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 302 lines 11.5 KB
Raw
1 import * as elasticache from "@distilled.cloud/aws/elasticache";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import { readElastiCacheTags, sameStringSet, tagsToWire } from "./internal.ts";
14
15 export class CacheClusterNotReady extends Data.TaggedError("CacheClusterNotReady")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export class CacheClusterUnexpectedResponse extends Data.TaggedError(
21 "CacheClusterUnexpectedResponse",
22 )<{
23 readonly message: string;
24 readonly cause?: unknown;
25 }> {}
26
27 export interface CacheClusterProps {
28 /** Cache cluster identifier. Generated deterministically when omitted. */
29 cacheClusterId?: string;
30 /** Memcached is the supported topology for this resource. */
31 engine?: "memcached";
32 engineVersion?: string;
33 /** ElastiCache node type. Must start with `cache.`, for example `cache.t4g.micro`. @default cache.t4g.micro */
34 nodeType?: `cache.${string}`;
35 /** Number of Memcached nodes. */
36 numCacheNodes?: number;
37 subnetGroupName?: string;
38 securityGroupIds?: string[];
39 parameterGroupName?: string;
40 preferredAvailabilityZones?: string[];
41 maintenanceWindow?: string;
42 notificationTopicArn?: string;
43 autoMinorVersionUpgrade?: boolean;
44 port?: number;
45 networkType?: elasticache.NetworkType;
46 ipDiscovery?: elasticache.IpDiscovery;
47 tags?: Record<string, string>;
48 }
49
50 export interface CacheNodeEndpoint {
51 address: string;
52 port: number;
53 }
54
55 export interface CacheCluster extends Resource<
56 "AWS.ElastiCache.CacheCluster",
57 CacheClusterProps,
58 {
59 cacheClusterId: string;
60 cacheClusterArn: string;
61 status: string;
62 engine: string;
63 engineVersion: string | undefined;
64 nodeType: string | undefined;
65 endpoints: CacheNodeEndpoint[];
66 transitEncryptionEnabled: boolean;
67 tags: Record<string, string>;
68 },
69 never,
70 Providers
71 > {}
72
73 /**
74 * A provisioned Memcached cluster. Use {@link ReplicationGroup} for Valkey or Redis.
75 *
76 * ### Creating a Memcached Cluster
77 * **Example:** Two-node cluster in a VPC
78 * ```typescript
79 * const cache = yield* CacheCluster("Cache", {
80 * subnetGroupName: subnets.subnetGroupName,
81 * securityGroupIds: [cacheSecurityGroup.groupId],
82 * numCacheNodes: 2,
83 * });
84 * ```
85 *
86 * @resource
87 */
88 export const CacheCluster = Resource<CacheCluster>("AWS.ElastiCache.CacheCluster");
89
90 export const CacheClusterProvider = () =>
91 Provider.effect(
92 CacheCluster,
93 Effect.gen(function* () {
94 const toName = (id: string, props: Partial<CacheClusterProps>) =>
95 props.cacheClusterId
96 ? Effect.succeed(props.cacheClusterId)
97 : createPhysicalName({ id, maxLength: 50, lowercase: true });
98 const readCluster = Effect.fn(function* (name: string) {
99 const response = yield* elasticache
100 .describeCacheClusters({
101 CacheClusterId: name,
102 ShowCacheNodeInfo: true,
103 })
104 .pipe(Effect.catchTag("CacheClusterNotFoundFault", () => Effect.undefined));
105 return response?.CacheClusters?.[0];
106 });
107 const waitForAvailable = Effect.fn(function* (name: string) {
108 return yield* readCluster(name).pipe(
109 Effect.flatMap((cluster) =>
110 cluster?.CacheClusterStatus === "available"
111 ? Effect.succeed(cluster)
112 : Effect.fail(
113 new CacheClusterNotReady({ message: `Cache cluster '${name}' is not available` }),
114 ),
115 ),
116 Effect.retry({
117 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]),
118 }),
119 );
120 });
121 const waitForDeleted = Effect.fn(function* (name: string) {
122 return yield* readCluster(name).pipe(
123 Effect.flatMap((cluster) =>
124 cluster === undefined
125 ? Effect.void
126 : Effect.fail(
127 new CacheClusterNotReady({
128 message: `Cache cluster '${name}' is still deleting`,
129 }),
130 ),
131 ),
132 Effect.retry({
133 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]),
134 }),
135 );
136 });
137 const attrs = Effect.fn(function* (cluster: elasticache.CacheCluster) {
138 if (!cluster.CacheClusterId || !cluster.ARN) {
139 return yield* new CacheClusterUnexpectedResponse({
140 message: "ElastiCache cache cluster is missing its id or ARN",
141 });
142 }
143 return {
144 cacheClusterId: cluster.CacheClusterId,
145 cacheClusterArn: cluster.ARN,
146 status: cluster.CacheClusterStatus ?? "available",
147 engine: cluster.Engine ?? "memcached",
148 engineVersion: cluster.EngineVersion,
149 nodeType: cluster.CacheNodeType,
150 endpoints: (cluster.CacheNodes ?? []).flatMap((node) =>
151 node.Endpoint?.Address !== undefined && node.Endpoint.Port !== undefined
152 ? [{ address: node.Endpoint.Address, port: node.Endpoint.Port }]
153 : [],
154 ),
155 transitEncryptionEnabled: cluster.TransitEncryptionEnabled ?? false,
156 tags: yield* readElastiCacheTags(cluster.ARN),
157 };
158 });
159 const replaces = (olds: Partial<CacheClusterProps>, news: Partial<CacheClusterProps>) =>
160 olds.subnetGroupName !== news.subnetGroupName ||
161 olds.port !== news.port ||
162 olds.networkType !== news.networkType ||
163 olds.engine !== news.engine;
164
165 return {
166 stables: ["cacheClusterId", "cacheClusterArn"],
167 diff: Effect.fn(function* ({ id, olds, news }) {
168 if (!isResolved(news)) return undefined;
169 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
170 return { action: "replace" } as const;
171 }
172 if (replaces(olds ?? {}, news ?? {})) return { action: "replace" } as const;
173 }),
174 read: Effect.fn(function* ({ id, olds, output }) {
175 const cluster = yield* readCluster(
176 output?.cacheClusterId ?? (yield* toName(id, olds ?? {})),
177 );
178 if (!cluster?.ARN) return undefined;
179 const result = yield* attrs(cluster);
180 return (yield* hasAlchemyTags(id, result.tags)) ? result : Unowned(result);
181 }),
182 reconcile: Effect.fn(function* ({ id, news, output, session }) {
183 const props = news ?? {};
184 const name = output?.cacheClusterId ?? (yield* toName(id, props));
185 const desiredTags = {
186 ...(yield* createInternalTags(id)),
187 ...props.tags,
188 };
189 let cluster = yield* readCluster(name);
190 if (!cluster) {
191 yield* elasticache
192 .createCacheCluster({
193 CacheClusterId: name,
194 Engine: "memcached",
195 EngineVersion: props.engineVersion,
196 CacheNodeType: props.nodeType ?? "cache.t4g.micro",
197 NumCacheNodes: props.numCacheNodes ?? 1,
198 CacheSubnetGroupName: props.subnetGroupName,
199 SecurityGroupIds: props.securityGroupIds,
200 CacheParameterGroupName: props.parameterGroupName,
201 PreferredAvailabilityZones: props.preferredAvailabilityZones,
202 PreferredMaintenanceWindow: props.maintenanceWindow,
203 NotificationTopicArn: props.notificationTopicArn,
204 AutoMinorVersionUpgrade: props.autoMinorVersionUpgrade,
205 Port: props.port,
206 NetworkType: props.networkType,
207 IpDiscovery: props.ipDiscovery,
208 Tags: tagsToWire(desiredTags),
209 })
210 .pipe(Effect.catchTag("CacheClusterAlreadyExistsFault", () => Effect.void));
211 }
212 cluster = yield* waitForAvailable(name);
213 const update: elasticache.ModifyCacheClusterMessage = {
214 CacheClusterId: name,
215 ApplyImmediately: true,
216 };
217 let changed = false;
218 const set = <K extends keyof elasticache.ModifyCacheClusterMessage>(
219 key: K,
220 desired: elasticache.ModifyCacheClusterMessage[K],
221 observed: unknown,
222 ) => {
223 if (desired !== undefined && desired !== observed) {
224 update[key] = desired;
225 changed = true;
226 }
227 };
228 set("NumCacheNodes", props.numCacheNodes, cluster.NumCacheNodes);
229 set("CacheNodeType", props.nodeType, cluster.CacheNodeType);
230 set("EngineVersion", props.engineVersion, cluster.EngineVersion);
231 set(
232 "CacheParameterGroupName",
233 props.parameterGroupName,
234 cluster.CacheParameterGroup?.CacheParameterGroupName,
235 );
236 set(
237 "PreferredMaintenanceWindow",
238 props.maintenanceWindow,
239 cluster.PreferredMaintenanceWindow,
240 );
241 set(
242 "AutoMinorVersionUpgrade",
243 props.autoMinorVersionUpgrade,
244 cluster.AutoMinorVersionUpgrade,
245 );
246 set("IpDiscovery", props.ipDiscovery, cluster.IpDiscovery);
247 if (props.securityGroupIds !== undefined) {
248 const observed = (cluster.SecurityGroups ?? [])
249 .map((group) => group.SecurityGroupId)
250 .filter((id): id is string => id !== undefined);
251 if (!sameStringSet(props.securityGroupIds, observed)) {
252 update.SecurityGroupIds = props.securityGroupIds;
253 changed = true;
254 }
255 }
256 if (changed) {
257 yield* elasticache.modifyCacheCluster(update);
258 cluster = yield* waitForAvailable(name);
259 }
260 if (cluster.ARN) {
261 const { removed, upsert } = diffTags(
262 yield* readElastiCacheTags(cluster.ARN),
263 desiredTags,
264 );
265 if (upsert.length)
266 yield* elasticache.addTagsToResource({
267 ResourceName: cluster.ARN,
268 Tags: upsert,
269 });
270 if (removed.length)
271 yield* elasticache.removeTagsFromResource({
272 ResourceName: cluster.ARN,
273 TagKeys: removed,
274 });
275 }
276 yield* session.note(name);
277 return yield* attrs(cluster);
278 }),
279 delete: Effect.fn(function* ({ output }) {
280 yield* elasticache.deleteCacheCluster({ CacheClusterId: output.cacheClusterId }).pipe(
281 Effect.catchTag("CacheClusterNotFoundFault", () => Effect.void),
282 Effect.retry({
283 while: (error) => error._tag === "InvalidCacheClusterStateFault",
284 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(12)]),
285 }),
286 );
287 yield* waitForDeleted(output.cacheClusterId);
288 }),
289 list: () =>
290 elasticache.describeCacheClusters.pages({ ShowCacheNodeInfo: true }).pipe(
291 Stream.runCollect,
292 Effect.map((pages) => Array.from(pages).flatMap((page) => page.CacheClusters ?? [])),
293 Effect.flatMap((clusters) =>
294 Effect.forEach(
295 clusters.filter((cluster) => cluster.ARN),
296 attrs,
297 ),
298 ),
299 ),
300 };
301 }),
302 );