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

main
ts 339 lines 11.5 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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12
13 export class DBProxyEndpointNotReady extends Data.TaggedError("DBProxyEndpointNotReady")<{
14 readonly message: string;
15 readonly cause?: unknown;
16 }> {}
17
18 export interface DBProxyEndpointProps {
19 /**
20 * Proxy endpoint name. If omitted, Alchemy generates one.
21 */
22 dbProxyEndpointName?: string;
23 /**
24 * Proxy that owns the endpoint.
25 */
26 dbProxyName: string;
27 /**
28 * Subnets used by the proxy endpoint.
29 */
30 vpcSubnetIds: string[];
31 /**
32 * Security groups attached to the endpoint.
33 */
34 vpcSecurityGroupIds?: string[];
35 /**
36 * Target role for the endpoint.
37 */
38 targetRole?: rds.DBProxyEndpointTargetRole;
39 /**
40 * Endpoint network type.
41 */
42 endpointNetworkType?: rds.EndpointNetworkType;
43 /**
44 * User-defined tags.
45 */
46 tags?: Record<string, string>;
47 }
48
49 export interface DBProxyEndpoint extends Resource<
50 "AWS.RDS.DBProxyEndpoint",
51 DBProxyEndpointProps,
52 {
53 /**
54 * Name of the proxy endpoint.
55 */
56 dbProxyEndpointName: string;
57 /**
58 * ARN of the proxy endpoint.
59 */
60 dbProxyEndpointArn: string;
61 /**
62 * Proxy that owns the endpoint.
63 */
64 dbProxyName: string | undefined;
65 /**
66 * DNS address applications connect to.
67 */
68 endpoint: string | undefined;
69 /**
70 * Status of the endpoint (e.g. `available`).
71 */
72 status: string | undefined;
73 /**
74 * VPC the endpoint is placed in.
75 */
76 vpcId: string | undefined;
77 /**
78 * Subnets the endpoint is attached to.
79 */
80 vpcSubnetIds: string[];
81 /**
82 * Security groups attached to the endpoint.
83 */
84 vpcSecurityGroupIds: string[];
85 /**
86 * Role of the endpoint (`READ_WRITE` or `READ_ONLY`).
87 */
88 targetRole: string | undefined;
89 /**
90 * Tags on the endpoint.
91 */
92 tags: Record<string, string>;
93 },
94 never,
95 Providers
96 > {}
97
98 /**
99 * An additional RDS Proxy endpoint — a second DNS name on an existing
100 * `DBProxy`, typically read-only for reader traffic or placed in a
101 * different VPC.
102 *
103 * Changing the name, owning proxy, subnets, or target role replaces the
104 * endpoint; security groups and tags update in place.
105 * ### Creating Proxy Endpoints
106 * **Example:** Read-Only Endpoint
107 * ```typescript
108 * const readerEndpoint = yield* DBProxyEndpoint("ReaderEndpoint", {
109 * dbProxyName: proxy.dbProxyName,
110 * vpcSubnetIds: [privateSubnetA.subnetId, privateSubnetB.subnetId],
111 * vpcSecurityGroupIds: [dbSecurityGroup.groupId],
112 * targetRole: "READ_ONLY",
113 * });
114 * ```
115 *
116 * @resource
117 */
118 export const DBProxyEndpoint = Resource<DBProxyEndpoint>("AWS.RDS.DBProxyEndpoint");
119
120 const toAttrs = ({
121 endpoint,
122 tags,
123 }: {
124 endpoint: rds.DBProxyEndpoint;
125 tags: Record<string, string>;
126 }): DBProxyEndpoint["Attributes"] => ({
127 dbProxyEndpointName: endpoint.DBProxyEndpointName ?? "",
128 dbProxyEndpointArn: endpoint.DBProxyEndpointArn ?? "",
129 dbProxyName: endpoint.DBProxyName,
130 endpoint: endpoint.Endpoint,
131 status: endpoint.Status,
132 vpcId: endpoint.VpcId,
133 vpcSubnetIds: endpoint.VpcSubnetIds ?? [],
134 vpcSecurityGroupIds: endpoint.VpcSecurityGroupIds ?? [],
135 targetRole: endpoint.TargetRole,
136 tags,
137 });
138
139 export const DBProxyEndpointProvider = () =>
140 Provider.effect(
141 DBProxyEndpoint,
142 Effect.gen(function* () {
143 const toName = (id: string, props: DBProxyEndpointProps) =>
144 props.dbProxyEndpointName
145 ? Effect.succeed(props.dbProxyEndpointName)
146 : createPhysicalName({ id, maxLength: 63 });
147
148 const readEndpoint = Effect.fn(function* ({
149 dbProxyName,
150 dbProxyEndpointName,
151 }: {
152 dbProxyName: string;
153 dbProxyEndpointName: string;
154 }) {
155 const response = yield* rds
156 .describeDBProxyEndpoints({
157 DBProxyName: dbProxyName,
158 DBProxyEndpointName: dbProxyEndpointName,
159 })
160 .pipe(Effect.catchTag("DBProxyEndpointNotFoundFault", () => Effect.undefined));
161 return response?.DBProxyEndpoints?.[0];
162 });
163
164 const waitForEndpoint = Effect.fn(function* (props: {
165 dbProxyName: string;
166 dbProxyEndpointName: string;
167 }) {
168 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]);
169 return yield* readEndpoint(props).pipe(
170 Effect.flatMap((endpoint) =>
171 endpoint?.DBProxyEndpointArn
172 ? Effect.succeed(endpoint)
173 : Effect.fail(
174 new DBProxyEndpointNotReady({
175 message: `DB proxy endpoint '${props.dbProxyEndpointName}' not ready`,
176 }),
177 ),
178 ),
179 Effect.retry({ schedule: readinessPolicy }),
180 );
181 });
182
183 return {
184 stables: ["dbProxyEndpointArn", "dbProxyEndpointName"],
185 list: () =>
186 Effect.gen(function* () {
187 // Endpoints are keyed under a parent proxy. Enumerate every proxy,
188 // then fan out `describeDBProxyEndpoints` per proxy (bounded
189 // concurrency) and flatten. `describe` does not surface tags
190 // inline, so each item hydrates with `tags: {}` — the same shape
191 // `read` returns when no prior tags are recorded.
192 const proxyNames = yield* rds.describeDBProxies.pages({}).pipe(
193 Stream.runCollect,
194 Effect.map((chunk) =>
195 Array.from(chunk).flatMap((page) =>
196 (page.DBProxies ?? [])
197 .map((proxy) => proxy.DBProxyName)
198 .filter((name): name is string => name != null),
199 ),
200 ),
201 );
202 const rows = yield* Effect.forEach(
203 proxyNames,
204 (dbProxyName) =>
205 rds.describeDBProxyEndpoints.pages({ DBProxyName: dbProxyName }).pipe(
206 Stream.runCollect,
207 Effect.map((chunk) =>
208 Array.from(chunk).flatMap((page) =>
209 (page.DBProxyEndpoints ?? []).map((endpoint) =>
210 toAttrs({ endpoint, tags: {} }),
211 ),
212 ),
213 ),
214 // A proxy (or its endpoints) may be deleted mid-enumeration.
215 Effect.catchTag(["DBProxyNotFoundFault", "DBProxyEndpointNotFoundFault"], () =>
216 Effect.succeed([] as DBProxyEndpoint["Attributes"][]),
217 ),
218 ),
219 { concurrency: 10 },
220 );
221 return rows.flat();
222 }),
223 diff: Effect.fn(function* ({ id, olds, news }) {
224 if (!isResolved(news)) return undefined;
225 if (
226 (yield* toName(id, olds ?? ({} as DBProxyEndpointProps))) !== (yield* toName(id, news))
227 ) {
228 return { action: "replace" } as const;
229 }
230 if (olds?.dbProxyName !== news.dbProxyName) {
231 return { action: "replace" } as const;
232 }
233 }),
234 read: Effect.fn(function* ({ id, olds, output }) {
235 const dbProxyEndpointName =
236 output?.dbProxyEndpointName ??
237 (yield* toName(
238 id,
239 olds ??
240 ({
241 dbProxyName: "",
242 vpcSubnetIds: [],
243 } as DBProxyEndpointProps),
244 ));
245 const endpoint = yield* readEndpoint({
246 dbProxyName: output?.dbProxyName ?? olds?.dbProxyName ?? "",
247 dbProxyEndpointName,
248 });
249 if (!endpoint?.DBProxyEndpointArn) {
250 return undefined;
251 }
252 return toAttrs({ endpoint, tags: output?.tags ?? {} });
253 }),
254 reconcile: Effect.fn(function* ({ id, news, output, session }) {
255 const dbProxyEndpointName = output?.dbProxyEndpointName ?? (yield* toName(id, news));
256 const internalTags = yield* createInternalTags(id);
257 const desiredTags = { ...internalTags, ...news.tags };
258
259 // Observe — fetch live endpoint state.
260 let observed = yield* readEndpoint({
261 dbProxyName: output?.dbProxyName ?? news.dbProxyName,
262 dbProxyEndpointName,
263 });
264
265 // Ensure — create if missing. Tolerate
266 // `DBProxyEndpointAlreadyExistsFault` as a race with a peer
267 // reconciler.
268 if (!observed?.DBProxyEndpointArn) {
269 yield* rds
270 .createDBProxyEndpoint({
271 DBProxyName: news.dbProxyName,
272 DBProxyEndpointName: dbProxyEndpointName,
273 VpcSubnetIds: news.vpcSubnetIds,
274 VpcSecurityGroupIds: news.vpcSecurityGroupIds,
275 TargetRole: news.targetRole,
276 EndpointNetworkType: news.endpointNetworkType,
277 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
278 Key,
279 Value,
280 })),
281 })
282 .pipe(Effect.catchTag("DBProxyEndpointAlreadyExistsFault", () => Effect.void));
283
284 observed = yield* waitForEndpoint({
285 dbProxyName: news.dbProxyName,
286 dbProxyEndpointName,
287 });
288 } else {
289 // Sync mutable endpoint config — security groups + rename. The
290 // rename argument is a no-op when desired matches observed.
291 yield* rds.modifyDBProxyEndpoint({
292 DBProxyEndpointName: dbProxyEndpointName,
293 VpcSecurityGroupIds: news.vpcSecurityGroupIds,
294 NewDBProxyEndpointName:
295 news.dbProxyEndpointName && news.dbProxyEndpointName !== dbProxyEndpointName
296 ? news.dbProxyEndpointName
297 : undefined,
298 });
299 observed = yield* waitForEndpoint({
300 dbProxyName: observed.DBProxyName ?? news.dbProxyName,
301 dbProxyEndpointName:
302 news.dbProxyEndpointName && news.dbProxyEndpointName !== dbProxyEndpointName
303 ? news.dbProxyEndpointName
304 : dbProxyEndpointName,
305 });
306 }
307
308 const dbProxyEndpointArn = observed.DBProxyEndpointArn ?? "";
309
310 // Sync tags — diff prior recorded tags against desired (describe
311 // does not surface tags inline).
312 const observedTags = output?.tags ?? {};
313 const { removed, upsert } = diffTags(observedTags, desiredTags);
314 if (upsert.length > 0 && dbProxyEndpointArn) {
315 yield* rds.addTagsToResource({
316 ResourceName: dbProxyEndpointArn,
317 Tags: upsert,
318 });
319 }
320 if (removed.length > 0 && dbProxyEndpointArn) {
321 yield* rds.removeTagsFromResource({
322 ResourceName: dbProxyEndpointArn,
323 TagKeys: removed,
324 });
325 }
326
327 yield* session.note(dbProxyEndpointArn || dbProxyEndpointName);
328 return toAttrs({ endpoint: observed, tags: desiredTags });
329 }),
330 delete: Effect.fn(function* ({ output }) {
331 yield* rds
332 .deleteDBProxyEndpoint({
333 DBProxyEndpointName: output.dbProxyEndpointName,
334 })
335 .pipe(Effect.catchTag("DBProxyEndpointNotFoundFault", () => Effect.void));
336 }),
337 };
338 }),
339 );