@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,255 @@
1
+ import { mutation } from "./_generated/server";
2
+ import type { MutationCtx } from "./_generated/server";
3
+ import { components } from "./_generated/api";
4
+ import { v } from "convex/values";
5
+ import { DirectAggregate } from "@convex-dev/aggregate";
6
+ import { ShardedCounter } from "@convex-dev/sharded-counter";
7
+ import { RateLimiter, MINUTE } from "@convex-dev/rate-limiter";
8
+ import { propsValidator, granularitiesValidator } from "./validators.js";
9
+ import { bucketStart, valKey } from "../shared.js";
10
+ import type { Granularity, Scalar } from "../shared.js";
11
+
12
+ type AggregateType = { Key: number; Id: string; Namespace: string };
13
+ const aggregate = new DirectAggregate<AggregateType>(components.aggregate as never);
14
+ const counter = new ShardedCounter(components.shardedCounter as never, {
15
+ defaultShards: 16,
16
+ });
17
+ const rateLimiter = new RateLimiter(components.rateLimiter as never, {
18
+ trackEvent: {
19
+ kind: "token bucket",
20
+ rate: 100,
21
+ period: MINUTE,
22
+ capacity: 10,
23
+ },
24
+ });
25
+
26
+ const TOTAL = "";
27
+
28
+ /** Increment one rollup row `(scope,name,gran,bucket,dim,val)` by 1, inserting if absent. */
29
+ async function bumpRollup(
30
+ ctx: MutationCtx,
31
+ scope: string,
32
+ name: string,
33
+ granularity: Granularity,
34
+ bucket: number,
35
+ dim: string,
36
+ val: string,
37
+ ): Promise<void> {
38
+ const existing = await ctx.db
39
+ .query("rollups")
40
+ .withIndex("by_scope_name_gran_bucket_dim", (q) =>
41
+ q
42
+ .eq("scope", scope)
43
+ .eq("name", name)
44
+ .eq("granularity", granularity)
45
+ .eq("bucket", bucket)
46
+ .eq("dim", dim)
47
+ .eq("val", val),
48
+ )
49
+ .unique();
50
+ if (existing) {
51
+ await ctx.db.patch("rollups", existing._id, { count: existing.count + 1 });
52
+ } else {
53
+ await ctx.db.insert("rollups", {
54
+ scope,
55
+ name,
56
+ granularity,
57
+ bucket,
58
+ dim,
59
+ val,
60
+ count: 1,
61
+ });
62
+ }
63
+ }
64
+
65
+ export const track = mutation({
66
+ args: {
67
+ scope: v.string(),
68
+ name: v.string(),
69
+ subjectRef: v.optional(v.string()),
70
+ sessionRef: v.optional(v.string()),
71
+ props: v.optional(propsValidator),
72
+ ts: v.optional(v.number()),
73
+ dedupeKey: v.optional(v.string()),
74
+ dimensions: v.array(v.string()),
75
+ granularities: granularitiesValidator,
76
+ sampleRate: v.optional(v.number()),
77
+ },
78
+ returns: v.union(v.literal("tracked"), v.literal("dropped"), v.literal("duplicate")),
79
+ handler: async (ctx, args) => {
80
+ const now = Date.now();
81
+ const scope = args.scope;
82
+ const ts = args.ts ?? now;
83
+ const props: Record<string, Scalar> = args.props ?? {};
84
+ const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
85
+
86
+ if (args.sessionRef !== undefined) {
87
+ const rl = await rateLimiter.limit(ctx, "trackEvent", { key: args.sessionRef });
88
+ if (!rl.ok) {
89
+ return "dropped";
90
+ }
91
+ }
92
+
93
+ const sampleRate = args.sampleRate ?? 1;
94
+ if (sampleRate < 1 && Math.random() >= sampleRate) {
95
+ return "dropped";
96
+ }
97
+
98
+ if (args.dedupeKey !== undefined) {
99
+ const dupe = await ctx.db
100
+ .query("events")
101
+ .withIndex("by_dedupe", (q) =>
102
+ q.eq("scope", scope).eq("dedupeKey", args.dedupeKey),
103
+ )
104
+ .first();
105
+ if (dupe) {
106
+ return "duplicate";
107
+ }
108
+ }
109
+
110
+ let sessionDoc = null;
111
+ if (args.sessionRef !== undefined) {
112
+ sessionDoc = await ctx.db
113
+ .query("sessions")
114
+ .withIndex("by_scope_session", (q) =>
115
+ q.eq("scope", scope).eq("sessionRef", args.sessionRef!),
116
+ )
117
+ .unique();
118
+ }
119
+ const seq = sessionDoc ? sessionDoc.eventCount : 0;
120
+
121
+ const eventId = await ctx.db.insert("events", {
122
+ scope,
123
+ name: args.name,
124
+ subjectRef: args.subjectRef,
125
+ sessionRef: args.sessionRef,
126
+ props,
127
+ ts,
128
+ seq,
129
+ dedupeKey: args.dedupeKey,
130
+ });
131
+
132
+ if (args.sessionRef !== undefined) {
133
+ if (sessionDoc) {
134
+ await ctx.db.patch("sessions", sessionDoc._id, {
135
+ lastTs: ts,
136
+ eventCount: sessionDoc.eventCount + 1,
137
+ subjectRef: args.subjectRef ?? sessionDoc.subjectRef,
138
+ });
139
+ } else {
140
+ await ctx.db.insert("sessions", {
141
+ scope,
142
+ sessionRef: args.sessionRef,
143
+ subjectRef: args.subjectRef,
144
+ startTs: ts,
145
+ lastTs: ts,
146
+ eventCount: 1,
147
+ });
148
+ }
149
+ }
150
+
151
+ if (args.subjectRef !== undefined) {
152
+ const subject = await ctx.db
153
+ .query("subjects")
154
+ .withIndex("by_scope_subject", (q) =>
155
+ q.eq("scope", scope).eq("subjectRef", args.subjectRef!),
156
+ )
157
+ .unique();
158
+ if (subject) {
159
+ await ctx.db.patch("subjects", subject._id, {
160
+ lastSeen: ts > subject.lastSeen ? ts : subject.lastSeen,
161
+ firstSeen: ts < subject.firstSeen ? ts : subject.firstSeen,
162
+ eventCount: subject.eventCount + 1,
163
+ });
164
+ } else {
165
+ await ctx.db.insert("subjects", {
166
+ scope,
167
+ subjectRef: args.subjectRef,
168
+ firstSeen: ts,
169
+ lastSeen: ts,
170
+ eventCount: 1,
171
+ });
172
+ }
173
+ }
174
+
175
+ for (const granularity of grans) {
176
+ const bucket = bucketStart(ts, granularity);
177
+ await bumpRollup(ctx, scope, args.name, granularity, bucket, TOTAL, TOTAL);
178
+ for (const dim of args.dimensions) {
179
+ if (dim in props) {
180
+ await bumpRollup(
181
+ ctx,
182
+ scope,
183
+ args.name,
184
+ granularity,
185
+ bucket,
186
+ dim,
187
+ valKey(props[dim]!),
188
+ );
189
+ }
190
+ }
191
+ }
192
+
193
+ await aggregate.insert(ctx, {
194
+ key: ts,
195
+ id: eventId as string,
196
+ namespace: `${scope}:${args.name}`,
197
+ });
198
+ await counter.add(ctx, `${scope}:${args.name}`);
199
+
200
+ return "tracked";
201
+ },
202
+ });
203
+
204
+ /** Insert-or-patch a single `(scope, key)` config row. */
205
+ async function upsertConfig(
206
+ ctx: MutationCtx,
207
+ scope: string,
208
+ key: string,
209
+ value: string,
210
+ ): Promise<void> {
211
+ const existing = await ctx.db
212
+ .query("config")
213
+ .withIndex("by_scope_key", (q) => q.eq("scope", scope).eq("key", key))
214
+ .unique();
215
+ if (existing) {
216
+ await ctx.db.patch("config", existing._id, { value });
217
+ } else {
218
+ await ctx.db.insert("config", { scope, key, value });
219
+ }
220
+ }
221
+
222
+ export const configSet = mutation({
223
+ args: { scope: v.string(), key: v.string(), value: v.string() },
224
+ returns: v.null(),
225
+ handler: async (ctx, args) => {
226
+ await upsertConfig(ctx, args.scope, args.key, args.value);
227
+ return null;
228
+ },
229
+ });
230
+
231
+ export const configure = mutation({
232
+ args: {
233
+ scope: v.string(),
234
+ retentionDays: v.optional(v.number()),
235
+ sampleRate: v.optional(v.number()),
236
+ sessionIdleMs: v.optional(v.number()),
237
+ },
238
+ returns: v.null(),
239
+ handler: async (ctx, args) => {
240
+ const entries: Array<[string, string]> = [];
241
+ if (args.retentionDays !== undefined) {
242
+ entries.push(["retentionDays", String(args.retentionDays)]);
243
+ }
244
+ if (args.sampleRate !== undefined) {
245
+ entries.push(["sampleRate", String(args.sampleRate)]);
246
+ }
247
+ if (args.sessionIdleMs !== undefined) {
248
+ entries.push(["sessionIdleMs", String(args.sessionIdleMs)]);
249
+ }
250
+ await Promise.all(
251
+ entries.map(([key, value]) => upsertConfig(ctx, args.scope, key, value)),
252
+ );
253
+ return null;
254
+ },
255
+ });
@@ -0,0 +1,436 @@
1
+ import { query } from "./_generated/server";
2
+ import { components } from "./_generated/api";
3
+ import { v } from "convex/values";
4
+ import { ShardedCounter } from "@convex-dev/sharded-counter";
5
+ import {
6
+ rangeValidator,
7
+ whereValidator,
8
+ granularityValidator,
9
+ topRow,
10
+ timeseriesPoint,
11
+ uniquesView,
12
+ funnelStep,
13
+ retentionCohort,
14
+ eventPage,
15
+ distributionView,
16
+ } from "./validators.js";
17
+ import { bucketStart, bucketSize, valKey } from "../shared.js";
18
+ import type { Granularity } from "../shared.js";
19
+
20
+ const counter = new ShardedCounter(components.shardedCounter as never, {
21
+ defaultShards: 16,
22
+ });
23
+
24
+ const TOTAL = "";
25
+
26
+ /** Total event count over a range, optionally filtered by one dimension value. */
27
+ export const metric = query({
28
+ args: {
29
+ scope: v.string(),
30
+ name: v.string(),
31
+ range: v.optional(rangeValidator),
32
+ where: v.optional(whereValidator),
33
+ },
34
+ returns: v.number(),
35
+ handler: async (ctx, args) => {
36
+ const dim = args.where ? args.where.dim : TOTAL;
37
+ const val = args.where ? valKey(args.where.val) : TOTAL;
38
+
39
+ if (!args.range && !args.where) {
40
+ return await counter.count(ctx, `${args.scope}:${args.name}`);
41
+ }
42
+
43
+ const rollups = await ctx.db
44
+ .query("rollups")
45
+ .withIndex("by_scope_name_gran_bucket_dim", (q) =>
46
+ q
47
+ .eq("scope", args.scope)
48
+ .eq("name", args.name)
49
+ .eq("granularity", "day"),
50
+ )
51
+ .collect();
52
+
53
+ let total = 0;
54
+ for (const r of rollups) {
55
+ if (r.dim !== dim || r.val !== val) continue;
56
+ if (args.range?.from !== undefined && r.bucket < bucketStart(args.range.from, "day")) {
57
+ continue;
58
+ }
59
+ if (args.range?.to !== undefined && r.bucket > bucketStart(args.range.to, "day")) {
60
+ continue;
61
+ }
62
+ total += r.count;
63
+ }
64
+ return total;
65
+ },
66
+ });
67
+
68
+ /** Top values of a dimension (breakdown), ranked by count. */
69
+ export const top = query({
70
+ args: {
71
+ scope: v.string(),
72
+ name: v.string(),
73
+ dimension: v.string(),
74
+ range: v.optional(rangeValidator),
75
+ limit: v.optional(v.number()),
76
+ },
77
+ returns: v.array(topRow),
78
+ handler: async (ctx, args) => {
79
+ const limit = Math.min(args.limit ?? 20, 100);
80
+ const rollups = await ctx.db
81
+ .query("rollups")
82
+ .withIndex("by_scope_name_gran_bucket_dim", (q) =>
83
+ q
84
+ .eq("scope", args.scope)
85
+ .eq("name", args.name)
86
+ .eq("granularity", "day"),
87
+ )
88
+ .collect();
89
+
90
+ const counts = new Map<string, number>();
91
+ for (const r of rollups) {
92
+ if (r.dim !== args.dimension) continue;
93
+ if (args.range?.from !== undefined && r.bucket < bucketStart(args.range.from, "day")) {
94
+ continue;
95
+ }
96
+ if (args.range?.to !== undefined && r.bucket > bucketStart(args.range.to, "day")) {
97
+ continue;
98
+ }
99
+ counts.set(r.val, (counts.get(r.val) ?? 0) + r.count);
100
+ }
101
+
102
+ return [...counts.entries()]
103
+ .map(([value, count]) => ({ value, count }))
104
+ .sort((a, b) => b.count - a.count)
105
+ .slice(0, limit);
106
+ },
107
+ });
108
+
109
+ /** Bucketed counts over a range, optionally filtered by one dimension value. */
110
+ export const timeseries = query({
111
+ args: {
112
+ scope: v.string(),
113
+ name: v.string(),
114
+ granularity: granularityValidator,
115
+ range: rangeValidator,
116
+ where: v.optional(whereValidator),
117
+ },
118
+ returns: v.array(timeseriesPoint),
119
+ handler: async (ctx, args) => {
120
+ const gran: Granularity = args.granularity;
121
+ const dim = args.where ? args.where.dim : TOTAL;
122
+ const val = args.where ? valKey(args.where.val) : TOTAL;
123
+
124
+ const rollups = await ctx.db
125
+ .query("rollups")
126
+ .withIndex("by_scope_name_gran_bucket_dim", (q) =>
127
+ q.eq("scope", args.scope).eq("name", args.name).eq("granularity", gran),
128
+ )
129
+ .collect();
130
+
131
+ const fromBucket =
132
+ args.range.from !== undefined ? bucketStart(args.range.from, gran) : undefined;
133
+ const toBucket =
134
+ args.range.to !== undefined ? bucketStart(args.range.to, gran) : undefined;
135
+
136
+ const counts = new Map<number, number>();
137
+ for (const r of rollups) {
138
+ if (r.dim !== dim || r.val !== val) continue;
139
+ if (fromBucket !== undefined && r.bucket < fromBucket) continue;
140
+ if (toBucket !== undefined && r.bucket > toBucket) continue;
141
+ counts.set(r.bucket, (counts.get(r.bucket) ?? 0) + r.count);
142
+ }
143
+
144
+ return [...counts.entries()]
145
+ .map(([bucket, count]) => ({ bucket, count }))
146
+ .sort((a, b) => a.bucket - b.bucket);
147
+ },
148
+ });
149
+
150
+ /** DAU/WAU/MAU distinct-subject counts from the subjects table. */
151
+ export const uniques = query({
152
+ args: {
153
+ scope: v.string(),
154
+ range: rangeValidator,
155
+ granularity: granularityValidator,
156
+ },
157
+ returns: uniquesView,
158
+ handler: async (ctx, args) => {
159
+ const now = Date.now();
160
+ const to = args.range.to ?? now;
161
+ const from = args.range.from ?? to - 30 * 24 * 60 * 60 * 1000;
162
+
163
+ const subjects = await ctx.db
164
+ .query("subjects")
165
+ .withIndex("by_scope_firstSeen", (q) => q.eq("scope", args.scope))
166
+ .collect();
167
+
168
+ const size = bucketSize(args.granularity);
169
+ const trendBuckets = new Map<number, Set<string>>();
170
+ let mau = 0;
171
+ let wau = 0;
172
+ const dayMs = 24 * 60 * 60 * 1000;
173
+ const wauCutoff = to - 7 * dayMs;
174
+ const mauCutoff = to - 30 * dayMs;
175
+
176
+ for (const s of subjects) {
177
+ if (s.lastSeen < from || s.lastSeen > to) continue;
178
+ mau += s.lastSeen >= mauCutoff ? 1 : 0;
179
+ wau += s.lastSeen >= wauCutoff ? 1 : 0;
180
+ const bucket = Math.floor(s.lastSeen / size) * size;
181
+ const set = trendBuckets.get(bucket) ?? new Set<string>();
182
+ set.add(s.subjectRef);
183
+ trendBuckets.set(bucket, set);
184
+ }
185
+
186
+ const trend = [...trendBuckets.entries()]
187
+ .map(([bucket, set]) => ({ bucket, uniques: set.size }))
188
+ .sort((a, b) => a.bucket - b.bucket);
189
+
190
+ const dau =
191
+ trend.length > 0
192
+ ? Math.round(trend.reduce((sum, p) => sum + p.uniques, 0) / trend.length)
193
+ : 0;
194
+
195
+ return { dau, wau, mau, trend };
196
+ },
197
+ });
198
+
199
+ /** Ordered step conversion over raw events, keyed by subjectRef. */
200
+ export const funnel = query({
201
+ args: {
202
+ scope: v.string(),
203
+ steps: v.array(v.string()),
204
+ range: rangeValidator,
205
+ },
206
+ returns: v.array(funnelStep),
207
+ handler: async (ctx, args) => {
208
+ if (args.steps.length < 2) {
209
+ throw new Error("Funnel requires at least 2 steps");
210
+ }
211
+ const now = Date.now();
212
+ const to = args.range.to ?? now;
213
+ const from = args.range.from ?? to - 30 * 24 * 60 * 60 * 1000;
214
+
215
+ const stepSubjects = await Promise.all(
216
+ args.steps.map(async (step) => {
217
+ const events = await ctx.db
218
+ .query("events")
219
+ .withIndex("by_scope_name_ts", (q) =>
220
+ q.eq("scope", args.scope).eq("name", step).gte("ts", from).lte("ts", to),
221
+ )
222
+ .take(10000);
223
+ const firstTs = new Map<string, number>();
224
+ for (const e of events) {
225
+ if (e.subjectRef === undefined) continue;
226
+ const prev = firstTs.get(e.subjectRef);
227
+ if (prev === undefined || e.ts < prev) {
228
+ firstTs.set(e.subjectRef, e.ts);
229
+ }
230
+ }
231
+ return firstTs;
232
+ }),
233
+ );
234
+
235
+ const results: Array<{ name: string; count: number; rate: number }> = [];
236
+ let qualified = new Set(stepSubjects[0]!.keys());
237
+ let firstCount = qualified.size;
238
+ results.push({ name: args.steps[0]!, count: firstCount, rate: 1 });
239
+
240
+ for (let i = 1; i < args.steps.length; i++) {
241
+ const prevTimes = stepSubjects[i - 1]!;
242
+ const thisTimes = stepSubjects[i]!;
243
+ const next = new Set<string>();
244
+ for (const subject of qualified) {
245
+ const prevTs = prevTimes.get(subject);
246
+ const thisTs = thisTimes.get(subject);
247
+ if (prevTs !== undefined && thisTs !== undefined && thisTs >= prevTs) {
248
+ next.add(subject);
249
+ }
250
+ }
251
+ results.push({
252
+ name: args.steps[i]!,
253
+ count: next.size,
254
+ rate: firstCount > 0 ? next.size / firstCount : 0,
255
+ });
256
+ qualified = next;
257
+ }
258
+
259
+ return results;
260
+ },
261
+ });
262
+
263
+ /** Cohort return rates by first-seen period. */
264
+ export const retention = query({
265
+ args: {
266
+ scope: v.string(),
267
+ cohortRange: rangeValidator,
268
+ periods: v.number(),
269
+ granularity: v.optional(granularityValidator),
270
+ },
271
+ returns: v.array(retentionCohort),
272
+ handler: async (ctx, args) => {
273
+ const gran: Granularity = args.granularity ?? "day";
274
+ const size = bucketSize(gran);
275
+ const now = Date.now();
276
+ const to = args.cohortRange.to ?? now;
277
+ const from = args.cohortRange.from ?? to - args.periods * size;
278
+ const periods = Math.min(args.periods, 30);
279
+
280
+ const subjects = await ctx.db
281
+ .query("subjects")
282
+ .withIndex("by_scope_firstSeen", (q) =>
283
+ q.eq("scope", args.scope).gte("firstSeen", from).lte("firstSeen", to),
284
+ )
285
+ .take(10000);
286
+
287
+ const cohortMap = new Map<
288
+ number,
289
+ Array<{ firstSeen: number; lastSeen: number }>
290
+ >();
291
+ for (const s of subjects) {
292
+ const cohort = Math.floor(s.firstSeen / size) * size;
293
+ const list = cohortMap.get(cohort) ?? [];
294
+ list.push({ firstSeen: s.firstSeen, lastSeen: s.lastSeen });
295
+ cohortMap.set(cohort, list);
296
+ }
297
+
298
+ return [...cohortMap.entries()]
299
+ .sort((a, b) => a[0] - b[0])
300
+ .map(([cohort, members]) => {
301
+ const retained: number[] = [];
302
+ for (let p = 1; p <= periods; p++) {
303
+ const periodStart = cohort + p * size;
304
+ const periodEnd = periodStart + size;
305
+ let count = 0;
306
+ for (const m of members) {
307
+ if (m.lastSeen >= periodStart && m.lastSeen < periodEnd) count++;
308
+ }
309
+ retained.push(count / members.length);
310
+ }
311
+ return { cohort, size: members.length, retained };
312
+ });
313
+ },
314
+ });
315
+
316
+ /**
317
+ * Histogram of a numeric measure over raw events: ascending upper-bound bins +
318
+ * an overflow bucket. A value `m` falls in the first bin whose `upper >= m`;
319
+ * values above the last bound land in `overflow`. Non-numeric measure values are
320
+ * ignored. `count`/`sum` give the population size and total (so mean = sum/count).
321
+ * Index-backed (`by_scope_name_ts`) and bounded — computed from raw events, like
322
+ * `funnel`/`retention`.
323
+ */
324
+ export const distribution = query({
325
+ args: {
326
+ scope: v.string(),
327
+ name: v.string(),
328
+ measure: v.string(),
329
+ buckets: v.array(v.number()),
330
+ range: v.optional(rangeValidator),
331
+ where: v.optional(whereValidator),
332
+ },
333
+ returns: distributionView,
334
+ handler: async (ctx, args) => {
335
+ const bins = [...args.buckets]
336
+ .sort((a, b) => a - b)
337
+ .map((upper) => ({ upper, count: 0 }));
338
+ let overflow = 0;
339
+ let count = 0;
340
+ let sum = 0;
341
+
342
+ const now = Date.now();
343
+ const to = args.range?.to ?? now;
344
+ const from = args.range?.from ?? 0;
345
+
346
+ const events = await ctx.db
347
+ .query("events")
348
+ .withIndex("by_scope_name_ts", (q) =>
349
+ q.eq("scope", args.scope).eq("name", args.name).gte("ts", from).lte("ts", to),
350
+ )
351
+ .take(50000);
352
+
353
+ for (const e of events) {
354
+ if (args.where) {
355
+ const pv = e.props[args.where.dim];
356
+ if (pv === undefined || valKey(pv) !== valKey(args.where.val)) continue;
357
+ }
358
+ const m = e.props[args.measure];
359
+ if (typeof m !== "number") continue;
360
+ count += 1;
361
+ sum += m;
362
+ const bin = bins.find((b) => m <= b.upper);
363
+ if (bin) {
364
+ bin.count += 1;
365
+ } else {
366
+ overflow += 1;
367
+ }
368
+ }
369
+
370
+ return { bins, overflow, count, sum };
371
+ },
372
+ });
373
+
374
+ /** Paginated raw events for an event name, newest first. */
375
+ export const list = query({
376
+ args: {
377
+ scope: v.string(),
378
+ name: v.string(),
379
+ paginationOpts: v.object({
380
+ numItems: v.number(),
381
+ cursor: v.union(v.string(), v.null()),
382
+ }),
383
+ },
384
+ returns: eventPage,
385
+ handler: async (ctx, args) => {
386
+ // `.paginate()` is not supported inside a Convex component, so paginate
387
+ // manually with a `ts`-keyed cursor (newest-first). Bounded + index-backed.
388
+ // Note: events sharing the exact boundary `ts` may be skipped across a page
389
+ // edge — adequate for a raw-event peek; precise feeds belong in the host.
390
+ const { numItems, cursor } = args.paginationOpts;
391
+ const before = cursor ? Number(cursor) : null;
392
+ const rows = await ctx.db
393
+ .query("events")
394
+ .withIndex("by_scope_name_ts", (q) => {
395
+ const base = q.eq("scope", args.scope).eq("name", args.name);
396
+ return before !== null ? base.lt("ts", before) : base;
397
+ })
398
+ .order("desc")
399
+ .take(numItems + 1);
400
+
401
+ const hasMore = rows.length > numItems;
402
+ const page = hasMore ? rows.slice(0, numItems) : rows;
403
+ const last = page.length > 0 ? page[page.length - 1]! : null;
404
+ return {
405
+ page: page.map((e) => ({
406
+ _id: e._id as string,
407
+ _creationTime: e._creationTime,
408
+ scope: e.scope,
409
+ name: e.name,
410
+ subjectRef: e.subjectRef,
411
+ sessionRef: e.sessionRef,
412
+ props: e.props,
413
+ ts: e.ts,
414
+ seq: e.seq,
415
+ dedupeKey: e.dedupeKey,
416
+ })),
417
+ isDone: !hasMore,
418
+ continueCursor: last ? String(last.ts) : "",
419
+ };
420
+ },
421
+ });
422
+
423
+ /** Read a single config value for a scope. */
424
+ export const configGet = query({
425
+ args: { scope: v.string(), key: v.string() },
426
+ returns: v.union(v.string(), v.null()),
427
+ handler: async (ctx, args) => {
428
+ const entry = await ctx.db
429
+ .query("config")
430
+ .withIndex("by_scope_key", (q) =>
431
+ q.eq("scope", args.scope).eq("key", args.key),
432
+ )
433
+ .unique();
434
+ return entry?.value ?? null;
435
+ },
436
+ });