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

main
ts 207 lines 7.26 KB
Raw
1 import * as customHostnames from "@distilled.cloud/cloudflare/custom-hostnames";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9 import { listAllZones } from "../Zone/lookup.ts";
10
11 export interface FallbackOriginProps {
12 /**
13 * Zone the fallback origin belongs to. Stable — a zone has exactly one
14 * fallback origin, so changing the zone triggers replacement.
15 */
16 zoneId: string;
17 /**
18 * Your origin hostname that requests to custom hostnames are sent to.
19 * Must be a DNS record (A, AAAA or CNAME) within the zone — create the
20 * `Cloudflare.DNS.Record` first and pass its name.
21 *
22 * Mutable — the API is a PUT-style upsert.
23 */
24 origin: string;
25 }
26
27 export interface FallbackOriginAttributes {
28 /** Zone that owns this fallback origin. */
29 zoneId: string;
30 /** The configured origin hostname. */
31 origin: string;
32 /**
33 * Activation status (`initializing`, `pending_deployment`, `active`,
34 * …). Deployment is asynchronous (typically minutes) and is not
35 * blocked on.
36 */
37 status: string | undefined;
38 }
39
40 export type FallbackOrigin = Resource<
41 "Cloudflare.CustomHostname.FallbackOrigin",
42 FallbackOriginProps,
43 FallbackOriginAttributes,
44 never,
45 Providers
46 >;
47
48 /**
49 * The Cloudflare for SaaS fallback origin of a zone.
50 *
51 * A zone-level singleton: requests to any of the zone's custom hostnames
52 * that don't have a `customOriginServer` are routed to this origin.
53 * Setting a fallback origin implicitly enables Cloudflare for SaaS on
54 * the zone.
55 *
56 * Safety: when there is no prior state, `read` reports an existing
57 * fallback origin as `Unowned`, so the engine refuses to overwrite an
58 * out-of-band configuration unless `--adopt` (or `adopt(true)`) is set.
59 * ### Setting the Fallback Origin
60 * **Example:** Point custom hostname traffic at your origin
61 * ```typescript
62 * const record = yield* Cloudflare.DNS.Record("Origin", {
63 * zoneId: zone.zoneId,
64 * name: "origin.my-saas.com",
65 * type: "A",
66 * content: "203.0.113.1",
67 * proxied: true,
68 * });
69 * const fallback = yield* Cloudflare.CustomHostname.FallbackOrigin("Fallback", {
70 * zoneId: zone.zoneId,
71 * origin: record.name,
72 * });
73 * ```
74 *
75 * @resource
76 * @product Custom Hostnames
77 * @category Domains & DNS
78 */
79 export const FallbackOrigin = Resource<FallbackOrigin>("Cloudflare.CustomHostname.FallbackOrigin", {
80 aliases: ["Cloudflare.FallbackOrigin"],
81 });
82
83 export const isFallbackOrigin = (value: unknown): value is FallbackOrigin =>
84 Predicate.hasProperty(value, "Type") && value.Type === "Cloudflare.CustomHostname.FallbackOrigin";
85
86 export const FallbackOriginProvider = () =>
87 Provider.succeed(FallbackOrigin, {
88 stables: ["zoneId"],
89
90 list: Effect.fn(function* () {
91 const { accountId } = yield* yield* CloudflareEnvironment;
92 // Zone singleton — no account-wide list. Enumerate every zone and
93 // read its fallback origin; zones without one configured (or
94 // without Cloudflare for SaaS access) are skipped.
95 const allZones = yield* listAllZones(accountId);
96 const rows = yield* Effect.forEach(
97 allZones.map((zone) => zone.id),
98 (zoneId) =>
99 observeFallbackOrigin(zoneId).pipe(
100 Effect.map((observed): FallbackOriginAttributes | undefined => {
101 if (
102 observed?.origin === undefined ||
103 observed.status === "pending_deletion" ||
104 observed.status === "deletion_timed_out"
105 ) {
106 return undefined;
107 }
108 return {
109 zoneId,
110 origin: observed.origin,
111 status: observed.status,
112 };
113 }),
114 // Zones without Cloudflare for SaaS entitlement reject the
115 // route; skip them rather than failing the whole enumeration.
116 Effect.catchTag(["SaasAccessNotGranted", "Forbidden"], () => Effect.undefined),
117 ),
118 { concurrency: 10 },
119 );
120 return rows.filter((row): row is FallbackOriginAttributes => row !== undefined);
121 }),
122
123 diff: Effect.fn(function* ({ olds = {}, news }) {
124 const o = olds as FallbackOriginProps;
125 const n = news as FallbackOriginProps;
126 // zoneId is Input<string>; compare only once both sides are
127 // concrete strings.
128 if (typeof o.zoneId === "string" && typeof n.zoneId === "string" && o.zoneId !== n.zoneId) {
129 return { action: "replace" } as const;
130 }
131 }),
132
133 reconcile: Effect.fn(function* ({ news }) {
134 // Inputs have been resolved to concrete strings by Plan.
135 const zoneId = news.zoneId as string;
136 const origin = news.origin as string;
137
138 // 1. Observe the singleton.
139 const observed = yield* observeFallbackOrigin(zoneId);
140
141 // 2/3. Ensure + sync — PUT is a true upsert; skip the API call
142 // entirely when the observed origin already matches (the
143 // status field converges asynchronously on its own).
144 if (
145 observed?.origin === origin &&
146 observed.status !== "pending_deletion" &&
147 observed.status !== "deletion_timed_out"
148 ) {
149 return { zoneId, origin: observed.origin, status: observed.status };
150 }
151 const updated = yield* customHostnames.putFallbackOrigin({
152 zoneId,
153 origin,
154 });
155
156 // 4. Return fresh attributes.
157 return {
158 zoneId,
159 origin: updated.origin ?? origin,
160 status: updated.status ?? undefined,
161 };
162 }),
163
164 delete: Effect.fn(function* ({ output }) {
165 yield* customHostnames
166 .deleteFallbackOrigin({ zoneId: output.zoneId })
167 .pipe(Effect.catchTag("FallbackOriginNotFound", () => Effect.void));
168 }),
169
170 read: Effect.fn(function* ({ output, olds }) {
171 const zoneId = output?.zoneId ?? (typeof olds?.zoneId === "string" ? olds.zoneId : undefined);
172 if (!zoneId) return undefined;
173 const observed = yield* observeFallbackOrigin(zoneId);
174 if (
175 observed?.origin === undefined ||
176 observed.status === "pending_deletion" ||
177 observed.status === "deletion_timed_out"
178 ) {
179 return undefined;
180 }
181 const attrs: FallbackOriginAttributes = {
182 zoneId,
183 origin: observed.origin,
184 status: observed.status,
185 };
186 // Owned path: we have persisted state — refresh it. Cold path: a
187 // fallback origin exists but we cannot prove we created it (the
188 // API has no ownership markers), so gate takeover behind adoption.
189 return output?.zoneId ? attrs : Unowned(attrs);
190 }),
191 });
192
193 interface ObservedFallbackOrigin {
194 readonly origin: string | undefined;
195 readonly status: string | undefined;
196 }
197
198 // An unset fallback origin is reported by the API as a bare 404 —
199 // typed in the distilled union as `FallbackOriginNotFound`.
200 const observeFallbackOrigin = (zoneId: string) =>
201 customHostnames.getFallbackOrigin({ zoneId }).pipe(
202 Effect.map((r): ObservedFallbackOrigin => ({
203 origin: r.origin ?? undefined,
204 status: r.status ?? undefined,
205 })),
206 Effect.catchTag("FallbackOriginNotFound", () => Effect.undefined),
207 );