@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 577 lines 20.7 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
14 export class ServerlessCacheNotReady extends Data.TaggedError("ServerlessCacheNotReady")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export class ServerlessCacheUnexpectedResponse extends Data.TaggedError(
20 "ServerlessCacheUnexpectedResponse",
21 )<{
22 readonly message: string;
23 readonly cause?: unknown;
24 }> {}
25
26 /**
27 * Cache engine for a serverless cache.
28 */
29 export type ServerlessCacheEngine = "valkey" | "redis" | "memcached";
30
31 /**
32 * Usage limits that cap how much a serverless cache can consume. Setting
33 * low maximums is the primary cost-control lever — serverless caches bill
34 * for data stored (GB-hours) and compute (ECPUs) with a monthly floor.
35 */
36 export interface ServerlessCacheUsageLimits {
37 /**
38 * Cached data storage limits in GB.
39 * The service-minimum for `maximum` is 1 GB.
40 */
41 dataStorage?: {
42 /** Maximum data storage in GB. */
43 maximum?: number;
44 /** Minimum (pre-provisioned) data storage in GB. */
45 minimum?: number;
46 };
47 /**
48 * ElastiCache Processing Unit (ECPU) rate limits.
49 * The service-minimum for `maximum` is 1000 ECPUs/second.
50 */
51 ecpuPerSecond?: {
52 /** Maximum ECPUs per second. */
53 maximum?: number;
54 /** Minimum (pre-provisioned) ECPUs per second. */
55 minimum?: number;
56 };
57 }
58
59 export interface ServerlessCacheProps {
60 /**
61 * Name of the serverless cache. Must be 1-40 alphanumeric characters or
62 * hyphens. If omitted, a deterministic physical name is generated.
63 * Changing the name replaces the cache.
64 */
65 serverlessCacheName?: string;
66 /**
67 * Cache engine.
68 * @default "valkey"
69 */
70 engine?: ServerlessCacheEngine;
71 /**
72 * Major engine version, e.g. `"8"` for valkey or `"7"` for redis.
73 * @default latest for the engine
74 */
75 majorEngineVersion?: string;
76 /**
77 * Human-readable description of the cache.
78 */
79 description?: string;
80 /**
81 * Usage limits capping storage (GB) and compute (ECPUs/second).
82 * Strongly recommended for cost control.
83 */
84 cacheUsageLimits?: ServerlessCacheUsageLimits;
85 /**
86 * Customer-managed KMS key for encryption at rest. Changing the key
87 * replaces the cache.
88 * @default AWS-owned key
89 */
90 kmsKeyId?: string;
91 /**
92 * VPC security groups that control network access to the cache endpoint.
93 * @default the VPC's default security group
94 */
95 securityGroupIds?: string[];
96 /**
97 * VPC subnets the cache is reachable from. Changing subnets replaces the
98 * cache.
99 * @default subnets of the account's default VPC
100 */
101 subnetIds?: string[];
102 /**
103 * User group for RBAC authentication (valkey/redis only).
104 */
105 userGroupId?: string;
106 /**
107 * Days to retain automatic daily snapshots. 0 disables automatic
108 * snapshots.
109 * @default 0
110 */
111 snapshotRetentionLimit?: number;
112 /**
113 * Daily time window (UTC, `HH:MM`) when automatic snapshots are taken.
114 */
115 dailySnapshotTime?: string;
116 /**
117 * IP discovery network type. Changing this replaces the cache.
118 * @default "ipv4"
119 */
120 networkType?: elasticache.NetworkType;
121 /**
122 * ARNs of snapshots to seed the cache from at creation (create-only).
123 */
124 snapshotArnsToRestore?: string[];
125 /**
126 * User-defined tags for the cache.
127 */
128 tags?: Record<string, string>;
129 }
130
131 export interface ServerlessCache extends Resource<
132 "AWS.ElastiCache.ServerlessCache",
133 ServerlessCacheProps,
134 {
135 /** The name of the serverless cache. */
136 serverlessCacheName: string;
137 /** The ARN of the serverless cache. */
138 serverlessCacheArn: string;
139 /** The cache status (e.g. `creating`, `available`, `modifying`). */
140 status: string;
141 /** The cache engine (`valkey`, `redis`, or `memcached`). */
142 engine: string;
143 /** The major engine version (e.g. `8`). */
144 majorEngineVersion: string | undefined;
145 /** The full engine version the cache is running. */
146 fullEngineVersion: string | undefined;
147 /** The DNS hostname of the primary endpoint. */
148 endpointAddress: string;
149 /** The port of the primary endpoint (6379 for valkey/redis, 11211 for memcached). */
150 endpointPort: number;
151 /** The DNS hostname of the reader endpoint, when the engine exposes one. */
152 readerEndpointAddress: string | undefined;
153 /** The port of the reader endpoint, when the engine exposes one. */
154 readerEndpointPort: number | undefined;
155 /** The IDs of the security groups associated with the cache. */
156 securityGroupIds: string[];
157 /** The IDs of the subnets the cache is deployed in. */
158 subnetIds: string[];
159 /** The tags applied to the cache. */
160 tags: Record<string, string>;
161 },
162 never,
163 Providers
164 > {}
165
166 /**
167 * An Amazon ElastiCache serverless cache (valkey, redis, or memcached).
168 *
169 * Serverless caches scale storage and compute automatically and are only
170 * reachable from inside a VPC. They are metered while they exist (with a
171 * monthly minimum), so set `cacheUsageLimits` and destroy caches you are
172 * not using.
173 * ### Creating a Serverless Cache
174 * **Example:** Valkey Cache with Cost-Control Limits
175 * ```typescript
176 * const cache = yield* ServerlessCache("SessionCache", {
177 * engine: "valkey",
178 * cacheUsageLimits: {
179 * dataStorage: { maximum: 1 },
180 * ecpuPerSecond: { maximum: 1000 },
181 * },
182 * });
183 * ```
184 *
185 * **Example:** Redis Cache in Specific Subnets
186 * ```typescript
187 * const cache = yield* ServerlessCache("Cache", {
188 * engine: "redis",
189 * majorEngineVersion: "7",
190 * subnetIds: [subnetA.subnetId, subnetB.subnetId],
191 * securityGroupIds: [cacheSecurityGroup.securityGroupId],
192 * });
193 * ```
194 *
195 * ### Connecting from a Lambda Function
196 * **Example:** Bind Connection Info into a Function
197 * ```typescript
198 * const connect = yield* ElastiCache.Connect(cache);
199 * // inside a handler:
200 * const { host, port, tls } = yield* connect;
201 * ```
202 *
203 * @resource
204 */
205 export const ServerlessCache = Resource<ServerlessCache>("AWS.ElastiCache.ServerlessCache");
206
207 const toTagRecord = (
208 tags: Array<{ Key?: string; Value?: string }> | undefined,
209 ): Record<string, string> =>
210 Object.fromEntries(
211 (tags ?? [])
212 .filter(
213 (tag): tag is { Key: string; Value: string } =>
214 typeof tag.Key === "string" && typeof tag.Value === "string",
215 )
216 .map((tag) => [tag.Key, tag.Value]),
217 );
218
219 const sameStringSet = (
220 a: readonly string[] | undefined,
221 b: readonly string[] | undefined,
222 ): boolean => {
223 const left = [...(a ?? [])].sort();
224 const right = [...(b ?? [])].sort();
225 return left.length === right.length && left.every((v, i) => v === right[i]);
226 };
227
228 /**
229 * Convert user-facing camelCase usage limits into the wire shape. Serverless
230 * data storage is always expressed in GB.
231 */
232 const toWireUsageLimits = (
233 limits: ServerlessCacheUsageLimits | undefined,
234 ): elasticache.CacheUsageLimits | undefined =>
235 limits === undefined
236 ? undefined
237 : {
238 ...(limits.dataStorage
239 ? {
240 DataStorage: {
241 Maximum: limits.dataStorage.maximum,
242 Minimum: limits.dataStorage.minimum,
243 Unit: "GB",
244 },
245 }
246 : {}),
247 ...(limits.ecpuPerSecond
248 ? {
249 ECPUPerSecond: {
250 Maximum: limits.ecpuPerSecond.maximum,
251 Minimum: limits.ecpuPerSecond.minimum,
252 },
253 }
254 : {}),
255 };
256
257 /**
258 * True when the desired usage limits differ from the observed ones for any
259 * field the user actually specified.
260 */
261 const usageLimitsDiffer = (
262 desired: elasticache.CacheUsageLimits | undefined,
263 observed: elasticache.CacheUsageLimits | undefined,
264 ): boolean => {
265 if (desired === undefined) return false;
266 // Only compare fields the user actually specified — the service fills in
267 // defaults (units, minimums) that must not trigger spurious modify calls.
268 if (desired.DataStorage) {
269 if (
270 (desired.DataStorage.Maximum !== undefined &&
271 desired.DataStorage.Maximum !== observed?.DataStorage?.Maximum) ||
272 (desired.DataStorage.Minimum !== undefined &&
273 desired.DataStorage.Minimum !== observed?.DataStorage?.Minimum)
274 ) {
275 return true;
276 }
277 }
278 if (desired.ECPUPerSecond) {
279 if (
280 (desired.ECPUPerSecond.Maximum !== undefined &&
281 desired.ECPUPerSecond.Maximum !== observed?.ECPUPerSecond?.Maximum) ||
282 (desired.ECPUPerSecond.Minimum !== undefined &&
283 desired.ECPUPerSecond.Minimum !== observed?.ECPUPerSecond?.Minimum)
284 ) {
285 return true;
286 }
287 }
288 return false;
289 };
290
291 export const ServerlessCacheProvider = () =>
292 Provider.effect(
293 ServerlessCache,
294 Effect.gen(function* () {
295 const toName = (id: string, props: ServerlessCacheProps) =>
296 props.serverlessCacheName
297 ? Effect.succeed(props.serverlessCacheName)
298 : createPhysicalName({ id, maxLength: 40, lowercase: true });
299
300 const readCache = Effect.fn(function* (name: string) {
301 const response = yield* elasticache
302 .describeServerlessCaches({ ServerlessCacheName: name })
303 .pipe(Effect.catchTag("ServerlessCacheNotFoundFault", () => Effect.undefined));
304 return response?.ServerlessCaches?.[0];
305 });
306
307 const readTags = Effect.fn(function* (arn: string) {
308 const response = yield* elasticache
309 .listTagsForResource({ ResourceName: arn })
310 .pipe(Effect.orElseSucceed(() => undefined));
311 return toTagRecord(response?.TagList);
312 });
313
314 // Bounded readiness wait. Serverless cache provisioning/modification
315 // typically completes in 1-3 minutes; budget ~10 min (60 * 10s) like
316 // the RDS cluster wait so slow regions still converge.
317 const waitForCache = Effect.fn(function* (name: string) {
318 const readinessPolicy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]);
319 return yield* readCache(name).pipe(
320 Effect.flatMap((cache) => {
321 if (!cache?.ARN) {
322 return Effect.fail(
323 new ServerlessCacheNotReady({ message: `Serverless cache '${name}' not found` }),
324 );
325 }
326 if (cache.Status !== "available") {
327 return Effect.fail(
328 new ServerlessCacheNotReady({
329 message: `Serverless cache '${name}' not available (status: ${cache.Status})`,
330 }),
331 );
332 }
333 return Effect.succeed(cache);
334 }),
335 Effect.retry({ schedule: readinessPolicy }),
336 );
337 });
338
339 // Wait for a cache to leave a transitional state before delete. Ends
340 // when the cache is available, deleting, or gone.
341 const waitUntilSettled = Effect.fn(function* (name: string) {
342 const settlePolicy = Schedule.max([Schedule.fixed("10 seconds"), Schedule.recurs(60)]);
343 return yield* readCache(name).pipe(
344 Effect.flatMap((cache) => {
345 if (
346 cache !== undefined &&
347 cache.Status !== "available" &&
348 cache.Status !== "deleting"
349 ) {
350 return Effect.fail(
351 new ServerlessCacheNotReady({
352 message: `Serverless cache '${name}' still settling (status: ${cache.Status})`,
353 }),
354 );
355 }
356 return Effect.succeed(cache);
357 }),
358 Effect.retry({ schedule: settlePolicy }),
359 );
360 });
361
362 const toAttrs = Effect.fn(function* (cache: elasticache.ServerlessCache) {
363 if (
364 !cache.ServerlessCacheName ||
365 !cache.ARN ||
366 !cache.Endpoint?.Address ||
367 cache.Endpoint.Port === undefined
368 ) {
369 return yield* new ServerlessCacheUnexpectedResponse({
370 message: `Serverless cache '${cache.ServerlessCacheName}' is missing its ARN or endpoint (status: ${cache.Status})`,
371 });
372 }
373 return {
374 serverlessCacheName: cache.ServerlessCacheName,
375 serverlessCacheArn: cache.ARN,
376 status: cache.Status ?? "available",
377 engine: cache.Engine ?? "valkey",
378 majorEngineVersion: cache.MajorEngineVersion,
379 fullEngineVersion: cache.FullEngineVersion,
380 endpointAddress: cache.Endpoint.Address,
381 endpointPort: cache.Endpoint.Port,
382 readerEndpointAddress: cache.ReaderEndpoint?.Address,
383 readerEndpointPort: cache.ReaderEndpoint?.Port,
384 securityGroupIds: [...(cache.SecurityGroupIds ?? [])],
385 subnetIds: [...(cache.SubnetIds ?? [])],
386 tags: yield* readTags(cache.ARN),
387 };
388 });
389
390 return {
391 stables: ["serverlessCacheName", "serverlessCacheArn"],
392
393 diff: Effect.fn(function* ({ id, olds, news }) {
394 if (!isResolved(news)) return undefined;
395 if ((yield* toName(id, olds ?? {})) !== (yield* toName(id, news ?? {}))) {
396 return { action: "replace" } as const;
397 }
398 // Create-only properties force a replacement.
399 if (
400 news?.subnetIds !== undefined &&
401 olds?.subnetIds !== undefined &&
402 !sameStringSet(news.subnetIds, olds.subnetIds)
403 ) {
404 return { action: "replace" } as const;
405 }
406 if ((news?.kmsKeyId ?? undefined) !== (olds?.kmsKeyId ?? undefined)) {
407 return { action: "replace" } as const;
408 }
409 if ((news?.networkType ?? undefined) !== (olds?.networkType ?? undefined)) {
410 return { action: "replace" } as const;
411 }
412 }),
413
414 read: Effect.fn(function* ({ id, olds, output }) {
415 const name = output?.serverlessCacheName ?? (yield* toName(id, olds ?? {}));
416 const cache = yield* readCache(name);
417 // A cache that is still provisioning has no endpoint yet; report
418 // it as missing so reconcile (which tolerates the AlreadyExists
419 // race and waits for availability) converges it.
420 if (!cache?.ARN || !cache.Endpoint?.Address || cache.Endpoint.Port === undefined) {
421 return undefined;
422 }
423 const attrs = yield* toAttrs(cache);
424 return (yield* hasAlchemyTags(id, attrs.tags)) ? attrs : Unowned(attrs);
425 }),
426
427 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
428 const name = output?.serverlessCacheName ?? (yield* toName(id, news));
429 const internalTags = yield* createInternalTags(id);
430 const desiredTags = { ...internalTags, ...news.tags };
431 const desiredLimits = toWireUsageLimits(news.cacheUsageLimits);
432
433 // 1. Observe — cloud state is authoritative.
434 let observed = yield* readCache(name);
435
436 // 2. Ensure — create if missing; tolerate AlreadyExists as a race.
437 if (observed === undefined) {
438 yield* elasticache
439 .createServerlessCache({
440 ServerlessCacheName: name,
441 Engine: news.engine ?? "valkey",
442 MajorEngineVersion: news.majorEngineVersion,
443 Description: news.description,
444 CacheUsageLimits: desiredLimits,
445 KmsKeyId: news.kmsKeyId,
446 SecurityGroupIds: news.securityGroupIds,
447 SubnetIds: news.subnetIds,
448 UserGroupId: news.userGroupId,
449 SnapshotRetentionLimit: news.snapshotRetentionLimit,
450 DailySnapshotTime: news.dailySnapshotTime,
451 NetworkType: news.networkType,
452 SnapshotArnsToRestore: news.snapshotArnsToRestore,
453 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
454 Key,
455 Value,
456 })),
457 })
458 .pipe(Effect.catchTag("ServerlessCacheAlreadyExistsFault", () => Effect.void));
459 }
460
461 // Provisioning and in-flight modifications both surface as a
462 // non-available status; wait for the cache to become available
463 // (bounded) so sync/modify calls do not hit
464 // InvalidServerlessCacheStateFault.
465 observed = yield* waitForCache(name);
466
467 // 3. Sync — compute the modify delta from OBSERVED state.
468 const modify: elasticache.ModifyServerlessCacheRequest = {};
469 if (news.description !== undefined && news.description !== observed.Description) {
470 modify.Description = news.description;
471 }
472 if (usageLimitsDiffer(desiredLimits, observed.CacheUsageLimits)) {
473 modify.CacheUsageLimits = desiredLimits;
474 }
475 if (
476 news.securityGroupIds !== undefined &&
477 !sameStringSet(news.securityGroupIds, observed.SecurityGroupIds)
478 ) {
479 modify.SecurityGroupIds = news.securityGroupIds;
480 }
481 if (news.userGroupId !== undefined && news.userGroupId !== observed.UserGroupId) {
482 modify.UserGroupId = news.userGroupId;
483 } else if (news.userGroupId === undefined && observed.UserGroupId !== undefined) {
484 modify.RemoveUserGroup = true;
485 }
486 if (
487 news.snapshotRetentionLimit !== undefined &&
488 news.snapshotRetentionLimit !== (observed.SnapshotRetentionLimit ?? 0)
489 ) {
490 modify.SnapshotRetentionLimit = news.snapshotRetentionLimit;
491 }
492 if (
493 news.dailySnapshotTime !== undefined &&
494 news.dailySnapshotTime !== observed.DailySnapshotTime
495 ) {
496 modify.DailySnapshotTime = news.dailySnapshotTime;
497 }
498 if (news.engine !== undefined && news.engine !== observed.Engine) {
499 // valkey <-> redis upgrades are supported in-place by the API.
500 modify.Engine = news.engine;
501 if (news.majorEngineVersion !== undefined) {
502 modify.MajorEngineVersion = news.majorEngineVersion;
503 }
504 } else if (
505 news.majorEngineVersion !== undefined &&
506 news.majorEngineVersion !== observed.MajorEngineVersion
507 ) {
508 modify.MajorEngineVersion = news.majorEngineVersion;
509 }
510
511 if (Object.keys(modify).length > 0) {
512 yield* elasticache.modifyServerlessCache({
513 ServerlessCacheName: name,
514 ...modify,
515 });
516 observed = yield* waitForCache(name);
517 }
518
519 // 3b. Sync tags — diff against OBSERVED cloud tags.
520 const arn = observed.ARN;
521 if (arn) {
522 const observedTags = yield* readTags(arn);
523 const { removed, upsert } = diffTags(observedTags, desiredTags);
524 if (upsert.length > 0) {
525 yield* elasticache.addTagsToResource({
526 ResourceName: arn,
527 Tags: upsert,
528 });
529 }
530 if (removed.length > 0) {
531 yield* elasticache.removeTagsFromResource({
532 ResourceName: arn,
533 TagKeys: removed,
534 });
535 }
536 }
537
538 // 4. Return fresh attributes.
539 yield* session.note(name);
540 return yield* toAttrs(observed);
541 }),
542
543 delete: Effect.fn(function* ({ output }) {
544 const name = output.serverlessCacheName;
545 // A cache mid-create/modify rejects deletion with
546 // InvalidServerlessCacheStateFault — wait (bounded) for it to
547 // settle first. A cache already deleting (or gone) is success.
548 yield* waitUntilSettled(name);
549 yield* elasticache.deleteServerlessCache({ ServerlessCacheName: name }).pipe(
550 Effect.catchTags({
551 ServerlessCacheNotFoundFault: () => Effect.void,
552 InvalidServerlessCacheStateFault: () =>
553 // Already deleting — deletion is in progress.
554 Effect.void,
555 }),
556 );
557 }),
558
559 list: () =>
560 elasticache.describeServerlessCaches.pages({}).pipe(
561 Stream.runCollect,
562 Effect.map((chunk) =>
563 Array.from(chunk).flatMap((page) =>
564 (page.ServerlessCaches ?? []).filter(
565 (cache) =>
566 cache.ServerlessCacheName !== undefined &&
567 cache.ARN !== undefined &&
568 cache.Endpoint?.Address !== undefined &&
569 cache.Endpoint.Port !== undefined,
570 ),
571 ),
572 ),
573 Effect.flatMap(Effect.forEach((cache) => toAttrs(cache), { concurrency: 4 })),
574 ),
575 };
576 }),
577 );