@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 276 lines 9.89 KB
Raw
1 import * as r53r from "@distilled.cloud/aws/route53resolver";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Schedule from "effect/Schedule";
7 import * as Stream from "effect/Stream";
8 import type { Providers } from "../Providers.ts";
9
10 export interface ResolverRuleAssociationProps {
11 /**
12 * ID of the resolver rule to attach. Changing it forces replacement.
13 */
14 resolverRuleId: string;
15 /**
16 * ID of the VPC the rule takes effect in. Changing it forces
17 * replacement.
18 */
19 vpcId: string;
20 /**
21 * Optional friendly name recorded on the association. Changing it forces
22 * replacement (associations cannot be updated).
23 */
24 name?: string;
25 }
26
27 export interface ResolverRuleAssociation extends Resource<
28 "AWS.Route53Resolver.ResolverRuleAssociation",
29 ResolverRuleAssociationProps,
30 {
31 /**
32 * ID of the association (e.g. `rslvr-rrassoc-...`).
33 */
34 resolverRuleAssociationId: string;
35 /**
36 * ID of the associated resolver rule.
37 */
38 resolverRuleId: string;
39 /**
40 * ID of the VPC the rule is associated with.
41 */
42 vpcId: string;
43 },
44 never,
45 Providers
46 > {}
47
48 /**
49 * An association between a Route 53 Resolver rule and a VPC. Once
50 * associated, Resolver applies the rule to DNS queries that originate in
51 * that VPC.
52 * ### Associating Rules
53 * **Example:** Attach a Forwarding Rule to a VPC
54 * ```typescript
55 * import * as Route53Resolver from "@alchemy.run/aws/Route53Resolver";
56 *
57 * const association = yield* Route53Resolver.ResolverRuleAssociation(
58 * "CorpForwardAssoc",
59 * {
60 * resolverRuleId: rule.resolverRuleId,
61 * vpcId: vpc.vpcId,
62 * },
63 * );
64 * ```
65 *
66 * @resource
67 */
68 export const ResolverRuleAssociation = Resource<ResolverRuleAssociation>(
69 "AWS.Route53Resolver.ResolverRuleAssociation",
70 );
71
72 /**
73 * Re-associating a (rule, VPC) pair whose previous association is still
74 * draining (`DELETING`) surfaces `InvalidRequestException` or
75 * `ResourceExistsException`; the rule itself may also still be settling
76 * (`ResourceUnavailableException`). All are bounded races — retry (~60s).
77 *
78 * Explicitly typed: inlining `Effect.retry` in provider lifecycle code can
79 * widen the provider layer to `unknown` in declaration emit.
80 *
81 * @internal
82 */
83 const retryAssociateRaces = <A, E extends { _tag: string }, R>(
84 self: Effect.Effect<A, E, R>,
85 ): Effect.Effect<A, E, R> =>
86 Effect.retry(self, {
87 while: (e) =>
88 e._tag === "InvalidRequestException" ||
89 e._tag === "ResourceExistsException" ||
90 e._tag === "ResourceUnavailableException",
91 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
92 });
93
94 /**
95 * Best-effort bounded wait (~30s) for an association to leave `CREATING`.
96 * Associations routinely take 1-2 minutes to reach `COMPLETE`; the
97 * association is already effective for reconciliation purposes, so the
98 * reconciler does not block on the full transition.
99 *
100 * @internal
101 */
102 const untilAssociationSettled = <E, R>(
103 self: Effect.Effect<r53r.ResolverRuleAssociation | undefined, E, R>,
104 ): Effect.Effect<r53r.ResolverRuleAssociation | undefined, E, R> =>
105 self.pipe(
106 Effect.repeat({
107 schedule: Schedule.fixed("3 seconds"),
108 until: (association) => association === undefined || association.Status !== "CREATING",
109 times: 10,
110 }),
111 );
112
113 /**
114 * Bounded wait (~2 min) for an association to fully drain after
115 * disassociation. Deletion must converge before returning: the parent
116 * resolver rule cannot be deleted while any association (even `DELETING`)
117 * remains, so returning early cascades `ResourceInUseException` onto the
118 * rule's delete.
119 *
120 * @internal
121 */
122 const untilAssociationGone = <A, E, R>(
123 self: Effect.Effect<A | undefined, E, R>,
124 ): Effect.Effect<A | undefined, E, R> =>
125 self.pipe(
126 Effect.repeat({
127 schedule: Schedule.fixed("5 seconds"),
128 until: (association) => association === undefined,
129 times: 24,
130 }),
131 );
132
133 /**
134 * Disassociating an association that is still `CREATING` transiently fails
135 * with `InvalidRequestException` — retry briefly until it settles.
136 *
137 * @internal
138 */
139 const retryDisassociateRaces = <A, E extends { _tag: string }, R>(
140 self: Effect.Effect<A, E, R>,
141 ): Effect.Effect<A, E, R> =>
142 Effect.retry(self, {
143 while: (e) => e._tag === "InvalidRequestException",
144 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
145 });
146
147 export const ResolverRuleAssociationProvider = () =>
148 Provider.effect(
149 ResolverRuleAssociation,
150 Effect.gen(function* () {
151 const listAssociations = (resolverRuleId: string, vpcId: string) =>
152 r53r
153 .listResolverRuleAssociations({
154 Filters: [
155 { Name: "ResolverRuleId", Values: [resolverRuleId] },
156 { Name: "VPCId", Values: [vpcId] },
157 ],
158 })
159 .pipe(Effect.map((r) => r.ResolverRuleAssociations ?? []));
160
161 // An association is identified by its (rule, VPC) pair; DELETING and
162 // FAILED associations count as missing so reconcile re-associates.
163 const observe = (resolverRuleId: string, vpcId: string) =>
164 listAssociations(resolverRuleId, vpcId).pipe(
165 Effect.map((associations) =>
166 associations.find(
167 (association) => association.Status !== "DELETING" && association.Status !== "FAILED",
168 ),
169 ),
170 );
171
172 // Any association record at all — used by delete to wait until the
173 // (rule, VPC) pair has fully drained, DELETING entries included.
174 const observeAny = (resolverRuleId: string, vpcId: string) =>
175 listAssociations(resolverRuleId, vpcId).pipe(Effect.map((associations) => associations[0]));
176
177 return ResolverRuleAssociation.Provider.of({
178 stables: ["resolverRuleAssociationId", "resolverRuleId", "vpcId"],
179 // Top-level enumeration: associations are listable account-wide.
180 list: () =>
181 r53r.listResolverRuleAssociations.pages({}).pipe(
182 Stream.runCollect,
183 Effect.map((chunk) =>
184 Array.from(chunk)
185 .flatMap((page) => page.ResolverRuleAssociations ?? [])
186 .flatMap((association) =>
187 association.Id !== undefined &&
188 association.ResolverRuleId !== undefined &&
189 association.VPCId !== undefined &&
190 // AWS creates an Internet Resolver association for each
191 // VPC. It cannot be disassociated directly and disappears
192 // automatically with the VPC.
193 !association.Id.startsWith("rslvr-autodefined") &&
194 !association.ResolverRuleId.startsWith("rslvr-autodefined")
195 ? [
196 {
197 resolverRuleAssociationId: association.Id,
198 resolverRuleId: association.ResolverRuleId,
199 vpcId: association.VPCId,
200 },
201 ]
202 : [],
203 ),
204 ),
205 ),
206 read: Effect.fn(function* ({ olds, output }) {
207 const resolverRuleId = output?.resolverRuleId ?? olds?.resolverRuleId;
208 const vpcId = output?.vpcId ?? olds?.vpcId;
209 if (resolverRuleId === undefined || vpcId === undefined) {
210 return undefined;
211 }
212 const association = yield* observe(resolverRuleId, vpcId);
213 if (association?.Id === undefined) {
214 return undefined;
215 }
216 return {
217 resolverRuleAssociationId: association.Id,
218 resolverRuleId,
219 vpcId,
220 };
221 }),
222 // Existence-only resource — every identifying property change
223 // replaces the association.
224 diff: Effect.fn(function* ({ olds, news }) {
225 if (!isResolved(news)) return undefined;
226 if (
227 olds.resolverRuleId !== news.resolverRuleId ||
228 olds.vpcId !== news.vpcId ||
229 olds.name !== news.name
230 ) {
231 return { action: "replace" } as const;
232 }
233 }),
234 // Existence-only: observe → if missing, associate. There is no
235 // sync step (an association has no mutable aspects).
236 reconcile: Effect.fn(function* ({ news, session }) {
237 let association = yield* observe(news.resolverRuleId, news.vpcId);
238 if (association === undefined) {
239 association = yield* retryAssociateRaces(
240 r53r.associateResolverRule({
241 ResolverRuleId: news.resolverRuleId,
242 VPCId: news.vpcId,
243 Name: news.name,
244 }),
245 ).pipe(Effect.map((r) => r.ResolverRuleAssociation!));
246 }
247 // Association setup is asynchronous but quick; wait (bounded) so
248 // the rule is actually in effect when the deploy completes.
249 const settled = yield* untilAssociationSettled(observe(news.resolverRuleId, news.vpcId));
250 association = settled ?? association;
251
252 yield* session.note(`${news.resolverRuleId}/${news.vpcId}`);
253 return {
254 resolverRuleAssociationId: association.Id!,
255 resolverRuleId: news.resolverRuleId,
256 vpcId: news.vpcId,
257 };
258 }),
259 delete: Effect.fn(function* ({ output }) {
260 yield* retryDisassociateRaces(
261 r53r.disassociateResolverRule({
262 ResolverRuleId: output.resolverRuleId,
263 VPCId: output.vpcId,
264 }),
265 ).pipe(
266 Effect.asVoid,
267 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
268 );
269 // Disassociation is asynchronous and the parent rule cannot be
270 // deleted until the association has fully drained — wait
271 // (bounded ~2 min) for it to disappear.
272 yield* untilAssociationGone(observeAny(output.resolverRuleId, output.vpcId));
273 }),
274 });
275 }),
276 );