@vllnt/convex-analytics 0.2.0-canary.7ef4d35 → 0.2.0-canary.dee16f7

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.
@@ -2,7 +2,7 @@ import { internal } from "./_generated/api.js";
2
2
  import { internalMutation } from "./_generated/server.js";
3
3
  import type { MutationCtx } from "./_generated/server.js";
4
4
  import { v } from "convex/values";
5
- import { granularitiesValidator } from "./validators.js";
5
+ import { assertNonEmpty, granularitiesValidator } from "./validators.js";
6
6
  import { bucketStart, valKey } from "../shared.js";
7
7
  import type { Granularity } from "../shared.js";
8
8
 
@@ -18,7 +18,11 @@ export function guardBackfillSize(eventCount: number): void {
18
18
  }
19
19
  }
20
20
 
21
- /** Read a numeric config value for a scope, falling back to a default. */
21
+ /**
22
+ * Read a positive numeric config value for a scope, falling back to the default. A stored value
23
+ * that is not a finite positive number (for example `"0"` written before `configSet` checked it)
24
+ * is ignored, so it can never move the prune cutoff to now or later.
25
+ */
22
26
  async function readNumber(
23
27
  ctx: MutationCtx,
24
28
  scope: string,
@@ -31,7 +35,7 @@ async function readNumber(
31
35
  .unique();
32
36
  if (!entry) return fallback;
33
37
  const n = Number(entry.value);
34
- return Number.isFinite(n) ? n : fallback;
38
+ return Number.isFinite(n) && n > 0 ? n : fallback;
35
39
  }
36
40
 
37
41
  const SCOPE_BATCH = 100;
@@ -151,7 +155,13 @@ export const backfill = internalMutation({
151
155
  },
152
156
  returns: v.object({ events: v.number(), rows: v.number() }),
153
157
  handler: async (ctx, args) => {
154
- const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
158
+ assertNonEmpty("scope", args.scope);
159
+ assertNonEmpty("name", args.name);
160
+ for (const dim of args.dimensions) assertNonEmpty("dimensions[]", dim);
161
+ // Each distinct dimension / granularity counts once, however often it is listed.
162
+ const dimensions = [...new Set(args.dimensions)];
163
+ const grans: readonly Granularity[] =
164
+ args.granularities.length > 0 ? [...new Set(args.granularities)] : ["day"];
155
165
 
156
166
  const events = await ctx.db
157
167
  .query("events")
@@ -184,7 +194,7 @@ export const backfill = internalMutation({
184
194
  for (const gran of grans) {
185
195
  const bucket = bucketStart(e.ts, gran);
186
196
  bump(gran, bucket, TOTAL, TOTAL);
187
- for (const dim of args.dimensions) {
197
+ for (const dim of dimensions) {
188
198
  if (Object.hasOwn(e.props, dim)) {
189
199
  bump(gran, bucket, dim, valKey(e.props[dim]!));
190
200
  }
@@ -10,8 +10,10 @@ import {
10
10
  assertProps,
11
11
  assertFiniteTs,
12
12
  assertNonEmpty,
13
+ assertRefLength,
13
14
  assertSampleRate,
14
- invalidInput,
15
+ assertPositiveConfig,
16
+ assertConfigValue,
15
17
  } from "./validators.js";
16
18
  import { bucketStart, tupleKey, valKey } from "../shared.js";
17
19
  import type { Granularity, Scalar } from "../shared.js";
@@ -77,6 +79,12 @@ async function bumpRollup(
77
79
  }
78
80
  }
79
81
 
82
+ /** A string a write stores in an index key: not empty, at most 512 characters. */
83
+ function assertWriteRef(field: string, value: string | undefined): void {
84
+ assertNonEmpty(field, value);
85
+ assertRefLength(field, value);
86
+ }
87
+
80
88
  export const track = mutation({
81
89
  args: {
82
90
  scope: v.string(),
@@ -92,12 +100,12 @@ export const track = mutation({
92
100
  },
93
101
  returns: v.union(v.literal("tracked"), v.literal("dropped"), v.literal("duplicate")),
94
102
  handler: async (ctx, args) => {
95
- assertNonEmpty("scope", args.scope);
96
- assertNonEmpty("name", args.name);
97
- assertNonEmpty("subjectRef", args.subjectRef);
98
- assertNonEmpty("sessionRef", args.sessionRef);
99
- assertNonEmpty("dedupeKey", args.dedupeKey);
100
- for (const dim of args.dimensions) assertNonEmpty("dimensions[]", dim);
103
+ assertWriteRef("scope", args.scope);
104
+ assertWriteRef("name", args.name);
105
+ assertWriteRef("subjectRef", args.subjectRef);
106
+ assertWriteRef("sessionRef", args.sessionRef);
107
+ assertWriteRef("dedupeKey", args.dedupeKey);
108
+ for (const dim of args.dimensions) assertWriteRef("dimensions[]", dim);
101
109
  assertFiniteTs("ts", args.ts);
102
110
  assertSampleRate(args.sampleRate);
103
111
  const props: Record<string, Scalar> = args.props ?? {};
@@ -106,7 +114,10 @@ export const track = mutation({
106
114
  const now = Date.now();
107
115
  const scope = args.scope;
108
116
  const ts = args.ts ?? now;
109
- const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
117
+ // Each distinct dimension / granularity counts once, however often it is listed.
118
+ const dimensions = [...new Set(args.dimensions)];
119
+ const grans: readonly Granularity[] =
120
+ args.granularities.length > 0 ? [...new Set(args.granularities)] : ["day"];
110
121
 
111
122
  if (args.sessionRef !== undefined) {
112
123
  const rl = await rateLimiter.limit(ctx, "trackEvent", {
@@ -205,7 +216,7 @@ export const track = mutation({
205
216
  for (const granularity of grans) {
206
217
  const bucket = bucketStart(ts, granularity);
207
218
  await bumpRollup(ctx, scope, args.name, granularity, bucket, TOTAL, TOTAL);
208
- for (const dim of args.dimensions) {
219
+ for (const dim of dimensions) {
209
220
  if (Object.hasOwn(props, dim)) {
210
221
  await bumpRollup(
211
222
  ctx,
@@ -248,8 +259,9 @@ export const configSet = mutation({
248
259
  args: { scope: v.string(), key: v.string(), value: v.string() },
249
260
  returns: v.null(),
250
261
  handler: async (ctx, args) => {
251
- assertNonEmpty("scope", args.scope);
252
- assertNonEmpty("key", args.key);
262
+ assertWriteRef("scope", args.scope);
263
+ assertWriteRef("key", args.key);
264
+ assertConfigValue(args.key, args.value);
253
265
  await ensureScope(ctx, args.scope);
254
266
  await upsertConfig(ctx, args.scope, args.key, args.value);
255
267
  return null;
@@ -265,16 +277,10 @@ export const configure = mutation({
265
277
  },
266
278
  returns: v.null(),
267
279
  handler: async (ctx, args) => {
268
- assertNonEmpty("scope", args.scope);
280
+ assertWriteRef("scope", args.scope);
269
281
  assertSampleRate(args.sampleRate);
270
- for (const [field, value] of [
271
- ["retentionDays", args.retentionDays],
272
- ["sessionIdleMs", args.sessionIdleMs],
273
- ] as const) {
274
- if (value !== undefined && !(Number.isFinite(value) && value > 0)) {
275
- throw invalidInput("INVALID_CONFIG", `${field} must be a positive finite number`);
276
- }
277
- }
282
+ assertPositiveConfig("retentionDays", args.retentionDays);
283
+ assertPositiveConfig("sessionIdleMs", args.sessionIdleMs);
278
284
  await ensureScope(ctx, args.scope);
279
285
  const entries: Array<[string, string]> = [];
280
286
  if (args.retentionDays !== undefined) {
@@ -16,6 +16,7 @@ import {
16
16
  eventPage,
17
17
  distributionView,
18
18
  assertCount,
19
+ assertNonEmpty,
19
20
  assertRange,
20
21
  invalidInput,
21
22
  } from "./validators.js";
@@ -90,6 +91,9 @@ export const metric = query({
90
91
  },
91
92
  returns: v.number(),
92
93
  handler: async (ctx, args) => {
94
+ assertNonEmpty("scope", args.scope);
95
+ assertNonEmpty("name", args.name);
96
+ assertNonEmpty("where.dim", args.where?.dim);
93
97
  assertRange(args.range);
94
98
  const dim = args.where ? args.where.dim : TOTAL;
95
99
  const val = args.where ? valKey(args.where.val) : TOTAL;
@@ -114,6 +118,9 @@ export const top = query({
114
118
  },
115
119
  returns: v.array(topRow),
116
120
  handler: async (ctx, args) => {
121
+ assertNonEmpty("scope", args.scope);
122
+ assertNonEmpty("name", args.name);
123
+ assertNonEmpty("dimension", args.dimension);
117
124
  assertRange(args.range);
118
125
  assertCount("limit", args.limit);
119
126
  const limit = Math.min(args.limit ?? 20, 100);
@@ -143,6 +150,9 @@ export const timeseries = query({
143
150
  },
144
151
  returns: v.array(timeseriesPoint),
145
152
  handler: async (ctx, args) => {
153
+ assertNonEmpty("scope", args.scope);
154
+ assertNonEmpty("name", args.name);
155
+ assertNonEmpty("where.dim", args.where?.dim);
146
156
  assertRange(args.range);
147
157
  const gran: Granularity = args.granularity;
148
158
  const dim = args.where ? args.where.dim : TOTAL;
@@ -162,6 +172,7 @@ export const uniques = query({
162
172
  },
163
173
  returns: uniquesView,
164
174
  handler: async (ctx, args) => {
175
+ assertNonEmpty("scope", args.scope);
165
176
  assertRange(args.range);
166
177
  const now = Date.now();
167
178
  const to = args.range.to ?? now;
@@ -216,6 +227,8 @@ export const funnel = query({
216
227
  if (args.steps.length < 2) {
217
228
  throw new Error("Funnel requires at least 2 steps");
218
229
  }
230
+ assertNonEmpty("scope", args.scope);
231
+ for (const step of args.steps) assertNonEmpty("steps[]", step);
219
232
  assertRange(args.range);
220
233
  const now = Date.now();
221
234
  const to = args.range.to ?? now;
@@ -281,6 +294,7 @@ export const retention = query({
281
294
  },
282
295
  returns: v.array(retentionCohort),
283
296
  handler: async (ctx, args) => {
297
+ assertNonEmpty("scope", args.scope);
284
298
  assertRange(args.cohortRange);
285
299
  assertCount("periods", args.periods);
286
300
  const gran: Granularity = args.granularity ?? "day";
@@ -345,6 +359,10 @@ export const distribution = query({
345
359
  },
346
360
  returns: distributionView,
347
361
  handler: async (ctx, args) => {
362
+ assertNonEmpty("scope", args.scope);
363
+ assertNonEmpty("name", args.name);
364
+ assertNonEmpty("measure", args.measure);
365
+ assertNonEmpty("where.dim", args.where?.dim);
348
366
  assertRange(args.range);
349
367
  if (!args.buckets.every(Number.isFinite)) {
350
368
  throw invalidInput("INVALID_BUCKETS", "buckets must be finite numbers");
@@ -388,6 +406,22 @@ export const distribution = query({
388
406
  },
389
407
  });
390
408
 
409
+ /**
410
+ * Parse a `list` cursor: `"<ts>:<_creationTime>"` of the last event returned, or the older
411
+ * `"<ts>"` form, which resumes strictly before `ts`. Each part must be the canonical string of a
412
+ * finite number, so `""`, blank and malformed cursors are rejected instead of restarting.
413
+ */
414
+ function parseCursor(cursor: string | null): { ts: number; creationTime?: number } | null {
415
+ if (cursor === null) return null;
416
+ const parts = cursor.split(":");
417
+ const numbers = parts.map(Number);
418
+ const valid =
419
+ parts.length <= 2 &&
420
+ numbers.every((n, i) => Number.isFinite(n) && String(n) === parts[i]);
421
+ if (!valid) throw invalidInput("INVALID_CURSOR", "cursor is not a value returned by list");
422
+ return { ts: numbers[0]!, creationTime: numbers[1] };
423
+ }
424
+
391
425
  /** Paginated raw events for an event name, newest first. */
392
426
  export const list = query({
393
427
  args: {
@@ -400,24 +434,42 @@ export const list = query({
400
434
  },
401
435
  returns: eventPage,
402
436
  handler: async (ctx, args) => {
403
- // `.paginate()` is not supported inside a Convex component, so paginate
404
- // manually with a `ts`-keyed cursor (newest-first). Bounded + index-backed.
405
- // Note: events sharing the exact boundary `ts` may be skipped across a page
406
- // edge — adequate for a raw-event peek; precise feeds belong in the host.
437
+ // `.paginate()` is not supported inside a Convex component, so paginate manually,
438
+ // newest first, on `by_scope_name_ts` (whose last key is the implicit `_creationTime`).
439
+ // The cursor is the last event's `(ts, _creationTime)`: first finish the events at that
440
+ // `ts` created before it, then continue below that `ts`. Each phase reads at most
441
+ // `numItems + 1` events, so events sharing a `ts` are never skipped or repeated.
442
+ assertNonEmpty("scope", args.scope);
443
+ assertNonEmpty("name", args.name);
407
444
  const { numItems, cursor } = args.paginationOpts;
408
445
  assertCount("numItems", numItems);
409
- const before = cursor ? Number(cursor) : null;
410
- if (before !== null && !Number.isFinite(before)) {
411
- throw invalidInput("INVALID_CURSOR", "cursor is not a value returned by list");
446
+ const after = parseCursor(cursor);
447
+ let rows: Doc<"events">[] = [];
448
+ if (after?.creationTime !== undefined) {
449
+ const { ts, creationTime } = after;
450
+ rows = await ctx.db
451
+ .query("events")
452
+ .withIndex("by_scope_name_ts", (q) =>
453
+ q
454
+ .eq("scope", args.scope)
455
+ .eq("name", args.name)
456
+ .eq("ts", ts)
457
+ .lt("_creationTime", creationTime),
458
+ )
459
+ .order("desc")
460
+ .take(numItems + 1);
461
+ }
462
+ if (rows.length <= numItems) {
463
+ const older = await ctx.db
464
+ .query("events")
465
+ .withIndex("by_scope_name_ts", (q) => {
466
+ const base = q.eq("scope", args.scope).eq("name", args.name);
467
+ return after !== null ? base.lt("ts", after.ts) : base;
468
+ })
469
+ .order("desc")
470
+ .take(numItems + 1 - rows.length);
471
+ rows = rows.concat(older);
412
472
  }
413
- const rows = await ctx.db
414
- .query("events")
415
- .withIndex("by_scope_name_ts", (q) => {
416
- const base = q.eq("scope", args.scope).eq("name", args.name);
417
- return before !== null ? base.lt("ts", before) : base;
418
- })
419
- .order("desc")
420
- .take(numItems + 1);
421
473
 
422
474
  const hasMore = rows.length > numItems;
423
475
  const page = hasMore ? rows.slice(0, numItems) : rows;
@@ -436,7 +488,7 @@ export const list = query({
436
488
  dedupeKey: e.dedupeKey,
437
489
  })),
438
490
  isDone: !hasMore,
439
- continueCursor: last ? String(last.ts) : "",
491
+ continueCursor: last ? `${last.ts}:${last._creationTime}` : "",
440
492
  };
441
493
  },
442
494
  });
@@ -96,6 +96,7 @@ export const distributionView = v.object({
96
96
  /** Stable machine-readable codes carried in `ConvexError.data.code`. */
97
97
  export type AnalyticsErrorCode =
98
98
  | "EMPTY_STRING"
99
+ | "STRING_TOO_LONG"
99
100
  | "INVALID_TIMESTAMP"
100
101
  | "INVALID_SAMPLE_RATE"
101
102
  | "INVALID_PROP_KEY"
@@ -120,6 +121,24 @@ export function assertNonEmpty(field: string, value: string | undefined): void {
120
121
  }
121
122
  }
122
123
 
124
+ /** Longest string a write accepts in a capped field, in characters (Unicode code points). */
125
+ const REF_LENGTH_CAP = 512;
126
+
127
+ /**
128
+ * Reject a string over 512 characters (Unicode code points) on a write path: `scope`, `name`,
129
+ * refs, `dedupeKey`, dimensions and config keys land in index keys and rollup rows.
130
+ * `undefined` passes. Reads and `backfill` skip this check, so rows stored earlier with a
131
+ * longer value stay readable.
132
+ */
133
+ export function assertRefLength(field: string, value: string | undefined): void {
134
+ if (value !== undefined && value.length > REF_LENGTH_CAP && [...value].length > REF_LENGTH_CAP) {
135
+ throw invalidInput(
136
+ "STRING_TOO_LONG",
137
+ `${field} must be at most ${REF_LENGTH_CAP} characters (Unicode code points)`,
138
+ );
139
+ }
140
+ }
141
+
123
142
  /** Reject NaN and +/-Infinity epoch-millis values. `undefined` passes. */
124
143
  export function assertFiniteTs(field: string, value: number | undefined): void {
125
144
  if (value !== undefined && !Number.isFinite(value)) {
@@ -147,6 +166,26 @@ export function assertSampleRate(value: number | undefined): void {
147
166
  }
148
167
  }
149
168
 
169
+ /** Reject a config value that is not a positive finite number (`retentionDays`, `sessionIdleMs`). */
170
+ export function assertPositiveConfig(field: string, value: number | undefined): void {
171
+ if (value !== undefined && !(Number.isFinite(value) && value > 0)) {
172
+ throw invalidInput("INVALID_CONFIG", `${field} must be a positive finite number`);
173
+ }
174
+ }
175
+
176
+ /**
177
+ * Reject a `configSet` value for a key that `configure` owns when `configure` would reject it,
178
+ * so the crons never read a value `configure` refuses. Other keys are stored as given.
179
+ */
180
+ export function assertConfigValue(key: string, value: string): void {
181
+ const n = value.trim() === "" ? NaN : Number(value);
182
+ if (key === "retentionDays" || key === "sessionIdleMs") {
183
+ assertPositiveConfig(key, n);
184
+ } else if (key === "sampleRate" && !(n >= 0 && n <= 1)) {
185
+ throw invalidInput("INVALID_CONFIG", "sampleRate must be a number between 0 and 1");
186
+ }
187
+ }
188
+
150
189
  /** Convex field names: 1-1024 printable ASCII characters, not starting with `$` (or empty). */
151
190
  const PROP_KEY = /^(?!\$)[\x20-\x7e]{0,1024}$/;
152
191