The best way to control Claude Code, Codex and more from any computer or phone
| 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, type ResourceBinding } from "alchemy/Resource"; |
| 5 | import type * as Duration from "effect/Duration"; |
| 6 | import * as Effect from "effect/Effect"; |
| 7 | import * as Schedule from "effect/Schedule"; |
| 8 | import { durationToSeconds } from "../IAM/common.ts"; |
| 9 | import type { Providers } from "../Providers.ts"; |
| 10 | import { resolveHostedZoneId } from "./HostedZoneLookup.ts"; |
| 11 | import { |
| 12 | canonicalName, |
| 13 | normalizeHostedZoneId, |
| 14 | normalizeName, |
| 15 | toAliasTarget, |
| 16 | toRecordSet, |
| 17 | type RecordAliasTarget, |
| 18 | type ResolvedRecordAliasTarget, |
| 19 | } from "./Record.ts"; |
| 20 | |
| 21 | /** |
| 22 | * Binding contract of {@link Records}: composites (e.g. an |
| 23 | * `AWS.Website.StaticSite` attached to an `AWS.Website.Router`) contribute |
| 24 | * additional record names without a circular input prop. |
| 25 | */ |
| 26 | export type RecordsBinding = { |
| 27 | /** |
| 28 | * Additional record names to manage alongside {@link RecordsProps.names}. |
| 29 | */ |
| 30 | names?: string[]; |
| 31 | }; |
| 32 | |
| 33 | export interface RecordsProps { |
| 34 | /** |
| 35 | * Hosted zone that owns the records. When omitted, the most specific |
| 36 | * PUBLIC hosted zone in the account containing the set's first name is |
| 37 | * inferred by walking its parent domains; the deploy fails actionably |
| 38 | * when no zone matches. Every name in the set lives in the one zone |
| 39 | * either way. |
| 40 | */ |
| 41 | hostedZoneId?: string; |
| 42 | /** |
| 43 | * Record type shared by every record in the set. |
| 44 | */ |
| 45 | type: route53.RRType; |
| 46 | /** |
| 47 | * Record names managed by this set. Names contributed through the binding |
| 48 | * contract (see {@link RecordsBinding}) are merged in at reconcile time. |
| 49 | */ |
| 50 | names?: string[]; |
| 51 | /** |
| 52 | * TTL for non-alias records, e.g. `"60 seconds"` (a bare number is |
| 53 | * milliseconds). Rounded to whole seconds on the wire. |
| 54 | */ |
| 55 | ttl?: Duration.Input; |
| 56 | /** |
| 57 | * Record values for non-alias records (shared by every name in the set). |
| 58 | */ |
| 59 | records?: string[]; |
| 60 | /** |
| 61 | * Alias target for alias records (shared by every name in the set). |
| 62 | */ |
| 63 | aliasTarget?: RecordAliasTarget; |
| 64 | } |
| 65 | |
| 66 | export interface Records extends Resource< |
| 67 | "AWS.Route53.Records", |
| 68 | RecordsProps, |
| 69 | { |
| 70 | /** |
| 71 | * Hosted zone that owns the records. `undefined` only while the set |
| 72 | * is empty with no explicit zone — resolved (explicit or inferred) on |
| 73 | * the first reconcile that has a name. |
| 74 | */ |
| 75 | hostedZoneId: string | undefined; |
| 76 | /** |
| 77 | * Record type shared by every record in the set. |
| 78 | */ |
| 79 | type: route53.RRType; |
| 80 | /** |
| 81 | * Fully qualified names of every record currently managed by this set |
| 82 | * (declared `names` plus bound names, as of the last reconcile). |
| 83 | */ |
| 84 | names: string[]; |
| 85 | /** |
| 86 | * Current TTL for non-alias records. |
| 87 | */ |
| 88 | ttl: number | undefined; |
| 89 | /** |
| 90 | * Current non-alias record values. |
| 91 | */ |
| 92 | records: string[] | undefined; |
| 93 | /** |
| 94 | * Current alias target, when the set manages alias records. |
| 95 | */ |
| 96 | aliasTarget: ResolvedRecordAliasTarget | undefined; |
| 97 | }, |
| 98 | RecordsBinding, |
| 99 | Providers |
| 100 | > {} |
| 101 | |
| 102 | /** |
| 103 | * A dynamic set of identically-configured Route 53 records that differ only |
| 104 | * by name. |
| 105 | * |
| 106 | * Unlike {@link Record} (one resource per record), `Records` reconciles a |
| 107 | * whole name set against the hosted zone — names added to the set are |
| 108 | * upserted, names removed from the set are deleted. The set is the union of |
| 109 | * the declared `names` prop and names contributed through the |
| 110 | * {@link RecordsBinding} binding contract, which is how composites (e.g. a |
| 111 | * site attached to an `AWS.Website.Router`) register hostnames on a |
| 112 | * distribution's DNS without a circular input prop. |
| 113 | * ### Managing Record Sets |
| 114 | * **Example:** Alias Records For Several Hostnames |
| 115 | * ```typescript |
| 116 | * const records = yield* Records("AliasRecords", { |
| 117 | * hostedZoneId: "Z1234567890", |
| 118 | * type: "A", |
| 119 | * names: ["www.example.com", "docs.example.com"], |
| 120 | * aliasTarget: { |
| 121 | * hostedZoneId: distribution.hostedZoneId, |
| 122 | * dnsName: distribution.domainName, |
| 123 | * }, |
| 124 | * }); |
| 125 | * ``` |
| 126 | * |
| 127 | * **Example:** Binding Target For Composite-Contributed Names |
| 128 | * ```typescript |
| 129 | * // Names may also arrive through the binding contract — an |
| 130 | * // `AWS.Website.Router` declares an empty set and attached sites bind |
| 131 | * // their hostnames onto it: |
| 132 | * const records = yield* Records("SiteAliasRecords", { |
| 133 | * hostedZoneId: "Z1234567890", |
| 134 | * type: "A", |
| 135 | * aliasTarget: { |
| 136 | * hostedZoneId: distribution.hostedZoneId, |
| 137 | * dnsName: distribution.domainName, |
| 138 | * }, |
| 139 | * }); |
| 140 | * // elsewhere: |
| 141 | * yield* records.bind`MySite`({ names: ["docs.example.com"] }); |
| 142 | * ``` |
| 143 | * |
| 144 | * @resource |
| 145 | */ |
| 146 | export const Records = Resource<Records>("AWS.Route53.Records"); |
| 147 | |
| 148 | /** |
| 149 | * Union of declared and bound record names, deduped (case-insensitively via |
| 150 | * trailing-dot-insensitive normalization) and sorted for stable comparisons. |
| 151 | * Tolerates both `{ sid, data }` rows (provider lifecycle) and bare binding |
| 152 | * payloads. |
| 153 | * @internal |
| 154 | */ |
| 155 | const resolveDesiredNames = ( |
| 156 | declared: string[] | undefined, |
| 157 | bindings: ReadonlyArray<RecordsBinding | ResourceBinding<RecordsBinding>>, |
| 158 | ): string[] => { |
| 159 | const bound = bindings.flatMap((binding) => |
| 160 | "data" in binding && binding.data !== undefined |
| 161 | ? ((binding as ResourceBinding<RecordsBinding>).data.names ?? []) |
| 162 | : ((binding as RecordsBinding).names ?? []), |
| 163 | ); |
| 164 | const byNormalized = new Map<string, string>(); |
| 165 | for (const name of [...(declared ?? []), ...bound]) { |
| 166 | const key = normalizeName(name).toLowerCase(); |
| 167 | if (!byNormalized.has(key)) { |
| 168 | byNormalized.set(key, name); |
| 169 | } |
| 170 | } |
| 171 | return [...byNormalized.values()].sort((a, b) => a.localeCompare(b)); |
| 172 | }; |
| 173 | |
| 174 | export const RecordsProvider = () => |
| 175 | Provider.effect( |
| 176 | Records, |
| 177 | Effect.gen(function* () { |
| 178 | const waitForChange = Effect.fn(function* (changeId: string) { |
| 179 | return yield* route53.getChange({ Id: changeId.replace(/^\/change\//, "") }).pipe( |
| 180 | Effect.map((response) => response.ChangeInfo.Status), |
| 181 | Effect.catchTag("NoSuchChange", () => Effect.succeed("PENDING")), |
| 182 | Effect.repeat({ |
| 183 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(60)]), |
| 184 | until: (status) => status === "INSYNC", |
| 185 | }), |
| 186 | ); |
| 187 | }); |
| 188 | |
| 189 | const findRecord = Effect.fn(function* ( |
| 190 | hostedZoneId: string, |
| 191 | name: string, |
| 192 | type: route53.RRType, |
| 193 | ) { |
| 194 | const response = yield* route53 |
| 195 | .listResourceRecordSets({ |
| 196 | HostedZoneId: normalizeHostedZoneId(hostedZoneId), |
| 197 | StartRecordName: normalizeName(name), |
| 198 | StartRecordType: type, |
| 199 | MaxItems: 10, |
| 200 | }) |
| 201 | .pipe(Effect.catchTag("NoSuchHostedZone", () => Effect.undefined)); |
| 202 | |
| 203 | return (response?.ResourceRecordSets ?? []).find( |
| 204 | (recordSet) => |
| 205 | canonicalName(recordSet.Name) === canonicalName(name) && |
| 206 | recordSet.Type === type && |
| 207 | recordSet.SetIdentifier === undefined, |
| 208 | ); |
| 209 | }); |
| 210 | |
| 211 | const desiredRecordSet = (news: RecordsProps, name: string) => |
| 212 | toRecordSet({ |
| 213 | name, |
| 214 | type: news.type, |
| 215 | ttl: durationToSeconds(news.ttl), |
| 216 | records: news.records, |
| 217 | aliasTarget: news.aliasTarget, |
| 218 | }); |
| 219 | |
| 220 | /** Trailing-dot/case-insensitive comparison of a live record set |
| 221 | * against the desired wire shape for one name. */ |
| 222 | const matchesDesired = ( |
| 223 | live: route53.ResourceRecordSet, |
| 224 | desired: route53.ResourceRecordSet, |
| 225 | ): boolean => { |
| 226 | const normalizeDns = (value: string | undefined) => value?.toLowerCase().replace(/\.$/, ""); |
| 227 | if (desired.AliasTarget) { |
| 228 | return ( |
| 229 | normalizeDns(live.AliasTarget?.DNSName) === normalizeDns(desired.AliasTarget.DNSName) && |
| 230 | live.AliasTarget?.HostedZoneId === desired.AliasTarget.HostedZoneId && |
| 231 | (live.AliasTarget?.EvaluateTargetHealth ?? false) === |
| 232 | (desired.AliasTarget.EvaluateTargetHealth ?? false) |
| 233 | ); |
| 234 | } |
| 235 | const liveValues = (live.ResourceRecords ?? []).map((record) => record.Value).sort(); |
| 236 | const desiredValues = (desired.ResourceRecords ?? []).map((record) => record.Value).sort(); |
| 237 | return ( |
| 238 | live.TTL === desired.TTL && |
| 239 | liveValues.length === desiredValues.length && |
| 240 | liveValues.every((value, index) => value === desiredValues[index]) |
| 241 | ); |
| 242 | }; |
| 243 | |
| 244 | /** Delete `names` (exact live shape) tolerantly — missing records, |
| 245 | * missing zones, and already-deleted batches are all no-ops. */ |
| 246 | const deleteNames = Effect.fn(function* ( |
| 247 | hostedZoneId: string, |
| 248 | type: route53.RRType, |
| 249 | names: string[], |
| 250 | ) { |
| 251 | const changes: route53.Change[] = []; |
| 252 | for (const name of names) { |
| 253 | const live = yield* findRecord(hostedZoneId, name, type); |
| 254 | if (live) { |
| 255 | changes.push({ Action: "DELETE", ResourceRecordSet: live }); |
| 256 | } |
| 257 | } |
| 258 | if (changes.length === 0) { |
| 259 | return; |
| 260 | } |
| 261 | yield* route53 |
| 262 | .changeResourceRecordSets({ |
| 263 | HostedZoneId: normalizeHostedZoneId(hostedZoneId), |
| 264 | ChangeBatch: { |
| 265 | Comment: "Alchemy Route53 record-set delete", |
| 266 | Changes: changes, |
| 267 | }, |
| 268 | }) |
| 269 | .pipe( |
| 270 | Effect.flatMap((response) => waitForChange(response.ChangeInfo.Id)), |
| 271 | Effect.catchTags({ |
| 272 | NoSuchHostedZone: () => Effect.void, |
| 273 | InvalidChangeBatch: () => Effect.void, |
| 274 | }), |
| 275 | ); |
| 276 | }); |
| 277 | |
| 278 | return { |
| 279 | stables: ["hostedZoneId", "type"], |
| 280 | diff: Effect.fn(function* ({ olds, news }) { |
| 281 | if (!isResolved(news)) return undefined; |
| 282 | // Identity change → replace (same rule as `Record`); the names |
| 283 | // themselves are mutable — prop/binding deltas fall through to |
| 284 | // the engine's default update logic. |
| 285 | if ( |
| 286 | // An undefined side means "inferred" — reconcile resolves it |
| 287 | // against the live account, so only two explicit, differing |
| 288 | // zones are a replacement. |
| 289 | (olds.hostedZoneId !== undefined && |
| 290 | news.hostedZoneId !== undefined && |
| 291 | normalizeHostedZoneId(olds.hostedZoneId) !== |
| 292 | normalizeHostedZoneId(news.hostedZoneId)) || |
| 293 | olds.type !== news.type |
| 294 | ) { |
| 295 | return { action: "replace" } as const; |
| 296 | } |
| 297 | }), |
| 298 | read: Effect.fn(function* ({ output }) { |
| 299 | if (output === undefined) { |
| 300 | // Without the previously-managed name set there is no identity |
| 301 | // to look up — report "not found" so the engine re-drives the |
| 302 | // reconcile (upserts converge on any half-created records). |
| 303 | return undefined; |
| 304 | } |
| 305 | if (output.hostedZoneId === undefined) { |
| 306 | // An empty set that never resolved a zone — nothing to observe. |
| 307 | return output; |
| 308 | } |
| 309 | const found: string[] = []; |
| 310 | let recordSet: route53.ResourceRecordSet | undefined; |
| 311 | for (const name of output.names) { |
| 312 | const live = yield* findRecord(output.hostedZoneId, name, output.type); |
| 313 | if (live) { |
| 314 | found.push(name); |
| 315 | recordSet ??= live; |
| 316 | } |
| 317 | } |
| 318 | return { |
| 319 | ...output, |
| 320 | names: found, |
| 321 | ttl: recordSet?.TTL ?? output.ttl, |
| 322 | records: recordSet?.ResourceRecords?.map((record) => record.Value) ?? output.records, |
| 323 | aliasTarget: toAliasTarget(recordSet?.AliasTarget) ?? output.aliasTarget, |
| 324 | }; |
| 325 | }), |
| 326 | reconcile: Effect.fn(function* ({ news, output, session, bindings }) { |
| 327 | const desired = resolveDesiredNames(news.names, bindings); |
| 328 | // Resolve the zone: explicit prop, else the zone this set already |
| 329 | // resolved to, else infer from the first name in the set. A set |
| 330 | // that is still empty with no explicit zone stays unresolved — |
| 331 | // the zone materializes on the first reconcile that has a name. |
| 332 | const explicitZoneId = news.hostedZoneId ?? output?.hostedZoneId; |
| 333 | if (explicitZoneId === undefined && desired.length === 0) { |
| 334 | yield* session.note(`${news.type} × 0 record(s)`); |
| 335 | return { |
| 336 | hostedZoneId: undefined, |
| 337 | type: news.type, |
| 338 | names: [], |
| 339 | ttl: undefined, |
| 340 | records: undefined, |
| 341 | aliasTarget: undefined, |
| 342 | }; |
| 343 | } |
| 344 | const hostedZoneId = yield* resolveHostedZoneId(explicitZoneId, desired[0] ?? ""); |
| 345 | // `output.names` is the cache of which records this resource |
| 346 | // managed before — the only way to know what to garbage-collect |
| 347 | // (Route 53 records carry no tags to observe ownership from). |
| 348 | const previous = output?.names ?? []; |
| 349 | const desiredKeys = new Set(desired.map((name) => normalizeName(name).toLowerCase())); |
| 350 | const stale = previous.filter( |
| 351 | (name) => !desiredKeys.has(normalizeName(name).toLowerCase()), |
| 352 | ); |
| 353 | |
| 354 | // Sync — observe each desired name and upsert only the delta. |
| 355 | const changes: route53.Change[] = []; |
| 356 | for (const name of desired) { |
| 357 | const target = desiredRecordSet(news, name); |
| 358 | const live = yield* findRecord(hostedZoneId, name, news.type); |
| 359 | if (!live || !matchesDesired(live, target)) { |
| 360 | changes.push({ Action: "UPSERT", ResourceRecordSet: target }); |
| 361 | } |
| 362 | } |
| 363 | if (changes.length > 0) { |
| 364 | const response = yield* route53.changeResourceRecordSets({ |
| 365 | HostedZoneId: normalizeHostedZoneId(hostedZoneId), |
| 366 | ChangeBatch: { |
| 367 | Comment: "Alchemy Route53 record-set upsert", |
| 368 | Changes: changes, |
| 369 | }, |
| 370 | }); |
| 371 | yield* waitForChange(response.ChangeInfo.Id); |
| 372 | } |
| 373 | |
| 374 | // Garbage-collect names that left the set. |
| 375 | yield* deleteNames(hostedZoneId, news.type, stale); |
| 376 | |
| 377 | yield* session.note( |
| 378 | `${news.type} × ${desired.length} record(s)` + |
| 379 | (stale.length > 0 ? ` (-${stale.length})` : ""), |
| 380 | ); |
| 381 | |
| 382 | const sample = |
| 383 | desired.length > 0 |
| 384 | ? yield* findRecord(hostedZoneId, desired[0]!, news.type) |
| 385 | : undefined; |
| 386 | return { |
| 387 | hostedZoneId: normalizeHostedZoneId(hostedZoneId), |
| 388 | type: news.type, |
| 389 | names: desired.map((name) => normalizeName(name)), |
| 390 | ttl: sample?.TTL, |
| 391 | records: sample?.ResourceRecords?.map((record) => record.Value), |
| 392 | aliasTarget: toAliasTarget(sample?.AliasTarget), |
| 393 | }; |
| 394 | }), |
| 395 | delete: Effect.fn(function* ({ output }) { |
| 396 | if (output.hostedZoneId === undefined) { |
| 397 | // The set never resolved a zone — it never created records. |
| 398 | return; |
| 399 | } |
| 400 | yield* deleteNames(output.hostedZoneId, output.type, output.names); |
| 401 | }), |
| 402 | }; |
| 403 | }), |
| 404 | ); |