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

main
ts 363 lines 12.5 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.CloudIntegration" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * The cloud provider an integration discovers resources from.
18 */
19 export type CloudIntegrationCloudType = "AWS" | "AZURE" | "GOOGLE" | "CLOUDFLARE";
20
21 /**
22 * Lifecycle state of a cloud integration.
23 */
24 export type CloudIntegrationLifecycleState = "ACTIVE" | "PENDING_SETUP" | "RETIRED";
25
26 /**
27 * Discovery state of a cloud integration.
28 */
29 export type CloudIntegrationState =
30 | "UNSPECIFIED"
31 | "PENDING"
32 | "DISCOVERING"
33 | "FAILED"
34 | "SUCCEEDED";
35
36 export interface CloudIntegrationProps {
37 /**
38 * The cloud provider this integration connects to.
39 *
40 * Immutable — changing the cloud type triggers a replacement.
41 */
42 cloudType: CloudIntegrationCloudType;
43 /**
44 * Human readable name for the integration. Used as the integration's
45 * identity for cold-state recovery, so it should be unique within the
46 * account. If omitted, a unique name is generated from the app, stage,
47 * and logical ID.
48 * @default ${app}-${stage}-${id}
49 */
50 friendlyName?: string;
51 /**
52 * Free-form description of the integration. Mutable.
53 */
54 description?: string;
55 /**
56 * AWS IAM role ARN Cloudflare assumes to discover resources
57 * (`cloudType: "AWS"` only). Mutable — wired after creating the role
58 * from the integration's setup data.
59 */
60 awsArn?: string;
61 /**
62 * Azure subscription to discover (`cloudType: "AZURE"` only). Mutable.
63 */
64 azureSubscriptionId?: string;
65 /**
66 * Azure tenant the subscription belongs to (`cloudType: "AZURE"` only).
67 * Mutable.
68 */
69 azureTenantId?: string;
70 /**
71 * GCP project to discover (`cloudType: "GOOGLE"` only). Mutable.
72 */
73 gcpProjectId?: string;
74 /**
75 * GCP service account email Cloudflare impersonates
76 * (`cloudType: "GOOGLE"` only). Mutable.
77 */
78 gcpServiceAccountEmail?: string;
79 }
80
81 export interface CloudIntegrationAttributes {
82 /** Cloudflare-assigned identifier of the integration. */
83 integrationId: string;
84 /** The Cloudflare account the integration belongs to. */
85 accountId: string;
86 /** The cloud provider this integration connects to. */
87 cloudType: CloudIntegrationCloudType;
88 /** Human readable name of the integration. */
89 friendlyName: string;
90 /** Free-form description, if set. */
91 description: string | undefined;
92 /** Lifecycle state (`PENDING_SETUP` until credentials are wired). */
93 lifecycleState: CloudIntegrationLifecycleState;
94 /** State of the most recent discovery run. */
95 state: CloudIntegrationState;
96 /** AWS IAM role ARN used for discovery, if wired. */
97 awsArn: string | undefined;
98 /** Azure subscription being discovered, if wired. */
99 azureSubscriptionId: string | undefined;
100 /** Azure tenant of the subscription, if wired. */
101 azureTenantId: string | undefined;
102 /** GCP project being discovered, if wired. */
103 gcpProjectId: string | undefined;
104 /** GCP service account email used for discovery, if wired. */
105 gcpServiceAccountEmail: string | undefined;
106 /** ISO8601 timestamp of the last change to the integration. */
107 lastUpdated: string;
108 }
109
110 export type CloudIntegration = Resource<
111 TypeId,
112 CloudIntegrationProps,
113 CloudIntegrationAttributes,
114 never,
115 Providers
116 >;
117
118 /**
119 * A Magic Cloud Networking cloud integration — registers an AWS, Azure, or
120 * GCP account with Cloudflare so Magic Cloud Networking can discover its
121 * networking resources (VPCs, subnets, gateways, …).
122 *
123 * Creating an integration returns provider-side setup data; credential
124 * wiring (`awsArn`, `azureSubscriptionId`/`azureTenantId`,
125 * `gcpProjectId`/`gcpServiceAccountEmail`) is applied in place. Only
126 * `cloudType` forces a replacement.
127 *
128 * Magic Cloud Networking is an entitlement-gated add-on (Magic WAN family).
129 * On accounts without the entitlement every API call fails with the typed
130 * `FeatureNotEnabled` error (Cloudflare code 1012, "feature not enabled").
131 * ### Creating an integration
132 * **Example:** Register an AWS account
133 * ```typescript
134 * const aws = yield* Cloudflare.MagicCloudNetworking.CloudIntegration("Discovery", {
135 * cloudType: "AWS",
136 * description: "production AWS account",
137 * });
138 * // aws.lifecycleState === "PENDING_SETUP" until credentials are wired
139 * ```
140 *
141 * **Example:** Wire credentials after creating the IAM role
142 * ```typescript
143 * yield* Cloudflare.MagicCloudNetworking.CloudIntegration("Discovery", {
144 * cloudType: "AWS",
145 * awsArn: "arn:aws:iam::123456789012:role/cloudflare-mcn-discovery",
146 * });
147 * ```
148 *
149 * ### GCP
150 * **Example:** Register a GCP project
151 * ```typescript
152 * yield* Cloudflare.MagicCloudNetworking.CloudIntegration("GcpDiscovery", {
153 * cloudType: "GOOGLE",
154 * gcpProjectId: "my-project",
155 * gcpServiceAccountEmail: "mcn@my-project.iam.gserviceaccount.com",
156 * });
157 * ```
158 *
159 * @see https://developers.cloudflare.com/magic-cloud-networking/
160 *
161 * @resource
162 * @product Magic Cloud Networking
163 * @category Network
164 */
165 export const CloudIntegration = Resource<CloudIntegration>(TypeId);
166
167 /**
168 * Returns true if the given value is a CloudIntegration resource.
169 */
170 export const isCloudIntegration = (value: unknown): value is CloudIntegration =>
171 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
172
173 export const CloudIntegrationProvider = () =>
174 Provider.succeed(CloudIntegration, {
175 stables: ["integrationId", "accountId", "cloudType"],
176
177 diff: Effect.fn(function* ({ olds, news, output }) {
178 if (!isResolved(news)) return undefined;
179 const oldCloudType =
180 output?.cloudType ?? (olds !== undefined && isResolved(olds) ? olds.cloudType : undefined);
181 if (oldCloudType !== undefined && oldCloudType !== news.cloudType) {
182 return { action: "replace" } as const;
183 }
184 return undefined;
185 }),
186
187 read: Effect.fn(function* ({ id, output, olds }) {
188 const { accountId } = yield* yield* CloudflareEnvironment;
189 const acct = output?.accountId ?? accountId;
190
191 // Owned path: refresh by our persisted integration id.
192 if (output?.integrationId) {
193 const observed = yield* getIntegration(acct, output.integrationId);
194 if (observed) return toAttributes(observed, acct);
195 return undefined;
196 }
197
198 // Cold read — recover from lost state by matching the deterministic
199 // physical name. Integrations carry no ownership markers, so report
200 // a match as Unowned and let the engine gate adoption.
201 const name = yield* integrationName(id, olds?.friendlyName);
202 const match = yield* findByName(acct, name);
203 return match ? Unowned(toAttributes(match, acct)) : undefined;
204 }),
205
206 reconcile: Effect.fn(function* ({ id, news, output }) {
207 const { accountId } = yield* yield* CloudflareEnvironment;
208 const name = yield* integrationName(id, news.friendlyName);
209
210 // 1. Observe — the id cached on `output` is a hint, not a guarantee:
211 // a missing integration falls through to the name scan and create.
212 let observed = output?.integrationId
213 ? yield* getIntegration(output.accountId ?? accountId, output.integrationId)
214 : undefined;
215 if (!observed) {
216 observed = yield* findByName(accountId, name);
217 }
218
219 // 2. Ensure — create when missing. Names are not unique on
220 // Cloudflare's side so there is no AlreadyExists race to tolerate.
221 if (!observed) {
222 const created = yield* mcn.createCloudIntegration({
223 accountId,
224 cloudType: news.cloudType,
225 friendlyName: name,
226 description: news.description,
227 });
228 observed = yield* getIntegration(accountId, created.id).pipe(
229 Effect.map((latest) => latest ?? created),
230 );
231 }
232
233 // 3. Sync — diff observed cloud state against desired; PATCH only the
234 // delta and skip the call entirely on a no-op.
235 const patch: mcn.PatchCloudIntegrationRequest = {
236 accountId,
237 providerId: observed.id,
238 };
239 let dirty = false;
240 if (observed.friendlyName !== name) {
241 patch.friendlyName = name;
242 dirty = true;
243 }
244 if (news.description !== undefined && (observed.description ?? "") !== news.description) {
245 patch.description = news.description;
246 dirty = true;
247 }
248 for (const key of credentialKeys) {
249 const desired = news[key];
250 if (desired !== undefined && (observed[key] ?? "") !== desired) {
251 patch[key] = desired;
252 dirty = true;
253 }
254 }
255 if (dirty) {
256 observed = yield* mcn.patchCloudIntegration(patch);
257 }
258
259 return toAttributes(observed, accountId);
260 }),
261
262 delete: Effect.fn(function* ({ output }) {
263 yield* mcn
264 .deleteCloudIntegration({
265 accountId: output.accountId,
266 providerId: output.integrationId,
267 })
268 .pipe(Effect.catchTag("CloudIntegrationNotFound", () => Effect.void));
269 }),
270
271 list: Effect.fn(function* () {
272 const { accountId } = yield* yield* CloudflareEnvironment;
273 // Account-scoped collection: the list response already carries the
274 // full per-integration shape `read` returns, so no per-item hydrate
275 // is needed. Paginate exhaustively and map each row to Attributes.
276 return yield* mcn.listCloudIntegrations.pages({ accountId }).pipe(
277 Stream.runCollect,
278 Effect.map((chunk) =>
279 Array.from(chunk).flatMap((page) =>
280 (page.result ?? []).map((integration) => toAttributes(integration, accountId)),
281 ),
282 ),
283 // Magic Cloud Networking is an entitlement-gated add-on; accounts
284 // without it can't enumerate integrations — treat as empty.
285 Effect.catchTag("FeatureNotEnabled", () => Effect.succeed([])),
286 );
287 }),
288 });
289
290 const credentialKeys = [
291 "awsArn",
292 "azureSubscriptionId",
293 "azureTenantId",
294 "gcpProjectId",
295 "gcpServiceAccountEmail",
296 ] as const;
297
298 type ObservedIntegration = Pick<
299 mcn.GetCloudIntegrationResponse,
300 | "id"
301 | "cloudType"
302 | "friendlyName"
303 | "description"
304 | "lifecycleState"
305 | "state"
306 | "lastUpdated"
307 | "awsArn"
308 | "azureSubscriptionId"
309 | "azureTenantId"
310 | "gcpProjectId"
311 | "gcpServiceAccountEmail"
312 >;
313
314 /**
315 * Read an integration by id, mapping "gone" (`CloudIntegrationNotFound`)
316 * to `undefined`.
317 */
318 const getIntegration = (accountId: string, providerId: string) =>
319 mcn.getCloudIntegration({ accountId, providerId }).pipe(
320 Effect.map((integration): ObservedIntegration | undefined => integration),
321 Effect.catchTag("CloudIntegrationNotFound", () => Effect.undefined),
322 );
323
324 /**
325 * Find an integration by exact friendly name. Names are not unique on
326 * Cloudflare's side; if several integrations carry the same name, pick the
327 * lexicographically-first id for determinism.
328 */
329 const findByName = (accountId: string, friendlyName: string) =>
330 mcn.listCloudIntegrations.items({ accountId }).pipe(
331 Stream.runCollect,
332 Effect.map((chunk) =>
333 Array.from(chunk)
334 .filter((integration) => integration.friendlyName === friendlyName)
335 .sort((a, b) => a.id.localeCompare(b.id))
336 .at(0),
337 ),
338 );
339
340 const integrationName = (id: string, name: string | undefined) =>
341 Effect.gen(function* () {
342 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
343 });
344
345 const toAttributes = (
346 integration: ObservedIntegration,
347 accountId: string,
348 ): CloudIntegrationAttributes => ({
349 integrationId: integration.id,
350 accountId,
351 // Distilled widens generated string enums to open unions (`string & {}`).
352 cloudType: integration.cloudType as CloudIntegrationCloudType,
353 friendlyName: integration.friendlyName,
354 description: integration.description ?? undefined,
355 lifecycleState: integration.lifecycleState as CloudIntegrationLifecycleState,
356 state: integration.state as CloudIntegrationState,
357 awsArn: integration.awsArn ?? undefined,
358 azureSubscriptionId: integration.azureSubscriptionId ?? undefined,
359 azureTenantId: integration.azureTenantId ?? undefined,
360 gcpProjectId: integration.gcpProjectId ?? undefined,
361 gcpServiceAccountEmail: integration.gcpServiceAccountEmail ?? undefined,
362 lastUpdated: integration.lastUpdated,
363 });