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

main
ts 344 lines 11.9 KB
Raw
1 import * as rum from "@distilled.cloud/cloudflare/rum";
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 * as Schedule from "effect/Schedule";
8 import * as Stream from "effect/Stream";
9 import { CloudflareEnvironment } from "../CloudflareEnvironment.ts";
10 import type { Providers } from "../Providers.ts";
11
12 const TypeId = "Cloudflare.Rum.Site" as const;
13 type TypeId = typeof TypeId;
14
15 export type SiteProps = {
16 /**
17 * The hostname to measure, for gray-clouded sites (sites that are not
18 * proxied through Cloudflare). Embed the produced `snippet` (or the
19 * `siteToken`) in the page yourself.
20 *
21 * Exactly one of `host` or `zoneTag` must be provided. Switching between
22 * the two identity models triggers a replacement; changing the hostname
23 * itself is an in-place update.
24 */
25 host?: string;
26 /**
27 * The zone identifier, for orange-clouded sites (zones proxied through
28 * Cloudflare). Web Analytics attaches to the zone, and `autoInstall` can
29 * inject the measurement snippet at the edge. Changing this property
30 * triggers a replacement.
31 */
32 zoneTag?: string;
33 /**
34 * If enabled, the JavaScript measurement snippet is automatically
35 * injected for orange-clouded sites — no manual embed needed.
36 * @default false
37 */
38 autoInstall?: boolean;
39 /**
40 * Enables or disables RUM measurement. Only valid when `autoInstall` is
41 * `true`.
42 * @default true
43 */
44 enabled?: boolean;
45 /**
46 * If enabled, the JavaScript snippet will not be injected for visitors
47 * from the EU.
48 * @default false
49 */
50 lite?: boolean;
51 };
52
53 export type SiteAttributes = {
54 /**
55 * The Web Analytics site identifier. Stable for the lifetime of the site.
56 */
57 siteTag: string;
58 /**
59 * The Web Analytics site token used by the JavaScript beacon.
60 */
61 siteToken: string;
62 /**
63 * Encoded JavaScript snippet to embed in pages of gray-clouded sites.
64 */
65 snippet: string | undefined;
66 /**
67 * The identifier of the site's implicit ruleset. Rules that include or
68 * exclude traffic from measurement live under this ruleset.
69 */
70 rulesetId: string | undefined;
71 /**
72 * The Cloudflare account the site belongs to.
73 */
74 accountId: string;
75 /**
76 * The measured hostname (gray-clouded sites only).
77 */
78 host: string | undefined;
79 /**
80 * The zone identifier (orange-clouded sites only).
81 */
82 zoneTag: string | undefined;
83 /**
84 * Whether the JavaScript snippet is automatically injected for
85 * orange-clouded sites.
86 */
87 autoInstall: boolean;
88 /**
89 * When the site was created.
90 */
91 created: string | undefined;
92 };
93
94 export type Site = Resource<TypeId, SiteProps, SiteAttributes, never, Providers>;
95
96 /**
97 * A Cloudflare Web Analytics (RUM) site.
98 *
99 * A site measures real-user performance for either a plain hostname
100 * (gray-clouded — embed the produced `snippet` yourself) or a Cloudflare
101 * zone (orange-clouded — set `autoInstall` to inject the snippet at the
102 * edge). The site is identified by its auto-assigned `siteTag`; `host` and
103 * `autoInstall` are mutable in place, while switching between `host` and
104 * `zoneTag` identity models (or changing `zoneTag`) triggers a replacement.
105 *
106 * Web Analytics is available on free accounts.
107 * ### Measuring a hostname
108 * **Example:** Gray-clouded site (manual snippet embed)
109 * ```typescript
110 * const site = yield* Cloudflare.Rum.Site("Analytics", {
111 * host: "example.com",
112 * });
113 *
114 * // Embed in your HTML — contains the site token:
115 * const snippet = site.snippet;
116 * ```
117 *
118 * ### Measuring a zone
119 * **Example:** Orange-clouded site with automatic snippet injection
120 * ```typescript
121 * const zone = yield* Cloudflare.Zone.Zone("Zone", { name: "example.com" });
122 *
123 * yield* Cloudflare.Rum.Site("ZoneAnalytics", {
124 * zoneTag: zone.zoneId,
125 * autoInstall: true,
126 * });
127 * ```
128 *
129 * **Example:** Skip injection for EU visitors
130 * ```typescript
131 * yield* Cloudflare.Rum.Site("ZoneAnalytics", {
132 * zoneTag: zone.zoneId,
133 * autoInstall: true,
134 * lite: true,
135 * });
136 * ```
137 *
138 * @see https://developers.cloudflare.com/web-analytics/
139 *
140 * @resource
141 * @product RUM
142 * @category Observability & Analytics
143 */
144 export const Site = Resource<Site>(TypeId);
145
146 /**
147 * Returns true if the given value is a Site resource.
148 */
149 export const isSite = (value: unknown): value is Site =>
150 Predicate.hasProperty(value, "Type") && value.Type === TypeId;
151
152 export const SiteProvider = () =>
153 Provider.succeed(Site, {
154 stables: ["siteTag", "siteToken", "accountId", "rulesetId", "created"],
155
156 diff: Effect.fn(function* ({ olds = {}, news, output }) {
157 const { accountId } = yield* yield* CloudflareEnvironment;
158 const o = olds as SiteProps;
159 const n = news as SiteProps;
160 if ((output?.accountId ?? accountId) !== accountId) {
161 return { action: "replace" } as const;
162 }
163 // Switching between host-based (gray-clouded) and zone-based
164 // (orange-clouded) measurement changes the site's identity model.
165 if ((o.zoneTag === undefined) !== (n.zoneTag === undefined)) {
166 return { action: "replace" } as const;
167 }
168 // zoneTag is Input<string>; compare only once both are concrete.
169 if (
170 typeof o.zoneTag === "string" &&
171 typeof n.zoneTag === "string" &&
172 o.zoneTag !== n.zoneTag
173 ) {
174 return { action: "replace" } as const;
175 }
176 return undefined;
177 }),
178
179 read: Effect.fn(function* ({ output, olds }) {
180 const { accountId } = yield* yield* CloudflareEnvironment;
181 const acct = output?.accountId ?? accountId;
182
183 // Owned path: refresh by our persisted site tag.
184 if (output?.siteTag) {
185 const observed = yield* getSite(acct, output.siteTag);
186 if (observed) return toAttributes(observed, acct);
187 }
188
189 // Adoption path: a site measuring the same host/zone may already
190 // exist. Web Analytics sites carry no ownership markers (and
191 // Cloudflare happily creates duplicates), so we cannot prove we
192 // created it — brand it `Unowned` so the engine refuses to take
193 // over unless `adopt` is set.
194 const host = output?.host ?? olds?.host;
195 const zoneTag =
196 output?.zoneTag ?? (typeof olds?.zoneTag === "string" ? olds.zoneTag : undefined);
197 if (host !== undefined || zoneTag !== undefined) {
198 const match = yield* findSite(acct, host, zoneTag);
199 if (match) return Unowned(toAttributes(match, acct));
200 }
201 return undefined;
202 }),
203
204 reconcile: Effect.fn(function* ({ news, output }) {
205 const { accountId } = yield* yield* CloudflareEnvironment;
206 // Inputs have been resolved to concrete strings by Plan.
207 const zoneTag = news.zoneTag as string | undefined;
208
209 // 1. Observe — the siteTag cached on `output` is a hint, not a
210 // guarantee: a missing site falls through to create.
211 let observed = output?.siteTag
212 ? yield* getSite(output.accountId ?? accountId, output.siteTag)
213 : undefined;
214
215 // 2. Ensure — create when missing. Cloudflare allows duplicate
216 // sites for the same host/zone, so there is no AlreadyExists
217 // race to tolerate. The create response omits `snippet` and
218 // `ruleset`, so re-read the full site state afterwards (riding
219 // out read-after-write lag on the freshly minted siteTag).
220 if (!observed) {
221 const created = yield* rum.createSiteInfo({
222 accountId,
223 host: news.host,
224 zoneTag,
225 autoInstall: news.autoInstall,
226 });
227 const siteTag = created.siteTag ?? "";
228 observed = yield* rum.getSiteInfo({ accountId, siteId: siteTag }).pipe(
229 Effect.retry({
230 while: (e) => e._tag === "SiteNotFound",
231 schedule: Schedule.exponential("250 millis"),
232 times: 5,
233 }),
234 );
235 // Greenfield with no post-create settings to apply — done.
236 if (news.enabled === undefined && news.lite === undefined) {
237 return toAttributes(observed, accountId);
238 }
239 }
240
241 // 3. Sync — diff observed cloud state against desired. The update
242 // API is a PUT that requires the full body (host/zoneTag/
243 // autoInstall must be re-sent). `enabled` and `lite` are write-
244 // only (never echoed back by the API), so they are applied
245 // whenever specified — observation cannot prove them converged.
246 const dirty =
247 (news.host !== undefined && observed.host !== news.host) ||
248 (observed.autoInstall ?? false) !== (news.autoInstall ?? false) ||
249 news.enabled !== undefined ||
250 news.lite !== undefined;
251 if (!dirty) {
252 return toAttributes(observed, accountId);
253 }
254
255 const updated = yield* rum.updateSiteInfo({
256 accountId,
257 siteId: observed.siteTag ?? "",
258 host: news.host,
259 zoneTag,
260 autoInstall: news.autoInstall,
261 enabled: news.enabled,
262 lite: news.lite,
263 });
264 return toAttributes(updated, accountId);
265 }),
266
267 delete: Effect.fn(function* ({ output }) {
268 yield* rum
269 .deleteSiteInfo({
270 accountId: output.accountId,
271 siteId: output.siteTag,
272 })
273 .pipe(Effect.catchTag("SiteNotFound", () => Effect.void));
274 }),
275
276 // Account collection: Web Analytics sites are enumerated account-wide
277 // via the paginated site-info list. Hydrate each row into the exact
278 // `read` Attributes shape — the list response carries the same fields
279 // (siteTag/siteToken/snippet/ruleset/host) so no per-item re-read is
280 // needed.
281 list: Effect.fn(function* () {
282 const { accountId } = yield* yield* CloudflareEnvironment;
283 return yield* rum.listSiteInfos.pages({ accountId }).pipe(
284 Stream.runCollect,
285 Effect.map((chunk) =>
286 Array.from(chunk).flatMap((page) =>
287 (page.result ?? []).map((site) => toAttributes(site, accountId)),
288 ),
289 ),
290 );
291 }),
292 });
293
294 type ObservedSite =
295 | rum.GetSiteInfoResponse
296 | rum.UpdateSiteInfoResponse
297 | rum.ListSiteInfosResponse["result"][number];
298
299 /**
300 * Read a site by tag, mapping "gone" (`SiteNotFound`, Cloudflare error code
301 * 10015 `web_analytics.configuration.api.notFound`) to `undefined`.
302 */
303 const getSite = (accountId: string, siteTag: string) =>
304 rum.getSiteInfo({ accountId, siteId: siteTag }).pipe(
305 Effect.map((site): ObservedSite | undefined => site),
306 Effect.catchTag("SiteNotFound", () => Effect.undefined),
307 );
308
309 /**
310 * Find a site measuring the given host (gray-clouded) or zone
311 * (orange-clouded). Cloudflare allows several sites for the same target, so
312 * pick the oldest for determinism.
313 */
314 const findSite = (accountId: string, host: string | undefined, zoneTag: string | undefined) =>
315 rum.listSiteInfos.items({ accountId }).pipe(
316 Stream.runCollect,
317 Effect.map((chunk) =>
318 Array.from(chunk)
319 .filter((site) =>
320 host !== undefined
321 ? site.host === host
322 : // A zone-identity site has no `host`. Host-scoped sites on the
323 // zone's subdomains ALSO carry `ruleset.zoneTag`, so a zone
324 // probe must only match true zone sites — otherwise an
325 // unrelated host site satisfies the probe and the engine
326 // refuses adoption with OwnedBySomeoneElse.
327 zoneTag !== undefined && !site.host && site.ruleset?.zoneTag === zoneTag,
328 )
329 .sort((a, b) => (a.created ?? "").localeCompare(b.created ?? ""))
330 .at(0),
331 ),
332 );
333
334 const toAttributes = (site: ObservedSite, accountId: string): SiteAttributes => ({
335 siteTag: site.siteTag ?? "",
336 siteToken: site.siteToken ?? "",
337 snippet: site.snippet ?? undefined,
338 rulesetId: site.ruleset?.id ?? undefined,
339 accountId,
340 host: site.host ?? undefined,
341 zoneTag: site.ruleset?.zoneTag ?? undefined,
342 autoInstall: site.autoInstall ?? false,
343 created: site.created ?? undefined,
344 });