@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 357 lines 12.2 KB
Raw
1 import * as rum from "@distilled.cloud/cloudflare/rum";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Effect from "effect/Effect";
7 import * as Predicate from "effect/Predicate";
8 import * as Schedule from "effect/Schedule";
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.Rum.Rule" as const;
14 type TypeId = typeof TypeId;
15
16 export type RuleProps = {
17 /**
18 * The identifier of the Web Analytics ruleset the rule belongs to.
19 * Each zone-based (orange-clouded) `Site` owns one implicit ruleset —
20 * pass its `rulesetId` attribute. Changing this property triggers a
21 * replacement.
22 */
23 rulesetId: string;
24 /**
25 * The hostname the rule applies to (e.g. `example.com`).
26 */
27 host?: string;
28 /**
29 * The paths the rule applies to (e.g. `["/blog/*"]`).
30 */
31 paths?: string[];
32 /**
33 * Whether the rule includes (`true`) or excludes (`false`) matching
34 * traffic from being measured.
35 * @default true
36 */
37 inclusive?: boolean;
38 /**
39 * Whether the rule is paused.
40 * @default false
41 */
42 isPaused?: boolean;
43 };
44
45 export type RuleAttributes = {
46 /**
47 * The Web Analytics rule identifier. Stable for the lifetime of the rule.
48 */
49 id: string;
50 /**
51 * The identifier of the ruleset the rule belongs to.
52 */
53 rulesetId: string;
54 /**
55 * The Cloudflare account the rule belongs to.
56 */
57 accountId: string;
58 /**
59 * The hostname the rule applies to.
60 */
61 host: string | undefined;
62 /**
63 * The paths the rule applies to.
64 */
65 paths: string[] | undefined;
66 /**
67 * Whether the rule includes or excludes matching traffic from being
68 * measured.
69 */
70 inclusive: boolean;
71 /**
72 * Whether the rule is paused.
73 */
74 isPaused: boolean;
75 /**
76 * The rule's evaluation priority within its ruleset (assigned by
77 * Cloudflare).
78 */
79 priority: number | undefined;
80 /**
81 * When the rule was created.
82 */
83 created: string | undefined;
84 };
85
86 export type Rule = Resource<TypeId, RuleProps, RuleAttributes, never, Providers>;
87
88 /**
89 * A Cloudflare Web Analytics (RUM) rule.
90 *
91 * Rules include or exclude traffic from Web Analytics measurement by
92 * hostname and path patterns. They live under the implicit ruleset of a
93 * zone-based (orange-clouded) `Site` — pass the site's `rulesetId`
94 * attribute. Host, paths, `inclusive`, and `isPaused` are all mutable in
95 * place; changing `rulesetId` triggers a replacement.
96 *
97 * Web Analytics is available on free accounts.
98 * ### Excluding traffic
99 * **Example:** Exclude a path from measurement
100 * ```typescript
101 * const zone = yield* Cloudflare.Zone.Zone("Zone", { name: "example.com" });
102 *
103 * const site = yield* Cloudflare.Rum.Site("Analytics", {
104 * zoneTag: zone.zoneId,
105 * autoInstall: true,
106 * });
107 *
108 * yield* Cloudflare.Rum.Rule("ExcludeAdmin", {
109 * rulesetId: site.rulesetId.as<string>(),
110 * host: "example.com",
111 * paths: ["/admin/*"],
112 * inclusive: false,
113 * });
114 * ```
115 *
116 * ### Pausing a rule
117 * **Example:** Keep the rule but stop applying it
118 * ```typescript
119 * yield* Cloudflare.Rum.Rule("ExcludeAdmin", {
120 * rulesetId: site.rulesetId.as<string>(),
121 * host: "example.com",
122 * paths: ["/admin/*"],
123 * inclusive: false,
124 * isPaused: true,
125 * });
126 * ```
127 *
128 * @see https://developers.cloudflare.com/web-analytics/
129 *
130 * @resource
131 * @product RUM
132 * @category Observability & Analytics
133 */
134 export const Rule = Resource<Rule>(TypeId);
135
136 /**
137 * Returns true if the given value is a Rule resource.
138 */
139 export const isRule = (value: unknown): value is Rule =>
140 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
141
142 export const RuleProvider = () =>
143 Provider.succeed(Rule, {
144 stables: ["id", "rulesetId", "accountId", "created"],
145
146 list: Effect.fn(function* () {
147 const { accountId } = yield* yield* CloudflareEnvironment;
148 // Rules live under a Site's implicit ruleset and there is no
149 // account-wide rule list. Enumerate every site (paginated), collect
150 // their ruleset ids, then fan out the per-ruleset rule list and
151 // flatten — the same listRules read path each rule's `read` uses.
152 const sites = yield* rum.listSiteInfos.pages({ accountId }).pipe(
153 Stream.runCollect,
154 Effect.map((chunk) => Array.from(chunk).flatMap((page) => page.result ?? [])),
155 );
156 const rulesetIds = Array.from(
157 new Set(
158 sites
159 .map((site) => site.ruleset?.id ?? undefined)
160 .filter((id): id is string => id !== undefined),
161 ),
162 );
163 const rows = yield* Effect.forEach(
164 rulesetIds,
165 (rulesetId) =>
166 listRules(accountId, rulesetId).pipe(
167 Effect.map((rules) =>
168 (rules ?? []).map((rule) => toAttributes(rule, rulesetId, accountId)),
169 ),
170 // A freshly minted scoped token can briefly 403 across the
171 // edge — skip rulesets we momentarily can't read.
172 Effect.catchTag("Forbidden", () => Effect.succeed([])),
173 ),
174 { concurrency: 10 },
175 );
176 return rows.flat();
177 }),
178
179 diff: Effect.fn(function* ({ news, output }) {
180 const { accountId } = yield* yield* CloudflareEnvironment;
181 if (!isResolved(news)) return undefined;
182 if ((output?.accountId ?? accountId) !== accountId) {
183 return { action: "replace" } as const;
184 }
185 // A rule cannot be moved between rulesets — moving it means a new
186 // rule under the new ruleset.
187 if (output !== undefined && news.rulesetId !== output.rulesetId) {
188 return { action: "replace" } as const;
189 }
190 return undefined;
191 }),
192
193 read: Effect.fn(function* ({ output, olds }) {
194 const { accountId } = yield* yield* CloudflareEnvironment;
195 const acct = output?.accountId ?? accountId;
196 const rulesetId =
197 output?.rulesetId ?? (typeof olds?.rulesetId === "string" ? olds.rulesetId : undefined);
198 if (rulesetId === undefined) return undefined;
199
200 // There is no getRule — read through the ruleset's rule list. A
201 // deleted ruleset (the parent site is gone) means the rule is gone.
202 const rules = yield* listRules(acct, rulesetId);
203 if (rules === undefined) return undefined;
204
205 // Owned path: refresh by our persisted rule id.
206 if (output?.id) {
207 const observed = rules.find((rule) => rule.id === output.id);
208 return observed ? toAttributes(observed, rulesetId, acct) : undefined;
209 }
210
211 // Adoption path: rules carry no ownership markers, so a rule matching
212 // the same host+paths cannot be proven ours — brand it `Unowned` so
213 // the engine refuses to take over unless `adopt` is set.
214 if (olds !== undefined && isResolved(olds)) {
215 const match = rules
216 .filter(
217 (rule) =>
218 (rule.host ?? undefined) === olds.host &&
219 samePaths(rule.paths ?? undefined, olds.paths),
220 )
221 .sort((a, b) => (a.created ?? "").localeCompare(b.created ?? ""))
222 .at(0);
223 if (match) return Unowned(toAttributes(match, rulesetId, acct));
224 }
225 return undefined;
226 }),
227
228 reconcile: Effect.fn(function* ({ news, output }) {
229 const { accountId } = yield* yield* CloudflareEnvironment;
230 // Inputs have been resolved to concrete strings by Plan.
231 const rulesetId = news.rulesetId as string;
232
233 // 1. Observe — the rule id cached on `output` is a hint, not a
234 // guarantee: a missing rule (or ruleset) falls through to create.
235 const rules =
236 output?.id !== undefined && output.rulesetId === rulesetId
237 ? yield* listRules(accountId, rulesetId)
238 : undefined;
239 let observed = rules?.find((rule) => rule.id === output?.id);
240
241 // 2. Ensure — create when missing. Rules have no uniqueness
242 // constraint, so there is no AlreadyExists race to tolerate. The
243 // API rejects bodies with absent `inclusive`/`is_paused`
244 // (`web_analytics.configuration.form.*.invalid`), so always send
245 // the full body with defaults. The create response omits
246 // `priority`, so re-read the rule from the list for the complete
247 // state.
248 if (!observed) {
249 const created = yield* rum
250 .createRule({
251 accountId,
252 rulesetId,
253 host: news.host,
254 paths: news.paths ?? [],
255 inclusive: news.inclusive ?? true,
256 isPaused: news.isPaused ?? false,
257 })
258 .pipe(
259 // The implicit ruleset of a freshly-created Site is eventually
260 // consistent: a createRule issued immediately after the site
261 // deploy can briefly 404 (`RulesetNotFound`, code
262 // `web_analytics.configuration.api.notFound`) before the ruleset is
263 // visible. Ride out the propagation window with a bounded retry.
264 Effect.retry({
265 while: (e) => e._tag === "RulesetNotFound",
266 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]),
267 }),
268 );
269 const fresh = yield* listRules(accountId, rulesetId);
270 observed = fresh?.find((rule) => rule.id === created.id) ?? toRule(created);
271 return toAttributes(observed, rulesetId, accountId);
272 }
273
274 // 3. Sync — diff observed cloud state against desired. The update
275 // API is a PUT; send the full desired body, but skip the call
276 // entirely on a no-op. Unspecified props keep their observed
277 // values.
278 const desired = {
279 host: news.host ?? observed.host ?? undefined,
280 paths: news.paths ?? [...(observed.paths ?? [])],
281 inclusive: news.inclusive ?? observed.inclusive ?? true,
282 isPaused: news.isPaused ?? observed.isPaused ?? false,
283 };
284 const dirty =
285 (observed.host ?? undefined) !== desired.host ||
286 !samePaths(observed.paths ?? undefined, desired.paths) ||
287 (observed.inclusive ?? true) !== desired.inclusive ||
288 (observed.isPaused ?? false) !== desired.isPaused;
289 if (!dirty) {
290 return toAttributes(observed, rulesetId, accountId);
291 }
292
293 const updated = yield* rum.updateRule({
294 accountId,
295 rulesetId,
296 ruleId: observed.id ?? "",
297 ...desired,
298 });
299 return toAttributes(
300 { ...toRule(updated), priority: updated.priority ?? observed.priority },
301 rulesetId,
302 accountId,
303 );
304 }),
305
306 delete: Effect.fn(function* ({ output }) {
307 yield* rum
308 .deleteRule({
309 accountId: output.accountId,
310 rulesetId: output.rulesetId,
311 ruleId: output.id,
312 })
313 .pipe(
314 // `RuleNotFound` (code 10003) — the rule is already gone;
315 // `RulesetNotFound` (404) — the parent site/ruleset is gone,
316 // taking the rule with it. Both make delete a success.
317 Effect.catchTag(["RuleNotFound", "RulesetNotFound"], () => Effect.void),
318 );
319 }),
320 });
321
322 type ObservedRule = NonNullable<NonNullable<rum.ListRulesResponse["rules"]>>[number];
323
324 /**
325 * List the rules of a ruleset, mapping "ruleset gone" (`RulesetNotFound`,
326 * HTTP 404 `web_analytics.configuration.api.notFound`) to `undefined`.
327 */
328 const listRules = (accountId: string, rulesetId: string) =>
329 rum.listRules({ accountId, rulesetId }).pipe(
330 Effect.map((response): readonly ObservedRule[] | undefined => response.rules ?? []),
331 Effect.catchTag("RulesetNotFound", () => Effect.undefined),
332 );
333
334 const toRule = (rule: rum.CreateRuleResponse | rum.UpdateRuleResponse): ObservedRule => rule;
335
336 const samePaths = (
337 observed: readonly string[] | undefined,
338 desired: readonly string[] | undefined,
339 ) =>
340 (observed ?? []).length === (desired ?? []).length &&
341 (observed ?? []).join("") === (desired ?? []).join("");
342
343 const toAttributes = (
344 rule: ObservedRule,
345 rulesetId: string,
346 accountId: string,
347 ): RuleAttributes => ({
348 id: rule.id ?? "",
349 rulesetId,
350 accountId,
351 host: rule.host ?? undefined,
352 paths: rule.paths ? [...rule.paths] : undefined,
353 inclusive: rule.inclusive ?? true,
354 isPaused: rule.isPaused ?? false,
355 priority: rule.priority ?? undefined,
356 created: rule.created ?? undefined,
357 });