@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, 06:00 UTC

main
ts 324 lines 11.4 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.CatalogSync" as const;
14 type TypeId = typeof TypeId;
15
16 /**
17 * Where a catalog sync writes the discovered resources.
18 */
19 export type CatalogSyncDestinationType = "NONE" | "ZERO_TRUST_LIST";
20
21 /**
22 * Whether the destination updates automatically as discoveries change, or
23 * only when explicitly refreshed.
24 */
25 export type CatalogSyncUpdateMode = "AUTO" | "MANUAL";
26
27 export interface CatalogSyncProps {
28 /**
29 * Type of destination the sync materializes into. `ZERO_TRUST_LIST`
30 * provisions a Zero Trust list owned by the sync.
31 *
32 * Immutable — the destination is provisioned at create time, so changing
33 * it triggers a replacement.
34 */
35 destinationType: CatalogSyncDestinationType;
36 /**
37 * Whether the destination updates automatically (`AUTO`) or only on an
38 * explicit refresh (`MANUAL`). Mutable.
39 */
40 updateMode: CatalogSyncUpdateMode;
41 /**
42 * Human readable name. Used as the sync's identity for cold-state
43 * recovery, so it should be unique within the account. If omitted, a
44 * unique name is generated from the app, stage, and logical ID.
45 * @default ${app}-${stage}-${id}
46 */
47 name?: string;
48 /**
49 * Free-form description of the sync. Mutable.
50 */
51 description?: string;
52 /**
53 * Filter expression selecting which discovered resources are included.
54 * See the prebuilt policies API for ready-made expressions. Mutable.
55 */
56 policy?: string;
57 /**
58 * Whether destroying the sync also deletes the destination it provisioned
59 * (e.g. the Zero Trust list). Consumed only at delete time.
60 * @default true
61 */
62 deleteDestination?: boolean;
63 }
64
65 export interface CatalogSyncAttributes {
66 /** Cloudflare-assigned identifier of the catalog sync. */
67 syncId: string;
68 /** The Cloudflare account the sync belongs to. */
69 accountId: string;
70 /** Human readable name of the sync. */
71 name: string;
72 /** Type of destination the sync materializes into. */
73 destinationType: CatalogSyncDestinationType;
74 /** Identifier of the provisioned destination (e.g. Zero Trust list id). */
75 destinationId: string;
76 /** Whether the destination updates automatically or manually. */
77 updateMode: CatalogSyncUpdateMode;
78 /** Free-form description. */
79 description: string;
80 /** Filter expression selecting included resources. */
81 policy: string;
82 /** ISO8601 timestamp of the last user-initiated update. */
83 lastUserUpdateAt: string;
84 /** Discoveries up to this ISO8601 timestamp are included, if any. */
85 includesDiscoveriesUntil: string | undefined;
86 /** Whether delete also removes the provisioned destination. */
87 deleteDestination: boolean;
88 }
89
90 export type CatalogSync = Resource<
91 TypeId,
92 CatalogSyncProps,
93 CatalogSyncAttributes,
94 never,
95 Providers
96 >;
97
98 /**
99 * A Magic Cloud Networking catalog sync — continuously materializes the
100 * catalog of discovered cloud resources (filtered by a policy expression)
101 * into a destination such as a Zero Trust list.
102 *
103 * The destination is provisioned when the sync is created, so
104 * `destinationType` is immutable and forces a replacement; `name`,
105 * `description`, `policy`, and `updateMode` are all patched in place.
106 *
107 * Magic Cloud Networking is an entitlement-gated add-on (Magic WAN family).
108 * On accounts without the entitlement every API call fails with the typed
109 * `FeatureNotEnabled` error (Cloudflare code 1012, "feature not enabled").
110 * ### Creating a sync
111 * **Example:** Sync discovered VPC CIDRs into a Zero Trust list
112 * ```typescript
113 * const sync = yield* Cloudflare.MagicCloudNetworking.CatalogSync("VpcCidrs", {
114 * destinationType: "ZERO_TRUST_LIST",
115 * updateMode: "AUTO",
116 * policy: "kind in ('aws_vpc','azurerm_virtual_network','google_compute_network')",
117 * });
118 * // sync.destinationId is the provisioned Zero Trust list
119 * ```
120 *
121 * **Example:** Manual sync without a destination
122 * ```typescript
123 * yield* Cloudflare.MagicCloudNetworking.CatalogSync("DryRun", {
124 * destinationType: "NONE",
125 * updateMode: "MANUAL",
126 * });
127 * ```
128 *
129 * ### Destroy behavior
130 * **Example:** Keep the destination list on destroy
131 * ```typescript
132 * yield* Cloudflare.MagicCloudNetworking.CatalogSync("VpcCidrs", {
133 * destinationType: "ZERO_TRUST_LIST",
134 * updateMode: "AUTO",
135 * deleteDestination: false,
136 * });
137 * ```
138 *
139 * @see https://developers.cloudflare.com/magic-cloud-networking/
140 *
141 * @resource
142 * @product Magic Cloud Networking
143 * @category Network
144 */
145 export const CatalogSync = Resource<CatalogSync>(TypeId);
146
147 /**
148 * Returns true if the given value is a CatalogSync resource.
149 */
150 export const isCatalogSync = (value: unknown): value is CatalogSync =>
151 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
152
153 export const CatalogSyncProvider = () =>
154 Provider.succeed(CatalogSync, {
155 stables: ["syncId", "accountId", "destinationType", "destinationId"],
156
157 diff: Effect.fn(function* ({ olds, news, output }) {
158 if (!isResolved(news)) return undefined;
159 const oldDestination =
160 output?.destinationType ??
161 (olds !== undefined && isResolved(olds) ? olds.destinationType : undefined);
162 if (oldDestination !== undefined && oldDestination !== news.destinationType) {
163 return { action: "replace" } as const;
164 }
165 return undefined;
166 }),
167
168 read: Effect.fn(function* ({ id, output, olds }) {
169 const { accountId } = yield* yield* CloudflareEnvironment;
170 const acct = output?.accountId ?? accountId;
171 const deleteDestination = output?.deleteDestination ?? olds?.deleteDestination ?? true;
172
173 // Owned path: refresh by our persisted sync id.
174 if (output?.syncId) {
175 const observed = yield* getSync(acct, output.syncId);
176 if (observed) return toAttributes(observed, acct, deleteDestination);
177 return undefined;
178 }
179
180 // Cold read — recover from lost state by matching the deterministic
181 // physical name. Syncs carry no ownership markers, so report a match
182 // as Unowned and let the engine gate adoption.
183 const name = yield* syncName(id, olds?.name);
184 const match = yield* findByName(acct, name);
185 return match ? Unowned(toAttributes(match, acct, deleteDestination)) : undefined;
186 }),
187
188 reconcile: Effect.fn(function* ({ id, news, output }) {
189 const { accountId } = yield* yield* CloudflareEnvironment;
190 const name = yield* syncName(id, news.name);
191 const deleteDestination = news.deleteDestination ?? true;
192
193 // 1. Observe — the id cached on `output` is a hint, not a guarantee:
194 // a missing sync falls through to the name scan and create.
195 let observed = output?.syncId
196 ? yield* getSync(output.accountId ?? accountId, output.syncId)
197 : undefined;
198 if (!observed) {
199 observed = yield* findByName(accountId, name);
200 }
201
202 // 2. Ensure — create when missing. Names are not unique on
203 // Cloudflare's side so there is no AlreadyExists race to tolerate.
204 if (!observed) {
205 observed = yield* mcn.createCatalogSync({
206 accountId,
207 name,
208 destinationType: news.destinationType,
209 updateMode: news.updateMode,
210 description: news.description,
211 policy: news.policy,
212 });
213 return toAttributes(observed, accountId, deleteDestination);
214 }
215
216 // 3. Sync — diff observed cloud state against desired; PATCH only the
217 // delta and skip the call entirely on a no-op.
218 const patch: mcn.PatchCatalogSyncRequest = {
219 accountId,
220 syncId: observed.id,
221 };
222 let dirty = false;
223 if (observed.name !== name) {
224 patch.name = name;
225 dirty = true;
226 }
227 if (observed.updateMode !== news.updateMode) {
228 patch.updateMode = news.updateMode;
229 dirty = true;
230 }
231 if (news.description !== undefined && observed.description !== news.description) {
232 patch.description = news.description;
233 dirty = true;
234 }
235 if (news.policy !== undefined && observed.policy !== news.policy) {
236 patch.policy = news.policy;
237 dirty = true;
238 }
239 if (dirty) {
240 observed = yield* mcn.patchCatalogSync(patch);
241 }
242
243 return toAttributes(observed, accountId, deleteDestination);
244 }),
245
246 delete: Effect.fn(function* ({ output }) {
247 yield* mcn
248 .deleteCatalogSync({
249 accountId: output.accountId,
250 syncId: output.syncId,
251 deleteDestination: output.deleteDestination,
252 })
253 .pipe(Effect.catchTag("CatalogSyncNotFound", () => Effect.void));
254 }),
255
256 // Account-scoped collection: exhaustively paginate the catalog-sync list
257 // API. `deleteDestination` is an alchemy-only prop with no cloud
258 // representation, so it defaults to `true`. Magic Cloud Networking is an
259 // entitlement-gated add-on; an unentitled account rejects the list with
260 // the typed `FeatureNotEnabled` error — treat that as "nothing to list".
261 list: Effect.fn(function* () {
262 const { accountId } = yield* yield* CloudflareEnvironment;
263 return yield* mcn.listCatalogSyncs.pages({ accountId }).pipe(
264 Stream.runCollect,
265 Effect.map((chunk) =>
266 Array.from(chunk).flatMap((page) =>
267 (page.result ?? []).map((sync) => toAttributes(sync, accountId, true)),
268 ),
269 ),
270 Effect.catchTag("FeatureNotEnabled", () => Effect.succeed([])),
271 );
272 }),
273 });
274
275 type ObservedSync = mcn.GetCatalogSyncResponse | mcn.CreateCatalogSyncResponse;
276
277 /**
278 * Read a sync by id, mapping "gone" (`CatalogSyncNotFound`) to `undefined`.
279 */
280 const getSync = (accountId: string, syncId: string) =>
281 mcn.getCatalogSync({ accountId, syncId }).pipe(
282 Effect.map((sync): ObservedSync | undefined => sync),
283 Effect.catchTag("CatalogSyncNotFound", () => Effect.undefined),
284 );
285
286 /**
287 * Find a sync by exact name. Names are not unique on Cloudflare's side; if
288 * several syncs carry the same name, pick the lexicographically-first id
289 * for determinism.
290 */
291 const findByName = (accountId: string, name: string) =>
292 mcn.listCatalogSyncs.items({ accountId }).pipe(
293 Stream.runCollect,
294 Effect.map((chunk) =>
295 Array.from(chunk)
296 .filter((sync) => sync.name === name)
297 .sort((a, b) => a.id.localeCompare(b.id))
298 .at(0),
299 ),
300 );
301
302 const syncName = (id: string, name: string | undefined) =>
303 Effect.gen(function* () {
304 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
305 });
306
307 const toAttributes = (
308 sync: ObservedSync,
309 accountId: string,
310 deleteDestination: boolean,
311 ): CatalogSyncAttributes => ({
312 syncId: sync.id,
313 accountId,
314 name: sync.name,
315 // Distilled widens generated string enums to open unions (`string & {}`).
316 destinationType: sync.destinationType as CatalogSyncDestinationType,
317 destinationId: sync.destinationId,
318 updateMode: sync.updateMode as CatalogSyncUpdateMode,
319 description: sync.description,
320 policy: sync.policy,
321 lastUserUpdateAt: sync.lastUserUpdateAt,
322 includesDiscoveriesUntil: sync.includesDiscoveriesUntil ?? undefined,
323 deleteDestination,
324 });