@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 316 lines 10.2 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 * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 const TypeId = "Cloudflare.MagicTransit.StaticRoute" as const;
12 type TypeId = typeof TypeId;
13
14 /**
15 * Scope of an ECMP static route — restricts the route to specific
16 * Cloudflare colos or regions.
17 */
18 export interface MagicStaticRouteScope {
19 /** List of colo names the route applies to. */
20 coloNames?: string[];
21 /** List of colo regions the route applies to. */
22 coloRegions?: string[];
23 }
24
25 export interface MagicStaticRouteProps {
26 /**
27 * IP prefix in CIDR notation that this route matches.
28 */
29 prefix: string;
30 /**
31 * The next-hop IP address for the static route — typically a Magic
32 * tunnel's customer-side interface address.
33 */
34 nexthop: string;
35 /**
36 * Priority of the static route. Lower values are preferred.
37 * @default 100
38 */
39 priority?: number;
40 /**
41 * An optional human-provided description of the static route.
42 */
43 description?: string;
44 /**
45 * Optional weight for ECMP routes.
46 */
47 weight?: number;
48 /**
49 * Used only for ECMP routes — restrict the route to colos/regions.
50 */
51 scope?: MagicStaticRouteScope;
52 }
53
54 export interface MagicStaticRouteAttributes {
55 /** Cloudflare-assigned identifier of the static route. */
56 routeId: string;
57 /** The Cloudflare account the route belongs to. */
58 accountId: string;
59 /** IP prefix in CIDR notation. */
60 prefix: string;
61 /** The next-hop IP address. */
62 nexthop: string;
63 /** Priority of the static route. */
64 priority: number;
65 /** The route description, if set. */
66 description: string | undefined;
67 /** ECMP weight, if set. */
68 weight: number | undefined;
69 /** ECMP scope, if set. */
70 scope: MagicStaticRouteScope | undefined;
71 /** ISO8601 creation timestamp. */
72 createdOn: string | undefined;
73 /** ISO8601 last-modified timestamp. */
74 modifiedOn: string | undefined;
75 }
76
77 export type MagicStaticRoute = Resource<
78 TypeId,
79 MagicStaticRouteProps,
80 MagicStaticRouteAttributes,
81 never,
82 Providers
83 >;
84
85 /**
86 * A Magic Transit / Magic WAN static route — steers traffic for a prefix
87 * to a next-hop (usually a Magic tunnel interface address).
88 *
89 * Requires a Magic Transit or Magic WAN subscription on the account —
90 * accounts that are not onboarded receive a typed
91 * `MagicTransitNotOnboarded` error (Cloudflare code 1012).
92 *
93 * All properties are mutable in place via PUT. A route's practical
94 * identity is the `(prefix, nexthop, priority)` triple — when state is
95 * lost, `read` scans for a matching route and reports it as `Unowned` so
96 * takeover is gated behind `--adopt`.
97 * ### Creating a static route
98 * **Example:** Route a prefix over a GRE tunnel
99 * ```typescript
100 * const tunnel = yield* Cloudflare.MagicTransit.GreTunnel("office", {
101 * name: "office-gre-1",
102 * cloudflareGreEndpoint: "203.0.113.1",
103 * customerGreEndpoint: "198.51.100.1",
104 * interfaceAddress: "10.213.0.8/31",
105 * });
106 *
107 * yield* Cloudflare.MagicTransit.MagicStaticRoute("office-route", {
108 * prefix: "10.100.0.0/24",
109 * nexthop: "10.213.0.9",
110 * priority: 100,
111 * });
112 * ```
113 *
114 * **Example:** ECMP route scoped to a region
115 * ```typescript
116 * yield* Cloudflare.MagicTransit.MagicStaticRoute("ecmp-route", {
117 * prefix: "10.100.0.0/24",
118 * nexthop: "10.213.0.9",
119 * priority: 100,
120 * weight: 50,
121 * scope: { coloRegions: ["ENAM"] },
122 * });
123 * ```
124 *
125 * @see https://developers.cloudflare.com/magic-transit/how-to/configure-static-routes/
126 *
127 * @resource
128 * @product Magic Transit
129 * @category Network
130 */
131 export const MagicStaticRoute = Resource<MagicStaticRoute>(TypeId);
132
133 /**
134 * Returns true if the given value is a MagicStaticRoute resource.
135 */
136 export const isMagicStaticRoute = (value: unknown): value is MagicStaticRoute =>
137 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
138
139 const DEFAULT_PRIORITY = 100;
140
141 export const MagicStaticRouteProvider = () =>
142 Provider.succeed(MagicStaticRoute, {
143 stables: ["routeId", "accountId", "createdOn"],
144
145 read: Effect.fn(function* ({ output, olds }) {
146 const { accountId } = yield* yield* CloudflareEnvironment;
147 const acct = output?.accountId ?? accountId;
148
149 if (output?.routeId) {
150 const observed = yield* getRoute(acct, output.routeId);
151 if (observed) return toAttributes(observed, acct);
152 }
153 // Cold read — match on the (prefix, nexthop, priority) triple.
154 // Routes carry no ownership markers; report as Unowned so takeover
155 // is gated behind the adopt policy.
156 const prefix = output?.prefix ?? olds?.prefix;
157 const nexthop =
158 output?.nexthop ??
159 (olds?.nexthop !== undefined && isResolved(olds.nexthop) ? olds.nexthop : undefined);
160 if (prefix && nexthop) {
161 const priority = output?.priority ?? olds?.priority ?? DEFAULT_PRIORITY;
162 const observed = yield* findRoute(acct, prefix, nexthop, priority);
163 if (observed) return Unowned(toAttributes(observed, acct));
164 }
165 return undefined;
166 }),
167
168 reconcile: Effect.fn(function* ({ news, output }) {
169 const { accountId } = yield* yield* CloudflareEnvironment;
170 // Inputs have been resolved to concrete strings by Plan.
171 const nexthop = news.nexthop as string;
172 const priority = news.priority ?? DEFAULT_PRIORITY;
173
174 // Observe — the id on `output` is a hint; fall back to scanning for
175 // the identity triple when it is gone.
176 let observed = output?.routeId ? yield* getRoute(accountId, output.routeId) : undefined;
177 if (!observed) {
178 observed = yield* findRoute(accountId, news.prefix, nexthop, priority);
179 }
180
181 // Ensure — create when missing.
182 if (!observed) {
183 const created = yield* magicTransit.createRoute({
184 accountId,
185 prefix: news.prefix,
186 nexthop,
187 priority,
188 description: news.description,
189 weight: news.weight,
190 scope: news.scope,
191 });
192 return toAttributes(created, accountId);
193 }
194
195 // Sync — diff observed cloud state against desired; full PUT, skip
196 // on no-op.
197 const dirty =
198 observed.prefix !== news.prefix ||
199 observed.nexthop !== nexthop ||
200 observed.priority !== priority ||
201 (news.description !== undefined &&
202 (observed.description ?? undefined) !== news.description) ||
203 (news.weight !== undefined && (observed.weight ?? undefined) !== news.weight) ||
204 scopeDirty(observed.scope, news.scope);
205 if (dirty) {
206 const updated = yield* magicTransit.updateRoute({
207 accountId,
208 routeId: observed.id,
209 prefix: news.prefix,
210 nexthop,
211 priority,
212 description: news.description,
213 weight: news.weight,
214 scope: news.scope,
215 });
216 observed = updated.modifiedRoute ?? (yield* getRoute(accountId, observed.id)) ?? observed;
217 }
218
219 return toAttributes(observed, accountId);
220 }),
221
222 delete: Effect.fn(function* ({ output }) {
223 yield* magicTransit
224 .deleteRoute({
225 accountId: output.accountId,
226 routeId: output.routeId,
227 })
228 .pipe(Effect.catchTag("RouteNotFound", () => Effect.void));
229 }),
230
231 list: Effect.fn(function* () {
232 const { accountId } = yield* yield* CloudflareEnvironment;
233 // Account-scoped collection — the list API already returns the full
234 // route shape, so each item maps directly to the `read` Attributes.
235 return yield* magicTransit.listRoutes({ accountId }).pipe(
236 Effect.map((response) =>
237 (response.routes ?? []).map((route) => toAttributes(route, accountId)),
238 ),
239 // Accounts without a Magic Transit / Magic WAN subscription can't
240 // enumerate routes — treat as empty rather than failing the list.
241 Effect.catchTag("MagicTransitNotOnboarded", () => Effect.succeed([])),
242 );
243 }),
244 });
245
246 interface ObservedRoute {
247 id: string;
248 nexthop: string;
249 prefix: string;
250 priority: number;
251 description?: string | null;
252 weight?: number | null;
253 scope?: {
254 coloNames?: string[] | null;
255 coloRegions?: string[] | null;
256 } | null;
257 createdOn?: string | null;
258 modifiedOn?: string | null;
259 }
260
261 /**
262 * Read a route by id, mapping "gone" (`RouteNotFound`, Cloudflare error
263 * code 1020) to `undefined`.
264 */
265 const getRoute = (accountId: string, routeId: string) =>
266 magicTransit.getRoute({ accountId, routeId }).pipe(
267 Effect.map((r): ObservedRoute | undefined => r.route ?? undefined),
268 Effect.catchTag("RouteNotFound", () => Effect.undefined),
269 );
270
271 /**
272 * Find a route by its (prefix, nexthop, priority) identity triple.
273 */
274 const findRoute = (accountId: string, prefix: string, nexthop: string, priority: number) =>
275 magicTransit
276 .listRoutes({ accountId })
277 .pipe(
278 Effect.map((r): ObservedRoute | undefined =>
279 (r.routes ?? []).find(
280 (route) =>
281 route.prefix === prefix && route.nexthop === nexthop && route.priority === priority,
282 ),
283 ),
284 );
285
286 const sameList = (a: string[] | null | undefined, b: string[] | undefined): boolean =>
287 [...(a ?? [])].sort().join(",") === [...(b ?? [])].sort().join(",");
288
289 const scopeDirty = (
290 observed: ObservedRoute["scope"],
291 desired: MagicStaticRouteScope | undefined,
292 ): boolean => {
293 if (desired === undefined) return false;
294 return (
295 !sameList(observed?.coloNames, desired.coloNames) ||
296 !sameList(observed?.coloRegions, desired.coloRegions)
297 );
298 };
299
300 const toAttributes = (route: ObservedRoute, accountId: string): MagicStaticRouteAttributes => ({
301 routeId: route.id,
302 accountId,
303 prefix: route.prefix,
304 nexthop: route.nexthop,
305 priority: route.priority,
306 description: route.description ?? undefined,
307 weight: route.weight ?? undefined,
308 scope: route.scope
309 ? {
310 coloNames: route.scope.coloNames ?? undefined,
311 coloRegions: route.scope.coloRegions ?? undefined,
312 }
313 : undefined,
314 createdOn: route.createdOn ?? undefined,
315 modifiedOn: route.modifiedOn ?? undefined,
316 });