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

main
ts 524 lines 18.1 KB
Raw
1 import * as mcn from "@distilled.cloud/cloudflare/magic-cloud-networking";
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 Effect from "effect/Effect";
8 import * as Predicate from "effect/Predicate";
9 import * as Stream from "effect/Stream";
10 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
11 import type { Providers } from "../Providers.ts";
12
13 const TypeId = "Cloudflare.MagicCloudNetworking.OnRamp" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * The cloud provider an on-ramp connects to Magic WAN.
18 */
19 export type OnRampCloudType = "AWS" | "AZURE" | "GOOGLE";
20
21 /**
22 * Topology of an on-ramp: a single VPC/VNet, or a hub (e.g. AWS Transit
23 * Gateway) with attached VPCs.
24 */
25 export type OnRampType = "OnrampTypeSingle" | "OnrampTypeHub";
26
27 export interface OnRampProps {
28 /**
29 * The cloud provider this on-ramp connects to.
30 *
31 * Immutable — changing the cloud type triggers a replacement.
32 */
33 cloudType: OnRampCloudType;
34 /**
35 * Topology of the on-ramp: `OnrampTypeSingle` connects one VPC/VNet,
36 * `OnrampTypeHub` provisions a hub (e.g. AWS Transit Gateway) that VPCs
37 * attach to.
38 *
39 * Immutable — changing the topology triggers a replacement.
40 */
41 type: OnRampType;
42 /**
43 * Enables BGP routing. When enabled, set both `installRoutesInCloud` and
44 * `installRoutesInMagicWan` to `false`.
45 *
46 * Immutable — the API offers no way to change it, so a change triggers a
47 * replacement.
48 */
49 dynamicRouting: boolean;
50 /**
51 * Whether Cloudflare installs Magic WAN routes into the cloud route
52 * tables. Mutable.
53 */
54 installRoutesInCloud: boolean;
55 /**
56 * Whether routes to the cloud networks are installed in Magic WAN.
57 * Mutable.
58 */
59 installRoutesInMagicWan: boolean;
60 /**
61 * Human readable name. Used as the on-ramp's identity for cold-state
62 * recovery, so it should be unique within the account. If omitted, a
63 * unique name is generated from the app, stage, and logical ID.
64 * @default ${app}-${stage}-${id}
65 */
66 name?: string;
67 /**
68 * Cloud region the on-ramp is provisioned in (e.g. `us-east-1`).
69 *
70 * Immutable — changing the region triggers a replacement.
71 */
72 region?: string;
73 /**
74 * The discovered VPC/VNet resource id to connect
75 * (`type: "OnrampTypeSingle"`). Mutable.
76 */
77 vpc?: string;
78 /**
79 * Cloud-side ASN for BGP. If unset or zero, the cloud's default ASN
80 * takes effect.
81 *
82 * Immutable — the API offers no way to change it, so a change triggers a
83 * replacement.
84 */
85 cloudAsn?: number;
86 /**
87 * Free-form description of the on-ramp. Mutable.
88 */
89 description?: string;
90 /**
91 * Adopt an existing hub (e.g. an existing Transit Gateway) instead of
92 * provisioning one (`type: "OnrampTypeHub"`).
93 *
94 * Immutable — hub identity cannot change, so a change triggers a
95 * replacement.
96 */
97 adoptedHubId?: string;
98 /**
99 * Cloud integration that owns the hub when it lives in a different
100 * provider account.
101 *
102 * Immutable — hub identity cannot change, so a change triggers a
103 * replacement.
104 */
105 hubProviderId?: string;
106 /**
107 * Hubs attached to this on-ramp. Mutable.
108 */
109 attachedHubs?: string[];
110 /**
111 * VPCs attached to this hub on-ramp (`type: "OnrampTypeHub"`). Mutable.
112 */
113 attachedVpcs?: string[];
114 /**
115 * Whether Cloudflare manages hub-to-hub attachments. Mutable.
116 */
117 manageHubToHubAttachments?: boolean;
118 /**
119 * Whether Cloudflare manages VPC-to-hub attachments. Mutable.
120 */
121 manageVpcToHubAttachments?: boolean;
122 /**
123 * Whether deleting the on-ramp also destroys the cloud-side resources it
124 * provisioned (VPN gateways, Transit Gateway, …). Consumed only at
125 * delete time.
126 * @default false
127 */
128 destroyOnDelete?: boolean;
129 }
130
131 export interface OnRampAttributes {
132 /** Cloudflare-assigned identifier of the on-ramp. */
133 onRampId: string;
134 /** The Cloudflare account the on-ramp belongs to. */
135 accountId: string;
136 /** Human readable name of the on-ramp. */
137 name: string;
138 /** The cloud provider this on-ramp connects to. */
139 cloudType: OnRampCloudType;
140 /** Topology of the on-ramp. */
141 type: OnRampType;
142 /** Whether BGP routing is enabled. */
143 dynamicRouting: boolean;
144 /** Whether Magic WAN routes are installed into the cloud route tables. */
145 installRoutesInCloud: boolean;
146 /** Whether cloud routes are installed in Magic WAN. */
147 installRoutesInMagicWan: boolean;
148 /** The connected VPC/VNet resource id, if set. */
149 vpc: string | undefined;
150 /** Cloud-side ASN, if set. */
151 cloudAsn: number | undefined;
152 /** Free-form description, if set. */
153 description: string | undefined;
154 /** Hubs attached to this on-ramp. */
155 attachedHubs: string[];
156 /** VPCs attached to this hub on-ramp. */
157 attachedVpcs: string[];
158 /** Whether Cloudflare manages hub-to-hub attachments, if reported. */
159 manageHubToHubAttachments: boolean | undefined;
160 /** Whether Cloudflare manages VPC-to-hub attachments, if reported. */
161 manageVpcToHubAttachments: boolean | undefined;
162 /** ISO8601 timestamp of the last change to the on-ramp. */
163 updatedAt: string;
164 /** Whether delete also destroys provisioned cloud-side resources. */
165 destroyOnDelete: boolean;
166 }
167
168 export type OnRamp = Resource<TypeId, OnRampProps, OnRampAttributes, never, Providers>;
169
170 /**
171 * A Magic Cloud Networking on-ramp — connects cloud VPCs/VNets to Magic WAN
172 * by provisioning VPN/Transit-Gateway constructs inside the cloud account
173 * registered via a `CloudIntegration`.
174 *
175 * On-ramps are heavily eventually consistent: after create/update the
176 * on-ramp goes through plan/apply phases that provision real cloud
177 * infrastructure (minutes). This resource creates and patches the on-ramp
178 * configuration and returns immediately; the apply lifecycle is driven by
179 * Cloudflare.
180 *
181 * `name`, `description`, `vpc`, route-installation flags, and attachments
182 * are patched in place; `cloudType`, `type`, `dynamicRouting`, `region`,
183 * `cloudAsn`, and hub identity force a replacement.
184 *
185 * Magic Cloud Networking is an entitlement-gated add-on (Magic WAN family).
186 * On accounts without the entitlement every API call fails with the typed
187 * `FeatureNotEnabled` error (Cloudflare code 1012, "feature not enabled").
188 * ### Connecting a single VPC
189 * **Example:** AWS VPC on-ramp
190 * ```typescript
191 * const onramp = yield* Cloudflare.MagicCloudNetworking.OnRamp("ProdVpc", {
192 * cloudType: "AWS",
193 * type: "OnrampTypeSingle",
194 * region: "us-east-1",
195 * vpc: discoveredVpcId,
196 * dynamicRouting: false,
197 * installRoutesInCloud: true,
198 * installRoutesInMagicWan: true,
199 * });
200 * ```
201 *
202 * ### Hub topologies
203 * **Example:** Transit Gateway hub with attached VPCs
204 * ```typescript
205 * yield* Cloudflare.MagicCloudNetworking.OnRamp("TgwHub", {
206 * cloudType: "AWS",
207 * type: "OnrampTypeHub",
208 * region: "us-east-1",
209 * dynamicRouting: true,
210 * installRoutesInCloud: false,
211 * installRoutesInMagicWan: false,
212 * attachedVpcs: [vpcA, vpcB],
213 * manageVpcToHubAttachments: true,
214 * });
215 * ```
216 *
217 * ### Destroy behavior
218 * **Example:** Tear down cloud-side resources on destroy
219 * ```typescript
220 * yield* Cloudflare.MagicCloudNetworking.OnRamp("ProdVpc", {
221 * cloudType: "AWS",
222 * type: "OnrampTypeSingle",
223 * region: "us-east-1",
224 * vpc: discoveredVpcId,
225 * dynamicRouting: false,
226 * installRoutesInCloud: true,
227 * installRoutesInMagicWan: true,
228 * destroyOnDelete: true,
229 * });
230 * ```
231 *
232 * @see https://developers.cloudflare.com/magic-cloud-networking/
233 *
234 * @resource
235 * @product Magic Cloud Networking
236 * @category Network
237 */
238 export const OnRamp = Resource<OnRamp>(TypeId);
239
240 /**
241 * Returns true if the given value is an OnRamp resource.
242 */
243 export const isOnRamp = (value: unknown): value is OnRamp =>
244 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
245
246 export const OnRampProvider = () =>
247 Provider.succeed(OnRamp, {
248 stables: ["onRampId", "accountId", "cloudType", "type", "dynamicRouting", "cloudAsn"],
249
250 diff: Effect.fn(function* ({ olds, news, output }) {
251 if (!isResolved(news)) return undefined;
252 const old = olds !== undefined && isResolved(olds) ? olds : undefined;
253 // Immutable identity/topology properties — the PATCH body accepts
254 // none of these, so any change is a replacement.
255 const oldCloudType = output?.cloudType ?? old?.cloudType;
256 if (oldCloudType !== undefined && oldCloudType !== news.cloudType) {
257 return { action: "replace" } as const;
258 }
259 const oldType = output?.type ?? old?.type;
260 if (oldType !== undefined && oldType !== news.type) {
261 return { action: "replace" } as const;
262 }
263 const oldDynamicRouting = output?.dynamicRouting ?? old?.dynamicRouting;
264 if (oldDynamicRouting !== undefined && oldDynamicRouting !== news.dynamicRouting) {
265 return { action: "replace" } as const;
266 }
267 if (old !== undefined) {
268 if (old.region !== news.region) {
269 return { action: "replace" } as const;
270 }
271 if (old.cloudAsn !== news.cloudAsn) {
272 return { action: "replace" } as const;
273 }
274 if (old.adoptedHubId !== news.adoptedHubId) {
275 return { action: "replace" } as const;
276 }
277 if (old.hubProviderId !== news.hubProviderId) {
278 return { action: "replace" } as const;
279 }
280 }
281 return undefined;
282 }),
283
284 read: Effect.fn(function* ({ id, output, olds }) {
285 const { accountId } = yield* yield* CloudflareEnvironment;
286 const acct = output?.accountId ?? accountId;
287 const destroyOnDelete = output?.destroyOnDelete ?? olds?.destroyOnDelete ?? false;
288
289 // Owned path: refresh by our persisted on-ramp id.
290 if (output?.onRampId) {
291 const observed = yield* getOnRamp(acct, output.onRampId);
292 if (observed) return toAttributes(observed, acct, destroyOnDelete);
293 return undefined;
294 }
295
296 // Cold read — recover from lost state by matching the deterministic
297 // physical name. On-ramps carry no ownership markers, so report a
298 // match as Unowned and let the engine gate adoption.
299 const name = yield* onRampName(id, olds?.name);
300 const match = yield* findByName(acct, name);
301 return match ? Unowned(toAttributes(match, acct, destroyOnDelete)) : undefined;
302 }),
303
304 reconcile: Effect.fn(function* ({ id, news, output }) {
305 const { accountId } = yield* yield* CloudflareEnvironment;
306 const name = yield* onRampName(id, news.name);
307 const destroyOnDelete = news.destroyOnDelete ?? false;
308
309 // 1. Observe — the id cached on `output` is a hint, not a guarantee:
310 // a missing on-ramp falls through to the name scan and create.
311 let observed = output?.onRampId
312 ? yield* getOnRamp(output.accountId ?? accountId, output.onRampId)
313 : undefined;
314 if (!observed) {
315 observed = yield* findByName(accountId, name);
316 }
317
318 // 2. Ensure — create when missing. Names are not unique on
319 // Cloudflare's side so there is no AlreadyExists race to tolerate.
320 if (!observed) {
321 observed = yield* mcn.createOnRamp({
322 accountId,
323 name,
324 cloudType: news.cloudType,
325 type: news.type,
326 dynamicRouting: news.dynamicRouting,
327 installRoutesInCloud: news.installRoutesInCloud,
328 installRoutesInMagicWan: news.installRoutesInMagicWan,
329 region: news.region,
330 vpc: news.vpc,
331 cloudAsn: news.cloudAsn,
332 description: news.description,
333 adoptedHubId: news.adoptedHubId,
334 hubProviderId: news.hubProviderId,
335 attachedHubs: news.attachedHubs,
336 attachedVpcs: news.attachedVpcs,
337 manageHubToHubAttachments: news.manageHubToHubAttachments,
338 manageVpcToHubAttachments: news.manageVpcToHubAttachments,
339 });
340 return toAttributes(observed, accountId, destroyOnDelete);
341 }
342
343 // 3. Sync — diff observed cloud state against desired; PATCH only the
344 // delta and skip the call entirely on a no-op.
345 const patch: mcn.PatchOnRampRequest = {
346 accountId,
347 onrampId: observed.id,
348 };
349 let dirty = false;
350 if (observed.name !== name) {
351 patch.name = name;
352 dirty = true;
353 }
354 if (news.description !== undefined && (observed.description ?? "") !== news.description) {
355 patch.description = news.description;
356 dirty = true;
357 }
358 if (news.vpc !== undefined && (observed.vpc ?? "") !== news.vpc) {
359 patch.vpc = news.vpc;
360 dirty = true;
361 }
362 if (observed.installRoutesInCloud !== news.installRoutesInCloud) {
363 patch.installRoutesInCloud = news.installRoutesInCloud;
364 dirty = true;
365 }
366 if (observed.installRoutesInMagicWan !== news.installRoutesInMagicWan) {
367 patch.installRoutesInMagicWan = news.installRoutesInMagicWan;
368 dirty = true;
369 }
370 if (
371 news.attachedHubs !== undefined &&
372 !sameIds(observed.attachedHubs ?? [], news.attachedHubs)
373 ) {
374 patch.attachedHubs = news.attachedHubs;
375 dirty = true;
376 }
377 if (
378 news.attachedVpcs !== undefined &&
379 !sameIds(observed.attachedVpcs ?? [], news.attachedVpcs)
380 ) {
381 patch.attachedVpcs = news.attachedVpcs;
382 dirty = true;
383 }
384 if (
385 news.manageHubToHubAttachments !== undefined &&
386 (observed.manageHubToHubAttachments ?? false) !== news.manageHubToHubAttachments
387 ) {
388 patch.manageHubToHubAttachments = news.manageHubToHubAttachments;
389 dirty = true;
390 }
391 if (
392 news.manageVpcToHubAttachments !== undefined &&
393 (observed.manageVpcToHubAttachments ?? false) !== news.manageVpcToHubAttachments
394 ) {
395 patch.manageVpcToHubAttachments = news.manageVpcToHubAttachments;
396 dirty = true;
397 }
398 if (dirty) {
399 observed = yield* mcn.patchOnRamp(patch);
400 }
401
402 return toAttributes(observed, accountId, destroyOnDelete);
403 }),
404
405 delete: Effect.fn(function* ({ output }) {
406 // Deleting an on-ramp tears down cloud-side infrastructure when
407 // `destroy` is set — slow and eventually consistent on Cloudflare's
408 // side, but the DELETE call itself returns promptly.
409 yield* mcn
410 .deleteOnRamp({
411 accountId: output.accountId,
412 onrampId: output.onRampId,
413 destroy: output.destroyOnDelete,
414 })
415 .pipe(Effect.catchTag("OnRampNotFound", () => Effect.void));
416 }),
417
418 list: Effect.fn(function* () {
419 const { accountId } = yield* yield* CloudflareEnvironment;
420 // Account-scoped collection: exhaustively paginate the on-ramp list,
421 // then hydrate each id into the exact `read` Attributes shape via
422 // `getOnRamp`. The list item omits some fields (`vpc`, `region`), so
423 // a per-item get is required for a fully-faithful Attributes object.
424 // Magic Cloud Networking is an entitlement-gated add-on; on accounts
425 // without it every call fails with `FeatureNotEnabled` — treat that
426 // as a non-listable account and return `[]`.
427 const ids = yield* mcn.listOnRamps.items({ accountId }).pipe(
428 Stream.map((onramp) => onramp.id),
429 Stream.runCollect,
430 Effect.map((chunk) => Array.from(chunk)),
431 Effect.catchTag("FeatureNotEnabled", () => Effect.succeed([] as string[])),
432 );
433 const rows = yield* Effect.forEach(
434 ids,
435 (onRampId) =>
436 getOnRamp(accountId, onRampId).pipe(
437 Effect.map((observed) =>
438 observed ? toAttributes(observed, accountId, false) : undefined,
439 ),
440 ),
441 { concurrency: 10 },
442 );
443 return rows.filter((row): row is OnRampAttributes => row !== undefined);
444 }),
445 });
446
447 type ObservedOnRamp = Pick<
448 mcn.GetOnRampResponse,
449 | "id"
450 | "name"
451 | "cloudType"
452 | "type"
453 | "dynamicRouting"
454 | "installRoutesInCloud"
455 | "installRoutesInMagicWan"
456 | "vpc"
457 | "cloudAsn"
458 | "description"
459 | "attachedHubs"
460 | "attachedVpcs"
461 | "manageHubToHubAttachments"
462 | "manageVpcToHubAttachments"
463 | "updatedAt"
464 | "region"
465 >;
466
467 /**
468 * Read an on-ramp by id, mapping "gone" (`OnRampNotFound`) to `undefined`.
469 */
470 const getOnRamp = (accountId: string, onrampId: string) =>
471 mcn.getOnRamp({ accountId, onrampId }).pipe(
472 Effect.map((onramp): ObservedOnRamp | undefined => onramp),
473 Effect.catchTag("OnRampNotFound", () => Effect.undefined),
474 );
475
476 /**
477 * Find an on-ramp by exact name. Names are not unique on Cloudflare's side;
478 * if several on-ramps carry the same name, pick the lexicographically-first
479 * id for determinism.
480 */
481 const findByName = (accountId: string, name: string) =>
482 mcn.listOnRamps.items({ accountId }).pipe(
483 Stream.runCollect,
484 Effect.map((chunk) =>
485 Array.from(chunk)
486 .filter((onramp) => onramp.name === name)
487 .sort((a, b) => a.id.localeCompare(b.id))
488 .at(0),
489 ),
490 );
491
492 const onRampName = (id: string, name: string | undefined) =>
493 Effect.gen(function* () {
494 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
495 });
496
497 const sameIds = (observed: readonly string[], desired: readonly string[]) =>
498 observed.length === desired.length &&
499 [...observed].sort().join(",") === [...desired].sort().join(",");
500
501 const toAttributes = (
502 onramp: ObservedOnRamp,
503 accountId: string,
504 destroyOnDelete: boolean,
505 ): OnRampAttributes => ({
506 onRampId: onramp.id,
507 accountId,
508 name: onramp.name,
509 // Distilled widens generated string enums to open unions (`string & {}`).
510 cloudType: onramp.cloudType as OnRampCloudType,
511 type: onramp.type as OnRampType,
512 dynamicRouting: onramp.dynamicRouting,
513 installRoutesInCloud: onramp.installRoutesInCloud,
514 installRoutesInMagicWan: onramp.installRoutesInMagicWan,
515 vpc: onramp.vpc ?? undefined,
516 cloudAsn: onramp.cloudAsn ?? undefined,
517 description: onramp.description ?? undefined,
518 attachedHubs: [...(onramp.attachedHubs ?? [])],
519 attachedVpcs: [...(onramp.attachedVpcs ?? [])],
520 manageHubToHubAttachments: onramp.manageHubToHubAttachments ?? undefined,
521 manageVpcToHubAttachments: onramp.manageVpcToHubAttachments ?? undefined,
522 updatedAt: onramp.updatedAt,
523 destroyOnDelete,
524 });