@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, 06:00 UTC

main
ts 373 lines 12.3 KB
Raw
1 import * as rds from "@distilled.cloud/aws/rds";
2 import { isResolved } from "alchemy/Diff";
3 import { createPhysicalName } from "alchemy/PhysicalName";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { createInternalTags, diffTags } from "alchemy/Tags";
7 import { toWireSeconds } from "alchemy/Util/Duration";
8 import * as Data from "effect/Data";
9 import type * as Duration from "effect/Duration";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14
15 export class DBProxyNotReady extends Data.TaggedError("DBProxyNotReady")<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface DBProxyProps {
21 /**
22 * Proxy name. If omitted, Alchemy generates one.
23 */
24 dbProxyName?: string;
25 /**
26 * Engine family such as `POSTGRESQL`.
27 */
28 engineFamily: rds.EngineFamily;
29 /**
30 * Authentication config for the proxy.
31 */
32 auth: rds.UserAuthConfig[];
33 /**
34 * IAM role ARN used by the proxy to read secrets.
35 */
36 roleArn: string;
37 /**
38 * Subnets used by the proxy.
39 */
40 vpcSubnetIds: string[];
41 /**
42 * Security groups attached to the proxy.
43 */
44 vpcSecurityGroupIds?: string[];
45 /**
46 * Require TLS from clients.
47 */
48 requireTLS?: boolean;
49 /**
50 * Idle client timeout (e.g. `"30 minutes"` or `Duration.minutes(30)`).
51 * Sent to the API in whole seconds.
52 */
53 idleClientTimeout?: Duration.Input;
54 /**
55 * Enable debug logging.
56 */
57 debugLogging?: boolean;
58 /**
59 * Endpoint network type.
60 */
61 endpointNetworkType?: rds.EndpointNetworkType;
62 /**
63 * Target connection network type.
64 */
65 targetConnectionNetworkType?: rds.TargetConnectionNetworkType;
66 /**
67 * User-defined tags.
68 */
69 tags?: Record<string, string>;
70 }
71
72 export interface DBProxy extends Resource<
73 "AWS.RDS.DBProxy",
74 DBProxyProps,
75 {
76 /**
77 * Name of the proxy.
78 */
79 dbProxyName: string;
80 /**
81 * ARN of the proxy.
82 */
83 dbProxyArn: string;
84 /**
85 * DNS endpoint applications connect to.
86 */
87 endpoint: string | undefined;
88 /**
89 * Status of the proxy (e.g. `available`).
90 */
91 status: string | undefined;
92 /**
93 * Engine family the proxy fronts (`POSTGRESQL`, `MYSQL`).
94 */
95 engineFamily: string | undefined;
96 /**
97 * IAM role the proxy uses to read credentials secrets.
98 */
99 roleArn: string | undefined;
100 /**
101 * VPC the proxy runs in.
102 */
103 vpcId: string | undefined;
104 /**
105 * Subnets the proxy is attached to.
106 */
107 vpcSubnetIds: string[];
108 /**
109 * Security groups attached to the proxy.
110 */
111 vpcSecurityGroupIds: string[];
112 /**
113 * Whether clients must use TLS.
114 */
115 requireTLS: boolean | undefined;
116 /**
117 * Idle client timeout in seconds.
118 */
119 idleClientTimeout: number | undefined;
120 /**
121 * Whether debug logging is enabled.
122 */
123 debugLogging: boolean | undefined;
124 /**
125 * Tags on the proxy.
126 */
127 tags: Record<string, string>;
128 },
129 never,
130 Providers
131 > {}
132
133 /**
134 * An RDS Proxy for pooled Lambda-to-Aurora connectivity.
135 *
136 * The proxy multiplexes many short-lived function connections over a small
137 * pool of database connections, absorbing connection storms from Lambda
138 * scale-out. It authenticates against the database with credentials read
139 * from Secrets Manager via the provided IAM role, then registers targets
140 * through a `DBProxyTargetGroup`. Changing the name, engine family, or
141 * subnets replaces the proxy; auth, TLS, timeout, and security groups
142 * update in place.
143 *
144 * For the common case, `Aurora("Db", { proxy: true })` wires the role,
145 * proxy, target group, and secret automatically.
146 * ### Creating a Proxy
147 * **Example:** Proxy in Front of an Aurora Cluster
148 * ```typescript
149 * const proxy = yield* DBProxy("Proxy", {
150 * engineFamily: "POSTGRESQL",
151 * auth: [
152 * {
153 * AuthScheme: "SECRETS",
154 * SecretArn: secret.secretArn,
155 * IAMAuth: "DISABLED",
156 * },
157 * ],
158 * roleArn: proxyRole.roleArn,
159 * vpcSubnetIds: [privateSubnetA.subnetId, privateSubnetB.subnetId],
160 * vpcSecurityGroupIds: [dbSecurityGroup.groupId],
161 * requireTLS: true,
162 * });
163 *
164 * // register the cluster behind the proxy
165 * const targets = yield* DBProxyTargetGroup("ProxyTargets", {
166 * dbProxyName: proxy.dbProxyName,
167 * dbClusterIdentifiers: [cluster.dbClusterIdentifier],
168 * });
169 * ```
170 *
171 * @resource
172 */
173 export const DBProxy = Resource<DBProxy>("AWS.RDS.DBProxy");
174
175 const toAttrs = ({
176 proxy,
177 tags,
178 }: {
179 proxy: rds.DBProxy;
180 tags: Record<string, string>;
181 }): DBProxy["Attributes"] => ({
182 dbProxyName: proxy.DBProxyName ?? "",
183 dbProxyArn: proxy.DBProxyArn ?? "",
184 endpoint: proxy.Endpoint,
185 status: proxy.Status,
186 engineFamily: proxy.EngineFamily,
187 roleArn: proxy.RoleArn,
188 vpcId: proxy.VpcId,
189 vpcSubnetIds: proxy.VpcSubnetIds ?? [],
190 vpcSecurityGroupIds: proxy.VpcSecurityGroupIds ?? [],
191 requireTLS: proxy.RequireTLS,
192 idleClientTimeout: proxy.IdleClientTimeout,
193 debugLogging: proxy.DebugLogging,
194 tags,
195 });
196
197 export const DBProxyProvider = () =>
198 Provider.effect(
199 DBProxy,
200 Effect.gen(function* () {
201 const toName = (id: string, props: DBProxyProps) =>
202 props.dbProxyName
203 ? Effect.succeed(props.dbProxyName)
204 : createPhysicalName({ id, maxLength: 63 });
205
206 const readProxy = Effect.fn(function* (name: string) {
207 const response = yield* rds
208 .describeDBProxies({
209 DBProxyName: name,
210 })
211 .pipe(Effect.catchTag("DBProxyNotFoundFault", () => Effect.undefined));
212 return response?.DBProxies?.[0];
213 });
214
215 const waitForProxy = Effect.fn(function* (name: string) {
216 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]);
217 return yield* readProxy(name).pipe(
218 Effect.flatMap((proxy) =>
219 proxy?.DBProxyArn
220 ? Effect.succeed(proxy)
221 : Effect.fail(new DBProxyNotReady({ message: `DB proxy '${name}' not ready` })),
222 ),
223 Effect.retry({ schedule: readinessPolicy }),
224 );
225 });
226
227 return {
228 stables: ["dbProxyArn", "dbProxyName"],
229 // Enumerate every DB proxy in the account/region via the paginated
230 // `describeDBProxies`, then hydrate each proxy's tags via
231 // `listTagsForResource` (describe does not return tags inline) so each
232 // element matches `read`'s `Attributes` shape exactly. A proxy deleted
233 // between the describe and the tag fetch surfaces `DBProxyNotFoundFault`
234 // per item and is dropped.
235 list: () =>
236 Effect.gen(function* () {
237 const proxies = yield* rds.describeDBProxies.pages({}).pipe(
238 Stream.runCollect,
239 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.DBProxies ?? [])),
240 );
241 const rows = yield* Effect.forEach(
242 proxies,
243 (proxy) =>
244 Effect.gen(function* () {
245 if (!proxy.DBProxyArn) return undefined;
246 const tagResponse = yield* rds
247 .listTagsForResource({ ResourceName: proxy.DBProxyArn })
248 .pipe(Effect.catchTag("DBProxyNotFoundFault", () => Effect.undefined));
249 if (tagResponse === undefined) return undefined;
250 const tags = Object.fromEntries(
251 (tagResponse.TagList ?? [])
252 .filter((tag): tag is rds.Tag & { Key: string } => tag.Key != null)
253 .map((tag) => [tag.Key, tag.Value ?? ""] as const),
254 );
255 return toAttrs({ proxy, tags });
256 }),
257 { concurrency: 10 },
258 );
259 return rows.filter((row): row is DBProxy["Attributes"] => row !== undefined);
260 }),
261 diff: Effect.fn(function* ({ id, olds, news }) {
262 if (!isResolved(news)) return undefined;
263 if ((yield* toName(id, olds ?? ({} as DBProxyProps))) !== (yield* toName(id, news))) {
264 return { action: "replace" } as const;
265 }
266 if (olds?.engineFamily !== news.engineFamily) {
267 return { action: "replace" } as const;
268 }
269 }),
270 read: Effect.fn(function* ({ id, olds, output }) {
271 const name =
272 output?.dbProxyName ??
273 (yield* toName(
274 id,
275 olds ??
276 ({
277 engineFamily: "POSTGRESQL",
278 auth: [],
279 roleArn: "",
280 vpcSubnetIds: [],
281 } as DBProxyProps),
282 ));
283 const proxy = yield* readProxy(name);
284 if (!proxy?.DBProxyArn) {
285 return undefined;
286 }
287 return toAttrs({ proxy, tags: output?.tags ?? {} });
288 }),
289 reconcile: Effect.fn(function* ({ id, news, output, session }) {
290 const name = output?.dbProxyName ?? (yield* toName(id, news));
291 const internalTags = yield* createInternalTags(id);
292 const desiredTags = { ...internalTags, ...news.tags };
293 // Duration prop → the wire unit the RDS API expects (whole seconds).
294 const idleClientTimeoutSeconds = toWireSeconds(news.idleClientTimeout);
295
296 // Observe — fetch live proxy state.
297 let observed = yield* readProxy(name);
298
299 // Ensure — create if missing. Tolerate
300 // `DBProxyAlreadyExistsFault` as a race with a peer reconciler.
301 if (!observed?.DBProxyArn) {
302 yield* rds
303 .createDBProxy({
304 DBProxyName: name,
305 EngineFamily: news.engineFamily,
306 Auth: news.auth,
307 RoleArn: news.roleArn,
308 VpcSubnetIds: news.vpcSubnetIds,
309 VpcSecurityGroupIds: news.vpcSecurityGroupIds,
310 RequireTLS: news.requireTLS,
311 IdleClientTimeout: idleClientTimeoutSeconds,
312 DebugLogging: news.debugLogging,
313 EndpointNetworkType: news.endpointNetworkType,
314 TargetConnectionNetworkType: news.targetConnectionNetworkType,
315 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
316 Key,
317 Value,
318 })),
319 })
320 .pipe(Effect.catchTag("DBProxyAlreadyExistsFault", () => Effect.void));
321
322 observed = yield* waitForProxy(name);
323 } else {
324 // Sync mutable proxy config — push desired shape via
325 // `modifyDBProxy`. Rename via `NewDBProxyName` is a no-op when
326 // the desired name already matches the observed name.
327 yield* rds.modifyDBProxy({
328 DBProxyName: name,
329 Auth: news.auth,
330 RoleArn: news.roleArn,
331 SecurityGroups: news.vpcSecurityGroupIds,
332 RequireTLS: news.requireTLS,
333 IdleClientTimeout: idleClientTimeoutSeconds,
334 DebugLogging: news.debugLogging,
335 NewDBProxyName:
336 news.dbProxyName && news.dbProxyName !== name ? news.dbProxyName : undefined,
337 });
338 observed = yield* waitForProxy(news.dbProxyName ?? name);
339 }
340
341 const dbProxyArn = observed.DBProxyArn ?? "";
342 const finalName = observed.DBProxyName ?? name;
343
344 // Sync tags — diff prior recorded tags against desired (describe
345 // does not surface tags inline).
346 const observedTags = output?.tags ?? {};
347 const { removed, upsert } = diffTags(observedTags, desiredTags);
348 if (upsert.length > 0 && dbProxyArn) {
349 yield* rds.addTagsToResource({
350 ResourceName: dbProxyArn,
351 Tags: upsert,
352 });
353 }
354 if (removed.length > 0 && dbProxyArn) {
355 yield* rds.removeTagsFromResource({
356 ResourceName: dbProxyArn,
357 TagKeys: removed,
358 });
359 }
360
361 yield* session.note(dbProxyArn || finalName);
362 return toAttrs({ proxy: observed, tags: desiredTags });
363 }),
364 delete: Effect.fn(function* ({ output }) {
365 yield* rds
366 .deleteDBProxy({
367 DBProxyName: output.dbProxyName,
368 })
369 .pipe(Effect.catchTag("DBProxyNotFoundFault", () => Effect.void));
370 }),
371 };
372 }),
373 );