@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 440 lines 15.8 KB
Raw
1 import * as mnm from "@distilled.cloud/cloudflare/magic-network-monitoring";
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 Schedule from "effect/Schedule";
10 import * as Stream from "effect/Stream";
11 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
12 import type { Providers } from "../Providers.ts";
13
14 const TypeId = "Cloudflare.MagicNetworkMonitoring.Rule" as const;
15 type TypeId = typeof TypeId;
16
17 /**
18 * MNM rule type: `threshold` (static bits/packets-per-second limits),
19 * `zscore` (anomaly detection), or `advanced_ddos` (requires Magic Transit).
20 */
21 export type RuleType = "threshold" | "zscore" | "advanced_ddos";
22
23 /**
24 * How long a threshold must be exceeded before an alert fires.
25 */
26 export type RuleDuration = "1m" | "5m" | "10m" | "15m" | "20m" | "30m" | "45m" | "60m";
27
28 export interface RuleProps {
29 /**
30 * The Cloudflare account the rule belongs to. Defaults to the profile's
31 * account. Pass the owning MNM Config's `accountId` output to sequence
32 * the rule after the configuration (rules cannot be created until the
33 * account's MNM configuration exists).
34 */
35 accountId?: string;
36 /**
37 * The name of the rule. Must be unique within the account. Supports
38 * `A-Z`, `a-z`, `0-9`, underscore, dash, period, and tilde — no spaces.
39 * Max 256 characters. If omitted, a unique name is generated from the
40 * app, stage, and logical ID. Mutable in place.
41 * @default ${app}-${stage}-${id}
42 */
43 name?: string;
44 /**
45 * MNM rule type. Immutable — the rule's alerting semantics differ
46 * entirely per type, so changing it triggers a replacement.
47 */
48 type: RuleType;
49 /**
50 * IPv4 CIDR prefixes the rule monitors. Mutable in place.
51 */
52 prefixes: string[];
53 /**
54 * Toggle on to have Cloudflare automatically advertise the rule's
55 * prefixes via Magic Transit when the rule triggers. Requires Magic
56 * Transit.
57 * @default false
58 */
59 automaticAdvertisement?: boolean;
60 /**
61 * Bits per second threshold (threshold rules). When exceeded for the
62 * set duration, an alert notification is sent. Minimum of 1.
63 */
64 bandwidthThreshold?: number;
65 /**
66 * Packets per second threshold (threshold rules). When exceeded for the
67 * set duration, an alert notification is sent. Minimum of 1.
68 */
69 packetThreshold?: number;
70 /**
71 * How long the threshold must be exceeded before an alert fires.
72 * @default "1m"
73 */
74 duration?: RuleDuration;
75 /**
76 * Sensitivity of the anomaly detection (zscore rules).
77 */
78 zscoreSensitivity?: "low" | "medium" | "high";
79 /**
80 * Target of the zscore rule analysis (zscore rules).
81 */
82 zscoreTarget?: "bits" | "packets";
83 /**
84 * Prefix match type applied for prefix auto-advertisement
85 * (advanced_ddos rules).
86 */
87 prefixMatch?: "exact" | "subnet" | "supernet";
88 }
89
90 export interface RuleAttributes {
91 /** Cloudflare-assigned identifier of the rule. */
92 ruleId: string;
93 /** The Cloudflare account the rule belongs to. */
94 accountId: string;
95 /** The rule's unique name. */
96 name: string;
97 /** MNM rule type. */
98 type: RuleType;
99 /** IPv4 CIDR prefixes the rule monitors. */
100 prefixes: string[];
101 /** Whether prefixes are auto-advertised via Magic Transit on trigger. */
102 automaticAdvertisement: boolean;
103 /** Bits per second threshold, if set. */
104 bandwidthThreshold: number | undefined;
105 /** Packets per second threshold, if set. */
106 packetThreshold: number | undefined;
107 /**
108 * Alert duration as reported by Cloudflare (normalized, e.g. `1m0s`).
109 */
110 duration: string | undefined;
111 /** Zscore sensitivity, if set. */
112 zscoreSensitivity: "low" | "medium" | "high" | (string & {}) | undefined;
113 /** Zscore target, if set. */
114 zscoreTarget: "bits" | "packets" | (string & {}) | undefined;
115 /** Prefix match type, if set. */
116 prefixMatch: "exact" | "subnet" | "supernet" | (string & {}) | undefined;
117 }
118
119 export type Rule = Resource<TypeId, RuleProps, RuleAttributes, never, Providers>;
120
121 /**
122 * A Magic Network Monitoring (MNM) rule — alerts when traffic to a set of
123 * IPv4 prefixes exceeds a static threshold (`threshold`), deviates from the
124 * learned baseline (`zscore`), or matches advanced DDoS criteria
125 * (`advanced_ddos`, Magic Transit only).
126 *
127 * Rules require the account's MNM configuration to exist first — pass the
128 * Config resource's `accountId` output as this rule's `accountId` to
129 * sequence the deployment. Rule names are unique per account; the rule
130 * `type` is immutable and changing it triggers a replacement.
131 * ### Threshold rules
132 * **Example:** Alert when bandwidth exceeds 1 Mbps for 5 minutes
133 * ```typescript
134 * const config = yield* Cloudflare.MagicNetworkMonitoring.Config("Mnm", {
135 * name: "my-network",
136 * defaultSampling: 1,
137 * });
138 * yield* Cloudflare.MagicNetworkMonitoring.Rule("BandwidthAlert", {
139 * accountId: config.accountId,
140 * type: "threshold",
141 * prefixes: ["10.0.0.0/24"],
142 * bandwidthThreshold: 1_000_000,
143 * duration: "5m",
144 * });
145 * ```
146 *
147 * **Example:** Packet-rate alert
148 * ```typescript
149 * yield* Cloudflare.MagicNetworkMonitoring.Rule("PacketAlert", {
150 * accountId: config.accountId,
151 * type: "threshold",
152 * prefixes: ["10.0.1.0/24"],
153 * packetThreshold: 10_000,
154 * });
155 * ```
156 *
157 * ### Anomaly detection
158 * **Example:** Zscore rule on bits
159 * ```typescript
160 * yield* Cloudflare.MagicNetworkMonitoring.Rule("AnomalyAlert", {
161 * accountId: config.accountId,
162 * type: "zscore",
163 * prefixes: ["10.0.2.0/24"],
164 * zscoreSensitivity: "medium",
165 * zscoreTarget: "bits",
166 * });
167 * ```
168 *
169 * @see https://developers.cloudflare.com/magic-network-monitoring/rules/
170 *
171 * @resource
172 * @product Magic Network Monitoring
173 * @category Network
174 */
175 export const Rule = Resource<Rule>(TypeId);
176
177 /**
178 * Returns true if the given value is a Rule resource.
179 */
180 export const isRule = (value: unknown): value is Rule =>
181 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
182
183 export const RuleProvider = () =>
184 Provider.succeed(Rule, {
185 stables: ["ruleId", "accountId"],
186
187 diff: Effect.fn(function* ({ olds, news, output }) {
188 if (!isResolved(news)) return undefined;
189 // The rule type is immutable — alerting semantics differ entirely.
190 const oldType =
191 output?.type ?? (olds !== undefined && isResolved(olds) ? olds.type : undefined);
192 if (oldType !== undefined && oldType !== news.type) {
193 return { action: "replace" } as const;
194 }
195 // accountId is Input<string>; compare only once both are concrete.
196 const oldAccount = output?.accountId;
197 if (
198 oldAccount !== undefined &&
199 typeof news.accountId === "string" &&
200 oldAccount !== news.accountId
201 ) {
202 return { action: "replace" } as const;
203 }
204 return undefined;
205 }),
206
207 read: Effect.fn(function* ({ id, output, olds }) {
208 const { accountId } = yield* yield* CloudflareEnvironment;
209 const acct =
210 output?.accountId ?? (typeof olds?.accountId === "string" ? olds.accountId : accountId);
211
212 // Owned path: refresh by our persisted rule id.
213 if (output?.ruleId) {
214 const observed = yield* getRule(acct, output.ruleId);
215 if (observed) return toAttributes(observed, acct);
216 }
217
218 // Cold read: rule names are unique per account, so an exact name
219 // match identifies the rule. We cannot prove we created it — brand
220 // it `Unowned` so takeover is gated behind the adopt policy.
221 const name = yield* createRuleName(id, olds?.name);
222 const match = yield* findByName(acct, name);
223 if (match) {
224 const attributes = toAttributes(match, acct);
225 return output === undefined ? Unowned(attributes) : attributes;
226 }
227 return undefined;
228 }),
229
230 reconcile: Effect.fn(function* ({ id, news, output }) {
231 const { accountId: defaultAccountId } = yield* yield* CloudflareEnvironment;
232 // Inputs have been resolved to concrete strings by Plan.
233 const accountId = (news.accountId as string | undefined) ?? defaultAccountId;
234 const name = yield* createRuleName(id, news.name);
235
236 // 1. Observe — the rule id cached on `output` is a hint, not a
237 // guarantee: a missing rule falls through to the name scan and
238 // then to create.
239 let observed = output?.ruleId ? yield* getRule(accountId, output.ruleId) : undefined;
240 if (!observed) {
241 observed = yield* findByName(accountId, name);
242 }
243
244 // 2. Ensure — create when missing. A concurrent create surfaces as
245 // `DuplicateMnmRuleName` (Cloudflare code 1008): converge by
246 // re-scanning for the rule that won the race.
247 if (!observed) {
248 observed = yield* mnm
249 .createRule({
250 accountId,
251 name,
252 type: news.type,
253 prefixes: news.prefixes,
254 automaticAdvertisement: news.automaticAdvertisement ?? false,
255 bandwidthThreshold: news.bandwidthThreshold,
256 packetThreshold: news.packetThreshold,
257 duration: news.duration,
258 zscoreSensitivity: news.zscoreSensitivity,
259 zscoreTarget: news.zscoreTarget,
260 prefixMatch: news.prefixMatch,
261 })
262 .pipe(
263 // The account MNM config is a freshly-created dependency (the test
264 // and real deployments create it immediately before the rule).
265 // Cloudflare returns `MnmConfigMissing` (code 1004) until the new
266 // config has propagated, so ride out that consistency window.
267 Effect.retry({
268 while: (e) => e._tag === "MnmConfigMissing",
269 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]),
270 }),
271 Effect.catchTag("DuplicateMnmRuleName", (error) =>
272 findByName(accountId, name).pipe(
273 Effect.flatMap((existing) =>
274 existing ? Effect.succeed(existing) : Effect.fail(error),
275 ),
276 ),
277 ),
278 );
279 return toAttributes(observed, accountId);
280 }
281
282 // 3. Sync — diff observed cloud state against desired; the PATCH
283 // takes a full body, so send everything but skip the call
284 // entirely on a no-op.
285 const dirty =
286 observed.name !== name ||
287 !samePrefixes(observed.prefixes, news.prefixes) ||
288 (observed.automaticAdvertisement ?? false) !== (news.automaticAdvertisement ?? false) ||
289 (news.bandwidthThreshold !== undefined &&
290 observed.bandwidthThreshold !== news.bandwidthThreshold) ||
291 (news.packetThreshold !== undefined && observed.packetThreshold !== news.packetThreshold) ||
292 (news.duration !== undefined && normalizeDuration(observed.duration) !== news.duration) ||
293 (news.zscoreSensitivity !== undefined &&
294 observed.zscoreSensitivity !== news.zscoreSensitivity) ||
295 (news.zscoreTarget !== undefined && observed.zscoreTarget !== news.zscoreTarget) ||
296 (news.prefixMatch !== undefined && observed.prefixMatch !== news.prefixMatch);
297
298 if (!dirty) return toAttributes(observed, accountId);
299
300 const ruleId = observed.id;
301 const patched = yield* mnm.patchRule({
302 accountId,
303 ruleId,
304 name,
305 type: news.type,
306 prefixes: news.prefixes,
307 automaticAdvertisement: news.automaticAdvertisement ?? false,
308 bandwidthThreshold: news.bandwidthThreshold,
309 packetThreshold: news.packetThreshold,
310 duration: news.duration,
311 zscoreSensitivity: news.zscoreSensitivity,
312 zscoreTarget: news.zscoreTarget,
313 prefixMatch: news.prefixMatch,
314 });
315 // Cloudflare omits `id` from the PATCH response body — carry the
316 // observed id through.
317 return toAttributes({ ...patched, id: patched.id ?? ruleId }, accountId);
318 }),
319
320 delete: Effect.fn(function* ({ output }) {
321 yield* mnm.deleteRule({ accountId: output.accountId, ruleId: output.ruleId }).pipe(
322 // Already gone (`MnmRuleNotFound`, Cloudflare code 1009) — also
323 // covers Cloudflare cascading rule deletion when the account's
324 // MNM config is deleted first.
325 Effect.catchTag("MnmRuleNotFound", () => Effect.void),
326 );
327 }),
328
329 // MNM rules are account-scoped: enumerate every rule in the ambient
330 // account. `listRules` paginates in "single" mode, so collect every
331 // page and flatten its `result` array, hydrating each item into the
332 // exact `read` Attributes shape. Accounts not onboarded to Magic
333 // Network Monitoring reject the route with `Forbidden` (HTTP 403) —
334 // treat that as "nothing to list" rather than an error.
335 list: Effect.fn(function* () {
336 const { accountId } = yield* yield* CloudflareEnvironment;
337 return yield* mnm.listRules.pages({ accountId }).pipe(
338 Stream.runCollect,
339 Effect.map((chunk) =>
340 Array.from(chunk).flatMap((page) =>
341 (page.result ?? [])
342 .filter((rule): rule is NonNullable<typeof rule> => rule != null)
343 .map((rule) => toAttributes(rule, accountId)),
344 ),
345 ),
346 Effect.catchTag("Forbidden", () => Effect.succeed([])),
347 );
348 }),
349 });
350
351 type ObservedRule = mnm.GetRuleResponse;
352
353 /**
354 * Read a rule by id, mapping "gone" (`MnmRuleNotFound`, Cloudflare error
355 * code 1009) to `undefined`.
356 */
357 const getRule = (accountId: string, ruleId: string) =>
358 mnm.getRule({ accountId, ruleId }).pipe(
359 Effect.map((rule): ObservedRule | undefined => rule),
360 Effect.catchTag("MnmRuleNotFound", () => Effect.undefined),
361 );
362
363 /**
364 * Find a rule by exact name. Names are unique per account, so at most one
365 * rule can match. An account with no rules answers `result: null`.
366 */
367 const findByName = (accountId: string, name: string) =>
368 mnm
369 .listRules({ accountId })
370 .pipe(
371 Effect.map((response) =>
372 (response.result ?? []).find(
373 (rule): rule is NonNullable<typeof rule> => rule?.name === name,
374 ),
375 ),
376 );
377
378 const createRuleName = (id: string, name: string | undefined) =>
379 Effect.gen(function* () {
380 return name ?? (yield* createPhysicalName({ id, lowercase: true }));
381 });
382
383 const samePrefixes = (observed: readonly string[], desired: readonly string[]) =>
384 observed.length === desired.length &&
385 [...observed].sort().join(",") === [...desired].sort().join(",");
386
387 /**
388 * Cloudflare normalizes durations to Go notation on read (`1m` → `1m0s`,
389 * `60m` → `1h0m0s`) — map the observed value back to the prop vocabulary
390 * for diffing.
391 */
392 const normalizeDuration = (duration: string | null | undefined): RuleDuration | undefined => {
393 switch (duration) {
394 case "1m0s":
395 case "1m":
396 return "1m";
397 case "5m0s":
398 case "5m":
399 return "5m";
400 case "10m0s":
401 case "10m":
402 return "10m";
403 case "15m0s":
404 case "15m":
405 return "15m";
406 case "20m0s":
407 case "20m":
408 return "20m";
409 case "30m0s":
410 case "30m":
411 return "30m";
412 case "45m0s":
413 case "45m":
414 return "45m";
415 case "1h0m0s":
416 case "60m":
417 return "60m";
418 default:
419 return undefined;
420 }
421 };
422
423 const toAttributes = (
424 rule: ObservedRule | (Omit<mnm.PatchRuleResponse, "id"> & { id: string }),
425 accountId: string,
426 ): RuleAttributes => ({
427 ruleId: rule.id,
428 accountId,
429 name: rule.name,
430 // Distilled widens generated string enums to open unions (`string & {}`).
431 type: rule.type as RuleType,
432 prefixes: [...rule.prefixes],
433 automaticAdvertisement: rule.automaticAdvertisement ?? false,
434 bandwidthThreshold: rule.bandwidthThreshold ?? undefined,
435 packetThreshold: rule.packetThreshold ?? undefined,
436 duration: rule.duration ?? undefined,
437 zscoreSensitivity: rule.zscoreSensitivity ?? undefined,
438 zscoreTarget: rule.zscoreTarget ?? undefined,
439 prefixMatch: rule.prefixMatch ?? undefined,
440 });