@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 394 lines 14.4 KB
Raw
1 import * as r53r from "@distilled.cloud/aws/route53resolver";
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, hasAlchemyTags } from "alchemy/Tags";
8 import * as Effect from "effect/Effect";
9 import * as Option from "effect/Option";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { Providers } from "../Providers.ts";
13 import {
14 fetchResolverTags,
15 sameStringSet,
16 syncResolverTags,
17 toResolverTagList,
18 } from "./internal.ts";
19
20 export interface ResolverEndpointIpAddress {
21 /**
22 * ID of the subnet to place a resolver network interface in. Changing the
23 * set of subnets forces replacement.
24 */
25 subnetId: string;
26 /**
27 * Optional fixed IPv4 address within the subnet. If omitted, Resolver
28 * picks an available address.
29 */
30 ip?: string;
31 /**
32 * Optional fixed IPv6 address within the subnet (dual-stack/IPv6
33 * endpoints only).
34 */
35 ipv6?: string;
36 }
37
38 export interface ResolverEndpointProps {
39 /**
40 * Friendly name of the endpoint. Also used as the `CreatorRequestId`.
41 * Changing it forces replacement.
42 * @default ${app}-${stage}-${id}
43 */
44 name?: string;
45 /**
46 * Whether the endpoint accepts DNS queries from your network (`INBOUND`)
47 * or forwards queries from your VPC to your network (`OUTBOUND`).
48 * Changing it forces replacement.
49 */
50 direction: "INBOUND" | "OUTBOUND";
51 /**
52 * IP addresses (one per subnet, minimum 2 subnets in different AZs) that
53 * the resolver endpoint's network interfaces are created in. Changing the
54 * subnet set forces replacement.
55 */
56 ipAddresses: ResolverEndpointIpAddress[];
57 /**
58 * IDs of the security groups controlling access to the endpoint's
59 * network interfaces. Changing them forces replacement.
60 */
61 securityGroupIds: string[];
62 /**
63 * The IP family of the endpoint.
64 * @default "IPV4"
65 */
66 resolverEndpointType?: "IPV4" | "IPV6" | "DUALSTACK";
67 /**
68 * DNS protocols the endpoint answers/forwards with.
69 * @default ["Do53"]
70 */
71 protocols?: ("Do53" | "DoH" | "DoH-FIPS")[];
72 /**
73 * Tags to apply to the endpoint. Merged with internal Alchemy tags.
74 */
75 tags?: Record<string, string>;
76 }
77
78 export interface ResolverEndpoint extends Resource<
79 "AWS.Route53Resolver.ResolverEndpoint",
80 ResolverEndpointProps,
81 {
82 /**
83 * ID of the resolver endpoint (e.g. `rslvr-in-...` / `rslvr-out-...`).
84 */
85 resolverEndpointId: string;
86 /**
87 * ARN of the resolver endpoint.
88 */
89 resolverEndpointArn: string;
90 /**
91 * Name of the endpoint.
92 */
93 name: string;
94 /**
95 * `INBOUND` or `OUTBOUND`.
96 */
97 direction: string;
98 /**
99 * ID of the VPC the endpoint's network interfaces live in.
100 */
101 hostVpcId: string;
102 },
103 never,
104 Providers
105 > {}
106
107 /**
108 * A Route 53 Resolver endpoint — the set of elastic network interfaces that
109 * connect your VPC's `.2` resolver to DNS resolvers on your own network.
110 *
111 * An `INBOUND` endpoint lets DNS resolvers on your network forward queries
112 * to Route 53 Resolver; an `OUTBOUND` endpoint lets Resolver forward queries
113 * from your VPCs to your network (paired with FORWARD `ResolverRule`s).
114 *
115 * Endpoint provisioning is asynchronous (typically 1-2 minutes); the
116 * provider waits (bounded) for the endpoint to become `OPERATIONAL` so
117 * dependent resolver rules can use it immediately.
118 * ### Creating Endpoints
119 * **Example:** Inbound Endpoint
120 * ```typescript
121 * import * as Route53Resolver from "@alchemy.run/aws/Route53Resolver";
122 *
123 * const inbound = yield* Route53Resolver.ResolverEndpoint("Inbound", {
124 * direction: "INBOUND",
125 * securityGroupIds: [sg.securityGroupId],
126 * ipAddresses: [
127 * { subnetId: subnetA.subnetId },
128 * { subnetId: subnetB.subnetId },
129 * ],
130 * });
131 * ```
132 *
133 * **Example:** Outbound Endpoint with Fixed IPs
134 * ```typescript
135 * const outbound = yield* Route53Resolver.ResolverEndpoint("Outbound", {
136 * direction: "OUTBOUND",
137 * securityGroupIds: [sg.securityGroupId],
138 * ipAddresses: [
139 * { subnetId: subnetA.subnetId, ip: "10.0.0.10" },
140 * { subnetId: subnetB.subnetId, ip: "10.0.1.10" },
141 * ],
142 * });
143 * ```
144 *
145 * ### Forwarding Queries
146 * **Example:** Forward a Domain through an Outbound Endpoint
147 * ```typescript
148 * const rule = yield* Route53Resolver.ResolverRule("CorpForward", {
149 * domainName: "corp.example.com",
150 * resolverEndpointId: outbound.resolverEndpointId,
151 * targetIps: [{ ip: "192.168.1.10" }],
152 * });
153 * ```
154 *
155 * @resource
156 */
157 export const ResolverEndpoint = Resource<ResolverEndpoint>("AWS.Route53Resolver.ResolverEndpoint");
158
159 /**
160 * Recreating an endpoint whose deterministic `CreatorRequestId` is still
161 * attached to a `DELETING` predecessor raises `ResourceExistsException`
162 * until the old endpoint is fully gone (~1 min). Retry on a bounded
163 * schedule (~2 min).
164 *
165 * Explicitly typed: inlining `Effect.retry` in provider lifecycle code can
166 * widen the provider layer to `unknown` in declaration emit.
167 *
168 * @internal
169 */
170 const retryEndpointExists = <A, E extends { _tag: string }, R>(
171 self: Effect.Effect<A, E, R>,
172 ): Effect.Effect<A, E, R> =>
173 Effect.retry(self, {
174 while: (e) => e._tag === "ResourceExistsException",
175 schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]),
176 });
177
178 /**
179 * Deleting an endpoint that still has resolver rules attached (their own
180 * deletion may still be propagating) surfaces `InvalidRequestException` —
181 * retry briefly so the delete converges.
182 *
183 * @internal
184 */
185 const retryEndpointInUse = <A, E extends { _tag: string }, R>(
186 self: Effect.Effect<A, E, R>,
187 ): Effect.Effect<A, E, R> =>
188 Effect.retry(self, {
189 while: (e) => e._tag === "InvalidRequestException",
190 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
191 });
192
193 /**
194 * Bounded wait (~3.5 min) for an endpoint to leave its transitional state
195 * (`CREATING`/`UPDATING`). If the budget is exhausted the last observation
196 * is returned and downstream consumers retry on their own typed errors.
197 *
198 * @internal
199 */
200 const untilEndpointSettled = <E, R>(
201 self: Effect.Effect<r53r.ResolverEndpoint | undefined, E, R>,
202 ): Effect.Effect<r53r.ResolverEndpoint | undefined, E, R> =>
203 self.pipe(
204 Effect.repeat({
205 schedule: Schedule.fixed("5 seconds"),
206 until: (endpoint) =>
207 endpoint === undefined ||
208 (endpoint.Status !== "CREATING" && endpoint.Status !== "UPDATING"),
209 times: 42,
210 }),
211 );
212
213 export const ResolverEndpointProvider = () =>
214 Provider.effect(
215 ResolverEndpoint,
216 Effect.gen(function* () {
217 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
218 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
219 });
220
221 const getEndpoint = (endpointId: string) =>
222 r53r.getResolverEndpoint({ ResolverEndpointId: endpointId }).pipe(
223 Effect.map((r) => r.ResolverEndpoint),
224 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
225 );
226
227 // Observe by the cached endpoint ID first, falling back to the
228 // deterministic CreatorRequestId (set to the physical name at create).
229 // Endpoints in DELETING state are treated as missing so a reconcile
230 // after an out-of-band delete recreates.
231 const observe = Effect.fn(function* (name: string, endpointId: string | undefined) {
232 if (endpointId !== undefined) {
233 const byId = yield* getEndpoint(endpointId);
234 if (byId !== undefined && byId.Status !== "DELETING") {
235 return byId;
236 }
237 }
238 return yield* r53r.listResolverEndpoints
239 .items({
240 Filters: [{ Name: "CreatorRequestId", Values: [name] }],
241 })
242 .pipe(
243 Stream.filter((endpoint) => endpoint.Status !== "DELETING"),
244 Stream.runHead,
245 Effect.map(Option.getOrUndefined),
246 );
247 });
248
249 return ResolverEndpoint.Provider.of({
250 stables: ["resolverEndpointId", "resolverEndpointArn", "name", "direction", "hostVpcId"],
251 // Top-level resource: enumerate every resolver endpoint in the
252 // ambient account/region.
253 list: () =>
254 r53r.listResolverEndpoints.pages({}).pipe(
255 Stream.runCollect,
256 Effect.map((chunk) =>
257 Array.from(chunk)
258 .flatMap((page) => page.ResolverEndpoints ?? [])
259 .flatMap((endpoint) =>
260 endpoint.Id !== undefined && endpoint.Arn !== undefined
261 ? [
262 {
263 resolverEndpointId: endpoint.Id,
264 resolverEndpointArn: endpoint.Arn,
265 name: endpoint.Name ?? "",
266 direction: endpoint.Direction ?? "",
267 hostVpcId: endpoint.HostVPCId ?? "",
268 },
269 ]
270 : [],
271 ),
272 ),
273 ),
274 read: Effect.fn(function* ({ id, olds, output }) {
275 const name = output?.name ?? (yield* createName(id, olds ?? {}));
276 const endpoint = yield* observe(name, output?.resolverEndpointId);
277 if (endpoint?.Id === undefined || endpoint.Arn === undefined) {
278 return undefined;
279 }
280 const attrs = {
281 resolverEndpointId: endpoint.Id,
282 resolverEndpointArn: endpoint.Arn,
283 name: endpoint.Name ?? name,
284 direction: endpoint.Direction ?? "",
285 hostVpcId: endpoint.HostVPCId ?? "",
286 };
287 const tags = yield* fetchResolverTags(endpoint.Arn);
288 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
289 }),
290 // Replacement detection only. Direction, security groups, and the
291 // subnet placement of the network interfaces are immutable;
292 // protocols/endpoint type/tags update in place via reconcile.
293 diff: Effect.fn(function* ({ id, news, olds }) {
294 if (!isResolved(news)) return undefined;
295 const oldName = yield* createName(id, olds);
296 const newName = yield* createName(id, news);
297 if (oldName !== newName) return { action: "replace" } as const;
298 if (olds.direction !== news.direction) {
299 return { action: "replace" } as const;
300 }
301 if (!sameStringSet(olds.securityGroupIds, news.securityGroupIds)) {
302 return { action: "replace" } as const;
303 }
304 const ipKey = (ip: ResolverEndpointIpAddress) =>
305 `${ip.subnetId}:${ip.ip ?? ""}:${ip.ipv6 ?? ""}`;
306 if (!sameStringSet(olds.ipAddresses.map(ipKey), news.ipAddresses.map(ipKey))) {
307 return { action: "replace" } as const;
308 }
309 }),
310 reconcile: Effect.fn(function* ({ id, news, output, session }) {
311 const name = output?.name ?? (yield* createName(id, news));
312 const internalTags = yield* createInternalTags(id);
313 const desiredTags = { ...news.tags, ...internalTags };
314
315 // 1. OBSERVE — cloud state is authoritative; output only caches
316 // the endpoint ID.
317 let endpoint = yield* observe(name, output?.resolverEndpointId);
318
319 // 2. ENSURE — create if missing. A DELETING predecessor holding
320 // the same CreatorRequestId surfaces ResourceExistsException,
321 // which is retried until the old endpoint drains.
322 if (endpoint === undefined) {
323 yield* session.note(`creating resolver endpoint ${name}`);
324 endpoint = yield* retryEndpointExists(
325 r53r.createResolverEndpoint({
326 CreatorRequestId: name,
327 Name: name,
328 Direction: news.direction,
329 SecurityGroupIds: news.securityGroupIds,
330 IpAddresses: news.ipAddresses.map((ip) => ({
331 SubnetId: ip.subnetId,
332 Ip: ip.ip,
333 Ipv6: ip.ipv6,
334 })),
335 ResolverEndpointType: news.resolverEndpointType,
336 Protocols: news.protocols,
337 Tags: toResolverTagList(desiredTags),
338 }),
339 ).pipe(Effect.map((r) => r.ResolverEndpoint!));
340 }
341 const endpointId = endpoint.Id!;
342
343 // Endpoint provisioning is asynchronous (~1-2 min). Wait (bounded)
344 // for it to settle so dependents (FORWARD rules) can use it.
345 yield* session.note(`waiting for resolver endpoint ${endpointId} to become OPERATIONAL`);
346 const settled = yield* untilEndpointSettled(getEndpoint(endpointId));
347 endpoint = settled ?? endpoint;
348
349 // 3. SYNC — protocols and endpoint type are mutable in place.
350 // Diff observed cloud state against desired; skip the API on
351 // no-op.
352 const desiredProtocols = news.protocols;
353 const protocolsDelta =
354 desiredProtocols !== undefined &&
355 !sameStringSet(endpoint.Protocols ?? [], desiredProtocols);
356 const desiredType = news.resolverEndpointType;
357 const typeDelta =
358 desiredType !== undefined && endpoint.ResolverEndpointType !== desiredType;
359 if (protocolsDelta || typeDelta) {
360 endpoint = yield* r53r
361 .updateResolverEndpoint({
362 ResolverEndpointId: endpointId,
363 ...(protocolsDelta ? { Protocols: desiredProtocols } : {}),
364 ...(typeDelta ? { ResolverEndpointType: desiredType } : {}),
365 })
366 .pipe(Effect.map((r) => r.ResolverEndpoint ?? endpoint!));
367 }
368
369 // 3b. SYNC TAGS — diff against observed cloud tags.
370 const arn = endpoint.Arn!;
371 yield* syncResolverTags(arn, desiredTags);
372
373 yield* session.note(endpointId);
374 return {
375 resolverEndpointId: endpointId,
376 resolverEndpointArn: arn,
377 name: endpoint.Name ?? name,
378 direction: endpoint.Direction ?? news.direction,
379 hostVpcId: endpoint.HostVPCId ?? "",
380 };
381 }),
382 delete: Effect.fn(function* ({ output }) {
383 yield* retryEndpointInUse(
384 r53r.deleteResolverEndpoint({
385 ResolverEndpointId: output.resolverEndpointId,
386 }),
387 ).pipe(
388 Effect.asVoid,
389 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
390 );
391 }),
392 });
393 }),
394 );