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

main
ts 280 lines 10 KB
Raw
1 import * as mnm from "@distilled.cloud/cloudflare/magic-network-monitoring";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Effect from "effect/Effect";
6 import * as Predicate from "effect/Predicate";
7 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
8 import type { Providers } from "../Providers.ts";
9
10 const TypeId = "Cloudflare.MagicNetworkMonitoring.Config" as const;
11 type TypeId = typeof TypeId;
12
13 /**
14 * A WARP device registered as a flow-data source on the MNM config.
15 */
16 export interface WarpDevice {
17 /**
18 * Unique identifier of the WARP device.
19 */
20 id: string;
21 /**
22 * Display name of the WARP device.
23 */
24 name: string;
25 /**
26 * IPv4 address the WARP device sends flow data from.
27 */
28 routerIp: string;
29 }
30
31 export interface ConfigProps {
32 /**
33 * The account name label stored on the MNM configuration. Freeform —
34 * mutable in place.
35 */
36 name: string;
37 /**
38 * Fallback sampling rate of flow messages being sent in packets per
39 * second. This should match the packet sampling rate configured on the
40 * router. Minimum of 1. Mutable in place.
41 */
42 defaultSampling: number;
43 /**
44 * IPv4 CIDR addresses (`/32`) of the routers that send flow data to
45 * Cloudflare. Registering router flow sources requires the Magic Network
46 * Monitoring router-flow entitlement — accounts without it reject any
47 * non-empty value with the typed `InvalidMnmConfig` error (Cloudflare
48 * code 1003).
49 * @default []
50 */
51 routerIps?: string[];
52 /**
53 * WARP devices registered as flow-data sources.
54 * @default []
55 */
56 warpDevices?: WarpDevice[];
57 }
58
59 export interface ConfigAttributes {
60 /** The Cloudflare account the configuration belongs to. */
61 accountId: string;
62 /** The account name label stored on the configuration. */
63 name: string;
64 /** Sampling rate of flow messages in packets per second. */
65 defaultSampling: number;
66 /** Router IPs registered as flow-data sources. */
67 routerIps: string[];
68 /** WARP devices registered as flow-data sources. */
69 warpDevices: WarpDevice[];
70 }
71
72 export type Config = Resource<TypeId, ConfigProps, ConfigAttributes, never, Providers>;
73
74 /**
75 * The Magic Network Monitoring (MNM) account configuration — the singleton
76 * that registers your network's routers (and optionally WARP devices) as
77 * flow-data sources and sets the fallback packet sampling rate.
78 *
79 * There is exactly one MNM configuration per Cloudflare account, and MNM
80 * rules cannot be created until it exists. Creating a second configuration
81 * fails (`MnmConfigAlreadyExists`), so reconcile tolerates the race by
82 * falling through to an update. When the engine has no prior state but a
83 * configuration already exists on the account, `read` reports it as
84 * `Unowned` and takeover is gated behind `--adopt`.
85 * ### Creating the configuration
86 * **Example:** Minimal configuration
87 * ```typescript
88 * const config = yield* Cloudflare.MagicNetworkMonitoring.Config("Mnm", {
89 * name: "my-network",
90 * defaultSampling: 1,
91 * });
92 * ```
93 *
94 * **Example:** Configuration with router IPs
95 * ```typescript
96 * const config = yield* Cloudflare.MagicNetworkMonitoring.Config("Mnm", {
97 * name: "my-network",
98 * defaultSampling: 100,
99 * routerIps: ["203.0.113.1/32"],
100 * });
101 * ```
102 *
103 * ### Rules depend on the configuration
104 * **Example:** Create the config before any rules
105 * ```typescript
106 * const config = yield* Cloudflare.MagicNetworkMonitoring.Config("Mnm", {
107 * name: "my-network",
108 * defaultSampling: 1,
109 * });
110 * // Reference an output attribute so the rule deploys after the config.
111 * yield* Cloudflare.MagicNetworkMonitoring.Rule("VolumetricAlert", {
112 * accountId: config.accountId,
113 * type: "threshold",
114 * prefixes: ["10.0.0.0/24"],
115 * bandwidthThreshold: 1_000_000,
116 * });
117 * ```
118 *
119 * @see https://developers.cloudflare.com/magic-network-monitoring/
120 *
121 * @resource
122 * @product Magic Network Monitoring
123 * @category Network
124 */
125 export const Config = Resource<Config>(TypeId);
126
127 /**
128 * Returns true if the given value is a Config resource.
129 */
130 export const isConfig = (value: unknown): value is Config =>
131 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
132
133 export const ConfigProvider = () =>
134 Provider.succeed(Config, {
135 stables: ["accountId"],
136
137 diff: Effect.fn(function* ({ output }) {
138 const { accountId } = yield* yield* CloudflareEnvironment;
139 // The config is an account singleton — moving accounts replaces it.
140 if (output !== undefined && output.accountId !== accountId) {
141 return { action: "replace" } as const;
142 }
143 return undefined;
144 }),
145
146 read: Effect.fn(function* ({ output }) {
147 const { accountId } = yield* yield* CloudflareEnvironment;
148 const acct = output?.accountId ?? accountId;
149 // A missing config answers HTTP 200 with `result: null` rather than
150 // a 404 — `observe` maps that to `undefined`.
151 const observed = observe(yield* mnm.getConfig({ accountId: acct }));
152 if (observed === undefined) return undefined;
153 // The config carries no ownership markers. With no prior state we
154 // cannot prove we created it — report `Unowned` so the engine gates
155 // takeover behind the adopt policy.
156 const attributes = toAttributes(observed, acct);
157 return output === undefined ? Unowned(attributes) : attributes;
158 }),
159
160 reconcile: Effect.fn(function* ({ news }) {
161 const { accountId } = yield* yield* CloudflareEnvironment;
162 const desired = {
163 accountId,
164 name: news.name,
165 defaultSampling: news.defaultSampling,
166 // Inputs have been resolved to concrete strings by Plan.
167 routerIps: (news.routerIps ?? []) as string[],
168 warpDevices: news.warpDevices ?? [],
169 };
170
171 // 1. Observe — a missing singleton answers `result: null` and maps
172 // to `undefined`.
173 const observed = observe(yield* mnm.getConfig({ accountId }));
174
175 // 2. Ensure — create when missing, converging a concurrent create
176 // (`MnmConfigAlreadyExists`, Cloudflare code 1005) into the
177 // update below.
178 if (observed === undefined) {
179 const created = observe(
180 yield* mnm
181 .createConfig(desired)
182 .pipe(Effect.catchTag("MnmConfigAlreadyExists", () => mnm.updateConfig(desired))),
183 );
184 // `updateConfig` answers `result: null` if the config vanished
185 // again mid-flight — fall back to one fresh create.
186 if (created !== undefined) return toAttributes(created, accountId);
187 const recreated = yield* mnm.createConfig(desired);
188 return toAttributes(observe(recreated) ?? desired, accountId);
189 }
190
191 // 3. Sync — diff observed cloud state against desired; the update
192 // is a full-body PUT, so skip the call entirely on a no-op.
193 const dirty =
194 observed.name !== desired.name ||
195 observed.defaultSampling !== desired.defaultSampling ||
196 !sameStrings(observed.routerIps, desired.routerIps) ||
197 !sameWarpDevices(observed.warpDevices, desired.warpDevices);
198 if (!dirty) return toAttributes(observed, accountId);
199
200 const updated = observe(yield* mnm.updateConfig(desired));
201 if (updated !== undefined) return toAttributes(updated, accountId);
202 // Deleted out-of-band between observe and update — recreate.
203 const recreated = yield* mnm.createConfig(desired);
204 return toAttributes(observe(recreated) ?? desired, accountId);
205 }),
206
207 delete: Effect.fn(function* ({ output }) {
208 yield* mnm.deleteConfig({ accountId: output.accountId }).pipe(
209 // Already gone (`MnmConfigNotFound`, Cloudflare code 1004).
210 Effect.catchTag("MnmConfigNotFound", () => Effect.void),
211 );
212 }),
213
214 // Account singleton — there is exactly one MNM config per account and
215 // only a per-account `getConfig`. Mirror `read`: return the one-element
216 // array when the config exists, `[]` when it is unset (HTTP 200 with
217 // `result: null`, which `observe` maps to `undefined`).
218 list: Effect.fn(function* () {
219 const { accountId } = yield* yield* CloudflareEnvironment;
220 const observed = observe(yield* mnm.getConfig({ accountId }));
221 return observed === undefined ? [] : [toAttributes(observed, accountId)];
222 }),
223 });
224
225 /**
226 * A normalized, definitely-present MNM configuration.
227 */
228 interface ObservedConfig {
229 name: string;
230 defaultSampling: number;
231 routerIps: readonly string[];
232 warpDevices: readonly WarpDevice[];
233 }
234
235 /**
236 * Normalize a config response to a definitely-present shape, mapping
237 * "missing" to `undefined`. Cloudflare answers HTTP 200 with
238 * `result: null` when no config exists; the distilled core client decodes
239 * that as an empty object, so a config without a `name` (a required field
240 * on every real config) means there is no config.
241 */
242 const observe = (
243 config: mnm.GetConfigResponse | mnm.UpdateConfigResponse,
244 ): ObservedConfig | undefined => {
245 if (config === null) return undefined;
246 const { name, defaultSampling } = config;
247 if (name == null || defaultSampling == null) return undefined;
248 return {
249 name,
250 defaultSampling,
251 routerIps: config.routerIps ?? [],
252 warpDevices: config.warpDevices ?? [],
253 };
254 };
255
256 const sameStrings = (observed: readonly string[], desired: readonly string[]) =>
257 observed.length === desired.length &&
258 [...observed].sort().join(",") === [...desired].sort().join(",");
259
260 const sameWarpDevices = (observed: readonly WarpDevice[], desired: readonly WarpDevice[]) =>
261 observed.length === desired.length &&
262 serializeWarpDevices(observed) === serializeWarpDevices(desired);
263
264 const serializeWarpDevices = (devices: readonly WarpDevice[]) =>
265 devices
266 .map((d) => `${d.id}|${d.name}|${d.routerIp}`)
267 .sort()
268 .join(",");
269
270 const toAttributes = (config: ObservedConfig, accountId: string): ConfigAttributes => ({
271 accountId,
272 name: config.name,
273 defaultSampling: config.defaultSampling,
274 routerIps: [...config.routerIps],
275 warpDevices: config.warpDevices.map((d) => ({
276 id: d.id,
277 name: d.name,
278 routerIp: d.routerIp,
279 })),
280 });