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
| 1 | import * as r53r from "@distilled.cloud/aws/route53resolver"; |
| 2 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 3 | import { isResolved } from "alchemy/Diff"; |
| 4 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 5 | import * as Provider from "alchemy/Provider"; |
| 6 | import { Resource } from "alchemy/Resource"; |
| 7 | import { createInternalTags, hasAlchemyTags } from "alchemy/Tags"; |
| 8 | import * as Effect from "effect/Effect"; |
| 9 | import * as Option from "effect/Option"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import * as Stream from "effect/Stream"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { fetchResolverTags, syncResolverTags, toResolverTagList } from "./internal.ts"; |
| 14 | |
| 15 | export interface ResolverRuleTargetIp { |
| 16 | /** |
| 17 | * IPv4 address of the DNS resolver on your network that queries are |
| 18 | * forwarded to. |
| 19 | */ |
| 20 | ip?: string; |
| 21 | /** |
| 22 | * IPv6 address of the DNS resolver on your network. |
| 23 | */ |
| 24 | ipv6?: string; |
| 25 | /** |
| 26 | * Port the target resolver listens on. |
| 27 | * @default 53 |
| 28 | */ |
| 29 | port?: number; |
| 30 | /** |
| 31 | * Protocol used to reach the target. |
| 32 | * @default "Do53" |
| 33 | */ |
| 34 | protocol?: "Do53" | "DoH"; |
| 35 | } |
| 36 | |
| 37 | export interface ResolverRuleProps { |
| 38 | /** |
| 39 | * Friendly name of the rule. Also used as the `CreatorRequestId`. |
| 40 | * Changing it forces replacement. |
| 41 | * @default ${app}-${stage}-${id} |
| 42 | */ |
| 43 | name?: string; |
| 44 | /** |
| 45 | * How Resolver handles queries for `domainName`. Only `FORWARD` rules |
| 46 | * can carry `targetIps`. Changing it forces replacement. |
| 47 | * @default "FORWARD" |
| 48 | */ |
| 49 | ruleType?: "FORWARD" | "SYSTEM" | "RECURSIVE" | "DELEGATE"; |
| 50 | /** |
| 51 | * Domain name that DNS queries are matched against (longest suffix |
| 52 | * match). Changing it forces replacement. |
| 53 | */ |
| 54 | domainName: string; |
| 55 | /** |
| 56 | * IP addresses of the DNS resolvers on your network that matching |
| 57 | * queries are forwarded to. Updatable in place. |
| 58 | */ |
| 59 | targetIps?: ResolverRuleTargetIp[]; |
| 60 | /** |
| 61 | * ID of the OUTBOUND resolver endpoint the forwarded queries pass |
| 62 | * through. Updatable in place. |
| 63 | */ |
| 64 | resolverEndpointId?: string; |
| 65 | /** |
| 66 | * Tags to apply to the rule. Merged with internal Alchemy tags. |
| 67 | */ |
| 68 | tags?: Record<string, string>; |
| 69 | } |
| 70 | |
| 71 | export interface ResolverRule extends Resource< |
| 72 | "AWS.Route53Resolver.ResolverRule", |
| 73 | ResolverRuleProps, |
| 74 | { |
| 75 | /** |
| 76 | * ID of the resolver rule (e.g. `rslvr-rr-...`). |
| 77 | */ |
| 78 | resolverRuleId: string; |
| 79 | /** |
| 80 | * ARN of the resolver rule. |
| 81 | */ |
| 82 | resolverRuleArn: string; |
| 83 | /** |
| 84 | * Name of the rule. |
| 85 | */ |
| 86 | name: string; |
| 87 | /** |
| 88 | * Domain name the rule matches (as stored by Route 53 Resolver, with a |
| 89 | * trailing dot). |
| 90 | */ |
| 91 | domainName: string; |
| 92 | }, |
| 93 | never, |
| 94 | Providers |
| 95 | > {} |
| 96 | |
| 97 | /** |
| 98 | * A Route 53 Resolver rule — tells Resolver how to handle DNS queries for a |
| 99 | * domain that originate in your VPCs. |
| 100 | * |
| 101 | * A `FORWARD` rule sends matching queries through an OUTBOUND |
| 102 | * `ResolverEndpoint` to the DNS resolvers on your network listed in |
| 103 | * `targetIps`. The rule takes effect in a VPC once attached with a |
| 104 | * `ResolverRuleAssociation`. |
| 105 | * ### Forwarding Rules |
| 106 | * **Example:** Forward a Domain to On-Prem Resolvers |
| 107 | * ```typescript |
| 108 | * import * as Route53Resolver from "@alchemy.run/aws/Route53Resolver"; |
| 109 | * |
| 110 | * const rule = yield* Route53Resolver.ResolverRule("CorpForward", { |
| 111 | * domainName: "corp.example.com", |
| 112 | * resolverEndpointId: outbound.resolverEndpointId, |
| 113 | * targetIps: [{ ip: "192.168.1.10" }, { ip: "192.168.1.11", port: 53 }], |
| 114 | * }); |
| 115 | * ``` |
| 116 | * |
| 117 | * ### Attaching to VPCs |
| 118 | * **Example:** Associate the Rule with a VPC |
| 119 | * ```typescript |
| 120 | * const association = yield* Route53Resolver.ResolverRuleAssociation( |
| 121 | * "CorpForwardAssoc", |
| 122 | * { |
| 123 | * resolverRuleId: rule.resolverRuleId, |
| 124 | * vpcId: vpc.vpcId, |
| 125 | * }, |
| 126 | * ); |
| 127 | * ``` |
| 128 | * |
| 129 | * @resource |
| 130 | */ |
| 131 | export const ResolverRule = Resource<ResolverRule>("AWS.Route53Resolver.ResolverRule"); |
| 132 | |
| 133 | /** |
| 134 | * Creating a FORWARD rule can transiently fail while its OUTBOUND endpoint |
| 135 | * is still provisioning (`ResourceUnavailableException`), and recreating a |
| 136 | * rule whose deterministic `CreatorRequestId` is held by a `DELETING` |
| 137 | * predecessor raises `ResourceExistsException`. Both are bounded races — |
| 138 | * retry (~2 min). |
| 139 | * |
| 140 | * Explicitly typed: inlining `Effect.retry` in provider lifecycle code can |
| 141 | * widen the provider layer to `unknown` in declaration emit. |
| 142 | * |
| 143 | * @internal |
| 144 | */ |
| 145 | const retryRuleCreateRaces = <A, E extends { _tag: string }, R>( |
| 146 | self: Effect.Effect<A, E, R>, |
| 147 | ): Effect.Effect<A, E, R> => |
| 148 | Effect.retry(self, { |
| 149 | while: (e) => e._tag === "ResourceUnavailableException" || e._tag === "ResourceExistsException", |
| 150 | schedule: Schedule.max([Schedule.fixed("5 seconds"), Schedule.recurs(24)]), |
| 151 | }); |
| 152 | |
| 153 | /** |
| 154 | * A rule cannot be deleted while it is still associated with VPCs |
| 155 | * (`ResourceInUseException`). Association teardown is asynchronous, so |
| 156 | * retry deletion on a bounded schedule (~60s) while associations drain. |
| 157 | * |
| 158 | * @internal |
| 159 | */ |
| 160 | const retryRuleInUse = <A, E extends { _tag: string }, R>( |
| 161 | self: Effect.Effect<A, E, R>, |
| 162 | ): Effect.Effect<A, E, R> => |
| 163 | Effect.retry(self, { |
| 164 | while: (e) => e._tag === "ResourceInUseException" || e._tag === "InvalidRequestException", |
| 165 | schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(30)]), |
| 166 | }); |
| 167 | |
| 168 | /** |
| 169 | * Route 53 Resolver stores domain names lowercased with a trailing dot; |
| 170 | * normalize both sides before comparing. |
| 171 | * |
| 172 | * @internal |
| 173 | */ |
| 174 | const normalizeDomain = (domain: string) => domain.toLowerCase().replace(/\.+$/, ""); |
| 175 | |
| 176 | export const ResolverRuleProvider = () => |
| 177 | Provider.effect( |
| 178 | ResolverRule, |
| 179 | Effect.gen(function* () { |
| 180 | const createName = Effect.fn(function* (id: string, props: { name?: string | undefined }) { |
| 181 | return props.name ?? (yield* createPhysicalName({ id, maxLength: 64 })); |
| 182 | }); |
| 183 | |
| 184 | const getRule = (ruleId: string) => |
| 185 | r53r.getResolverRule({ ResolverRuleId: ruleId }).pipe( |
| 186 | Effect.map((r) => r.ResolverRule), |
| 187 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 188 | ); |
| 189 | |
| 190 | const observe = Effect.fn(function* (name: string, ruleId: string | undefined) { |
| 191 | if (ruleId !== undefined) { |
| 192 | const byId = yield* getRule(ruleId); |
| 193 | if (byId !== undefined && byId.Status !== "DELETING") { |
| 194 | return byId; |
| 195 | } |
| 196 | } |
| 197 | return yield* r53r.listResolverRules |
| 198 | .items({ |
| 199 | Filters: [{ Name: "CreatorRequestId", Values: [name] }], |
| 200 | }) |
| 201 | .pipe( |
| 202 | Stream.filter((rule) => rule.Status !== "DELETING"), |
| 203 | Stream.runHead, |
| 204 | Effect.map(Option.getOrUndefined), |
| 205 | ); |
| 206 | }); |
| 207 | |
| 208 | // Desired-vs-observed comparison of target IPs, tolerant of the |
| 209 | // defaults Route 53 Resolver fills in (port 53, protocol Do53). |
| 210 | const targetKey = (targets: readonly r53r.TargetAddress[]) => |
| 211 | targets |
| 212 | .map((t) => `${t.Ip ?? ""}|${t.Ipv6 ?? ""}|${t.Port ?? 53}|${t.Protocol ?? "Do53"}`) |
| 213 | .sort() |
| 214 | .join(","); |
| 215 | const toWireTargets = (targets: readonly ResolverRuleTargetIp[]): r53r.TargetAddress[] => |
| 216 | targets.map((t) => ({ |
| 217 | Ip: t.ip, |
| 218 | Ipv6: t.ipv6, |
| 219 | Port: t.port, |
| 220 | Protocol: t.protocol, |
| 221 | })); |
| 222 | |
| 223 | return ResolverRule.Provider.of({ |
| 224 | stables: ["resolverRuleId", "resolverRuleArn", "name", "domainName"], |
| 225 | // Top-level resource: enumerate every resolver rule in the ambient |
| 226 | // account/region (includes AWS-managed SYSTEM rules, which read as |
| 227 | // Unowned). |
| 228 | list: () => |
| 229 | r53r.listResolverRules.pages({}).pipe( |
| 230 | Stream.runCollect, |
| 231 | Effect.map((chunk) => |
| 232 | Array.from(chunk) |
| 233 | .flatMap((page) => page.ResolverRules ?? []) |
| 234 | .flatMap((rule) => |
| 235 | rule.Id !== undefined && |
| 236 | rule.Arn !== undefined && |
| 237 | // Autodefined rules (e.g. the Internet Resolver rule for |
| 238 | // `.`, id `rslvr-autodefined-rr-internet-resolver`) are |
| 239 | // owned by Route 53 Resolver itself and can never be |
| 240 | // deleted — keep them out of enumeration for account-wide |
| 241 | // teardown (nuke). |
| 242 | !rule.Id.startsWith("rslvr-autodefined") |
| 243 | ? [ |
| 244 | { |
| 245 | resolverRuleId: rule.Id, |
| 246 | resolverRuleArn: rule.Arn, |
| 247 | name: rule.Name ?? "", |
| 248 | domainName: rule.DomainName ?? "", |
| 249 | }, |
| 250 | ] |
| 251 | : [], |
| 252 | ), |
| 253 | ), |
| 254 | ), |
| 255 | read: Effect.fn(function* ({ id, olds, output }) { |
| 256 | const name = output?.name ?? (yield* createName(id, olds ?? {})); |
| 257 | const rule = yield* observe(name, output?.resolverRuleId); |
| 258 | if (rule?.Id === undefined || rule.Arn === undefined) { |
| 259 | return undefined; |
| 260 | } |
| 261 | const attrs = { |
| 262 | resolverRuleId: rule.Id, |
| 263 | resolverRuleArn: rule.Arn, |
| 264 | name: rule.Name ?? name, |
| 265 | domainName: rule.DomainName ?? "", |
| 266 | }; |
| 267 | const tags = yield* fetchResolverTags(rule.Arn); |
| 268 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 269 | }), |
| 270 | // Replacement detection: domain name and rule type are immutable; |
| 271 | // target IPs and the endpoint reference update in place. |
| 272 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 273 | if (!isResolved(news)) return undefined; |
| 274 | const oldName = yield* createName(id, olds); |
| 275 | const newName = yield* createName(id, news); |
| 276 | if (oldName !== newName) return { action: "replace" } as const; |
| 277 | if ((olds.ruleType ?? "FORWARD") !== (news.ruleType ?? "FORWARD")) { |
| 278 | return { action: "replace" } as const; |
| 279 | } |
| 280 | if (normalizeDomain(olds.domainName) !== normalizeDomain(news.domainName)) { |
| 281 | return { action: "replace" } as const; |
| 282 | } |
| 283 | }), |
| 284 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 285 | const name = output?.name ?? (yield* createName(id, news)); |
| 286 | const internalTags = yield* createInternalTags(id); |
| 287 | const desiredTags = { ...news.tags, ...internalTags }; |
| 288 | |
| 289 | // 1. OBSERVE |
| 290 | let rule = yield* observe(name, output?.resolverRuleId); |
| 291 | |
| 292 | // 2. ENSURE — create if missing, riding out the bounded races |
| 293 | // (endpoint still provisioning, DELETING predecessor). |
| 294 | if (rule === undefined) { |
| 295 | yield* session.note(`creating resolver rule ${name}`); |
| 296 | rule = yield* retryRuleCreateRaces( |
| 297 | r53r.createResolverRule({ |
| 298 | CreatorRequestId: name, |
| 299 | Name: name, |
| 300 | RuleType: news.ruleType ?? "FORWARD", |
| 301 | DomainName: news.domainName, |
| 302 | TargetIps: news.targetIps ? toWireTargets(news.targetIps) : undefined, |
| 303 | ResolverEndpointId: news.resolverEndpointId, |
| 304 | Tags: toResolverTagList(desiredTags), |
| 305 | }), |
| 306 | ).pipe(Effect.map((r) => r.ResolverRule!)); |
| 307 | } |
| 308 | const ruleId = rule.Id!; |
| 309 | |
| 310 | // 3. SYNC — name, target IPs, and the endpoint reference are |
| 311 | // mutable via UpdateResolverRule. Diff observed against |
| 312 | // desired; skip the API on no-op. |
| 313 | const desiredTargets = news.targetIps ? toWireTargets(news.targetIps) : undefined; |
| 314 | const targetsDelta = |
| 315 | desiredTargets !== undefined && |
| 316 | targetKey(rule.TargetIps ?? []) !== targetKey(desiredTargets); |
| 317 | const endpointDelta = |
| 318 | news.resolverEndpointId !== undefined && |
| 319 | rule.ResolverEndpointId !== news.resolverEndpointId; |
| 320 | const nameDelta = rule.Name !== name; |
| 321 | if (targetsDelta || endpointDelta || nameDelta) { |
| 322 | rule = yield* r53r |
| 323 | .updateResolverRule({ |
| 324 | ResolverRuleId: ruleId, |
| 325 | Config: { |
| 326 | ...(nameDelta ? { Name: name } : {}), |
| 327 | ...(targetsDelta ? { TargetIps: desiredTargets } : {}), |
| 328 | ...(endpointDelta ? { ResolverEndpointId: news.resolverEndpointId } : {}), |
| 329 | }, |
| 330 | }) |
| 331 | .pipe(Effect.map((r) => r.ResolverRule ?? rule!)); |
| 332 | } |
| 333 | |
| 334 | // 3b. SYNC TAGS — diff against observed cloud tags. |
| 335 | const arn = rule.Arn!; |
| 336 | yield* syncResolverTags(arn, desiredTags); |
| 337 | |
| 338 | yield* session.note(ruleId); |
| 339 | return { |
| 340 | resolverRuleId: ruleId, |
| 341 | resolverRuleArn: arn, |
| 342 | name: rule.Name ?? name, |
| 343 | domainName: rule.DomainName ?? news.domainName, |
| 344 | }; |
| 345 | }), |
| 346 | delete: Effect.fn(function* ({ output }) { |
| 347 | // A rule associated with VPCs cannot be deleted — disassociate all |
| 348 | // associations first (idempotent: a vanished association is |
| 349 | // already gone). |
| 350 | const associations = yield* r53r.listResolverRuleAssociations |
| 351 | .pages({ |
| 352 | Filters: [{ Name: "ResolverRuleId", Values: [output.resolverRuleId] }], |
| 353 | }) |
| 354 | .pipe( |
| 355 | Stream.runCollect, |
| 356 | Effect.map((chunk) => |
| 357 | Array.from(chunk).flatMap((page) => page.ResolverRuleAssociations ?? []), |
| 358 | ), |
| 359 | Effect.orElseSucceed(() => [] as r53r.ResolverRuleAssociation[]), |
| 360 | ); |
| 361 | yield* Effect.forEach( |
| 362 | associations, |
| 363 | (assoc) => |
| 364 | assoc.VPCId |
| 365 | ? r53r |
| 366 | .disassociateResolverRule({ |
| 367 | ResolverRuleId: output.resolverRuleId, |
| 368 | VPCId: assoc.VPCId, |
| 369 | }) |
| 370 | .pipe( |
| 371 | Effect.catchTag("ResourceNotFoundException", () => Effect.undefined), |
| 372 | Effect.asVoid, |
| 373 | ) |
| 374 | : Effect.void, |
| 375 | { discard: true }, |
| 376 | ); |
| 377 | yield* retryRuleInUse( |
| 378 | r53r.deleteResolverRule({ |
| 379 | ResolverRuleId: output.resolverRuleId, |
| 380 | }), |
| 381 | ).pipe( |
| 382 | Effect.asVoid, |
| 383 | Effect.catchTag("ResourceNotFoundException", () => Effect.void), |
| 384 | ); |
| 385 | }), |
| 386 | }); |
| 387 | }), |
| 388 | ); |