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

main
ts 289 lines 10.1 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 Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export class DBClusterEndpointUnexpectedResponse extends Data.TaggedError(
13 "DBClusterEndpointUnexpectedResponse",
14 )<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 export interface DBClusterEndpointProps {
20 /**
21 * Endpoint identifier. If omitted, Alchemy generates one.
22 */
23 dbClusterEndpointIdentifier?: string;
24 /**
25 * Cluster that owns the endpoint.
26 */
27 dbClusterIdentifier: string;
28 /**
29 * Endpoint type such as `READER`, `WRITER`, or `ANY`.
30 */
31 endpointType: string;
32 /**
33 * Static members explicitly attached to the endpoint.
34 */
35 staticMembers?: string[];
36 /**
37 * Members excluded from the endpoint.
38 */
39 excludedMembers?: string[];
40 /**
41 * User-defined tags.
42 */
43 tags?: Record<string, string>;
44 }
45
46 export interface DBClusterEndpoint extends Resource<
47 "AWS.RDS.DBClusterEndpoint",
48 DBClusterEndpointProps,
49 {
50 /**
51 * Identifier of the custom endpoint.
52 */
53 dbClusterEndpointIdentifier: string;
54 /**
55 * ARN of the custom endpoint.
56 */
57 dbClusterEndpointArn: string | undefined;
58 /**
59 * Cluster that owns the endpoint.
60 */
61 dbClusterIdentifier: string | undefined;
62 /**
63 * DNS address applications connect to.
64 */
65 endpoint: string | undefined;
66 /**
67 * Status of the endpoint (e.g. `available`).
68 */
69 status: string | undefined;
70 /**
71 * Endpoint type (`CUSTOM` for managed endpoints).
72 */
73 endpointType: string | undefined;
74 /**
75 * Traffic routing type of the custom endpoint (`READER`, `ANY`).
76 */
77 customEndpointType: string | undefined;
78 /**
79 * Instances explicitly attached to the endpoint.
80 */
81 staticMembers: string[];
82 /**
83 * Instances excluded from the endpoint.
84 */
85 excludedMembers: string[];
86 /**
87 * Tags on the endpoint.
88 */
89 tags: Record<string, string>;
90 },
91 never,
92 Providers
93 > {}
94
95 /**
96 * A custom Aurora cluster endpoint — a DNS name that routes to a chosen
97 * subset of a cluster's instances, on top of the built-in writer and reader
98 * endpoints of a `DBCluster`.
99 *
100 * Use it to pin analytics traffic to specific readers or to keep a stable
101 * address across instance replacements. Changing the identifier or owning
102 * cluster replaces the endpoint; type and membership update in place.
103 * ### Creating Custom Endpoints
104 * **Example:** Reader Endpoint for a Cluster
105 * ```typescript
106 * const readers = yield* DBClusterEndpoint("Readers", {
107 * dbClusterIdentifier: cluster.dbClusterIdentifier,
108 * endpointType: "READER",
109 * });
110 * ```
111 *
112 * **Example:** Pin Specific Instances
113 * ```typescript
114 * const analytics = yield* DBClusterEndpoint("Analytics", {
115 * dbClusterIdentifier: cluster.dbClusterIdentifier,
116 * endpointType: "ANY",
117 * staticMembers: [reporting.dbInstanceIdentifier],
118 * });
119 * ```
120 *
121 * @resource
122 */
123 export const DBClusterEndpoint = Resource<DBClusterEndpoint>("AWS.RDS.DBClusterEndpoint");
124
125 const toAttrs = ({
126 endpoint,
127 tags,
128 }: {
129 endpoint: rds.DBClusterEndpoint;
130 tags: Record<string, string>;
131 }): DBClusterEndpoint["Attributes"] => ({
132 dbClusterEndpointIdentifier: endpoint.DBClusterEndpointIdentifier ?? "",
133 dbClusterEndpointArn: endpoint.DBClusterEndpointArn,
134 dbClusterIdentifier: endpoint.DBClusterIdentifier,
135 endpoint: endpoint.Endpoint,
136 status: endpoint.Status,
137 endpointType: endpoint.EndpointType,
138 customEndpointType: endpoint.CustomEndpointType,
139 staticMembers: endpoint.StaticMembers ?? [],
140 excludedMembers: endpoint.ExcludedMembers ?? [],
141 tags,
142 });
143
144 export const DBClusterEndpointProvider = () =>
145 Provider.effect(
146 DBClusterEndpoint,
147 Effect.gen(function* () {
148 const toIdentifier = (id: string, props: DBClusterEndpointProps) =>
149 props.dbClusterEndpointIdentifier
150 ? Effect.succeed(props.dbClusterEndpointIdentifier)
151 : createPhysicalName({ id, maxLength: 63 });
152
153 const readEndpoint = Effect.fn(function* (identifier: string) {
154 const response = yield* rds
155 .describeDBClusterEndpoints({
156 DBClusterEndpointIdentifier: identifier,
157 })
158 .pipe(Effect.catchTag("DBClusterNotFoundFault", () => Effect.undefined));
159 return response?.DBClusterEndpoints?.[0];
160 });
161
162 return {
163 stables: ["dbClusterEndpointArn", "dbClusterEndpointIdentifier"],
164 // Enumerate every custom cluster endpoint in the account/region.
165 // `describeDBClusterEndpoints` with no filter returns custom endpoints
166 // across all clusters; system endpoints (EndpointType WRITER/READER)
167 // aren't managed via createDBClusterEndpoint, so we keep only CUSTOM
168 // ones. Tags aren't returned by describe, so each item carries `{}`
169 // (matching `read`'s default when there is no recorded tag set).
170 list: () =>
171 rds.describeDBClusterEndpoints.pages({}).pipe(
172 Stream.runCollect,
173 Effect.map((chunk) =>
174 Array.from(chunk).flatMap((page) =>
175 (page.DBClusterEndpoints ?? [])
176 .filter((endpoint) => endpoint.EndpointType === "CUSTOM")
177 .map((endpoint) => toAttrs({ endpoint, tags: {} })),
178 ),
179 ),
180 ),
181 diff: Effect.fn(function* ({ id, olds, news }) {
182 if (!isResolved(news)) return;
183 if (
184 (yield* toIdentifier(id, olds ?? ({} as DBClusterEndpointProps))) !==
185 (yield* toIdentifier(id, news))
186 ) {
187 return { action: "replace" } as const;
188 }
189 if (olds?.dbClusterIdentifier !== news.dbClusterIdentifier) {
190 return { action: "replace" } as const;
191 }
192 }),
193 read: Effect.fn(function* ({ id, olds, output }) {
194 const identifier =
195 output?.dbClusterEndpointIdentifier ??
196 (yield* toIdentifier(
197 id,
198 olds ??
199 ({
200 dbClusterIdentifier: "",
201 endpointType: "READER",
202 } as DBClusterEndpointProps),
203 ));
204 const endpoint = yield* readEndpoint(identifier);
205 if (!endpoint?.DBClusterEndpointIdentifier) {
206 return undefined;
207 }
208 return toAttrs({ endpoint, tags: output?.tags ?? {} });
209 }),
210 reconcile: Effect.fn(function* ({ id, news, output, session }) {
211 const identifier = output?.dbClusterEndpointIdentifier ?? (yield* toIdentifier(id, news));
212 const internalTags = yield* createInternalTags(id);
213 const desiredTags = { ...internalTags, ...news.tags };
214
215 // Observe — fetch the endpoint's live state.
216 let observed = yield* readEndpoint(identifier);
217
218 // Ensure — create if missing. Tolerate
219 // `DBClusterEndpointAlreadyExistsFault` as a race with a peer
220 // reconciler.
221 if (!observed?.DBClusterEndpointIdentifier) {
222 yield* rds
223 .createDBClusterEndpoint({
224 DBClusterIdentifier: news.dbClusterIdentifier,
225 DBClusterEndpointIdentifier: identifier,
226 EndpointType: news.endpointType,
227 StaticMembers: news.staticMembers,
228 ExcludedMembers: news.excludedMembers,
229 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
230 Key,
231 Value,
232 })),
233 })
234 .pipe(Effect.catchTag("DBClusterEndpointAlreadyExistsFault", () => Effect.void));
235 observed = yield* readEndpoint(identifier);
236 if (!observed?.DBClusterEndpointIdentifier) {
237 return yield* new DBClusterEndpointUnexpectedResponse({
238 message: `DB cluster endpoint '${identifier}' not found after create`,
239 });
240 }
241 } else {
242 // Sync mutable endpoint config — push desired shape.
243 yield* rds.modifyDBClusterEndpoint({
244 DBClusterEndpointIdentifier: identifier,
245 EndpointType: news.endpointType,
246 StaticMembers: news.staticMembers,
247 ExcludedMembers: news.excludedMembers,
248 });
249 observed = yield* readEndpoint(identifier);
250 if (!observed?.DBClusterEndpointIdentifier) {
251 return yield* new DBClusterEndpointUnexpectedResponse({
252 message: `DB cluster endpoint '${identifier}' not found after update`,
253 });
254 }
255 }
256
257 const dbClusterEndpointArn = observed.DBClusterEndpointArn;
258
259 // Sync tags — diff observed cloud tags against desired. The
260 // describeDBClusterEndpoints response does not include tags, so we
261 // diff against the previously-recorded tag set on `output`.
262 const observedTags = output?.tags ?? {};
263 const { removed, upsert } = diffTags(observedTags, desiredTags);
264 if (upsert.length > 0 && dbClusterEndpointArn) {
265 yield* rds.addTagsToResource({
266 ResourceName: dbClusterEndpointArn,
267 Tags: upsert,
268 });
269 }
270 if (removed.length > 0 && dbClusterEndpointArn) {
271 yield* rds.removeTagsFromResource({
272 ResourceName: dbClusterEndpointArn,
273 TagKeys: removed,
274 });
275 }
276
277 yield* session.note(dbClusterEndpointArn ?? identifier);
278 return toAttrs({ endpoint: observed, tags: desiredTags });
279 }),
280 delete: Effect.fn(function* ({ output }) {
281 yield* rds
282 .deleteDBClusterEndpoint({
283 DBClusterEndpointIdentifier: output.dbClusterEndpointIdentifier,
284 })
285 .pipe(Effect.catchTag("DBClusterEndpointNotFoundFault", () => Effect.void));
286 }),
287 };
288 }),
289 );