@vllnt/convex-analytics 0.1.0-canary.e99d8e6 → 0.1.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 (62) hide show
  1. package/README.md +1 -12
  2. package/dist/client/index.d.ts.map +1 -1
  3. package/dist/client/index.js.map +1 -1
  4. package/dist/component/_generated/api.d.ts +30 -6
  5. package/dist/component/_generated/api.d.ts.map +1 -1
  6. package/dist/component/_generated/api.js +21 -2
  7. package/dist/component/_generated/api.js.map +1 -1
  8. package/dist/component/_generated/component.d.ts +181 -0
  9. package/dist/component/_generated/component.d.ts.map +1 -0
  10. package/dist/component/_generated/component.js +11 -0
  11. package/dist/component/_generated/component.js.map +1 -0
  12. package/dist/component/_generated/dataModel.d.ts +33 -0
  13. package/dist/component/_generated/dataModel.d.ts.map +1 -1
  14. package/dist/component/_generated/dataModel.js +3 -0
  15. package/dist/component/_generated/dataModel.js.map +1 -1
  16. package/dist/component/_generated/server.d.ts +113 -0
  17. package/dist/component/_generated/server.d.ts.map +1 -1
  18. package/dist/component/_generated/server.js +65 -0
  19. package/dist/component/_generated/server.js.map +1 -1
  20. package/dist/component/convex.config.d.ts +1 -1
  21. package/dist/component/convex.config.d.ts.map +1 -1
  22. package/dist/component/crons.d.ts +3 -0
  23. package/dist/component/crons.d.ts.map +1 -0
  24. package/dist/component/crons.js +7 -0
  25. package/dist/component/crons.js.map +1 -0
  26. package/dist/component/http.d.ts.map +1 -1
  27. package/dist/component/internal_mutations.d.ts +5 -2
  28. package/dist/component/internal_mutations.d.ts.map +1 -1
  29. package/dist/component/internal_mutations.js +72 -42
  30. package/dist/component/internal_mutations.js.map +1 -1
  31. package/dist/component/mutations.d.ts +11 -11
  32. package/dist/component/mutations.d.ts.map +1 -1
  33. package/dist/component/mutations.js +24 -9
  34. package/dist/component/mutations.js.map +1 -1
  35. package/dist/component/queries.d.ts +21 -21
  36. package/dist/component/queries.d.ts.map +1 -1
  37. package/dist/component/queries.js +20 -20
  38. package/dist/component/queries.js.map +1 -1
  39. package/dist/component/schema.d.ts +35 -26
  40. package/dist/component/schema.d.ts.map +1 -1
  41. package/dist/component/schema.js +6 -1
  42. package/dist/component/schema.js.map +1 -1
  43. package/dist/component/validators.d.ts +40 -40
  44. package/dist/shared.d.ts +2 -0
  45. package/dist/shared.d.ts.map +1 -1
  46. package/dist/shared.js +4 -0
  47. package/dist/shared.js.map +1 -1
  48. package/dist/test.d.ts +35 -26
  49. package/dist/test.d.ts.map +1 -1
  50. package/dist/test.js.map +1 -1
  51. package/dist/web/index.d.ts.map +1 -1
  52. package/package.json +24 -19
  53. package/src/component/_generated/api.ts +36 -9
  54. package/src/component/_generated/component.ts +196 -0
  55. package/src/component/_generated/dataModel.ts +36 -0
  56. package/src/component/_generated/server.ts +130 -3
  57. package/src/component/crons.ts +19 -0
  58. package/src/component/internal_mutations.ts +102 -55
  59. package/src/component/mutations.ts +26 -9
  60. package/src/component/queries.ts +22 -20
  61. package/src/component/schema.ts +7 -1
  62. package/src/shared.ts +5 -0
@@ -0,0 +1,196 @@
1
+ /* eslint-disable */
2
+ /**
3
+ * Generated `ComponentApi` utility.
4
+ *
5
+ * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
8
+ * @module
9
+ */
10
+
11
+ import type { FunctionReference } from "convex/server";
12
+
13
+ /**
14
+ * A utility for referencing a Convex component's exposed API.
15
+ *
16
+ * Useful when expecting a parameter like `components.myComponent`.
17
+ * Usage:
18
+ * ```ts
19
+ * async function myFunction(ctx: QueryCtx, component: ComponentApi) {
20
+ * return ctx.runQuery(component.someFile.someQuery, { ...args });
21
+ * }
22
+ * ```
23
+ */
24
+ export type ComponentApi<Name extends string | undefined = string | undefined> =
25
+ {
26
+ mutations: {
27
+ configSet: FunctionReference<
28
+ "mutation",
29
+ "internal",
30
+ { key: string; scope: string; value: string },
31
+ null,
32
+ Name
33
+ >;
34
+ configure: FunctionReference<
35
+ "mutation",
36
+ "internal",
37
+ {
38
+ retentionDays?: number;
39
+ sampleRate?: number;
40
+ scope: string;
41
+ sessionIdleMs?: number;
42
+ },
43
+ null,
44
+ Name
45
+ >;
46
+ track: FunctionReference<
47
+ "mutation",
48
+ "internal",
49
+ {
50
+ dedupeKey?: string;
51
+ dimensions: Array<string>;
52
+ granularities: Array<"minute" | "hour" | "day">;
53
+ name: string;
54
+ props?: Record<string, string | number | boolean | null>;
55
+ sampleRate?: number;
56
+ scope: string;
57
+ sessionRef?: string;
58
+ subjectRef?: string;
59
+ ts?: number;
60
+ },
61
+ "tracked" | "dropped" | "duplicate",
62
+ Name
63
+ >;
64
+ };
65
+ queries: {
66
+ configGet: FunctionReference<
67
+ "query",
68
+ "internal",
69
+ { key: string; scope: string },
70
+ string | null,
71
+ Name
72
+ >;
73
+ distribution: FunctionReference<
74
+ "query",
75
+ "internal",
76
+ {
77
+ buckets: Array<number>;
78
+ measure: string;
79
+ name: string;
80
+ range?: { from?: number; to?: number };
81
+ scope: string;
82
+ where?: { dim: string; val: string | number | boolean | null };
83
+ },
84
+ {
85
+ bins: Array<{ count: number; upper: number }>;
86
+ count: number;
87
+ overflow: number;
88
+ sum: number;
89
+ },
90
+ Name
91
+ >;
92
+ funnel: FunctionReference<
93
+ "query",
94
+ "internal",
95
+ {
96
+ range: { from?: number; to?: number };
97
+ scope: string;
98
+ steps: Array<string>;
99
+ },
100
+ Array<{ count: number; name: string; rate: number }>,
101
+ Name
102
+ >;
103
+ list: FunctionReference<
104
+ "query",
105
+ "internal",
106
+ {
107
+ name: string;
108
+ paginationOpts: { cursor: string | null; numItems: number };
109
+ scope: string;
110
+ },
111
+ {
112
+ continueCursor: string;
113
+ isDone: boolean;
114
+ page: Array<{
115
+ _creationTime: number;
116
+ _id: string;
117
+ dedupeKey?: string;
118
+ name: string;
119
+ props: Record<string, string | number | boolean | null>;
120
+ scope: string;
121
+ seq: number;
122
+ sessionRef?: string;
123
+ subjectRef?: string;
124
+ ts: number;
125
+ }>;
126
+ },
127
+ Name
128
+ >;
129
+ metric: FunctionReference<
130
+ "query",
131
+ "internal",
132
+ {
133
+ name: string;
134
+ range?: { from?: number; to?: number };
135
+ scope: string;
136
+ where?: { dim: string; val: string | number | boolean | null };
137
+ },
138
+ number,
139
+ Name
140
+ >;
141
+ retention: FunctionReference<
142
+ "query",
143
+ "internal",
144
+ {
145
+ cohortRange: { from?: number; to?: number };
146
+ granularity?: "minute" | "hour" | "day";
147
+ periods: number;
148
+ scope: string;
149
+ },
150
+ Array<{ cohort: number; retained: Array<number>; size: number }>,
151
+ Name
152
+ >;
153
+ timeseries: FunctionReference<
154
+ "query",
155
+ "internal",
156
+ {
157
+ granularity: "minute" | "hour" | "day";
158
+ name: string;
159
+ range: { from?: number; to?: number };
160
+ scope: string;
161
+ where?: { dim: string; val: string | number | boolean | null };
162
+ },
163
+ Array<{ bucket: number; count: number }>,
164
+ Name
165
+ >;
166
+ top: FunctionReference<
167
+ "query",
168
+ "internal",
169
+ {
170
+ dimension: string;
171
+ limit?: number;
172
+ name: string;
173
+ range?: { from?: number; to?: number };
174
+ scope: string;
175
+ },
176
+ Array<{ count: number; value: string }>,
177
+ Name
178
+ >;
179
+ uniques: FunctionReference<
180
+ "query",
181
+ "internal",
182
+ {
183
+ granularity: "minute" | "hour" | "day";
184
+ range: { from?: number; to?: number };
185
+ scope: string;
186
+ },
187
+ {
188
+ dau: number;
189
+ mau: number;
190
+ trend: Array<{ bucket: number; uniques: number }>;
191
+ wau: number;
192
+ },
193
+ Name
194
+ >;
195
+ };
196
+ };
@@ -1,7 +1,10 @@
1
1
  /* eslint-disable */
2
2
  /**
3
3
  * Generated data model types.
4
+ *
4
5
  * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
5
8
  * @module
6
9
  */
7
10
 
@@ -14,11 +17,44 @@ import type {
14
17
  import type { GenericId } from "convex/values";
15
18
  import schema from "../schema.js";
16
19
 
20
+ /**
21
+ * The names of all of your Convex tables.
22
+ */
17
23
  export type TableNames = TableNamesInDataModel<DataModel>;
24
+
25
+ /**
26
+ * The type of a document stored in Convex.
27
+ *
28
+ * @typeParam TableName - A string literal type of the table name (like "users").
29
+ */
18
30
  export type Doc<TableName extends TableNames> = DocumentByName<
19
31
  DataModel,
20
32
  TableName
21
33
  >;
34
+
35
+ /**
36
+ * An identifier for a document in Convex.
37
+ *
38
+ * Convex documents are uniquely identified by their `Id`, which is accessible
39
+ * on the `_id` field. To learn more, see [Document IDs](https://docs.convex.dev/using/document-ids).
40
+ *
41
+ * Documents can be loaded using `db.get(tableName, id)` in query and mutation functions.
42
+ *
43
+ * IDs are just strings at runtime, but this type can be used to distinguish them from other
44
+ * strings when type checking.
45
+ *
46
+ * @typeParam TableName - A string literal type of the table name (like "users").
47
+ */
22
48
  export type Id<TableName extends TableNames | SystemTableNames> =
23
49
  GenericId<TableName>;
50
+
51
+ /**
52
+ * A type describing your Convex data model.
53
+ *
54
+ * This type includes information about what tables you have, the type of
55
+ * documents stored in those tables, and the indexes defined on them.
56
+ *
57
+ * This type is used to parameterize methods like `queryGeneric` and
58
+ * `mutationGeneric` to make them type-safe.
59
+ */
24
60
  export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
@@ -1,7 +1,10 @@
1
1
  /* eslint-disable */
2
2
  /**
3
3
  * Generated utilities for implementing server-side Convex query and mutation functions.
4
+ *
4
5
  * THIS CODE IS AUTOMATICALLY GENERATED.
6
+ *
7
+ * To regenerate, run `npx convex dev`.
5
8
  * @module
6
9
  */
7
10
 
@@ -27,16 +30,140 @@ import {
27
30
  } from "convex/server";
28
31
  import type { DataModel } from "./dataModel.js";
29
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
+ */
30
52
  export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
31
- export const internalQuery: QueryBuilder<DataModel, "internal"> = internalQueryGeneric;
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
+ */
32
73
  export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
33
- export const internalMutation: MutationBuilder<DataModel, "internal"> = internalMutationGeneric;
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
+ */
34
97
  export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
35
- export const internalAction: ActionBuilder<DataModel, "internal"> = internalActionGeneric;
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
+ */
36
119
  export const httpAction: HttpActionBuilder = httpActionGeneric;
120
+ export const env: Env = (globalThis as unknown as { process: { env: Env } })
121
+ .process.env;
37
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
+ */
38
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
+ */
39
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
+ */
40
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
+ */
41
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
+ */
42
169
  export type DatabaseWriter = GenericDatabaseWriter<DataModel>;
@@ -0,0 +1,19 @@
1
+ import { cronJobs } from "convex/server";
2
+ import { internal } from "./_generated/api";
3
+
4
+ const crons = cronJobs();
5
+
6
+ crons.interval(
7
+ "analytics:close-sessions",
8
+ { minutes: 30 },
9
+ internal.internal_mutations.closeSessions,
10
+ {},
11
+ );
12
+ crons.interval(
13
+ "analytics:prune-events",
14
+ { hours: 24 },
15
+ internal.internal_mutations.prune,
16
+ {},
17
+ );
18
+
19
+ export default crons;
@@ -1,3 +1,4 @@
1
+ import { internal } from "./_generated/api";
1
2
  import { internalMutation } from "./_generated/server";
2
3
  import type { MutationCtx } from "./_generated/server";
3
4
  import { v } from "convex/values";
@@ -5,12 +6,18 @@ import { granularitiesValidator } from "./validators.js";
5
6
  import { bucketStart, valKey } from "../shared.js";
6
7
  import type { Granularity } from "../shared.js";
7
8
 
8
- const PRUNE_CAP = 10000;
9
+ const MAINTENANCE_CAP = 500;
9
10
  const DAY_MS = 24 * 60 * 60 * 1000;
10
11
  const DEFAULT_RETENTION_DAYS = 90;
11
12
  const DEFAULT_SESSION_IDLE_MS = 30 * 60 * 1000;
12
13
  const TOTAL = "";
13
14
 
15
+ export function guardBackfillSize(eventCount: number): void {
16
+ if (eventCount > 50000) {
17
+ throw new Error("backfill requires at most 50000 retained events; existing rollups were preserved");
18
+ }
19
+ }
20
+
14
21
  /** Read a numeric config value for a scope, falling back to a default. */
15
22
  async function readNumber(
16
23
  ctx: MutationCtx,
@@ -27,68 +34,107 @@ async function readNumber(
27
34
  return Number.isFinite(n) ? n : fallback;
28
35
  }
29
36
 
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
- }
37
+ const SCOPE_BATCH = 100;
35
38
 
36
39
  /** Delete raw events past `retentionDays` for a scope. Rollups are kept forever. Idempotent. */
37
40
  export const prune = internalMutation({
38
- args: { scope: v.optional(v.string()) },
41
+ args: { scope: v.optional(v.string()), afterScope: v.optional(v.string()) },
39
42
  returns: v.object({ deleted: v.number() }),
40
43
  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,
44
+ if (args.scope === undefined) {
45
+ const scopes = await ctx.db
46
+ .query("scopes")
47
+ .withIndex("by_scope", (q) =>
48
+ args.afterScope === undefined ? q : q.gt("scope", args.afterScope),
49
+ )
50
+ .take(SCOPE_BATCH);
51
+ await Promise.all(
52
+ scopes.map((row) =>
53
+ ctx.scheduler.runAfter(0, internal.internal_mutations.prune, {
54
+ scope: row.scope,
55
+ }),
56
+ ),
49
57
  );
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(e._id)));
58
- return toDelete.length;
59
- };
58
+ if (scopes.length === SCOPE_BATCH) {
59
+ await ctx.scheduler.runAfter(0, internal.internal_mutations.prune, {
60
+ afterScope: scopes[scopes.length - 1]!.scope,
61
+ });
62
+ }
63
+ return { deleted: 0 };
64
+ }
60
65
 
61
- const counts = await Promise.all(scopes.map(pruneScope));
62
- return { deleted: counts.reduce((a, b) => a + b, 0) };
66
+ const retentionDays = await readNumber(
67
+ ctx,
68
+ args.scope,
69
+ "retentionDays",
70
+ DEFAULT_RETENTION_DAYS,
71
+ );
72
+ const cutoff = Date.now() - retentionDays * DAY_MS;
73
+ const stale = await ctx.db
74
+ .query("events")
75
+ .withIndex("by_scope_ts", (q) => q.eq("scope", args.scope!).lt("ts", cutoff))
76
+ .take(MAINTENANCE_CAP);
77
+ await Promise.all(stale.map((event) => ctx.db.delete("events", event._id)));
78
+ if (stale.length === MAINTENANCE_CAP) {
79
+ await ctx.scheduler.runAfter(0, internal.internal_mutations.prune, {
80
+ scope: args.scope,
81
+ });
82
+ }
83
+ return { deleted: stale.length };
63
84
  },
64
85
  });
65
86
 
66
87
  /** Close sessions idle past `sessionIdleMs` (set `endTs`). Idempotent. */
67
88
  export const closeSessions = internalMutation({
68
- args: { scope: v.optional(v.string()) },
89
+ args: { scope: v.optional(v.string()), afterScope: v.optional(v.string()) },
69
90
  returns: v.object({ closed: v.number() }),
70
91
  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,
92
+ if (args.scope === undefined) {
93
+ const scopes = await ctx.db
94
+ .query("scopes")
95
+ .withIndex("by_scope", (q) =>
96
+ args.afterScope === undefined ? q : q.gt("scope", args.afterScope),
97
+ )
98
+ .take(SCOPE_BATCH);
99
+ await Promise.all(
100
+ scopes.map((row) =>
101
+ ctx.scheduler.runAfter(0, internal.internal_mutations.closeSessions, {
102
+ scope: row.scope,
103
+ }),
104
+ ),
79
105
  );
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(stale.map((s) => ctx.db.patch(s._id, { endTs: s.lastTs })));
87
- return stale.length;
88
- };
106
+ if (scopes.length === SCOPE_BATCH) {
107
+ await ctx.scheduler.runAfter(0, internal.internal_mutations.closeSessions, {
108
+ afterScope: scopes[scopes.length - 1]!.scope,
109
+ });
110
+ }
111
+ return { closed: 0 };
112
+ }
89
113
 
90
- const counts = await Promise.all(scopes.map(closeScope));
91
- return { closed: counts.reduce((a, b) => a + b, 0) };
114
+ const idleMs = await readNumber(
115
+ ctx,
116
+ args.scope,
117
+ "sessionIdleMs",
118
+ DEFAULT_SESSION_IDLE_MS,
119
+ );
120
+ const cutoff = Date.now() - idleMs;
121
+ const stale = await ctx.db
122
+ .query("sessions")
123
+ .withIndex("by_scope_endTs_lastTs", (q) =>
124
+ q.eq("scope", args.scope!).eq("endTs", undefined).lt("lastTs", cutoff),
125
+ )
126
+ .take(MAINTENANCE_CAP);
127
+ await Promise.all(
128
+ stale.map((session) =>
129
+ ctx.db.patch("sessions", session._id, { endTs: session.lastTs }),
130
+ ),
131
+ );
132
+ if (stale.length === MAINTENANCE_CAP) {
133
+ await ctx.scheduler.runAfter(0, internal.internal_mutations.closeSessions, {
134
+ scope: args.scope,
135
+ });
136
+ }
137
+ return { closed: stale.length };
92
138
  },
93
139
  });
94
140
 
@@ -107,20 +153,21 @@ export const backfill = internalMutation({
107
153
  handler: async (ctx, args) => {
108
154
  const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
109
155
 
156
+ const events = await ctx.db
157
+ .query("events")
158
+ .withIndex("by_scope_name_ts", (q) =>
159
+ q.eq("scope", args.scope).eq("name", args.name),
160
+ )
161
+ .take(50001);
162
+ guardBackfillSize(events.length);
163
+
110
164
  const existing = await ctx.db
111
165
  .query("rollups")
112
166
  .withIndex("by_scope_name_dim_val", (q) =>
113
167
  q.eq("scope", args.scope).eq("name", args.name),
114
168
  )
115
169
  .collect();
116
- await Promise.all(existing.map((r) => ctx.db.delete(r._id)));
117
-
118
- const events = await ctx.db
119
- .query("events")
120
- .withIndex("by_scope_name_ts", (q) =>
121
- q.eq("scope", args.scope).eq("name", args.name),
122
- )
123
- .take(50000);
170
+ await Promise.all(existing.map((r) => ctx.db.delete("rollups", r._id)));
124
171
 
125
172
  const counts = new Map<string, number>();
126
173
  const meta = new Map<