@vllnt/convex-analytics 0.1.0-canary.2b9f918

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 (88) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +198 -0
  3. package/dist/client/index.d.ts +94 -0
  4. package/dist/client/index.d.ts.map +1 -0
  5. package/dist/client/index.js +132 -0
  6. package/dist/client/index.js.map +1 -0
  7. package/dist/client/types.d.ts +109 -0
  8. package/dist/client/types.d.ts.map +1 -0
  9. package/dist/client/types.js +2 -0
  10. package/dist/client/types.js.map +1 -0
  11. package/dist/component/_generated/api.d.ts +46 -0
  12. package/dist/component/_generated/api.d.ts.map +1 -0
  13. package/dist/component/_generated/api.js +31 -0
  14. package/dist/component/_generated/api.js.map +1 -0
  15. package/dist/component/_generated/component.d.ts +181 -0
  16. package/dist/component/_generated/component.d.ts.map +1 -0
  17. package/dist/component/_generated/component.js +11 -0
  18. package/dist/component/_generated/component.js.map +1 -0
  19. package/dist/component/_generated/dataModel.d.ts +46 -0
  20. package/dist/component/_generated/dataModel.d.ts.map +1 -0
  21. package/dist/component/_generated/dataModel.js +11 -0
  22. package/dist/component/_generated/dataModel.js.map +1 -0
  23. package/dist/component/_generated/server.d.ts +133 -0
  24. package/dist/component/_generated/server.d.ts.map +1 -0
  25. package/dist/component/_generated/server.js +80 -0
  26. package/dist/component/_generated/server.js.map +1 -0
  27. package/dist/component/convex.config.d.ts +3 -0
  28. package/dist/component/convex.config.d.ts.map +1 -0
  29. package/dist/component/convex.config.js +10 -0
  30. package/dist/component/convex.config.js.map +1 -0
  31. package/dist/component/http.d.ts +13 -0
  32. package/dist/component/http.d.ts.map +1 -0
  33. package/dist/component/http.js +180 -0
  34. package/dist/component/http.js.map +1 -0
  35. package/dist/component/internal_mutations.d.ts +26 -0
  36. package/dist/component/internal_mutations.d.ts.map +1 -0
  37. package/dist/component/internal_mutations.js +126 -0
  38. package/dist/component/internal_mutations.js.map +1 -0
  39. package/dist/component/mutations.d.ts +24 -0
  40. package/dist/component/mutations.d.ts.map +1 -0
  41. package/dist/component/mutations.js +209 -0
  42. package/dist/component/mutations.js.map +1 -0
  43. package/dist/component/queries.d.ts +148 -0
  44. package/dist/component/queries.d.ts.map +1 -0
  45. package/dist/component/queries.js +376 -0
  46. package/dist/component/queries.js.map +1 -0
  47. package/dist/component/schema.d.ts +104 -0
  48. package/dist/component/schema.d.ts.map +1 -0
  49. package/dist/component/schema.js +72 -0
  50. package/dist/component/schema.js.map +1 -0
  51. package/dist/component/validators.d.ts +195 -0
  52. package/dist/component/validators.d.ts.map +1 -0
  53. package/dist/component/validators.js +71 -0
  54. package/dist/component/validators.js.map +1 -0
  55. package/dist/react/index.d.ts +89 -0
  56. package/dist/react/index.d.ts.map +1 -0
  57. package/dist/react/index.js +63 -0
  58. package/dist/react/index.js.map +1 -0
  59. package/dist/shared.d.ts +14 -0
  60. package/dist/shared.d.ts.map +1 -0
  61. package/dist/shared.js +18 -0
  62. package/dist/shared.js.map +1 -0
  63. package/dist/test.d.ts +117 -0
  64. package/dist/test.d.ts.map +1 -0
  65. package/dist/test.js +28 -0
  66. package/dist/test.js.map +1 -0
  67. package/dist/web/index.d.ts +121 -0
  68. package/dist/web/index.d.ts.map +1 -0
  69. package/dist/web/index.js +169 -0
  70. package/dist/web/index.js.map +1 -0
  71. package/package.json +121 -0
  72. package/src/client/index.ts +259 -0
  73. package/src/client/types.ts +121 -0
  74. package/src/component/_generated/api.ts +62 -0
  75. package/src/component/_generated/component.ts +196 -0
  76. package/src/component/_generated/dataModel.ts +60 -0
  77. package/src/component/_generated/server.ts +169 -0
  78. package/src/component/convex.config.ts +12 -0
  79. package/src/component/http.ts +204 -0
  80. package/src/component/internal_mutations.ts +167 -0
  81. package/src/component/mutations.ts +255 -0
  82. package/src/component/queries.ts +436 -0
  83. package/src/component/schema.ts +76 -0
  84. package/src/component/validators.ts +94 -0
  85. package/src/react/index.tsx +127 -0
  86. package/src/shared.ts +30 -0
  87. package/src/test.ts +44 -0
  88. package/src/web/index.ts +232 -0
@@ -0,0 +1,169 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type {
12
+ ActionBuilder,
13
+ HttpActionBuilder,
14
+ MutationBuilder,
15
+ QueryBuilder,
16
+ GenericActionCtx,
17
+ GenericMutationCtx,
18
+ GenericQueryCtx,
19
+ GenericDatabaseReader,
20
+ GenericDatabaseWriter,
21
+ } from "convex/server";
22
+ import {
23
+ actionGeneric,
24
+ httpActionGeneric,
25
+ queryGeneric,
26
+ mutationGeneric,
27
+ internalActionGeneric,
28
+ internalMutationGeneric,
29
+ internalQueryGeneric,
30
+ } from "convex/server";
31
+ import type { DataModel } from "./dataModel.js";
32
+
33
+ /**
34
+ * Typesafe environment variables.
35
+ *
36
+ * This includes platform-provided env vars and any variables declared in
37
+ * `convex.config.ts`.
38
+ */
39
+ type Env = {
40
+ readonly CONVEX_CLOUD_URL: string;
41
+ readonly CONVEX_SITE_URL: string;
42
+ };
43
+
44
+ /**
45
+ * Define a query in this Convex app's public API.
46
+ *
47
+ * This function will be allowed to read your Convex database and will be accessible from the client.
48
+ *
49
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
50
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
51
+ */
52
+ export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
53
+
54
+ /**
55
+ * Define a query that is only accessible from other Convex functions (but not from the client).
56
+ *
57
+ * This function will be allowed to read from your Convex database. It will not be accessible from the client.
58
+ *
59
+ * @param func - The query function. It receives a {@link QueryCtx} as its first argument.
60
+ * @returns The wrapped query. Include this as an `export` to name it and make it accessible.
61
+ */
62
+ export const internalQuery: QueryBuilder<DataModel, "internal"> =
63
+ internalQueryGeneric;
64
+
65
+ /**
66
+ * Define a mutation in this Convex app's public API.
67
+ *
68
+ * This function will be allowed to modify your Convex database and will be accessible from the client.
69
+ *
70
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
71
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
72
+ */
73
+ export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
74
+
75
+ /**
76
+ * Define a mutation that is only accessible from other Convex functions (but not from the client).
77
+ *
78
+ * This function will be allowed to modify your Convex database. It will not be accessible from the client.
79
+ *
80
+ * @param func - The mutation function. It receives a {@link MutationCtx} as its first argument.
81
+ * @returns The wrapped mutation. Include this as an `export` to name it and make it accessible.
82
+ */
83
+ export const internalMutation: MutationBuilder<DataModel, "internal"> =
84
+ internalMutationGeneric;
85
+
86
+ /**
87
+ * Define an action in this Convex app's public API.
88
+ *
89
+ * An action is a function which can execute any JavaScript code, including non-deterministic
90
+ * code and code with side-effects, like calling third-party services.
91
+ * They can be run in Convex's JavaScript environment or in Node.js using the "use node" directive.
92
+ * They can interact with the database indirectly by calling queries and mutations using the {@link ActionCtx}.
93
+ *
94
+ * @param func - The action. It receives an {@link ActionCtx} as its first argument.
95
+ * @returns The wrapped action. Include this as an `export` to name it and make it accessible.
96
+ */
97
+ export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
98
+
99
+ /**
100
+ * Define an action that is only accessible from other Convex functions (but not from the client).
101
+ *
102
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument.
103
+ * @returns The wrapped function. Include this as an `export` to name it and make it accessible.
104
+ */
105
+ export const internalAction: ActionBuilder<DataModel, "internal"> =
106
+ internalActionGeneric;
107
+
108
+ /**
109
+ * Define an HTTP action.
110
+ *
111
+ * The wrapped function will be used to respond to HTTP requests received
112
+ * by a Convex deployment if the requests matches the path and method where
113
+ * this action is routed. Be sure to route your httpAction in `convex/http.js`.
114
+ *
115
+ * @param func - The function. It receives an {@link ActionCtx} as its first argument
116
+ * and a Fetch API `Request` object as its second.
117
+ * @returns The wrapped function. Import this function from `convex/http.js` and route it to hook it up.
118
+ */
119
+ export const httpAction: HttpActionBuilder = httpActionGeneric;
120
+ export const env: Env = (globalThis as unknown as { process: { env: Env } })
121
+ .process.env;
122
+
123
+ /**
124
+ * A set of services for use within Convex query functions.
125
+ *
126
+ * The query context is passed as the first argument to any Convex query
127
+ * function run on the server.
128
+ *
129
+ * If you're using code generation, use the `QueryCtx` type in `convex/_generated/server.d.ts` instead.
130
+ */
131
+ export type QueryCtx = GenericQueryCtx<DataModel>;
132
+
133
+ /**
134
+ * A set of services for use within Convex mutation functions.
135
+ *
136
+ * The mutation context is passed as the first argument to any Convex mutation
137
+ * function run on the server.
138
+ *
139
+ * If you're using code generation, use the `MutationCtx` type in `convex/_generated/server.d.ts` instead.
140
+ */
141
+ export type MutationCtx = GenericMutationCtx<DataModel>;
142
+
143
+ /**
144
+ * A set of services for use within Convex action functions.
145
+ *
146
+ * The action context is passed as the first argument to any Convex action
147
+ * function run on the server.
148
+ */
149
+ export type ActionCtx = GenericActionCtx<DataModel>;
150
+
151
+ /**
152
+ * An interface to read from the database within Convex query functions.
153
+ *
154
+ * The two entry points are {@link DatabaseReader.get}, which fetches a single
155
+ * document by its {@link Id}, or {@link DatabaseReader.query}, which starts
156
+ * building a query.
157
+ */
158
+ export type DatabaseReader = GenericDatabaseReader<DataModel>;
159
+
160
+ /**
161
+ * An interface to read from and write to the database within Convex mutation
162
+ * functions.
163
+ *
164
+ * Convex guarantees that all writes within a single mutation are
165
+ * executed atomically, so you never have to worry about partial writes leaving
166
+ * your data in an inconsistent state. See [the Convex Guide](https://docs.convex.dev/understanding/convex-fundamentals/functions#atomicity-and-optimistic-concurrency-control)
167
+ * for the guarantees Convex provides your functions.
168
+ */
169
+ export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,12 @@
1
+ import { defineComponent } from "convex/server";
2
+ import aggregate from "@convex-dev/aggregate/convex.config";
3
+ import shardedCounter from "@convex-dev/sharded-counter/convex.config";
4
+ import rateLimiter from "@convex-dev/rate-limiter/convex.config";
5
+
6
+ const component = defineComponent("analytics");
7
+
8
+ component.use(aggregate);
9
+ component.use(shardedCounter);
10
+ component.use(rateLimiter);
11
+
12
+ export default component;
@@ -0,0 +1,204 @@
1
+ import { httpRouter } from "convex/server";
2
+ import { httpAction } from "./_generated/server";
3
+ import { api } from "./_generated/api";
4
+
5
+ function json(data: unknown, status = 200): Response {
6
+ return new Response(JSON.stringify(data), {
7
+ status,
8
+ headers: { "Content-Type": "application/json" },
9
+ });
10
+ }
11
+
12
+ function error(message: string, status = 400): Response {
13
+ return json({ error: message }, status);
14
+ }
15
+
16
+ function timingSafeEqual(a: string, b: string): boolean {
17
+ if (a.length !== b.length) return false;
18
+ let result = 0;
19
+ for (let i = 0; i < a.length; i++) {
20
+ result |= a.charCodeAt(i) ^ b.charCodeAt(i);
21
+ }
22
+ return result === 0;
23
+ }
24
+
25
+ function scopeOf(value: unknown): string {
26
+ return typeof value === "string" && value.length > 0 ? value : "default";
27
+ }
28
+
29
+ /**
30
+ * Gate a request by API key. Keys are a JSON string array stored at config
31
+ * `(scope, "apiKeys")`. Returns an error Response on failure, else null.
32
+ */
33
+ async function requireApiKey(
34
+ ctx: { runQuery: (ref: never, args: never) => Promise<unknown> },
35
+ request: Request,
36
+ scope: string,
37
+ ): Promise<Response | null> {
38
+ const key = request.headers.get("x-api-key");
39
+ if (!key) return error("Missing x-api-key header", 401);
40
+ const config = await ctx.runQuery(api.queries.configGet as never, {
41
+ scope,
42
+ key: "apiKeys",
43
+ } as never);
44
+ if (!config) return error("API keys not configured", 401);
45
+ const keys = JSON.parse(config as string) as string[];
46
+ const matched = keys.some((stored) => timingSafeEqual(stored, key));
47
+ if (!matched) return error("Invalid API key", 401);
48
+ return null;
49
+ }
50
+
51
+ function parseJsonSafe(
52
+ request: Request,
53
+ ): Promise<{ ok: true; data: unknown } | { ok: false }> {
54
+ return request.json().then(
55
+ (data) => ({ ok: true as const, data }),
56
+ () => ({ ok: false as const }),
57
+ );
58
+ }
59
+
60
+ function getParams(request: Request): URLSearchParams {
61
+ return new URL(request.url).searchParams;
62
+ }
63
+
64
+ function range(params: URLSearchParams): { from?: number; to?: number } | undefined {
65
+ const from = params.get("from");
66
+ const to = params.get("to");
67
+ if (from === null && to === null) return undefined;
68
+ return {
69
+ from: from !== null ? Number(from) : undefined,
70
+ to: to !== null ? Number(to) : undefined,
71
+ };
72
+ }
73
+
74
+ export const trackEndpoint = httpAction(async (ctx, request) => {
75
+ const parsed = await parseJsonSafe(request);
76
+ if (!parsed.ok) return error("Invalid JSON body");
77
+ const body = parsed.data as Record<string, unknown>;
78
+
79
+ const scope = scopeOf(body["scope"]);
80
+ const authError = await requireApiKey(ctx, request, scope);
81
+ if (authError) return authError;
82
+
83
+ if (typeof body["name"] !== "string" || body["name"].length === 0) {
84
+ return error("name is required");
85
+ }
86
+ if (!Array.isArray(body["dimensions"])) {
87
+ return error("dimensions (string[]) is required");
88
+ }
89
+
90
+ const result = await ctx.runMutation(api.mutations.track as never, {
91
+ scope,
92
+ name: body["name"],
93
+ subjectRef: typeof body["subjectRef"] === "string" ? body["subjectRef"] : undefined,
94
+ sessionRef: typeof body["sessionRef"] === "string" ? body["sessionRef"] : undefined,
95
+ props: body["props"] ?? undefined,
96
+ ts: typeof body["ts"] === "number" ? body["ts"] : undefined,
97
+ dedupeKey: typeof body["dedupeKey"] === "string" ? body["dedupeKey"] : undefined,
98
+ dimensions: body["dimensions"],
99
+ granularities: Array.isArray(body["granularities"]) ? body["granularities"] : ["day"],
100
+ sampleRate: typeof body["sampleRate"] === "number" ? body["sampleRate"] : undefined,
101
+ } as never);
102
+
103
+ return json({ result }, 201);
104
+ });
105
+
106
+ export const metricEndpoint = httpAction(async (ctx, request) => {
107
+ const params = getParams(request);
108
+ const scope = scopeOf(params.get("scope"));
109
+ const authError = await requireApiKey(ctx, request, scope);
110
+ if (authError) return authError;
111
+
112
+ const name = params.get("name");
113
+ if (!name) return error("name parameter required");
114
+ const dim = params.get("dim");
115
+ const val = params.get("val");
116
+
117
+ const count = await ctx.runQuery(api.queries.metric as never, {
118
+ scope,
119
+ name,
120
+ range: range(params),
121
+ where: dim !== null && val !== null ? { dim, val } : undefined,
122
+ } as never);
123
+
124
+ return json({ name, count });
125
+ });
126
+
127
+ export const topEndpoint = httpAction(async (ctx, request) => {
128
+ const params = getParams(request);
129
+ const scope = scopeOf(params.get("scope"));
130
+ const authError = await requireApiKey(ctx, request, scope);
131
+ if (authError) return authError;
132
+
133
+ const name = params.get("name");
134
+ const dimension = params.get("dimension");
135
+ if (!name) return error("name parameter required");
136
+ if (!dimension) return error("dimension parameter required");
137
+
138
+ const result = await ctx.runQuery(api.queries.top as never, {
139
+ scope,
140
+ name,
141
+ dimension,
142
+ range: range(params),
143
+ limit: params.get("limit") ? Number(params.get("limit")) : undefined,
144
+ } as never);
145
+
146
+ return json(result);
147
+ });
148
+
149
+ export const timeseriesEndpoint = httpAction(async (ctx, request) => {
150
+ const params = getParams(request);
151
+ const scope = scopeOf(params.get("scope"));
152
+ const authError = await requireApiKey(ctx, request, scope);
153
+ if (authError) return authError;
154
+
155
+ const name = params.get("name");
156
+ if (!name) return error("name parameter required");
157
+ const granularity = params.get("granularity") ?? "day";
158
+ if (granularity !== "minute" && granularity !== "hour" && granularity !== "day") {
159
+ return error("granularity must be minute, hour, or day");
160
+ }
161
+
162
+ const result = await ctx.runQuery(api.queries.timeseries as never, {
163
+ scope,
164
+ name,
165
+ granularity,
166
+ range: range(params) ?? {},
167
+ } as never);
168
+
169
+ return json(result);
170
+ });
171
+
172
+ export const uniquesEndpoint = httpAction(async (ctx, request) => {
173
+ const params = getParams(request);
174
+ const scope = scopeOf(params.get("scope"));
175
+ const authError = await requireApiKey(ctx, request, scope);
176
+ if (authError) return authError;
177
+
178
+ const granularity = params.get("granularity") ?? "day";
179
+ if (granularity !== "minute" && granularity !== "hour" && granularity !== "day") {
180
+ return error("granularity must be minute, hour, or day");
181
+ }
182
+
183
+ const result = await ctx.runQuery(api.queries.uniques as never, {
184
+ scope,
185
+ granularity,
186
+ range: range(params) ?? {},
187
+ } as never);
188
+
189
+ return json(result);
190
+ });
191
+
192
+ /**
193
+ * Lean generic HTTP surface. Routes are namespaced under the host's chosen
194
+ * `httpPrefix` when the component is mounted with one. All routes require an
195
+ * `x-api-key` matching the JSON-array config at `(scope, "apiKeys")`.
196
+ */
197
+ const http = httpRouter();
198
+ http.route({ path: "/track", method: "POST", handler: trackEndpoint });
199
+ http.route({ path: "/metric", method: "GET", handler: metricEndpoint });
200
+ http.route({ path: "/top", method: "GET", handler: topEndpoint });
201
+ http.route({ path: "/timeseries", method: "GET", handler: timeseriesEndpoint });
202
+ http.route({ path: "/uniques", method: "GET", handler: uniquesEndpoint });
203
+
204
+ export default http;
@@ -0,0 +1,167 @@
1
+ import { internalMutation } from "./_generated/server";
2
+ import type { MutationCtx } from "./_generated/server";
3
+ import { v } from "convex/values";
4
+ import { granularitiesValidator } from "./validators.js";
5
+ import { bucketStart, valKey } from "../shared.js";
6
+ import type { Granularity } from "../shared.js";
7
+
8
+ const PRUNE_CAP = 10000;
9
+ const DAY_MS = 24 * 60 * 60 * 1000;
10
+ const DEFAULT_RETENTION_DAYS = 90;
11
+ const DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1000;
12
+ const TOTAL = "";
13
+
14
+ /** Read a numeric config value for a scope, falling back to a default. */
15
+ async function readNumber(
16
+ ctx: MutationCtx,
17
+ scope: string,
18
+ key: string,
19
+ fallback: number,
20
+ ): Promise<number> {
21
+ const entry = await ctx.db
22
+ .query("config")
23
+ .withIndex("by_scope_key", (q) => q.eq("scope", scope).eq("key", key))
24
+ .unique();
25
+ if (!entry) return fallback;
26
+ const n = Number(entry.value);
27
+ return Number.isFinite(n) ? n : fallback;
28
+ }
29
+
30
+ /** List every scope that has at least one config row (the scopes a cron should sweep). */
31
+ async function configuredScopes(ctx: MutationCtx): Promise<string[]> {
32
+ const rows = await ctx.db.query("config").collect();
33
+ return [...new Set(rows.map((r) => r.scope))];
34
+ }
35
+
36
+ /** Delete raw events past `retentionDays` for a scope. Rollups are kept forever. Idempotent. */
37
+ export const prune = internalMutation({
38
+ args: { scope: v.optional(v.string()) },
39
+ returns: v.object({ deleted: v.number() }),
40
+ handler: async (ctx, args) => {
41
+ const scopes = args.scope !== undefined ? [args.scope] : await configuredScopes(ctx);
42
+
43
+ const pruneScope = async (scope: string): Promise<number> => {
44
+ const retentionDays = await readNumber(
45
+ ctx,
46
+ scope,
47
+ "retentionDays",
48
+ DEFAULT_RETENTION_DAYS,
49
+ );
50
+ const cutoff = Date.now() - retentionDays * DAY_MS;
51
+ const oldest = await ctx.db
52
+ .query("events")
53
+ .withIndex("by_scope_name_ts", (q) => q.eq("scope", scope))
54
+ .order("asc")
55
+ .take(PRUNE_CAP);
56
+ const toDelete = oldest.filter((e) => e.ts < cutoff);
57
+ await Promise.all(toDelete.map((e) => ctx.db.delete("events", e._id)));
58
+ return toDelete.length;
59
+ };
60
+
61
+ const counts = await Promise.all(scopes.map(pruneScope));
62
+ return { deleted: counts.reduce((a, b) => a + b, 0) };
63
+ },
64
+ });
65
+
66
+ /** Close sessions idle past `sessionIdleMs` (set `endTs`). Idempotent. */
67
+ export const closeSessions = internalMutation({
68
+ args: { scope: v.optional(v.string()) },
69
+ returns: v.object({ closed: v.number() }),
70
+ handler: async (ctx, args) => {
71
+ const scopes = args.scope !== undefined ? [args.scope] : await configuredScopes(ctx);
72
+
73
+ const closeScope = async (scope: string): Promise<number> => {
74
+ const idleMs = await readNumber(
75
+ ctx,
76
+ scope,
77
+ "sessionIdleMs",
78
+ DEFAULT_SESSION_IDLE_MS,
79
+ );
80
+ const cutoff = Date.now() - idleMs;
81
+ const open = await ctx.db
82
+ .query("sessions")
83
+ .withIndex("by_scope_lastTs", (q) => q.eq("scope", scope).lt("lastTs", cutoff))
84
+ .take(1000);
85
+ const stale = open.filter((s) => s.endTs === undefined);
86
+ await Promise.all(
87
+ stale.map((s) => ctx.db.patch("sessions", s._id, { endTs: s.lastTs })),
88
+ );
89
+ return stale.length;
90
+ };
91
+
92
+ const counts = await Promise.all(scopes.map(closeScope));
93
+ return { closed: counts.reduce((a, b) => a + b, 0) };
94
+ },
95
+ });
96
+
97
+ /**
98
+ * Re-derive rollups from raw events for a `(scope, name)`. Idempotent: deletes
99
+ * existing rollup rows for the name, then recomputes from the retained raw events.
100
+ */
101
+ export const backfill = internalMutation({
102
+ args: {
103
+ scope: v.string(),
104
+ name: v.string(),
105
+ dimensions: v.array(v.string()),
106
+ granularities: granularitiesValidator,
107
+ },
108
+ returns: v.object({ events: v.number(), rows: v.number() }),
109
+ handler: async (ctx, args) => {
110
+ const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
111
+
112
+ const existing = await ctx.db
113
+ .query("rollups")
114
+ .withIndex("by_scope_name_dim_val", (q) =>
115
+ q.eq("scope", args.scope).eq("name", args.name),
116
+ )
117
+ .collect();
118
+ await Promise.all(existing.map((r) => ctx.db.delete("rollups", r._id)));
119
+
120
+ const events = await ctx.db
121
+ .query("events")
122
+ .withIndex("by_scope_name_ts", (q) =>
123
+ q.eq("scope", args.scope).eq("name", args.name),
124
+ )
125
+ .take(50000);
126
+
127
+ const counts = new Map<string, number>();
128
+ const meta = new Map<
129
+ string,
130
+ { gran: Granularity; bucket: number; dim: string; val: string }
131
+ >();
132
+ const bump = (gran: Granularity, bucket: number, dim: string, val: string): void => {
133
+ const k = `${gran}|${bucket}|${dim}|${val}`;
134
+ counts.set(k, (counts.get(k) ?? 0) + 1);
135
+ if (!meta.has(k)) meta.set(k, { gran, bucket, dim, val });
136
+ };
137
+
138
+ for (const e of events) {
139
+ for (const gran of grans) {
140
+ const bucket = bucketStart(e.ts, gran);
141
+ bump(gran, bucket, TOTAL, TOTAL);
142
+ for (const dim of args.dimensions) {
143
+ if (dim in e.props) {
144
+ bump(gran, bucket, dim, valKey(e.props[dim]!));
145
+ }
146
+ }
147
+ }
148
+ }
149
+
150
+ await Promise.all(
151
+ [...counts].map(([k, count]) => {
152
+ const m = meta.get(k)!;
153
+ return ctx.db.insert("rollups", {
154
+ scope: args.scope,
155
+ name: args.name,
156
+ granularity: m.gran,
157
+ bucket: m.bucket,
158
+ dim: m.dim,
159
+ val: m.val,
160
+ count,
161
+ });
162
+ }),
163
+ );
164
+
165
+ return { events: events.length, rows: counts.size };
166
+ },
167
+ });