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

main
ts 358 lines 11.9 KB
Raw
1 import * as magicTransit from "@distilled.cloud/cloudflare/magic-transit";
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 * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Predicate from "effect/Predicate";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 export class SiteWanUnexpectedResponse extends Data.TaggedError("SiteWanUnexpectedResponse")<{
15 readonly message: string;
16 readonly cause?: unknown;
17 }> {}
18
19 const TypeId = "Cloudflare.MagicTransit.SiteWan" as const;
20 type TypeId = typeof TypeId;
21
22 /**
23 * Static addressing configuration for a Magic WAN site WAN — omit to use
24 * DHCP. Submit `secondaryAddress` when the site is in high availability
25 * mode.
26 */
27 export interface MagicSiteWanStaticAddressing {
28 /** A valid CIDR notation representing the WAN address. */
29 address: string;
30 /** A valid IPv4 address for the WAN gateway. */
31 gatewayAddress: string;
32 /** Secondary address, required when the site is in HA mode. */
33 secondaryAddress?: string;
34 }
35
36 export interface MagicSiteWanProps {
37 /**
38 * The site this WAN belongs to. Changing it triggers a replacement.
39 */
40 siteId: string;
41 /**
42 * The physical port number on the connector this WAN is attached to.
43 */
44 physport: number;
45 /**
46 * The name of the WAN. If omitted, a unique name is generated from the
47 * app, stage, and logical ID.
48 * @default ${app}-${stage}-${id}
49 */
50 name?: string;
51 /**
52 * Priority of the WAN for traffic load balancing. Lower is preferred.
53 */
54 priority?: number;
55 /**
56 * VLAN ID. Use zero for untagged.
57 * @default 0
58 */
59 vlanTag?: number;
60 /**
61 * Static addressing configuration; omit to use DHCP.
62 */
63 staticAddressing?: MagicSiteWanStaticAddressing;
64 }
65
66 export interface MagicSiteWanAttributes {
67 /** Cloudflare-assigned identifier of the WAN. */
68 wanId: string;
69 /** The site the WAN belongs to. */
70 siteId: string;
71 /** The Cloudflare account the WAN belongs to. */
72 accountId: string;
73 /** The name of the WAN. */
74 name: string;
75 /** The physical port number. */
76 physport: number | undefined;
77 /** Priority of the WAN for traffic load balancing. */
78 priority: number | undefined;
79 /** The VLAN ID (zero for untagged). */
80 vlanTag: number | undefined;
81 /** Magic WAN health-check rate for tunnels created on this link. */
82 healthCheckRate: string | undefined;
83 }
84
85 export type MagicSiteWan = Resource<
86 TypeId,
87 MagicSiteWanProps,
88 MagicSiteWanAttributes,
89 never,
90 Providers
91 >;
92
93 /**
94 * A WAN attached to a Magic WAN site — describes an uplink on a Magic WAN
95 * Connector port (addressing, VLAN, load-balancing priority). Cloudflare
96 * automatically creates IPsec tunnels over each WAN.
97 *
98 * Requires a Magic WAN subscription — accounts without it receive a typed
99 * `MagicWanUnauthorized` error (Cloudflare code 1025) or `MagicWanNotEnabled`
100 * (code 1101, "forbidden: feature not enabled").
101 *
102 * `siteId` is create-only — changing it triggers a replacement. Everything
103 * else is updated in place.
104 * ### Creating a WAN
105 * **Example:** DHCP uplink
106 * ```typescript
107 * const wan = yield* Cloudflare.MagicTransit.MagicSiteWan("hq-wan", {
108 * siteId: site.siteId,
109 * physport: 1,
110 * });
111 * ```
112 *
113 * **Example:** Static uplink with priority
114 * ```typescript
115 * const wan = yield* Cloudflare.MagicTransit.MagicSiteWan("hq-wan", {
116 * siteId: site.siteId,
117 * physport: 1,
118 * priority: 10,
119 * staticAddressing: {
120 * address: "203.0.113.10/24",
121 * gatewayAddress: "203.0.113.1",
122 * },
123 * });
124 * ```
125 *
126 * @see https://developers.cloudflare.com/magic-wan/configuration/connector/
127 *
128 * @resource
129 * @product Magic Transit
130 * @category Network
131 */
132 export const MagicSiteWan = Resource<MagicSiteWan>(TypeId);
133
134 /**
135 * Returns true if the given value is a MagicSiteWan resource.
136 */
137 export const isMagicSiteWan = (value: unknown): value is MagicSiteWan =>
138 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
139
140 export const MagicSiteWanProvider = () =>
141 Provider.succeed(MagicSiteWan, {
142 stables: ["wanId", "siteId", "accountId"],
143
144 diff: Effect.fn(function* ({ olds, news }) {
145 if (!isResolved(news)) return undefined;
146 if (olds === undefined) return undefined;
147 // WANs cannot move between sites.
148 if (
149 typeof olds.siteId === "string" &&
150 typeof news.siteId === "string" &&
151 olds.siteId !== news.siteId
152 ) {
153 return { action: "replace" } as const;
154 }
155 return undefined;
156 }),
157
158 read: Effect.fn(function* ({ id, output, olds }) {
159 const { accountId } = yield* yield* CloudflareEnvironment;
160 const acct = output?.accountId ?? accountId;
161 const siteId = output?.siteId ?? (typeof olds?.siteId === "string" ? olds.siteId : undefined);
162 if (!siteId) return undefined;
163
164 if (output?.wanId) {
165 const observed = yield* getWan(acct, siteId, output.wanId);
166 if (observed) return toAttributes(observed, siteId, acct);
167 }
168 // Cold read — match the deterministic physical name. WANs carry no
169 // ownership markers; report as Unowned so takeover is gated behind
170 // the adopt policy.
171 const name = yield* createWanName(id, olds?.name);
172 const observed = yield* findByName(acct, siteId, name);
173 if (observed) return Unowned(toAttributes(observed, siteId, acct));
174 return undefined;
175 }),
176
177 reconcile: Effect.fn(function* ({ id, news, output }) {
178 const { accountId } = yield* yield* CloudflareEnvironment;
179 // Inputs have been resolved to concrete strings by Plan.
180 const siteId = news.siteId as string;
181 const name = yield* createWanName(id, news.name);
182
183 // Observe — the id on `output` is a hint; fall back to a name scan.
184 let observed = output?.wanId ? yield* getWan(accountId, siteId, output.wanId) : undefined;
185 if (!observed) {
186 observed = yield* findByName(accountId, siteId, name);
187 }
188
189 // Ensure — create when missing. The create API returns the site's
190 // WAN list; pick the created WAN by name.
191 if (!observed) {
192 const created = yield* magicTransit.createSiteWan({
193 accountId,
194 siteId,
195 name,
196 physport: news.physport,
197 priority: news.priority,
198 vlanTag: news.vlanTag,
199 staticAddressing: news.staticAddressing,
200 });
201 observed =
202 created.result.find((wan) => wan.name === name) ??
203 created.result.at(0) ??
204 (yield* findByName(accountId, siteId, name));
205 if (observed) return toAttributes(observed, siteId, accountId);
206 return yield* new SiteWanUnexpectedResponse({
207 message: `Magic WAN site WAN ${name} not visible after create`,
208 });
209 }
210
211 // Sync — the update API is a PUT; send the full desired state, but
212 // skip the call entirely on a no-op of the observable fields.
213 const dirty =
214 (observed.name ?? undefined) !== name ||
215 (observed.physport ?? undefined) !== news.physport ||
216 (news.priority !== undefined && (observed.priority ?? undefined) !== news.priority) ||
217 (news.vlanTag !== undefined && (observed.vlanTag ?? undefined) !== news.vlanTag) ||
218 staticAddressingDirty(observed.staticAddressing, news.staticAddressing);
219 if (dirty) {
220 const updated = yield* magicTransit.updateSiteWan({
221 accountId,
222 siteId,
223 wanId: observed.id!,
224 name,
225 physport: news.physport,
226 priority: news.priority,
227 vlanTag: news.vlanTag,
228 staticAddressing: news.staticAddressing,
229 });
230 observed = { ...updated, id: updated.id ?? observed.id };
231 }
232
233 return toAttributes(observed, siteId, accountId);
234 }),
235
236 delete: Effect.fn(function* ({ output }) {
237 yield* magicTransit
238 .deleteSiteWan({
239 accountId: output.accountId,
240 siteId: output.siteId,
241 wanId: output.wanId,
242 })
243 .pipe(Effect.catchTag("SiteWanNotFound", () => Effect.void));
244 }),
245
246 // Parent fan-out: WANs are sub-resources keyed by site, and there is no
247 // account-wide WAN enumeration API. Enumerate every Magic site (account
248 // scope), then list WANs per site with bounded concurrency, paginating
249 // each list exhaustively. Magic WAN-gated accounts (and partial-scope
250 // tokens) reject these routes with the typed `MagicWanUnauthorized`
251 // (code 1025) / `Forbidden` tags — treat those as "nothing to list".
252 list: Effect.fn(function* () {
253 const { accountId } = yield* yield* CloudflareEnvironment;
254
255 const siteIds = yield* magicTransit.listSites.pages({ accountId }).pipe(
256 Stream.runCollect,
257 Effect.map((chunk) =>
258 Array.from(chunk).flatMap((page) =>
259 (page.result ?? []).flatMap((site) => (site.id ? [site.id] : [])),
260 ),
261 ),
262 Effect.catchTag(["MagicWanUnauthorized", "MagicWanNotEnabled", "Forbidden"], () =>
263 Effect.succeed([] as string[]),
264 ),
265 );
266
267 const rows = yield* Effect.forEach(
268 siteIds,
269 (siteId) =>
270 magicTransit.listSiteWans.pages({ accountId, siteId }).pipe(
271 Stream.runCollect,
272 Effect.map((chunk) =>
273 Array.from(chunk).flatMap((page) =>
274 (page.result ?? []).map((wan) => toAttributes(wan, siteId, accountId)),
275 ),
276 ),
277 // Site vanished or became inaccessible mid-enumeration — skip it.
278 Effect.catchTag(["MagicWanUnauthorized", "MagicWanNotEnabled", "Forbidden"], () =>
279 Effect.succeed([] as MagicSiteWanAttributes[]),
280 ),
281 ),
282 { concurrency: 10 },
283 );
284
285 return rows.flat();
286 }),
287 });
288
289 interface ObservedWan {
290 id?: string | null;
291 name?: string | null;
292 physport?: number | null;
293 priority?: number | null;
294 vlanTag?: number | null;
295 healthCheckRate?: string | null;
296 staticAddressing?: {
297 address: string;
298 gatewayAddress: string;
299 secondaryAddress?: string | null;
300 } | null;
301 }
302
303 /**
304 * Read a WAN by id, mapping "gone" (`SiteWanNotFound`, HTTP 404) to
305 * `undefined`.
306 */
307 const getWan = (accountId: string, siteId: string, wanId: string) =>
308 magicTransit.getSiteWan({ accountId, siteId, wanId }).pipe(
309 Effect.map((wan): ObservedWan | undefined => wan),
310 Effect.catchTag("SiteWanNotFound", () => Effect.undefined),
311 );
312
313 /**
314 * Find a WAN by exact name within a site. Names are not enforced unique;
315 * pick the first match deterministically by id.
316 */
317 const findByName = (accountId: string, siteId: string, name: string) =>
318 magicTransit.listSiteWans({ accountId, siteId }).pipe(
319 Effect.map((r): ObservedWan | undefined =>
320 r.result
321 .filter((wan) => wan.name === name)
322 .sort((a, b) => (a.id ?? "").localeCompare(b.id ?? ""))
323 .at(0),
324 ),
325 );
326
327 const createWanName = (id: string, name: string | undefined) =>
328 Effect.gen(function* () {
329 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
330 });
331
332 const staticAddressingDirty = (
333 observed: ObservedWan["staticAddressing"],
334 desired: MagicSiteWanStaticAddressing | undefined,
335 ): boolean => {
336 if (desired === undefined) return false;
337 return (
338 (observed?.address ?? undefined) !== desired.address ||
339 (observed?.gatewayAddress ?? undefined) !== desired.gatewayAddress ||
340 (desired.secondaryAddress !== undefined &&
341 (observed?.secondaryAddress ?? undefined) !== desired.secondaryAddress)
342 );
343 };
344
345 const toAttributes = (
346 wan: ObservedWan,
347 siteId: string,
348 accountId: string,
349 ): MagicSiteWanAttributes => ({
350 wanId: wan.id ?? "",
351 siteId,
352 accountId,
353 name: wan.name ?? "",
354 physport: wan.physport ?? undefined,
355 priority: wan.priority ?? undefined,
356 vlanTag: wan.vlanTag ?? undefined,
357 healthCheckRate: wan.healthCheckRate ?? undefined,
358 });