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

main
ts 790 lines 25.9 KB
Raw
1 import * as route53 from "@distilled.cloud/aws/route-53";
2 import { isResolved } from "alchemy/Diff";
3 import type { Input } from "alchemy/Input";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import { Stack } from "alchemy/Stack";
7 import { State, isActionState } from "alchemy/State/State";
8 import type * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { durationToSeconds } from "../IAM/common.ts";
13 import type { Providers } from "../Providers.ts";
14 import { resolveHostedZoneId } from "./HostedZoneLookup.ts";
15
16 export interface RecordAliasTarget {
17 /**
18 * Hosted zone ID for the alias target.
19 */
20 hostedZoneId: Input<string>;
21 /**
22 * DNS name for the alias target.
23 */
24 dnsName: Input<string>;
25 /**
26 * Whether Route 53 should evaluate target health for the alias.
27 * @default false
28 */
29 evaluateTargetHealth?: boolean;
30 }
31
32 /**
33 * Fully-resolved alias target as stored in the record's attributes — a
34 * `RecordAliasTarget` with all `Input` values resolved.
35 */
36 export interface ResolvedRecordAliasTarget {
37 /**
38 * Hosted zone ID for the alias target.
39 */
40 hostedZoneId: string;
41 /**
42 * DNS name for the alias target.
43 */
44 dnsName: string;
45 /**
46 * Whether Route 53 evaluates target health for the alias.
47 * @default false
48 */
49 evaluateTargetHealth?: boolean;
50 }
51
52 export interface RecordGeoLocation {
53 /**
54 * Two-letter continent code (e.g. `"NA"`, `"EU"`). Mutually exclusive with
55 * `countryCode`.
56 */
57 continentCode?: string;
58 /**
59 * Two-letter country code, or `"*"` for the default (catch-all) record.
60 */
61 countryCode?: string;
62 /**
63 * Subdivision code (e.g. a US state). Requires `countryCode`.
64 */
65 subdivisionCode?: string;
66 }
67
68 export interface RecordGeoProximityCoordinates {
69 /** Latitude as a string (e.g. `"49.22"`). */
70 latitude: string;
71 /** Longitude as a string (e.g. `"-122.41"`). */
72 longitude: string;
73 }
74
75 export interface RecordGeoProximityLocation {
76 /** AWS Region for the endpoint. Mutually exclusive with `coordinates`. */
77 awsRegion?: string;
78 /** Local Zone Group for the endpoint. */
79 localZoneGroup?: string;
80 /** Explicit latitude/longitude of the endpoint. */
81 coordinates?: RecordGeoProximityCoordinates;
82 /** Bias (-99 to 99) that expands or shrinks the geographic region. */
83 bias?: number;
84 }
85
86 export interface RecordCidrRoutingConfig {
87 /** ID of the CIDR collection. */
88 collectionId: string;
89 /** Name of the CIDR location within the collection. */
90 locationName: string;
91 }
92
93 export interface RecordProps {
94 /**
95 * Hosted zone that owns the record. When omitted, the most specific
96 * PUBLIC hosted zone in the account containing `name` is inferred by
97 * walking the name's parent domains (`svc.api.example.com` →
98 * `api.example.com` → `example.com`); the deploy fails actionably when
99 * no zone matches.
100 */
101 hostedZoneId?: string;
102 /**
103 * Record name.
104 */
105 name: string;
106 /**
107 * Record type.
108 */
109 type: route53.RRType;
110 /**
111 * TTL for non-alias records, e.g. `"60 seconds"` or `Duration.minutes(5)`
112 * (a bare number is milliseconds). Rounded to whole seconds on the wire.
113 */
114 ttl?: Duration.Input;
115 /**
116 * Record values for non-alias records.
117 */
118 records?: string[];
119 /**
120 * Alias target for alias records.
121 */
122 aliasTarget?: RecordAliasTarget;
123 /**
124 * Optional set identifier for weighted, latency, failover, and other routing
125 * policies that require unique record identities.
126 */
127 setIdentifier?: string;
128 /**
129 * Weight (0-255) for weighted routing. Requires `setIdentifier`.
130 */
131 weight?: number;
132 /**
133 * AWS Region for latency-based routing. Requires `setIdentifier`.
134 */
135 region?: route53.ResourceRecordSetRegion;
136 /**
137 * Failover role for failover routing. Requires `setIdentifier`.
138 */
139 failover?: "PRIMARY" | "SECONDARY";
140 /**
141 * Geolocation routing rule. Requires `setIdentifier`.
142 */
143 geoLocation?: RecordGeoLocation;
144 /**
145 * Geoproximity routing rule. Requires `setIdentifier`.
146 */
147 geoProximityLocation?: RecordGeoProximityLocation;
148 /**
149 * Whether this record participates in multivalue answer routing. Requires
150 * `setIdentifier`.
151 */
152 multiValueAnswer?: boolean;
153 /**
154 * IP-based (CIDR) routing rule. Requires `setIdentifier`.
155 */
156 cidrRoutingConfig?: RecordCidrRoutingConfig;
157 /**
158 * Health check that gates whether Route 53 returns this record. Typically a
159 * `HealthCheck.id`.
160 */
161 healthCheckId?: string;
162 }
163
164 export interface Record extends Resource<
165 "AWS.Route53.Record",
166 RecordProps,
167 {
168 /**
169 * Hosted zone that owns the record.
170 */
171 hostedZoneId: string;
172 /**
173 * Fully qualified record name.
174 */
175 name: string;
176 /**
177 * Record type.
178 */
179 type: route53.RRType;
180 /**
181 * Current TTL for non-alias records.
182 */
183 ttl: number | undefined;
184 /**
185 * Current non-alias record values.
186 */
187 records: string[] | undefined;
188 /**
189 * Current alias target, when this record is an alias.
190 */
191 aliasTarget: ResolvedRecordAliasTarget | undefined;
192 /**
193 * Optional routing set identifier.
194 */
195 setIdentifier: string | undefined;
196 /**
197 * Weight for weighted routing.
198 */
199 weight: number | undefined;
200 /**
201 * AWS Region for latency routing.
202 */
203 region: route53.ResourceRecordSetRegion | undefined;
204 /**
205 * Failover role for failover routing.
206 */
207 failover: "PRIMARY" | "SECONDARY" | undefined;
208 /**
209 * Geolocation routing rule.
210 */
211 geoLocation: RecordGeoLocation | undefined;
212 /**
213 * Geoproximity routing rule.
214 */
215 geoProximityLocation: RecordGeoProximityLocation | undefined;
216 /**
217 * Whether this record participates in multivalue answer routing.
218 */
219 multiValueAnswer: boolean | undefined;
220 /**
221 * IP-based (CIDR) routing rule.
222 */
223 cidrRoutingConfig: RecordCidrRoutingConfig | undefined;
224 /**
225 * Health check that gates this record.
226 */
227 healthCheckId: string | undefined;
228 },
229 never,
230 Providers
231 > {}
232
233 /**
234 * A Route 53 DNS record set.
235 *
236 * `Record` manages a single Route 53 record set using `UPSERT` for create and
237 * update operations, and waits for Route 53 change propagation before
238 * returning.
239 * ### Creating Records
240 * **Example:** A Record Alias To CloudFront
241 * ```typescript
242 * const record = yield* Record("WebsiteAlias", {
243 * hostedZoneId: "Z1234567890",
244 * name: "www.example.com",
245 * type: "A",
246 * aliasTarget: {
247 * hostedZoneId: distribution.hostedZoneId,
248 * dnsName: distribution.domainName,
249 * },
250 * });
251 * ```
252 *
253 * **Example:** TXT Record
254 * ```typescript
255 * const record = yield* Record("VerificationRecord", {
256 * hostedZoneId: "Z1234567890",
257 * name: "_acme-challenge.example.com",
258 * type: "TXT",
259 * ttl: "60 seconds",
260 * records: ["\"value\""],
261 * });
262 * ```
263 *
264 * ### Routing Policies
265 * **Example:** Weighted Routing
266 * ```typescript
267 * const blue = yield* Record("Blue", {
268 * hostedZoneId: zone.id,
269 * name: "api.example.com",
270 * type: "A",
271 * ttl: "60 seconds",
272 * records: ["1.2.3.4"],
273 * setIdentifier: "blue",
274 * weight: 90,
275 * });
276 * const green = yield* Record("Green", {
277 * hostedZoneId: zone.id,
278 * name: "api.example.com",
279 * type: "A",
280 * ttl: "60 seconds",
281 * records: ["5.6.7.8"],
282 * setIdentifier: "green",
283 * weight: 10,
284 * });
285 * ```
286 *
287 * **Example:** Failover Routing With Health Check
288 * ```typescript
289 * const primary = yield* Record("Primary", {
290 * hostedZoneId: zone.id,
291 * name: "app.example.com",
292 * type: "A",
293 * ttl: "60 seconds",
294 * records: ["1.2.3.4"],
295 * setIdentifier: "primary",
296 * failover: "PRIMARY",
297 * healthCheckId: healthCheck.id,
298 * });
299 * const secondary = yield* Record("Secondary", {
300 * hostedZoneId: zone.id,
301 * name: "app.example.com",
302 * type: "A",
303 * ttl: "60 seconds",
304 * records: ["5.6.7.8"],
305 * setIdentifier: "secondary",
306 * failover: "SECONDARY",
307 * });
308 * ```
309 *
310 * **Example:** Latency Routing
311 * ```typescript
312 * const record = yield* Record("UsEast", {
313 * hostedZoneId: zone.id,
314 * name: "api.example.com",
315 * type: "A",
316 * ttl: "60 seconds",
317 * records: ["1.2.3.4"],
318 * setIdentifier: "us-east-1",
319 * region: "us-east-1",
320 * });
321 * ```
322 *
323 * **Example:** Geolocation Routing
324 * ```typescript
325 * const record = yield* Record("Default", {
326 * hostedZoneId: zone.id,
327 * name: "www.example.com",
328 * type: "A",
329 * ttl: "60 seconds",
330 * records: ["1.2.3.4"],
331 * setIdentifier: "default",
332 * geoLocation: { countryCode: "*" },
333 * });
334 * ```
335 *
336 * @resource
337 */
338 export const Record = Resource<Record>("AWS.Route53.Record");
339
340 /** @internal shared with `Records.ts` — not exported from the barrel. */
341 export const normalizeHostedZoneId = (hostedZoneId: string) =>
342 hostedZoneId.replace(/^\/hostedzone\//, "");
343
344 /** @internal shared with `Records.ts` — not exported from the barrel. */
345 export const normalizeName = (name: string) => (name.endsWith(".") ? name : `${name}.`);
346
347 /**
348 * Route 53 returns record names in lowercase with special characters as
349 * `\ddd` octal escapes (a wildcard `*` comes back as `\052`), so compare
350 * names in that decoded, lowercase form.
351 *
352 * @internal shared with `Records.ts` — not exported from the barrel.
353 */
354 export const canonicalName = (name: string) =>
355 normalizeName(name)
356 .replace(/\\(\d{3})/g, (_, code: string) => String.fromCharCode(Number.parseInt(code, 8)))
357 .toLowerCase();
358
359 /** @internal shared with `Records.ts` — not exported from the barrel. */
360 export const toAliasTarget = (
361 aliasTarget: route53.AliasTarget | undefined,
362 ): ResolvedRecordAliasTarget | undefined =>
363 aliasTarget
364 ? {
365 hostedZoneId: aliasTarget.HostedZoneId,
366 dnsName: aliasTarget.DNSName,
367 evaluateTargetHealth: aliasTarget.EvaluateTargetHealth,
368 }
369 : undefined;
370
371 const toGeoLocation = (geo: RecordGeoLocation | undefined): route53.GeoLocation | undefined =>
372 geo
373 ? {
374 ContinentCode: geo.continentCode,
375 CountryCode: geo.countryCode,
376 SubdivisionCode: geo.subdivisionCode,
377 }
378 : undefined;
379
380 const fromGeoLocation = (geo: route53.GeoLocation | undefined): RecordGeoLocation | undefined =>
381 geo
382 ? {
383 continentCode: geo.ContinentCode,
384 countryCode: geo.CountryCode,
385 subdivisionCode: geo.SubdivisionCode,
386 }
387 : undefined;
388
389 const toGeoProximity = (
390 geo: RecordGeoProximityLocation | undefined,
391 ): route53.GeoProximityLocation | undefined =>
392 geo
393 ? {
394 AWSRegion: geo.awsRegion,
395 LocalZoneGroup: geo.localZoneGroup,
396 Coordinates: geo.coordinates
397 ? {
398 Latitude: geo.coordinates.latitude,
399 Longitude: geo.coordinates.longitude,
400 }
401 : undefined,
402 Bias: geo.bias,
403 }
404 : undefined;
405
406 const fromGeoProximity = (
407 geo: route53.GeoProximityLocation | undefined,
408 ): RecordGeoProximityLocation | undefined =>
409 geo
410 ? {
411 awsRegion: geo.AWSRegion,
412 localZoneGroup: geo.LocalZoneGroup,
413 coordinates: geo.Coordinates
414 ? {
415 latitude: geo.Coordinates.Latitude,
416 longitude: geo.Coordinates.Longitude,
417 }
418 : undefined,
419 bias: geo.Bias,
420 }
421 : undefined;
422
423 const toCidrRouting = (
424 cidr: RecordCidrRoutingConfig | undefined,
425 ): route53.CidrRoutingConfig | undefined =>
426 cidr ? { CollectionId: cidr.collectionId, LocationName: cidr.locationName } : undefined;
427
428 const fromCidrRouting = (
429 cidr: route53.CidrRoutingConfig | undefined,
430 ): RecordCidrRoutingConfig | undefined =>
431 cidr ? { collectionId: cidr.CollectionId, locationName: cidr.LocationName } : undefined;
432
433 /**
434 * Build the full `ResourceRecordSet` wire shape from props. Used for both the
435 * UPSERT change batch and the DELETE change batch — DELETE requires an exact
436 * match of every policy field, so this must round-trip the entire surface.
437 * @internal shared with `Records.ts` — not exported from the barrel.
438 */
439 export const toRecordSet = (
440 props: Pick<
441 RecordProps,
442 | "name"
443 | "type"
444 | "records"
445 | "aliasTarget"
446 | "setIdentifier"
447 | "weight"
448 | "region"
449 | "failover"
450 | "geoLocation"
451 | "geoProximityLocation"
452 | "multiValueAnswer"
453 | "cidrRoutingConfig"
454 | "healthCheckId"
455 > & {
456 /** TTL already converted to wire seconds. */
457 ttl?: number;
458 },
459 ): route53.ResourceRecordSet => ({
460 Name: normalizeName(props.name),
461 Type: props.type,
462 SetIdentifier: props.setIdentifier,
463 Weight: props.weight,
464 Region: props.region,
465 Failover: props.failover,
466 GeoLocation: toGeoLocation(props.geoLocation),
467 GeoProximityLocation: toGeoProximity(props.geoProximityLocation),
468 MultiValueAnswer: props.multiValueAnswer,
469 CidrRoutingConfig: toCidrRouting(props.cidrRoutingConfig),
470 HealthCheckId: props.healthCheckId,
471 TTL: props.aliasTarget ? undefined : props.ttl,
472 ResourceRecords: props.aliasTarget
473 ? undefined
474 : (props.records ?? []).map((Value) => ({ Value })),
475 AliasTarget: props.aliasTarget
476 ? {
477 HostedZoneId: normalizeHostedZoneId(props.aliasTarget.hostedZoneId as string),
478 DNSName: props.aliasTarget.dnsName as string,
479 EvaluateTargetHealth: props.aliasTarget.evaluateTargetHealth ?? false,
480 }
481 : undefined,
482 });
483
484 const toAttrs = (recordSet: route53.ResourceRecordSet, hostedZoneId: string) => ({
485 hostedZoneId: normalizeHostedZoneId(hostedZoneId),
486 name: recordSet.Name,
487 type: recordSet.Type,
488 ttl: recordSet.TTL,
489 records: recordSet.ResourceRecords?.map((record) => record.Value),
490 aliasTarget: toAliasTarget(recordSet.AliasTarget),
491 setIdentifier: recordSet.SetIdentifier,
492 weight: recordSet.Weight,
493 region: recordSet.Region,
494 failover: recordSet.Failover as "PRIMARY" | "SECONDARY" | undefined,
495 geoLocation: fromGeoLocation(recordSet.GeoLocation),
496 geoProximityLocation: fromGeoProximity(recordSet.GeoProximityLocation),
497 multiValueAnswer: recordSet.MultiValueAnswer,
498 cidrRoutingConfig: fromCidrRouting(recordSet.CidrRoutingConfig),
499 healthCheckId: recordSet.HealthCheckId,
500 });
501
502 /**
503 * Route 53 identifies a record set by zone + name + type (+ set identifier),
504 * so two resources can hold the same record set at different times — e.g.
505 * swapping the names of two records replaces both, and each replacement's
506 * UPSERT takes over the record set the other one's old generation still
507 * points at. Returns whether another current resource in this stack holds
508 * the record set, in which case deleting it would delete the live record.
509 */
510 const isRecordSetClaimed = Effect.fn(function* (
511 instanceId: string,
512 recordSet: Pick<Record["Attributes"], "hostedZoneId" | "name" | "type" | "setIdentifier">,
513 ) {
514 const stack = yield* Stack;
515 const state = yield* yield* State;
516 const zone = normalizeHostedZoneId(recordSet.hostedZoneId);
517 const name = canonicalName(recordSet.name);
518 for (const fqn of yield* state.list({ stack: stack.name, stage: stack.stage })) {
519 const row = yield* state.get({ stack: stack.name, stage: stack.stage, fqn });
520 if (
521 !row ||
522 isActionState(row) ||
523 row.status === "deleting" ||
524 // The generation being deleted is not a claim on its own record set.
525 row.instanceId === instanceId ||
526 row.attr === undefined
527 ) {
528 continue;
529 }
530 const attr = row.attr;
531 if (row.resourceType === "AWS.Route53.Record") {
532 if (
533 attr.hostedZoneId !== undefined &&
534 normalizeHostedZoneId(attr.hostedZoneId) === zone &&
535 canonicalName(attr.name) === name &&
536 attr.type === recordSet.type &&
537 (attr.setIdentifier ?? undefined) === (recordSet.setIdentifier ?? undefined)
538 ) {
539 return true;
540 }
541 } else if (row.resourceType === "AWS.Route53.Records") {
542 if (
543 recordSet.setIdentifier === undefined &&
544 attr.hostedZoneId !== undefined &&
545 normalizeHostedZoneId(attr.hostedZoneId) === zone &&
546 attr.type === recordSet.type &&
547 (attr.names ?? []).some((candidate: string) => canonicalName(candidate) === name)
548 ) {
549 return true;
550 }
551 }
552 }
553 return false;
554 });
555
556 export const RecordProvider = () =>
557 Provider.effect(
558 Record,
559 Effect.gen(function* () {
560 // Poll `getChange` until the change reaches INSYNC. `getChange` is
561 // eventually consistent and can briefly return `NoSuchChange` right after
562 // submit, so coalesce that to a non-INSYNC status and keep polling.
563 // `ChangeInfo.Id` comes back as "/change/C..." but `getChange` only
564 // accepts the bare id — the prefixed form returns `NoSuchChange`
565 // forever, silently burning the full repeat cap on every change.
566 const waitForChange = Effect.fn(function* (changeId: string) {
567 return yield* route53.getChange({ Id: changeId.replace(/^\/change\//, "") }).pipe(
568 Effect.map((response) => response.ChangeInfo.Status),
569 Effect.catchTag("NoSuchChange", () => Effect.succeed("PENDING")),
570 Effect.repeat({
571 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]),
572 until: (status) => status === "INSYNC",
573 }),
574 );
575 });
576
577 const findRecord = Effect.fn(function* (
578 hostedZoneId: string,
579 props: Pick<RecordProps, "name" | "type" | "setIdentifier">,
580 ) {
581 const response = yield* route53
582 .listResourceRecordSets({
583 HostedZoneId: normalizeHostedZoneId(hostedZoneId),
584 StartRecordName: normalizeName(props.name),
585 StartRecordType: props.type,
586 MaxItems: 100,
587 })
588 .pipe(Effect.catchTag("NoSuchHostedZone", () => Effect.undefined));
589
590 return (response?.ResourceRecordSets ?? []).find(
591 (recordSet) =>
592 canonicalName(recordSet.Name) === canonicalName(props.name) &&
593 recordSet.Type === props.type &&
594 (recordSet.SetIdentifier ?? undefined) === props.setIdentifier,
595 );
596 });
597
598 const upsertRecord = Effect.fn(function* (hostedZoneId: string, props: RecordProps) {
599 const response = yield* route53.changeResourceRecordSets({
600 HostedZoneId: normalizeHostedZoneId(hostedZoneId),
601 ChangeBatch: {
602 Comment: "Alchemy Route53 record upsert",
603 Changes: [
604 {
605 Action: "UPSERT",
606 ResourceRecordSet: toRecordSet({
607 ...props,
608 ttl: durationToSeconds(props.ttl),
609 }),
610 },
611 ],
612 },
613 });
614
615 yield* waitForChange(response.ChangeInfo.Id);
616 });
617
618 // `listResourceRecordSets` is not paginated by distilled, so manually
619 // walk the `IsTruncated` / `NextRecord*` cursor to collect every record
620 // set in a hosted zone.
621 const listAllRecordSets = Effect.fn(function* (hostedZoneId: string) {
622 const all: route53.ResourceRecordSet[] = [];
623 let request: route53.ListResourceRecordSetsRequest = {
624 HostedZoneId: normalizeHostedZoneId(hostedZoneId),
625 MaxItems: 300,
626 };
627 while (true) {
628 const response = yield* route53.listResourceRecordSets(request);
629 all.push(...(response.ResourceRecordSets ?? []));
630 if (!response.IsTruncated || response.NextRecordName === undefined) {
631 break;
632 }
633 request = {
634 HostedZoneId: normalizeHostedZoneId(hostedZoneId),
635 StartRecordName: response.NextRecordName,
636 StartRecordType: response.NextRecordType,
637 StartRecordIdentifier: response.NextRecordIdentifier,
638 MaxItems: 300,
639 };
640 }
641 return all;
642 });
643
644 return {
645 stables: ["hostedZoneId", "name", "type", "setIdentifier"],
646 list: () =>
647 Effect.gen(function* () {
648 // Records are hosted-zone-scoped: enumerate every hosted zone
649 // (paginated), then fan out one `listResourceRecordSets` walk per
650 // zone with bounded concurrency.
651 const zones = yield* route53.listHostedZones.pages({}).pipe(
652 Stream.runCollect,
653 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.HostedZones ?? [])),
654 );
655
656 const rows = yield* Effect.forEach(
657 zones,
658 (zone) =>
659 listAllRecordSets(zone.Id).pipe(
660 Effect.map((recordSets) =>
661 recordSets.map((recordSet) => toAttrs(recordSet, zone.Id)),
662 ),
663 // A zone may be deleted concurrently with enumeration; treat
664 // a vanished zone as contributing no records.
665 Effect.catchTag("NoSuchHostedZone", () => Effect.succeed([])),
666 ),
667 { concurrency: 10 },
668 );
669
670 return rows.flat();
671 }),
672 diff: Effect.fn(function* ({ olds, news }) {
673 if (!isResolved(news)) return undefined;
674 // Identity change → replace, but only when the old value is known —
675 // a half-created state row can't round-trip Output-valued props
676 // (they deserialize as `undefined`), and an unknown old identity
677 // must fall through to the create/update recovery path.
678 if (
679 // An undefined side means "inferred" — reconcile resolves it
680 // against the live account, so only two explicit, differing
681 // zones are a replacement.
682 (olds.hostedZoneId !== undefined &&
683 news.hostedZoneId !== undefined &&
684 normalizeHostedZoneId(olds.hostedZoneId) !==
685 normalizeHostedZoneId(news.hostedZoneId)) ||
686 (olds.name !== undefined && normalizeName(olds.name) !== normalizeName(news.name)) ||
687 olds.type !== news.type ||
688 olds.setIdentifier !== news.setIdentifier
689 ) {
690 return { action: "replace" } as const;
691 }
692 }),
693 read: Effect.fn(function* ({ olds, output }) {
694 const hostedZoneId = output?.hostedZoneId ?? olds?.hostedZoneId;
695 const name = output?.name ?? olds?.name;
696 const type = output?.type ?? olds?.type;
697 if (hostedZoneId === undefined || name === undefined || type === undefined) {
698 // Output-valued props don't survive a `creating`-state round-trip
699 // — without the record's identity we can't look it up. Report
700 // "not found" so the engine re-drives the create (the UPSERT in
701 // reconcile converges on any half-created record).
702 return undefined;
703 }
704 const recordSet = yield* findRecord(hostedZoneId, {
705 name,
706 type,
707 setIdentifier: output?.setIdentifier ?? olds?.setIdentifier,
708 });
709
710 if (!recordSet) {
711 return undefined;
712 }
713
714 return toAttrs(recordSet, hostedZoneId);
715 }),
716 reconcile: Effect.fn(function* ({ news, output, session }) {
717 // Resolve the zone: explicit prop, else the zone this resource
718 // already resolved to (stable across reconciles), else infer the
719 // most specific public zone containing the record name.
720 const hostedZoneId = yield* resolveHostedZoneId(
721 news.hostedZoneId ?? output?.hostedZoneId,
722 news.name,
723 );
724
725 // Route 53 `changeResourceRecordSets` with `UPSERT` is naturally
726 // reconciler-friendly: it creates the record if missing and
727 // overwrites it if present. There's no separate ensure/sync split
728 // — one call converges to the desired record set.
729 yield* upsertRecord(hostedZoneId, news);
730
731 // Re-read so the returned attributes reflect the actual current
732 // record (including server-applied defaults).
733 const recordSet = yield* findRecord(hostedZoneId, news);
734
735 if (!recordSet) {
736 return yield* Effect.die(new Error("Route53 record was not found after upsert"));
737 }
738
739 yield* session.note(`${news.type} ${normalizeName(news.name)}`);
740 return toAttrs(recordSet, hostedZoneId);
741 }),
742 delete: Effect.fn(function* ({ instanceId, output, session }) {
743 if (yield* isRecordSetClaimed(instanceId, output)) {
744 yield* session.note(
745 `${output.type} ${output.name} is now managed by another resource — leaving it in place`,
746 );
747 return;
748 }
749 yield* route53
750 .changeResourceRecordSets({
751 HostedZoneId: normalizeHostedZoneId(output.hostedZoneId),
752 ChangeBatch: {
753 Comment: "Alchemy Route53 record delete",
754 Changes: [
755 {
756 Action: "DELETE",
757 // Serialize the full record set — DELETE requires an exact
758 // match including routing-policy fields, so reuse the same
759 // builder as UPSERT against the stored attributes.
760 ResourceRecordSet: toRecordSet({
761 name: output.name,
762 type: output.type,
763 ttl: output.ttl,
764 records: output.records,
765 aliasTarget: output.aliasTarget,
766 setIdentifier: output.setIdentifier,
767 weight: output.weight,
768 region: output.region,
769 failover: output.failover,
770 geoLocation: output.geoLocation,
771 geoProximityLocation: output.geoProximityLocation,
772 multiValueAnswer: output.multiValueAnswer,
773 cidrRoutingConfig: output.cidrRoutingConfig,
774 healthCheckId: output.healthCheckId,
775 }),
776 },
777 ],
778 },
779 })
780 .pipe(
781 Effect.flatMap((response) => waitForChange(response.ChangeInfo.Id)),
782 Effect.catchTags({
783 NoSuchHostedZone: () => Effect.void,
784 InvalidChangeBatch: () => Effect.void,
785 }),
786 );
787 }),
788 };
789 }),
790 );