@vllnt/convex-analytics 0.1.0-canary.332b387
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.
- package/LICENSE +21 -0
- package/README.md +209 -0
- package/dist/client/index.d.ts +94 -0
- package/dist/client/index.d.ts.map +1 -0
- package/dist/client/index.js +132 -0
- package/dist/client/index.js.map +1 -0
- package/dist/client/types.d.ts +109 -0
- package/dist/client/types.d.ts.map +1 -0
- package/dist/client/types.js +2 -0
- package/dist/client/types.js.map +1 -0
- package/dist/component/_generated/api.d.ts +22 -0
- package/dist/component/_generated/api.d.ts.map +1 -0
- package/dist/component/_generated/api.js +12 -0
- package/dist/component/_generated/api.js.map +1 -0
- package/dist/component/_generated/dataModel.d.ts +13 -0
- package/dist/component/_generated/dataModel.d.ts.map +1 -0
- package/dist/component/_generated/dataModel.js +8 -0
- package/dist/component/_generated/dataModel.js.map +1 -0
- package/dist/component/_generated/server.d.ts +20 -0
- package/dist/component/_generated/server.d.ts.map +1 -0
- package/dist/component/_generated/server.js +15 -0
- package/dist/component/_generated/server.js.map +1 -0
- package/dist/component/convex.config.d.ts +3 -0
- package/dist/component/convex.config.d.ts.map +1 -0
- package/dist/component/convex.config.js +10 -0
- package/dist/component/convex.config.js.map +1 -0
- package/dist/component/http.d.ts +13 -0
- package/dist/component/http.d.ts.map +1 -0
- package/dist/component/http.js +180 -0
- package/dist/component/http.js.map +1 -0
- package/dist/component/internal_mutations.d.ts +26 -0
- package/dist/component/internal_mutations.d.ts.map +1 -0
- package/dist/component/internal_mutations.js +126 -0
- package/dist/component/internal_mutations.js.map +1 -0
- package/dist/component/mutations.d.ts +24 -0
- package/dist/component/mutations.d.ts.map +1 -0
- package/dist/component/mutations.js +209 -0
- package/dist/component/mutations.js.map +1 -0
- package/dist/component/queries.d.ts +148 -0
- package/dist/component/queries.d.ts.map +1 -0
- package/dist/component/queries.js +376 -0
- package/dist/component/queries.js.map +1 -0
- package/dist/component/schema.d.ts +104 -0
- package/dist/component/schema.d.ts.map +1 -0
- package/dist/component/schema.js +72 -0
- package/dist/component/schema.js.map +1 -0
- package/dist/component/validators.d.ts +195 -0
- package/dist/component/validators.d.ts.map +1 -0
- package/dist/component/validators.js +71 -0
- package/dist/component/validators.js.map +1 -0
- package/dist/react/index.d.ts +89 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +63 -0
- package/dist/react/index.js.map +1 -0
- package/dist/shared.d.ts +14 -0
- package/dist/shared.d.ts.map +1 -0
- package/dist/shared.js +18 -0
- package/dist/shared.js.map +1 -0
- package/dist/test.d.ts +117 -0
- package/dist/test.d.ts.map +1 -0
- package/dist/test.js +28 -0
- package/dist/test.js.map +1 -0
- package/dist/web/index.d.ts +121 -0
- package/dist/web/index.d.ts.map +1 -0
- package/dist/web/index.js +169 -0
- package/dist/web/index.js.map +1 -0
- package/package.json +116 -0
- package/src/client/index.ts +259 -0
- package/src/client/types.ts +121 -0
- package/src/component/_generated/api.ts +35 -0
- package/src/component/_generated/dataModel.ts +24 -0
- package/src/component/_generated/server.ts +42 -0
- package/src/component/convex.config.ts +12 -0
- package/src/component/http.ts +204 -0
- package/src/component/internal_mutations.ts +165 -0
- package/src/component/mutations.ts +255 -0
- package/src/component/queries.ts +436 -0
- package/src/component/schema.ts +76 -0
- package/src/component/validators.ts +94 -0
- package/src/react/index.tsx +127 -0
- package/src/shared.ts +30 -0
- package/src/test.ts +44 -0
- package/src/web/index.ts +232 -0
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import type { Scalar, Props, Granularity } from "../shared.js";
|
|
2
|
+
|
|
3
|
+
export type { Scalar, Props, Granularity };
|
|
4
|
+
|
|
5
|
+
/** A time range in epoch millis. */
|
|
6
|
+
export interface Range {
|
|
7
|
+
from?: number;
|
|
8
|
+
to?: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Filter a query to events where one dimension equals one value. */
|
|
12
|
+
export interface Where {
|
|
13
|
+
dim: string;
|
|
14
|
+
val: Scalar;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Client-owned config. Stored on the client and applied to every call. */
|
|
18
|
+
export interface AnalyticsConfig {
|
|
19
|
+
/** Multi-tenant partition. Default `"default"`. */
|
|
20
|
+
scope?: string;
|
|
21
|
+
/** Prop keys to roll up on (drives rollup-on-write). Default `[]`. */
|
|
22
|
+
dimensions?: string[];
|
|
23
|
+
/** Rollup bucket granularities. Default `["day"]`. */
|
|
24
|
+
granularities?: Granularity[];
|
|
25
|
+
/** Raw-event TTL in days (rollups kept forever). Default `90`. */
|
|
26
|
+
retentionDays?: number;
|
|
27
|
+
/** Sampling rate `0..1`. Default `1`. */
|
|
28
|
+
sampleRate?: number;
|
|
29
|
+
/** Session idle-close timeout in millis. Default `1800000` (30m). */
|
|
30
|
+
sessionIdleMs?: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Options for a single `track` call. */
|
|
34
|
+
export interface TrackOpts<TProps extends Props = Props> {
|
|
35
|
+
subjectRef?: string;
|
|
36
|
+
sessionRef?: string;
|
|
37
|
+
props?: TProps;
|
|
38
|
+
ts?: number;
|
|
39
|
+
/** Override the client's default scope for this event. */
|
|
40
|
+
scope?: string;
|
|
41
|
+
/** Skip if an event with this dedupe key already exists in the scope. */
|
|
42
|
+
dedupeKey?: string;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Outcome of a `track` call. */
|
|
46
|
+
export type TrackResult = "tracked" | "dropped" | "duplicate";
|
|
47
|
+
|
|
48
|
+
/** A `(value, count)` breakdown row. */
|
|
49
|
+
export interface TopRow {
|
|
50
|
+
value: string;
|
|
51
|
+
count: number;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** A `(bucket, count)` timeseries point. */
|
|
55
|
+
export interface TimeseriesPoint {
|
|
56
|
+
bucket: number;
|
|
57
|
+
count: number;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** DAU/WAU/MAU rollup. */
|
|
61
|
+
export interface UniquesView {
|
|
62
|
+
dau: number;
|
|
63
|
+
wau: number;
|
|
64
|
+
mau: number;
|
|
65
|
+
trend: Array<{ bucket: number; uniques: number }>;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** A funnel step result. */
|
|
69
|
+
export interface FunnelStep {
|
|
70
|
+
name: string;
|
|
71
|
+
count: number;
|
|
72
|
+
rate: number;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A retention cohort row. */
|
|
76
|
+
export interface RetentionCohort {
|
|
77
|
+
cohort: number;
|
|
78
|
+
size: number;
|
|
79
|
+
retained: number[];
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** A histogram bin: events whose measure is at or below `upper`. */
|
|
83
|
+
export interface DistributionBin {
|
|
84
|
+
upper: number;
|
|
85
|
+
count: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Histogram of a numeric measure: bins by ascending upper bound + overflow. */
|
|
89
|
+
export interface DistributionView {
|
|
90
|
+
bins: DistributionBin[];
|
|
91
|
+
overflow: number;
|
|
92
|
+
count: number;
|
|
93
|
+
sum: number;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** A raw event as returned by `list`. */
|
|
97
|
+
export interface EventView {
|
|
98
|
+
_id: string;
|
|
99
|
+
_creationTime: number;
|
|
100
|
+
scope: string;
|
|
101
|
+
name: string;
|
|
102
|
+
subjectRef?: string;
|
|
103
|
+
sessionRef?: string;
|
|
104
|
+
props: Props;
|
|
105
|
+
ts: number;
|
|
106
|
+
seq: number;
|
|
107
|
+
dedupeKey?: string;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Convex pagination options. */
|
|
111
|
+
export interface PaginationOpts {
|
|
112
|
+
numItems: number;
|
|
113
|
+
cursor: string | null;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** A page of raw events. */
|
|
117
|
+
export interface EventPage {
|
|
118
|
+
page: EventView[];
|
|
119
|
+
isDone: boolean;
|
|
120
|
+
continueCursor: string;
|
|
121
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated `api` utility.
|
|
4
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type * as mutations from "../mutations.js";
|
|
9
|
+
import type * as queries from "../queries.js";
|
|
10
|
+
import type * as internal_mutations from "../internal_mutations.js";
|
|
11
|
+
import type * as http from "../http.js";
|
|
12
|
+
|
|
13
|
+
import type {
|
|
14
|
+
ApiFromModules,
|
|
15
|
+
FilterApi,
|
|
16
|
+
FunctionReference,
|
|
17
|
+
} from "convex/server";
|
|
18
|
+
import { anyApi, componentsGeneric } from "convex/server";
|
|
19
|
+
|
|
20
|
+
const fullApi: ApiFromModules<{
|
|
21
|
+
mutations: typeof mutations;
|
|
22
|
+
queries: typeof queries;
|
|
23
|
+
internal_mutations: typeof internal_mutations;
|
|
24
|
+
http: typeof http;
|
|
25
|
+
}> = anyApi as any;
|
|
26
|
+
|
|
27
|
+
export const api: FilterApi<typeof fullApi, FunctionReference<any, "public">> =
|
|
28
|
+
fullApi as any;
|
|
29
|
+
export const internal: FilterApi<
|
|
30
|
+
typeof fullApi,
|
|
31
|
+
FunctionReference<any, "internal">
|
|
32
|
+
> = fullApi as any;
|
|
33
|
+
|
|
34
|
+
export const components: ReturnType<typeof componentsGeneric> =
|
|
35
|
+
componentsGeneric() as any;
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated data model types.
|
|
4
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type {
|
|
9
|
+
DataModelFromSchemaDefinition,
|
|
10
|
+
DocumentByName,
|
|
11
|
+
TableNamesInDataModel,
|
|
12
|
+
SystemTableNames,
|
|
13
|
+
} from "convex/server";
|
|
14
|
+
import type { GenericId } from "convex/values";
|
|
15
|
+
import schema from "../schema.js";
|
|
16
|
+
|
|
17
|
+
export type TableNames = TableNamesInDataModel<DataModel>;
|
|
18
|
+
export type Doc<TableName extends TableNames> = DocumentByName<
|
|
19
|
+
DataModel,
|
|
20
|
+
TableName
|
|
21
|
+
>;
|
|
22
|
+
export type Id<TableName extends TableNames | SystemTableNames> =
|
|
23
|
+
GenericId<TableName>;
|
|
24
|
+
export type DataModel = DataModelFromSchemaDefinition<typeof schema>;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/* eslint-disable */
|
|
2
|
+
/**
|
|
3
|
+
* Generated utilities for implementing server-side Convex query and mutation functions.
|
|
4
|
+
* THIS CODE IS AUTOMATICALLY GENERATED.
|
|
5
|
+
* @module
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type {
|
|
9
|
+
ActionBuilder,
|
|
10
|
+
HttpActionBuilder,
|
|
11
|
+
MutationBuilder,
|
|
12
|
+
QueryBuilder,
|
|
13
|
+
GenericActionCtx,
|
|
14
|
+
GenericMutationCtx,
|
|
15
|
+
GenericQueryCtx,
|
|
16
|
+
GenericDatabaseReader,
|
|
17
|
+
GenericDatabaseWriter,
|
|
18
|
+
} from "convex/server";
|
|
19
|
+
import {
|
|
20
|
+
actionGeneric,
|
|
21
|
+
httpActionGeneric,
|
|
22
|
+
queryGeneric,
|
|
23
|
+
mutationGeneric,
|
|
24
|
+
internalActionGeneric,
|
|
25
|
+
internalMutationGeneric,
|
|
26
|
+
internalQueryGeneric,
|
|
27
|
+
} from "convex/server";
|
|
28
|
+
import type { DataModel } from "./dataModel.js";
|
|
29
|
+
|
|
30
|
+
export const query: QueryBuilder<DataModel, "public"> = queryGeneric;
|
|
31
|
+
export const internalQuery: QueryBuilder<DataModel, "internal"> = internalQueryGeneric;
|
|
32
|
+
export const mutation: MutationBuilder<DataModel, "public"> = mutationGeneric;
|
|
33
|
+
export const internalMutation: MutationBuilder<DataModel, "internal"> = internalMutationGeneric;
|
|
34
|
+
export const action: ActionBuilder<DataModel, "public"> = actionGeneric;
|
|
35
|
+
export const internalAction: ActionBuilder<DataModel, "internal"> = internalActionGeneric;
|
|
36
|
+
export const httpAction: HttpActionBuilder = httpActionGeneric;
|
|
37
|
+
|
|
38
|
+
export type QueryCtx = GenericQueryCtx<DataModel>;
|
|
39
|
+
export type MutationCtx = GenericMutationCtx<DataModel>;
|
|
40
|
+
export type ActionCtx = GenericActionCtx<DataModel>;
|
|
41
|
+
export type DatabaseReader = GenericDatabaseReader<DataModel>;
|
|
42
|
+
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,165 @@
|
|
|
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(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(stale.map((s) => ctx.db.patch(s._id, { endTs: s.lastTs })));
|
|
87
|
+
return stale.length;
|
|
88
|
+
};
|
|
89
|
+
|
|
90
|
+
const counts = await Promise.all(scopes.map(closeScope));
|
|
91
|
+
return { closed: counts.reduce((a, b) => a + b, 0) };
|
|
92
|
+
},
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Re-derive rollups from raw events for a `(scope, name)`. Idempotent: deletes
|
|
97
|
+
* existing rollup rows for the name, then recomputes from the retained raw events.
|
|
98
|
+
*/
|
|
99
|
+
export const backfill = internalMutation({
|
|
100
|
+
args: {
|
|
101
|
+
scope: v.string(),
|
|
102
|
+
name: v.string(),
|
|
103
|
+
dimensions: v.array(v.string()),
|
|
104
|
+
granularities: granularitiesValidator,
|
|
105
|
+
},
|
|
106
|
+
returns: v.object({ events: v.number(), rows: v.number() }),
|
|
107
|
+
handler: async (ctx, args) => {
|
|
108
|
+
const grans = args.granularities.length > 0 ? args.granularities : (["day"] as const);
|
|
109
|
+
|
|
110
|
+
const existing = await ctx.db
|
|
111
|
+
.query("rollups")
|
|
112
|
+
.withIndex("by_scope_name_dim_val", (q) =>
|
|
113
|
+
q.eq("scope", args.scope).eq("name", args.name),
|
|
114
|
+
)
|
|
115
|
+
.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);
|
|
124
|
+
|
|
125
|
+
const counts = new Map<string, number>();
|
|
126
|
+
const meta = new Map<
|
|
127
|
+
string,
|
|
128
|
+
{ gran: Granularity; bucket: number; dim: string; val: string }
|
|
129
|
+
>();
|
|
130
|
+
const bump = (gran: Granularity, bucket: number, dim: string, val: string): void => {
|
|
131
|
+
const k = `${gran}|${bucket}|${dim}|${val}`;
|
|
132
|
+
counts.set(k, (counts.get(k) ?? 0) + 1);
|
|
133
|
+
if (!meta.has(k)) meta.set(k, { gran, bucket, dim, val });
|
|
134
|
+
};
|
|
135
|
+
|
|
136
|
+
for (const e of events) {
|
|
137
|
+
for (const gran of grans) {
|
|
138
|
+
const bucket = bucketStart(e.ts, gran);
|
|
139
|
+
bump(gran, bucket, TOTAL, TOTAL);
|
|
140
|
+
for (const dim of args.dimensions) {
|
|
141
|
+
if (dim in e.props) {
|
|
142
|
+
bump(gran, bucket, dim, valKey(e.props[dim]!));
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
await Promise.all(
|
|
149
|
+
[...counts].map(([k, count]) => {
|
|
150
|
+
const m = meta.get(k)!;
|
|
151
|
+
return ctx.db.insert("rollups", {
|
|
152
|
+
scope: args.scope,
|
|
153
|
+
name: args.name,
|
|
154
|
+
granularity: m.gran,
|
|
155
|
+
bucket: m.bucket,
|
|
156
|
+
dim: m.dim,
|
|
157
|
+
val: m.val,
|
|
158
|
+
count,
|
|
159
|
+
});
|
|
160
|
+
}),
|
|
161
|
+
);
|
|
162
|
+
|
|
163
|
+
return { events: events.length, rows: counts.size };
|
|
164
|
+
},
|
|
165
|
+
});
|