cursedbelt-server 4.59.0 → 4.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/dist/server/engagement/api.d.ts +6 -0
  2. package/dist/server/engagement/api.js +3 -0
  3. package/dist/server/engagement/d1.d.ts +7 -0
  4. package/dist/server/engagement/d1.js +4 -0
  5. package/dist/server/engagement/events.d.ts +26 -0
  6. package/dist/server/engagement/events.js +52 -0
  7. package/dist/server/events/actions.d.ts +46 -0
  8. package/dist/server/events/actions.js +62 -0
  9. package/dist/server/events/actor.d.ts +19 -0
  10. package/dist/server/events/actor.js +30 -0
  11. package/dist/server/events/gauge.d.ts +21 -0
  12. package/dist/server/events/gauge.js +60 -0
  13. package/dist/server/events/index.d.ts +14 -0
  14. package/dist/server/events/index.js +14 -0
  15. package/dist/server/events/point.d.ts +77 -0
  16. package/dist/server/events/point.js +149 -0
  17. package/dist/server/events/sink.d.ts +97 -0
  18. package/dist/server/events/sink.js +113 -0
  19. package/dist/server/events/views.d.ts +24 -0
  20. package/dist/server/events/views.js +41 -0
  21. package/package.json +8 -2
  22. package/src/server/bench/cpuBudget.spec.ts +12 -8
  23. package/src/server/engagement/api.ts +8 -0
  24. package/src/server/engagement/d1.ts +9 -0
  25. package/src/server/engagement/events.ts +79 -0
  26. package/src/server/events/actions.spec.ts +126 -0
  27. package/src/server/events/actions.ts +113 -0
  28. package/src/server/events/actor.ts +34 -0
  29. package/src/server/events/gauge.spec.ts +75 -0
  30. package/src/server/events/gauge.ts +81 -0
  31. package/src/server/events/index.ts +47 -0
  32. package/src/server/events/point.spec.ts +145 -0
  33. package/src/server/events/point.ts +197 -0
  34. package/src/server/events/sink.spec.ts +289 -0
  35. package/src/server/events/sink.ts +221 -0
  36. package/src/server/events/views.ts +62 -0
  37. package/src/server/telemetryIsWorkerSafe.spec.ts +23 -0
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The engagement beacon's second write: every accepted `POST /view` is a `view` point and every
3
+ * accepted `POST /action` an `action` point in the app's `EVENTS` dataset (`../events`), beside
4
+ * the D1/sqlite fold that station reads. The store is untouched; the recorder calls these after
5
+ * it has recorded, and nothing here can fail the beacon's answer.
6
+ *
7
+ * Purposes come from a small per-app map; what the map leaves out follows the schema's defaults:
8
+ * a sign-in or settings place is `account`, an admin place `admin`, a help/docs place `support`,
9
+ * a search place `search`, anything else `read`; an action defaults to `edit`.
10
+ */
11
+ import type { Context } from "hono";
12
+ import type { EventActor, EventPurpose, EventSink } from "../events/index.js";
13
+ import type { ActionUse } from "./actions.js";
14
+
15
+ export interface EngagementEvents {
16
+ sink: EventSink;
17
+ /** Place id → purpose, for the places the defaults below get wrong. */
18
+ purposes?: Readonly<Record<string, EventPurpose>>;
19
+ /** Action id → purpose; the default is `edit`. */
20
+ actionPurposes?: Readonly<Record<string, EventPurpose>>;
21
+ /** The account beyond its key — label and ownership. Default: the key as the id. */
22
+ actorOf?: (c: Context) => EventActor | null;
23
+ }
24
+
25
+ const ACCOUNT_RE = /sign-?in|log-?in|settings|account|profile|session/i;
26
+ const ADMIN_RE = /admin|owner/i;
27
+ const SUPPORT_RE = /help|docs|manual|support|about/i;
28
+ const SEARCH_RE = /search/i;
29
+
30
+ export function placePurpose(place: string, purposes?: Readonly<Record<string, EventPurpose>>): EventPurpose {
31
+ const mapped = purposes?.[place];
32
+ if (mapped) return mapped;
33
+ if (ACCOUNT_RE.test(place)) return "account";
34
+ if (ADMIN_RE.test(place)) return "admin";
35
+ if (SUPPORT_RE.test(place)) return "support";
36
+ if (SEARCH_RE.test(place)) return "search";
37
+ return "read";
38
+ }
39
+
40
+ export function actionPurpose(action: string, purposes?: Readonly<Record<string, EventPurpose>>): EventPurpose {
41
+ return purposes?.[action] ?? "edit";
42
+ }
43
+
44
+ function actorFor(events: EngagementEvents, c: Context, userKey: string): EventActor {
45
+ return events.actorOf?.(c) ?? { id: userKey };
46
+ }
47
+
48
+ export function recordEngagementView(events: EngagementEvents | undefined, c: Context, userKey: string, place: string): void {
49
+ if (!events) return;
50
+ events.sink.record(c.req.raw, {
51
+ kind: "view",
52
+ name: place,
53
+ place,
54
+ purpose: placePurpose(place, events.purposes),
55
+ actor: actorFor(events, c, userKey),
56
+ status: 200,
57
+ });
58
+ }
59
+
60
+ export function recordEngagementActions(
61
+ events: EngagementEvents | undefined,
62
+ c: Context,
63
+ userKey: string,
64
+ uses: readonly ActionUse[],
65
+ ): void {
66
+ if (!events) return;
67
+ const actor = actorFor(events, c, userKey);
68
+ for (const use of uses) {
69
+ events.sink.record(c.req.raw, {
70
+ kind: "action",
71
+ name: use.action,
72
+ place: use.place,
73
+ purpose: actionPurpose(use.action, events.actionPurposes),
74
+ actor,
75
+ status: 200,
76
+ value: use.uses ?? 1,
77
+ });
78
+ }
79
+ }
@@ -0,0 +1,126 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { Hono } from "hono";
3
+ import { matchServerAction, type ServerActionRule, serverActions } from "./actions.js";
4
+ import { createEventSink, type EventsDataset } from "./sink.js";
5
+
6
+ type Point = Parameters<EventsDataset["writeDataPoint"]>[0];
7
+
8
+ function fakeDataset(): EventsDataset & { points: Point[] } {
9
+ const points: Point[] = [];
10
+ return {
11
+ points,
12
+ writeDataPoint(point) {
13
+ points.push(point);
14
+ },
15
+ };
16
+ }
17
+
18
+ const BROWSER = "Mozilla/5.0 (Macintosh; Intel Mac OS X 14_0) AppleWebKit/537.36 Chrome/120 Safari/537.36";
19
+ const RULES: ServerActionRule[] = [
20
+ { method: "POST", route: "/api/upload", name: "file.upload", purpose: "upload", place: "upload", bytes: "request" },
21
+ { method: "GET", route: "/api/tracks/:id/stream", name: "track.play", purpose: "play", bytes: "response" },
22
+ { method: "DELETE", route: "/api/playlists/:id", name: "playlist.delete", purpose: "organize" },
23
+ { method: "GET", route: "/api/search", name: "search", purpose: "search" },
24
+ ];
25
+
26
+ function harness(status = 200) {
27
+ const dataset = fakeDataset();
28
+ const events = createEventSink(dataset, { app: "music", build: "abc", now: () => 1_000 });
29
+ const app = new Hono();
30
+ app.use(
31
+ "/api/*",
32
+ serverActions(events, RULES, {
33
+ actorOf: () => ({ id: "curt@example.com", label: "Curt", owner: true }),
34
+ valueFor: (_c, rule) => (rule.name === "search" ? 12 : undefined),
35
+ }),
36
+ );
37
+ app.post("/api/upload", (c) => c.body("ok", status));
38
+ app.get("/api/tracks/:id/stream", (c) => c.body("bytes".repeat(10), status, { "content-length": "50" }));
39
+ app.delete("/api/playlists/:id", (c) => c.json({ ok: true }, status));
40
+ app.get("/api/search", (c) => c.json({ items: [] }, status));
41
+ app.get("/api/tracks", (c) => c.json({ items: [] }));
42
+ const send = (method: string, path: string, headers: Record<string, string> = {}) =>
43
+ app.request(`https://music.cursedalchemy.com${path}`, {
44
+ method,
45
+ headers: { "user-agent": BROWSER, "cf-connecting-ip": "203.0.113.9", ...headers },
46
+ });
47
+ return { dataset, send };
48
+ }
49
+
50
+ describe("serverActions — the API seam that names a state-changing act", () => {
51
+ test("an upload becomes action:file.upload with the request's bytes and the actor", async () => {
52
+ const { dataset, send } = harness();
53
+ await send("POST", "/api/upload", { "content-length": "4096" });
54
+ expect(dataset.points).toHaveLength(1);
55
+ const [point] = dataset.points;
56
+ expect(point.indexes).toEqual(["action:file.upload"]);
57
+ expect(point.blobs?.slice(2, 11)).toEqual([
58
+ "action",
59
+ "file.upload",
60
+ "upload",
61
+ "curt@example.com",
62
+ "owner",
63
+ "Curt",
64
+ "",
65
+ "web",
66
+ "upload",
67
+ ]);
68
+ expect(point.blobs?.[13]).toBe("ok");
69
+ expect(point.doubles).toEqual([1, 0, 4096, 0]);
70
+ });
71
+
72
+ test("a stream names track.play with the response's bytes; a route pattern, never the id", async () => {
73
+ const { dataset, send } = harness();
74
+ await send("GET", "/api/tracks/42/stream");
75
+ expect(dataset.points[0]?.indexes).toEqual(["action:track.play"]);
76
+ expect(dataset.points[0]?.doubles?.[2]).toBe(50);
77
+ expect(JSON.stringify(dataset.points[0])).not.toContain("/42");
78
+ });
79
+
80
+ test("a search carries the app's value; a read-only GET with no rule writes nothing", async () => {
81
+ const { dataset, send } = harness();
82
+ await send("GET", "/api/search?q=secret");
83
+ expect(dataset.points[0]?.doubles).toEqual([1, 0, 0, 12]);
84
+ expect(JSON.stringify(dataset.points[0])).not.toContain("secret");
85
+ await send("GET", "/api/tracks");
86
+ expect(dataset.points).toHaveLength(1);
87
+ });
88
+
89
+ test("a 5xx writes the action AND an error point of the same name", async () => {
90
+ const { dataset, send } = harness(503);
91
+ await send("DELETE", "/api/playlists/7");
92
+ expect(dataset.points.map((p) => p.indexes?.[0])).toEqual(["action:playlist.delete", "error:playlist.delete"]);
93
+ expect(dataset.points.map((p) => p.blobs?.[13])).toEqual(["error", "error"]);
94
+ });
95
+
96
+ test("a ctgr GET-twin counts as its real verb", async () => {
97
+ const dataset = fakeDataset();
98
+ const events = createEventSink(dataset, { app: "music" });
99
+ const app = new Hono();
100
+ app.use("/api/*", serverActions(events, RULES, { actorOf: () => ({ id: "curt@example.com" }) }));
101
+ app.get("/api/ctgrte/playlists/:id", (c) => c.json({ ok: true }));
102
+ await app.request("https://music.cursedalchemy.com/api/ctgrte/playlists/7", { headers: { "user-agent": BROWSER } });
103
+ expect(dataset.points[0]?.indexes).toEqual(["action:playlist.delete"]);
104
+ });
105
+
106
+ test("an unbound sink costs nothing and a throwing classifier never reaches the response", async () => {
107
+ const events = createEventSink(undefined, { app: "music" });
108
+ const app = new Hono();
109
+ app.use(
110
+ "/api/*",
111
+ serverActions(events, RULES, {
112
+ actorOf: () => {
113
+ throw new Error("boom");
114
+ },
115
+ }),
116
+ );
117
+ app.post("/api/upload", (c) => c.text("ok"));
118
+ const res = await app.request("https://x.test/api/upload", { method: "POST" });
119
+ expect(res.status).toBe(200);
120
+ });
121
+
122
+ test("matchServerAction is case-insensitive on the method and exact on the pattern", () => {
123
+ expect(matchServerAction(RULES, "post", "/api/upload")?.name).toBe("file.upload");
124
+ expect(matchServerAction(RULES, "POST", "/api/upload/")).toBeNull();
125
+ });
126
+ });
@@ -0,0 +1,113 @@
1
+ /**
2
+ * `serverActions(events, rules, options)` — the one Hono seam that turns a state-changing API call
3
+ * into an `action` point, classified by method + matched route pattern (`normalizeRoute`, so a
4
+ * ctgr GET-twin counts as its real verb).
5
+ *
6
+ * ```ts
7
+ * app.use("/api/*", serverActions(events, MUSIC_ACTIONS, { actorOf: (c) => actorOf(door.sso.userOf(c)) }));
8
+ * ```
9
+ *
10
+ * Every rule names ONE (name, purpose) for one `METHOD /route/:pattern`; a request matching no rule
11
+ * writes nothing (the requests layer already counts it). A 5xx on a matched rule also writes an
12
+ * `error` point named after the action — "an act that failed in front of the person".
13
+ *
14
+ * Only after `next()`: the point carries the response status, the elapsed ms and, when the rule
15
+ * says so, the bytes the request carried (`Content-Length`) or the response sent — never the body.
16
+ */
17
+ import type { Context, MiddlewareHandler } from "hono";
18
+ import { normalizeRoute } from "../metrics/normalizeRoute.js";
19
+ import type { EventPurpose, EventVia } from "./point.js";
20
+ import type { EventActor, EventSink } from "./sink.js";
21
+
22
+ export interface ServerActionRule {
23
+ /** `POST`, `GET`, `DELETE`, … — compared case-insensitively. */
24
+ method: string;
25
+ /** The Hono route pattern as `normalizeRoute` reports it: `/api/tracks/:id/stream`. */
26
+ route: string;
27
+ /** Verb-object, short, stable: `file.upload`, `track.play`, `search`. */
28
+ name: string;
29
+ purpose: EventPurpose;
30
+ /** The page/view the act belongs to, when the app has one. */
31
+ place?: string;
32
+ /** Which `Content-Length` becomes the point's bytes. */
33
+ bytes?: "request" | "response";
34
+ }
35
+
36
+ export interface ServerActionsOptions {
37
+ /** Who sent it — `null` for no session (the anonymous hash then). */
38
+ actorOf?: (c: Context) => EventActor | null | undefined;
39
+ /** Default `web`; an API-token surface says `api`. */
40
+ via?: EventVia | ((c: Context) => EventVia);
41
+ /** Workspace/tenant id when the app has one. */
42
+ tenantOf?: (c: Context) => string | undefined;
43
+ /** A number worth keeping with the point (items returned, tracks zipped). */
44
+ valueFor?: (c: Context, rule: ServerActionRule) => number | undefined;
45
+ now?: () => number;
46
+ }
47
+
48
+ function ruleKey(method: string, route: string): string {
49
+ return `${method.toUpperCase()} ${route}`;
50
+ }
51
+
52
+ /** The rule a method + route pattern maps to, or `null` — exposed so an app can pin its table. */
53
+ export function matchServerAction(
54
+ rules: readonly ServerActionRule[],
55
+ method: string,
56
+ route: string,
57
+ ): ServerActionRule | null {
58
+ const key = ruleKey(method, route);
59
+ for (const rule of rules) if (ruleKey(rule.method, rule.route) === key) return rule;
60
+ return null;
61
+ }
62
+
63
+ function contentLength(headers: Headers | undefined): number {
64
+ const raw = headers?.get("content-length");
65
+ const n = raw ? Number(raw) : 0;
66
+ return Number.isFinite(n) && n > 0 ? n : 0;
67
+ }
68
+
69
+ export function serverActions(
70
+ events: EventSink,
71
+ rules: readonly ServerActionRule[],
72
+ options: ServerActionsOptions = {},
73
+ ): MiddlewareHandler {
74
+ const now = options.now ?? (() => Date.now());
75
+ const index = new Map<string, ServerActionRule>();
76
+ for (const rule of rules) index.set(ruleKey(rule.method, rule.route), rule);
77
+ return async (c, next) => {
78
+ const started = now();
79
+ await next();
80
+ if (!events.bound) return;
81
+ try {
82
+ const { method, route } = normalizeRoute(c);
83
+ const rule = index.get(ruleKey(method, route));
84
+ if (!rule) return;
85
+ const status = c.res.status;
86
+ const ms = Math.max(0, now() - started);
87
+ const bytes =
88
+ rule.bytes === "request"
89
+ ? contentLength(c.req.raw.headers)
90
+ : rule.bytes === "response"
91
+ ? contentLength(c.res.headers)
92
+ : 0;
93
+ const via = typeof options.via === "function" ? options.via(c) : options.via;
94
+ const tenant = options.tenantOf?.(c);
95
+ const value = options.valueFor?.(c, rule);
96
+ const base = {
97
+ place: rule.place ?? "",
98
+ purpose: rule.purpose,
99
+ actor: options.actorOf?.(c) ?? null,
100
+ status,
101
+ ms,
102
+ bytes,
103
+ ...(via ? { via } : {}),
104
+ ...(tenant ? { tenant } : {}),
105
+ ...(value !== undefined ? { value } : {}),
106
+ };
107
+ events.record(c.req.raw, { kind: "action", name: rule.name, ...base });
108
+ if (status >= 500) events.record(c.req.raw, { kind: "error", name: rule.name, ...base });
109
+ } catch (error) {
110
+ console.warn(`[events] a server action was not classified: ${String(error)}`);
111
+ }
112
+ };
113
+ }
@@ -0,0 +1,34 @@
1
+ /**
2
+ * The anonymous actor: `"anon:"` + the first 16 hex characters of
3
+ * `sha256(`${utcDay}|${ip}|${userAgent}|${EVENTS_SALT}`)`. It rotates daily and is stored nowhere
4
+ * else, so a visitor is countable within a day and unlinkable across days — the schema's rule.
5
+ *
6
+ * Web Crypto only (`crypto.subtle`), so a Worker, Bun and Node all hash the same way with no
7
+ * `bun:` or `node:` import — `telemetryIsWorkerSafe.spec.ts` walks this file.
8
+ */
9
+ import { utcDay } from "./point.js";
10
+
11
+ /**
12
+ * What a deployment with NO `EVENTS_SALT` hashes with — local dev and tests. A production write
13
+ * still happens with it (the schema says so); `worker:secrets` is what makes it a real secret.
14
+ */
15
+ export const LOCAL_EVENTS_SALT = "local-events-salt";
16
+
17
+ export const ANON_PREFIX = "anon:";
18
+
19
+ /** The hash input as the schema spells it, so a test can pin the exact string. */
20
+ export function anonymousActorInput(input: { ip: string; userAgent: string; salt: string; now: number }): string {
21
+ return `${utcDay(input.now)}|${input.ip}|${input.userAgent}|${input.salt}`;
22
+ }
23
+
24
+ export async function anonymousActor(input: { ip: string; userAgent: string; salt?: string | null; now?: number }): Promise<string> {
25
+ const text = anonymousActorInput({
26
+ ip: input.ip,
27
+ userAgent: input.userAgent,
28
+ salt: input.salt || LOCAL_EVENTS_SALT,
29
+ now: input.now ?? Date.now(),
30
+ });
31
+ const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text));
32
+ const hex = Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, "0")).join("");
33
+ return `${ANON_PREFIX}${hex.slice(0, 16)}`;
34
+ }
@@ -0,0 +1,75 @@
1
+ import { Database } from "bun:sqlite";
2
+ import { afterEach, describe, expect, test } from "bun:test";
3
+ import { createLocalD1 } from "../d1/local.js";
4
+ import { dailyGauge, resetDailyGaugeMemo } from "./gauge.js";
5
+
6
+ const DAY1 = Date.UTC(2026, 9, 31, 12);
7
+ const DAY2 = Date.UTC(2026, 10, 1, 0, 1);
8
+
9
+ afterEach(() => resetDailyGaugeMemo());
10
+
11
+ describe("dailyGauge — once per UTC day per key, claimed in D1", () => {
12
+ test("the first call of a day runs the gauge; the same day again does not; the next day does", async () => {
13
+ const db = createLocalD1(new Database(":memory:"));
14
+ const runs: string[] = [];
15
+ const emit = (day: string) => {
16
+ runs.push(day);
17
+ };
18
+ expect(await dailyGauge(db, "storage", emit, { now: () => DAY1 })).toBe(true);
19
+ expect(await dailyGauge(db, "storage", emit, { now: () => DAY1 })).toBe(false);
20
+ resetDailyGaugeMemo(); // another isolate, same database
21
+ expect(await dailyGauge(db, "storage", emit, { now: () => DAY1 })).toBe(false);
22
+ expect(await dailyGauge(db, "storage", emit, { now: () => DAY2 })).toBe(true);
23
+ expect(runs).toEqual(["2026-10-31", "2026-11-01"]);
24
+ });
25
+
26
+ test("a gauge that throws releases the day so the next trigger retries", async () => {
27
+ const db = createLocalD1(new Database(":memory:"));
28
+ let attempts = 0;
29
+ const emit = () => {
30
+ attempts += 1;
31
+ if (attempts === 1) throw new Error("D1 hiccup");
32
+ };
33
+ expect(await dailyGauge(db, "storage", emit, { now: () => DAY1 })).toBe(false);
34
+ expect(await dailyGauge(db, "storage", emit, { now: () => DAY1 })).toBe(true);
35
+ expect(attempts).toBe(2);
36
+ });
37
+
38
+ test("keys are independent and old days are pruned", async () => {
39
+ const db = createLocalD1(new Database(":memory:"));
40
+ expect(await dailyGauge(db, "storage", () => undefined, { now: () => DAY1 })).toBe(true);
41
+ expect(await dailyGauge(db, "members", () => undefined, { now: () => DAY1 })).toBe(true);
42
+ const later = DAY1 + 30 * 86_400_000;
43
+ expect(await dailyGauge(db, "storage", () => undefined, { now: () => later })).toBe(true);
44
+ const rows = await db.prepare("SELECT key, day FROM events_days ORDER BY key, day").all();
45
+ expect(rows.results).toEqual([
46
+ { key: "members", day: "2026-10-31" },
47
+ { key: "storage", day: "2026-11-30" },
48
+ ]);
49
+ });
50
+
51
+ test("a database that cannot claim runs nothing and does not throw", async () => {
52
+ const db = {
53
+ prepare: () => ({
54
+ bind: () => ({
55
+ run: async () => {
56
+ throw new Error("D1_ERROR: connection lost");
57
+ },
58
+ }),
59
+ }),
60
+ batch: async () => [],
61
+ } as unknown as Parameters<typeof dailyGauge>[0];
62
+ let ran = false;
63
+ expect(
64
+ await dailyGauge(
65
+ db,
66
+ "storage",
67
+ () => {
68
+ ran = true;
69
+ },
70
+ { now: () => DAY1 },
71
+ ),
72
+ ).toBe(false);
73
+ expect(ran).toBe(false);
74
+ });
75
+ });
@@ -0,0 +1,81 @@
1
+ /**
2
+ * `dailyGauge(db, key, emit)` — runs `emit` at most once per UTC day per key, guarded in the app's
3
+ * own D1 (`events_days`, created on first use like the engagement tables). The schema's `storage`
4
+ * gauge comes from "an existing cron or the first request of the day"; a Worker has many isolates
5
+ * and a cron may fire more than once, so the day's claim lives in the database, not in memory.
6
+ *
7
+ * ```ts
8
+ * ctx.waitUntil(dailyGauge(db, "storage", () => emitStorageGauges(events, db)));
9
+ * ```
10
+ *
11
+ * Returns `true` when `emit` ran. A failed claim (D1 down) runs nothing and warns; the gauge is
12
+ * counted nowhere else, so a lost day is a gap, never a double. A thrown `emit` releases the claim
13
+ * so the next trigger retries.
14
+ */
15
+ import type { D1LikeDatabase } from "../d1/types.js";
16
+ import { utcDay } from "./point.js";
17
+
18
+ export const EVENTS_DAYS_DDL = [
19
+ "CREATE TABLE IF NOT EXISTS events_days (key TEXT NOT NULL, day TEXT NOT NULL, PRIMARY KEY (key, day))",
20
+ ];
21
+
22
+ const CLAIM = "INSERT OR IGNORE INTO events_days (key, day) VALUES (?, ?)";
23
+ const RELEASE = "DELETE FROM events_days WHERE key = ? AND day = ?";
24
+ /** Days older than this leave the table on each claim, so it never grows past a few rows per key. */
25
+ const KEEP_DAYS = 7;
26
+
27
+ /** The isolate remembers the day it already claimed, so a busy Worker asks D1 once per day. */
28
+ const claimed = new Map<string, string>();
29
+
30
+ async function claimDay(db: D1LikeDatabase, key: string, day: string): Promise<boolean> {
31
+ const run = () => db.prepare(CLAIM).bind(key, day).run();
32
+ const result = await run().catch(async (error: unknown) => {
33
+ if (!/no such table/i.test(String(error))) throw error;
34
+ await db.batch(EVENTS_DAYS_DDL.map((ddl) => db.prepare(ddl)));
35
+ return run();
36
+ });
37
+ return (result.meta?.changes ?? 0) > 0;
38
+ }
39
+
40
+ export async function dailyGauge(
41
+ db: D1LikeDatabase,
42
+ key: string,
43
+ emit: (day: string) => Promise<void> | void,
44
+ options: { now?: () => number } = {},
45
+ ): Promise<boolean> {
46
+ const day = utcDay((options.now ?? Date.now)());
47
+ if (claimed.get(key) === day) return false;
48
+ let won = false;
49
+ try {
50
+ won = await claimDay(db, key, day);
51
+ } catch (error) {
52
+ console.warn(`[events] the ${key} gauge's day was not claimed: ${String(error)}`);
53
+ return false;
54
+ }
55
+ claimed.set(key, day);
56
+ if (!won) return false;
57
+ try {
58
+ await emit(day);
59
+ } catch (error) {
60
+ console.warn(`[events] the ${key} gauge was not emitted: ${String(error)}`);
61
+ claimed.delete(key);
62
+ await db
63
+ .prepare(RELEASE)
64
+ .bind(key, day)
65
+ .run()
66
+ .catch(() => undefined);
67
+ return false;
68
+ }
69
+ const cutoff = utcDay((options.now ?? Date.now)() - KEEP_DAYS * 86_400_000);
70
+ await db
71
+ .prepare("DELETE FROM events_days WHERE key = ? AND day < ?")
72
+ .bind(key, cutoff)
73
+ .run()
74
+ .catch(() => undefined);
75
+ return true;
76
+ }
77
+
78
+ /** Test seam: forget what this isolate claimed. */
79
+ export function resetDailyGaugeMemo(): void {
80
+ claimed.clear();
81
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * `cursedbelt-server/events` — first-party user-event telemetry into a Worker's `EVENTS`
3
+ * Analytics Engine dataset, beside (never instead of) `./telemetry`'s per-request points.
4
+ *
5
+ * 🔴 Worker-safe: nothing reachable from here at runtime imports `bun:*`
6
+ * (`telemetryIsWorkerSafe.spec.ts` walks it). `./point.ts` is the wire format; `./sink.ts` the
7
+ * seam; `./actor.ts` the anonymous hash; `./views.ts` the server-side view of an HTML navigation.
8
+ */
9
+ export { ANON_PREFIX, LOCAL_EVENTS_SALT, anonymousActor, anonymousActorInput } from "./actor.js";
10
+ export {
11
+ ACTOR_KINDS,
12
+ type ActorKind,
13
+ BOT_USER_AGENT_WORDS,
14
+ EVENT_KINDS,
15
+ EVENT_PURPOSES,
16
+ EVENT_SCHEMA,
17
+ EVENT_VIAS,
18
+ type EventDevice,
19
+ type EventKind,
20
+ type EventOutcome,
21
+ type EventPoint,
22
+ type EventPurpose,
23
+ type EventVia,
24
+ classifyDevice,
25
+ isBotUserAgent,
26
+ outcomeOf,
27
+ referrerHost,
28
+ toEventPoint,
29
+ truncateUtf8,
30
+ utcDay,
31
+ } from "./point.js";
32
+ export {
33
+ DEFAULT_SMOKE_ACCOUNTS,
34
+ type EventActor,
35
+ type EventFields,
36
+ type EventSink,
37
+ type EventSinkOptions,
38
+ type EventsDataset,
39
+ type RequestFacts,
40
+ createEventSink,
41
+ recordEvent,
42
+ requestFacts,
43
+ resolveActorKind,
44
+ } from "./sink.js";
45
+ export { type HtmlNavigation, htmlNavigationOf, recordHtmlView } from "./views.js";
46
+ export { type ServerActionRule, type ServerActionsOptions, matchServerAction, serverActions } from "./actions.js";
47
+ export { EVENTS_DAYS_DDL, dailyGauge, resetDailyGaugeMemo } from "./gauge.js";