@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 275 lines 10.2 KB
Raw
1 import * as profiles from "@distilled.cloud/aws/route53profiles";
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 } from "alchemy/Tags";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export interface ProfileAssociationProps {
13 /**
14 * ID of the Route 53 Profile to apply. Changing it forces replacement.
15 */
16 profileId: string;
17 /**
18 * ID of the VPC to associate the Profile with. A VPC can have only one
19 * Profile associated with it. Changing it forces replacement.
20 */
21 resourceId: string;
22 /**
23 * Friendly name recorded on the association. If omitted, a unique name
24 * is generated. Associations cannot be renamed, so changing it forces
25 * replacement.
26 */
27 name?: string;
28 }
29
30 export interface ProfileAssociation extends Resource<
31 "AWS.Route53Profiles.ProfileAssociation",
32 ProfileAssociationProps,
33 {
34 /** ID of the association (e.g. `rpassoc-...`). */
35 profileAssociationId: string;
36 /** ID of the associated Profile. */
37 profileId: string;
38 /** ID of the associated VPC. */
39 resourceId: string;
40 /** Name recorded on the association. */
41 name: string;
42 /**
43 * Status of the association at the end of the deploy. Associations
44 * complete asynchronously (typically within a couple of minutes), so
45 * this is usually `CREATING`; the Profile's DNS settings take effect in
46 * the VPC once the association reaches `COMPLETE`.
47 */
48 status: profiles.ProfileStatus;
49 },
50 never,
51 Providers
52 > {}
53
54 /**
55 * An association between a Route 53 Profile and a VPC. Once the association
56 * completes, every DNS resource attached to the Profile (private hosted
57 * zones, Resolver rules, DNS Firewall rule groups) takes effect in the VPC.
58 *
59 * A VPC can have only one Profile associated with it; a Profile can be
60 * associated with thousands of VPCs. The association is created immediately
61 * but completes asynchronously — the returned `status` is typically still
62 * `CREATING` when the deploy finishes.
63 * ### Associating a Profile
64 * **Example:** Apply a Profile to a VPC
65 * ```typescript
66 * import * as Route53Profiles from "@alchemy.run/aws/Route53Profiles";
67 *
68 * const association = yield* Route53Profiles.ProfileAssociation("AppVpcDns", {
69 * profileId: profile.profileId,
70 * resourceId: vpc.vpcId,
71 * });
72 * ```
73 *
74 * @resource
75 */
76 export const ProfileAssociation = Resource<ProfileAssociation>(
77 "AWS.Route53Profiles.ProfileAssociation",
78 );
79
80 /**
81 * Associating/disassociating while the Profile or a prior association is
82 * still settling surfaces `ConflictException`; retry on a bounded schedule
83 * (~60s).
84 *
85 * Explicitly typed: inlining `Effect.retry` in provider lifecycle code can
86 * widen the provider layer to `unknown` in declaration emit.
87 *
88 * @internal
89 */
90 const retryConflict = <A, E extends { _tag: string }, R>(
91 self: Effect.Effect<A, E, R>,
92 ): Effect.Effect<A, E, R> =>
93 Effect.retry(self, {
94 while: (e) => e._tag === "ConflictException",
95 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
96 });
97
98 /**
99 * Bounded wait (~2 min) for a disassociation to drain. Disassociation was
100 * observed to take ~1–2 minutes; waiting here keeps teardown ordering sound
101 * (the Profile and the VPC both reject deletion while the association
102 * exists). If the association is still draining after the budget we proceed
103 * — the Profile and VPC providers absorb the residual with their own
104 * bounded conflict/dependency retries.
105 *
106 * @internal
107 */
108 const untilAssociationGone = <E, R>(
109 self: Effect.Effect<profiles.ProfileAssociation | undefined, E, R>,
110 ): Effect.Effect<profiles.ProfileAssociation | undefined, E, R> =>
111 self.pipe(
112 Effect.repeat({
113 schedule: Schedule.fixed("4 seconds"),
114 until: (association) => association === undefined,
115 times: 30,
116 }),
117 );
118
119 export const ProfileAssociationProvider = () =>
120 Provider.effect(
121 ProfileAssociation,
122 Effect.gen(function* () {
123 const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) {
124 return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 }));
125 });
126
127 // `DELETING`/`DELETED` associations count as missing so reconcile
128 // re-associates and delete converges.
129 const isLive = (association: profiles.ProfileAssociation | undefined) =>
130 association !== undefined &&
131 association.Status !== "DELETING" &&
132 association.Status !== "DELETED"
133 ? association
134 : undefined;
135
136 const observeById = (profileAssociationId: string) =>
137 profiles
138 .getProfileAssociation({
139 ProfileAssociationId: profileAssociationId,
140 })
141 .pipe(
142 Effect.map((r) => isLive(r.ProfileAssociation)),
143 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
144 );
145
146 const observeByPair = (profileId: string, resourceId: string) =>
147 profiles.listProfileAssociations
148 .items({ ProfileId: profileId, ResourceId: resourceId })
149 .pipe(
150 Stream.runCollect,
151 Effect.map((chunk) =>
152 Array.from(chunk)
153 .map(isLive)
154 .find((association) => association !== undefined),
155 ),
156 );
157
158 return ProfileAssociation.Provider.of({
159 stables: ["profileAssociationId", "profileId", "resourceId", "name"],
160 // Top-level enumeration: associations are listable account-wide.
161 list: () =>
162 profiles.listProfileAssociations.items({}).pipe(
163 Stream.runCollect,
164 Effect.map((chunk) =>
165 Array.from(chunk).flatMap((association) =>
166 association.Id !== undefined &&
167 association.ProfileId !== undefined &&
168 association.ResourceId !== undefined &&
169 association.Status !== "DELETING" &&
170 association.Status !== "DELETED"
171 ? [
172 {
173 profileAssociationId: association.Id,
174 profileId: association.ProfileId,
175 resourceId: association.ResourceId,
176 name: association.Name ?? "",
177 status: association.Status ?? "COMPLETE",
178 },
179 ]
180 : [],
181 ),
182 ),
183 ),
184 read: Effect.fn(function* ({ olds, output }) {
185 const association = output?.profileAssociationId
186 ? yield* observeById(output.profileAssociationId)
187 : olds?.profileId !== undefined && olds.resourceId !== undefined
188 ? yield* observeByPair(olds.profileId, olds.resourceId)
189 : undefined;
190 if (association?.Id === undefined) return undefined;
191 return {
192 profileAssociationId: association.Id,
193 profileId: association.ProfileId!,
194 resourceId: association.ResourceId!,
195 name: association.Name ?? "",
196 status: association.Status ?? "COMPLETE",
197 };
198 }),
199 // Existence-only resource — every identifying property change
200 // replaces the association (there is no update API).
201 diff: Effect.fn(function* ({ id, news, olds }) {
202 if (!isResolved(news)) return undefined;
203 const oldName = yield* createName(id, olds);
204 const newName = yield* createName(id, news);
205 if (
206 olds.profileId !== news.profileId ||
207 olds.resourceId !== news.resourceId ||
208 oldName !== newName
209 ) {
210 return { action: "replace" } as const;
211 }
212 }),
213 // Existence-only: observe → if missing, associate. There is no sync
214 // step. We deliberately do NOT wait for `COMPLETE` — the association
215 // takes a couple of minutes to propagate and is usable as a
216 // reference immediately.
217 reconcile: Effect.fn(function* ({ id, news, output, session }) {
218 const name = output?.name ?? (yield* createName(id, news));
219 const internalTags = yield* createInternalTags(id);
220
221 let association = output?.profileAssociationId
222 ? yield* observeById(output.profileAssociationId)
223 : undefined;
224 if (!association) {
225 association = yield* observeByPair(news.profileId, news.resourceId);
226 }
227
228 if (!association) {
229 association = yield* retryConflict(
230 profiles.associateProfile({
231 ProfileId: news.profileId,
232 ResourceId: news.resourceId,
233 Name: name,
234 Tags: Object.entries(internalTags).map(([Key, Value]) => ({
235 Key,
236 Value,
237 })),
238 }),
239 ).pipe(
240 Effect.map((r) => r.ProfileAssociation!),
241 // A concurrent reconcile won the race — re-observe.
242 Effect.catchTag("ResourceExistsException", () =>
243 observeByPair(news.profileId, news.resourceId).pipe(
244 Effect.map((existing) => existing!),
245 ),
246 ),
247 );
248 }
249
250 yield* session.note(`${news.profileId}/${news.resourceId}`);
251 return {
252 profileAssociationId: association.Id!,
253 profileId: news.profileId,
254 resourceId: news.resourceId,
255 name: association.Name ?? name,
256 status: association.Status ?? "CREATING",
257 };
258 }),
259 delete: Effect.fn(function* ({ output }) {
260 yield* retryConflict(
261 profiles.disassociateProfile({
262 ProfileId: output.profileId,
263 ResourceId: output.resourceId,
264 }),
265 ).pipe(
266 Effect.asVoid,
267 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
268 );
269 // Disassociation drains asynchronously (~1–2 min). Wait (bounded)
270 // so the Profile and VPC can be deleted right after.
271 yield* untilAssociationGone(observeById(output.profileAssociationId));
272 }),
273 });
274 }),
275 );