@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 375 lines 13.4 KB
Raw
1 import * as route53 from "@distilled.cloud/aws/route-53";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, diffTags } from "alchemy/Tags";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10
11 export interface HostedZoneProps {
12 /**
13 * Fully qualified domain name for the zone (e.g. `"example.com"`). A trailing
14 * dot is added automatically. Changing the name forces replacement.
15 */
16 name: string;
17 /**
18 * Optional comment describing the zone. Updated in place.
19 */
20 comment?: string;
21 /**
22 * Whether this is a private hosted zone. Requires `vpc`. Changing this forces
23 * replacement.
24 * @default false
25 */
26 privateZone?: boolean;
27 /**
28 * VPC to associate with a private hosted zone at create time. Changing the
29 * initial VPC forces replacement.
30 */
31 vpc?: {
32 /** VPC ID. */
33 vpcId: string;
34 /** Region the VPC lives in. */
35 vpcRegion: string;
36 };
37 /**
38 * ID of a reusable delegation set to associate with the zone. Changing this
39 * forces replacement.
40 */
41 delegationSetId?: string;
42 /**
43 * Whether to delete all non-SOA/NS records before deleting the zone.
44 * @default false
45 */
46 forceDestroy?: boolean;
47 /**
48 * Tags applied to the hosted zone.
49 */
50 tags?: Record<string, string>;
51 }
52
53 export interface HostedZone extends Resource<
54 "AWS.Route53.HostedZone",
55 HostedZoneProps,
56 {
57 /**
58 * Hosted zone ID (without the `/hostedzone/` prefix).
59 */
60 id: string;
61 /**
62 * Fully qualified zone name (with trailing dot).
63 */
64 name: string;
65 /**
66 * Authoritative name servers for the zone.
67 */
68 nameServers: string[];
69 /**
70 * Current zone comment.
71 */
72 comment: string | undefined;
73 },
74 never,
75 Providers
76 > {}
77
78 /**
79 * A Route 53 hosted zone.
80 *
81 * `HostedZone` manages the lifecycle of a public or private hosted zone,
82 * including its comment and tags. For public zones, the four authoritative
83 * name servers are exposed as `nameServers`.
84 * ### Creating a Hosted Zone
85 * **Example:** Public Hosted Zone
86 * ```typescript
87 * const zone = yield* HostedZone("MyZone", {
88 * name: "example.com",
89 * comment: "Primary zone",
90 * });
91 * // zone.nameServers -> the 4 NS records to set at your registrar
92 * ```
93 *
94 * **Example:** Force Destroy
95 * ```typescript
96 * const zone = yield* HostedZone("MyZone", {
97 * name: "example.com",
98 * forceDestroy: true, // delete leftover records on destroy
99 * });
100 * ```
101 *
102 * @resource
103 */
104 export const HostedZone = Resource<HostedZone>("AWS.Route53.HostedZone");
105
106 const normalizeId = (id: string) => id.replace(/^\/hostedzone\//, "");
107
108 const normalizeName = (name: string) => (name.endsWith(".") ? name : `${name}.`);
109
110 export const HostedZoneProvider = () =>
111 Provider.effect(
112 HostedZone,
113 Effect.gen(function* () {
114 // Poll `getChange` until the change reaches INSYNC. `getChange` is
115 // eventually consistent and can briefly return `NoSuchChange` right after
116 // submit, so coalesce that to a non-INSYNC status and keep polling.
117 // `ChangeInfo.Id` comes back as "/change/C..." but `getChange` only
118 // accepts the bare id — the prefixed form returns `NoSuchChange`
119 // forever, silently burning the full repeat cap on every change.
120 const waitForChange = Effect.fn(function* (changeId: string) {
121 return yield* route53.getChange({ Id: changeId.replace(/^\/change\//, "") }).pipe(
122 Effect.map((r) => r.ChangeInfo.Status),
123 Effect.catchTag("NoSuchChange", () => Effect.succeed("PENDING")),
124 Effect.repeat({
125 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]),
126 until: (status) => status === "INSYNC",
127 }),
128 );
129 });
130
131 const findByName = Effect.fn(function* (name: string) {
132 const response = yield* route53.listHostedZonesByName({
133 DNSName: normalizeName(name),
134 MaxItems: 1,
135 });
136 return (response.HostedZones ?? []).find((zone) => zone.Name === normalizeName(name));
137 });
138
139 const observe = Effect.fn(function* (id: string) {
140 return yield* route53
141 .getHostedZone({ Id: normalizeId(id) })
142 .pipe(Effect.catchTag("NoSuchHostedZone", () => Effect.undefined));
143 });
144
145 const observedTags = Effect.fn(function* (id: string) {
146 const response = yield* route53.listTagsForResource({
147 ResourceType: "hostedzone",
148 ResourceId: normalizeId(id),
149 });
150 const record: Record<string, string> = {};
151 for (const tag of response.ResourceTagSet.Tags ?? []) {
152 if (tag.Key !== undefined && tag.Value !== undefined) {
153 record[tag.Key] = tag.Value;
154 }
155 }
156 return record;
157 });
158
159 const syncTags = Effect.fn(function* (
160 id: string,
161 logicalId: string,
162 userTags: Record<string, string> | undefined,
163 ) {
164 const internalTags = yield* createInternalTags(logicalId);
165 const newTags = { ...userTags, ...internalTags };
166 const oldTags = yield* observedTags(id);
167 const { upsert, removed } = diffTags(oldTags, newTags);
168 if (upsert.length === 0 && removed.length === 0) {
169 return;
170 }
171 yield* route53.changeTagsForResource({
172 ResourceType: "hostedzone",
173 ResourceId: normalizeId(id),
174 AddTags: upsert.length > 0 ? upsert : undefined,
175 RemoveTagKeys: removed.length > 0 ? removed : undefined,
176 });
177 });
178
179 // Delete every non-SOA/NS record set so the zone can be deleted.
180 const purgeRecords = Effect.fn(function* (id: string) {
181 const sets: route53.ResourceRecordSet[] = [];
182 let request: route53.ListResourceRecordSetsRequest = {
183 HostedZoneId: normalizeId(id),
184 MaxItems: 300,
185 };
186 while (true) {
187 const response = yield* route53.listResourceRecordSets(request);
188 sets.push(...(response.ResourceRecordSets ?? []));
189 if (!response.IsTruncated || response.NextRecordName === undefined) {
190 break;
191 }
192 request = {
193 HostedZoneId: normalizeId(id),
194 StartRecordName: response.NextRecordName,
195 StartRecordType: response.NextRecordType,
196 StartRecordIdentifier: response.NextRecordIdentifier,
197 MaxItems: 300,
198 };
199 }
200 const deletable = sets.filter((set) => set.Type !== "SOA" && set.Type !== "NS");
201 if (deletable.length === 0) {
202 return;
203 }
204 yield* route53
205 .changeResourceRecordSets({
206 HostedZoneId: normalizeId(id),
207 ChangeBatch: {
208 Comment: "Alchemy HostedZone forceDestroy",
209 Changes: deletable.map((set) => ({
210 Action: "DELETE" as const,
211 ResourceRecordSet: set,
212 })),
213 },
214 })
215 .pipe(Effect.flatMap((response) => waitForChange(response.ChangeInfo.Id)));
216 });
217
218 return {
219 stables: ["id", "name"],
220 list: () =>
221 route53.listHostedZones.pages({}).pipe(
222 Stream.runCollect,
223 Effect.map((chunk) =>
224 Array.from(chunk).flatMap((page) =>
225 (page.HostedZones ?? []).map((zone) => ({
226 id: normalizeId(zone.Id),
227 name: zone.Name,
228 nameServers: [] as string[],
229 comment: zone.Config?.Comment,
230 })),
231 ),
232 ),
233 ),
234 diff: Effect.fn(function* ({ olds, news }) {
235 if (!isResolved(news)) return undefined;
236 // Name change → replace, but only when the old name is known — a
237 // half-created state row can't round-trip an Output-valued `name`
238 // (it deserializes as `undefined`), and an unknown old name must
239 // fall through to the create/update recovery path.
240 if (
241 (olds.name !== undefined && normalizeName(olds.name) !== normalizeName(news.name)) ||
242 (olds.privateZone ?? false) !== (news.privateZone ?? false) ||
243 olds.delegationSetId !== news.delegationSetId ||
244 olds.vpc?.vpcId !== news.vpc?.vpcId
245 ) {
246 return { action: "replace" } as const;
247 }
248 }),
249 read: Effect.fn(function* ({ olds, output }) {
250 // Resolve the zone id: prefer the stored output, else look up by name
251 // (adoption / state-loss recovery). The persisted `name` may be
252 // `undefined` when a `creating` row was written before upstream
253 // Outputs resolved — report "not found" and let the engine
254 // re-drive the create.
255 const zoneId =
256 output?.id ??
257 (olds?.name !== undefined ? (yield* findByName(olds.name))?.Id : undefined);
258 if (zoneId === undefined) {
259 return undefined;
260 }
261 const detail = yield* observe(zoneId);
262 if (!detail) {
263 return undefined;
264 }
265 return {
266 id: normalizeId(detail.HostedZone.Id),
267 name: detail.HostedZone.Name,
268 nameServers: detail.DelegationSet?.NameServers ?? [],
269 comment: detail.HostedZone.Config?.Comment,
270 };
271 }),
272 reconcile: Effect.fn(function* ({ id, instanceId, news, output }) {
273 // Observe.
274 let zone = output?.id ? yield* observe(output.id) : undefined;
275
276 // Ensure.
277 if (!zone) {
278 const created = yield* route53
279 .createHostedZone({
280 Name: normalizeName(news.name),
281 CallerReference: instanceId,
282 HostedZoneConfig:
283 news.comment !== undefined || news.privateZone
284 ? {
285 Comment: news.comment,
286 PrivateZone: news.privateZone,
287 }
288 : undefined,
289 VPC: news.vpc
290 ? { VPCId: news.vpc.vpcId, VPCRegion: news.vpc.vpcRegion }
291 : undefined,
292 DelegationSetId: news.delegationSetId,
293 })
294 .pipe(
295 Effect.map((response) => ({
296 HostedZone: response.HostedZone,
297 DelegationSet: response.DelegationSet,
298 })),
299 // Re-running with the same CallerReference races; re-observe.
300 Effect.catchTag("HostedZoneAlreadyExists", () =>
301 Effect.gen(function* () {
302 const existing = yield* findByName(news.name);
303 if (!existing) {
304 return yield* Effect.die(
305 new Error("hosted zone not found after HostedZoneAlreadyExists"),
306 );
307 }
308 return yield* observe(existing.Id).pipe(
309 Effect.map((z) =>
310 z
311 ? {
312 HostedZone: z.HostedZone,
313 DelegationSet: z.DelegationSet,
314 }
315 : undefined,
316 ),
317 );
318 }),
319 ),
320 );
321 if (!created) {
322 return yield* Effect.die(new Error("hosted zone could not be observed after create"));
323 }
324 zone = {
325 HostedZone: created.HostedZone,
326 DelegationSet: created.DelegationSet,
327 VPCs: undefined,
328 };
329 }
330
331 const zoneId = zone.HostedZone.Id;
332
333 // Sync comment.
334 if ((zone.HostedZone.Config?.Comment ?? undefined) !== news.comment) {
335 yield* route53.updateHostedZoneComment({
336 Id: normalizeId(zoneId),
337 Comment: news.comment ?? "",
338 });
339 }
340
341 // Sync tags.
342 yield* syncTags(zoneId, id, news.tags);
343
344 // Re-read for fresh name servers + comment.
345 const detail = yield* observe(zoneId);
346 return {
347 id: normalizeId(zoneId),
348 name: detail?.HostedZone.Name ?? normalizeName(news.name),
349 nameServers: detail?.DelegationSet?.NameServers ?? [],
350 comment: detail?.HostedZone.Config?.Comment ?? news.comment,
351 };
352 }),
353 delete: Effect.fn(function* ({ olds, output }) {
354 if (olds.forceDestroy) {
355 yield* purgeRecords(output.id).pipe(
356 Effect.catchTag("NoSuchHostedZone", () => Effect.void),
357 );
358 }
359 yield* route53.deleteHostedZone({ Id: normalizeId(output.id) }).pipe(
360 Effect.asVoid,
361 Effect.catchTag("NoSuchHostedZone", () => Effect.void),
362 // A still-non-empty zone (without forceDestroy) is retried briefly
363 // in case a referencing record's delete is still propagating —
364 // records looked up by zone NAME (e.g. `ECS.Service`'s `domain`)
365 // have no dependency edge on the zone, so their deletes run
366 // concurrently with ours (a classic Dependency Violation).
367 Effect.retry({
368 while: (e) => e._tag === "PriorRequestNotComplete" || e._tag === "HostedZoneNotEmpty",
369 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(20)]),
370 }),
371 );
372 }),
373 };
374 }),
375 );