@voltro/plugin-analytics-postgres 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.
@@ -0,0 +1,73 @@
1
+ import { AggregateQuery } from '@voltro/runtime';
2
+ import { AnalyticsBucket } from '@voltro/runtime';
3
+ import { AnalyticsEvent } from '@voltro/runtime';
4
+ import { AnalyticsSinkImpl } from '@voltro/runtime';
5
+ import { AnalyticsTopEntry } from '@voltro/runtime';
6
+ import { SqlClient } from '@effect/sql';
7
+ import { TableLike } from '@voltro/database';
8
+ import { TimeseriesQuery } from '@voltro/runtime';
9
+ import { TopNQuery } from '@voltro/runtime';
10
+
11
+ export { AggregateQuery }
12
+
13
+ export { AnalyticsBucket }
14
+
15
+ export { AnalyticsEvent }
16
+
17
+ export { AnalyticsTopEntry }
18
+
19
+ /**
20
+ * Construct the spec. The framework's boot path looks for `kind:
21
+ * 'postgres-analytics'` in `apiConfig.analytics`, calls `build()` with
22
+ * the active SqlClient, and wires the result under `AnalyticsSink`.
23
+ */
24
+ export declare const postgresAnalytics: (options?: PostgresAnalyticsOptions) => PostgresAnalyticsSpec;
25
+
26
+ export declare interface PostgresAnalyticsOptions {
27
+ /**
28
+ * Optional override — by default the sink uses the same SqlClient
29
+ * the main DataStore is bound to (recommended; events live in the
30
+ * same DB as your app). Pass a different SqlClient when you want
31
+ * events to land in a SEPARATE database — e.g. a dedicated analytics
32
+ * Postgres while the main app uses MySQL. Note: the events table
33
+ * must exist there (run `applySchema([_voltroEventsTable], dialect)`
34
+ * manually against that DB).
35
+ */
36
+ readonly sqlClient?: SqlClient.SqlClient;
37
+ /**
38
+ * Reactive tables to CDC-mirror into the warehouse. Each table gets a
39
+ * `_voltro_mirror_<table>` table (`{ id, data }`); the framework
40
+ * streams `DataStore` changes into it so analytical queries can JOIN
41
+ * events against live user data. Empty / omitted → events-only.
42
+ *
43
+ * analytics: postgresAnalytics({ mirrorTables: ['users', 'teams'] })
44
+ */
45
+ readonly mirrorTables?: ReadonlyArray<string>;
46
+ /** Primary-key column on the mirrored source rows. Default `'id'`. */
47
+ readonly mirrorPrimaryKey?: string;
48
+ }
49
+
50
+ /**
51
+ * Sentinel the framework recognises in `apiConfig.analytics`. The cli
52
+ * binds it to the running SqlClient at boot and provides the resulting
53
+ * sink under `AnalyticsSink`. Users don't usually need the internal
54
+ * shape — just call `postgresAnalytics()` and pass it through.
55
+ */
56
+ export declare interface PostgresAnalyticsSpec {
57
+ readonly kind: 'postgres-analytics';
58
+ readonly options: PostgresAnalyticsOptions;
59
+ /** Internal — the cli calls this with the resolved SqlClient. */
60
+ readonly build: (sqlClient: SqlClient.SqlClient) => AnalyticsSinkImpl;
61
+ /** Tables the plugin needs in the user's schema. */
62
+ readonly tables: ReadonlyArray<{
63
+ readonly tableName: string;
64
+ }>;
65
+ }
66
+
67
+ export { TimeseriesQuery }
68
+
69
+ export { TopNQuery }
70
+
71
+ export declare const _voltroEventsTable: TableLike;
72
+
73
+ export { }
package/dist/index.js ADDED
@@ -0,0 +1,177 @@
1
+ import { id as e, json as t, registerRetention as n, retentionTtlMsFromEnv as r, table as i, text as a, timestamp as o } from "@voltro/database";
2
+ import { Effect as s } from "effect";
3
+ import { AnalyticsError as c } from "@voltro/runtime";
4
+ //#region src/eventsTable.ts
5
+ var l = i("_voltro_events", {
6
+ id: e({ scheme: "numeric" }),
7
+ name: a(),
8
+ subjectId: a().nullable(),
9
+ tenantId: a().nullable(),
10
+ properties: t().default(() => ({})),
11
+ occurredAt: o().default("now")
12
+ }).index(["name", "occurredAt"]).index(["subjectId", "occurredAt"]).index([
13
+ "tenantId",
14
+ "name",
15
+ "occurredAt"
16
+ ]), u = (e, t, n) => {
17
+ let r = `$.${n}`;
18
+ return e.onDialectOrElse({
19
+ mssql: () => e`JSON_VALUE(${e(t)}, ${r})`,
20
+ mysql: () => e`JSON_UNQUOTE(JSON_EXTRACT(${e(t)}, ${r}))`,
21
+ sqlite: () => e`json_extract(${e(t)}, ${r})`,
22
+ orElse: () => e`${e(t)}->>'${e.literal(n)}'`
23
+ });
24
+ }, d = (e, t, n) => {
25
+ let r = `$.${n}`;
26
+ return e.onDialectOrElse({
27
+ mssql: () => e`TRY_CAST(JSON_VALUE(${e(t)}, ${r}) AS DECIMAL(38, 10))`,
28
+ mysql: () => e`CAST(JSON_UNQUOTE(JSON_EXTRACT(${e(t)}, ${r})) AS DECIMAL(38, 10))`,
29
+ sqlite: () => e`CAST(json_extract(${e(t)}, ${r}) AS REAL)`,
30
+ orElse: () => e`(${e(t)}->>'${e.literal(n)}')::numeric`
31
+ });
32
+ }, f = (e, t, n) => {
33
+ let r = e(t);
34
+ return n === "minute" ? e.onDialectOrElse({
35
+ mssql: () => e`DATEADD(minute, DATEDIFF(minute, 0, ${r}), 0)`,
36
+ mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-%d %H:%i:00')`,
37
+ sqlite: () => e`strftime('%Y-%m-%dT%H:%M:00', ${r})`,
38
+ orElse: () => e`date_trunc('minute', ${r})`
39
+ }) : n === "hour" ? e.onDialectOrElse({
40
+ mssql: () => e`DATEADD(hour, DATEDIFF(hour, 0, ${r}), 0)`,
41
+ mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-%d %H:00:00')`,
42
+ sqlite: () => e`strftime('%Y-%m-%dT%H:00:00', ${r})`,
43
+ orElse: () => e`date_trunc('hour', ${r})`
44
+ }) : n === "day" ? e.onDialectOrElse({
45
+ mssql: () => e`DATEADD(day, DATEDIFF(day, 0, ${r}), 0)`,
46
+ mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-%d 00:00:00')`,
47
+ sqlite: () => e`strftime('%Y-%m-%dT00:00:00', ${r})`,
48
+ orElse: () => e`date_trunc('day', ${r})`
49
+ }) : n === "week" ? e.onDialectOrElse({
50
+ mssql: () => e`DATEADD(week, DATEDIFF(week, 0, ${r}), 0)`,
51
+ mysql: () => e`DATE_FORMAT(DATE_SUB(${r}, INTERVAL WEEKDAY(${r}) DAY), '%Y-%m-%d 00:00:00')`,
52
+ sqlite: () => e`strftime('%Y-%m-%dT00:00:00', ${r}, 'weekday 1', '-7 days')`,
53
+ orElse: () => e`date_trunc('week', ${r})`
54
+ }) : e.onDialectOrElse({
55
+ mssql: () => e`DATEADD(month, DATEDIFF(month, 0, ${r}), 0)`,
56
+ mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-01 00:00:00')`,
57
+ sqlite: () => e`strftime('%Y-%m-01T00:00:00', ${r})`,
58
+ orElse: () => e`date_trunc('month', ${r})`
59
+ });
60
+ }, p = "postgres-analytics", m = "_voltro_events", h = (e) => `_voltro_mirror_${e}`, g = (e) => s.mapError((t) => new c({
61
+ provider: p,
62
+ operation: e,
63
+ cause: t instanceof Error ? `${t.name}: ${t.message}` : String(t)
64
+ })), _ = (e, t, n, r, i) => {
65
+ let a = e("name"), o = e("occurredAt");
66
+ return e`WHERE ${a} = ${t} AND ${o} >= ${n.from} AND ${o} < ${n.to ?? /* @__PURE__ */ new Date()}${r !== void 0 && Object.keys(r).length > 0 ? e` AND ${e.and(Object.entries(r).map(([t, n]) => e`${u(e, "properties", t)} = ${n}`))}` : e``}${i == null ? e`` : e` AND ${e("tenantId")} = ${i}`}`;
67
+ }, v = (e, t) => t === "count" ? e`COUNT(*)` : t === "unique" ? e`COUNT(DISTINCT ${e("subjectId")})` : "sum" in t ? e`COALESCE(SUM(${d(e, "properties", t.sum)}), 0)` : e`AVG(${d(e, "properties", t.avg)})`, y = (e, t) => t === "count" ? e`COUNT(*)` : e`COALESCE(SUM(${d(e, "properties", t.sum)}), 0)`, b = (e, t, n) => {
68
+ let r = /* @__PURE__ */ new Set(), i = (t) => s.gen(function* () {
69
+ r.has(t) || (yield* e`
70
+ CREATE TABLE IF NOT EXISTS ${e(h(t))} (
71
+ ${e("id")} TEXT PRIMARY KEY,
72
+ ${e("data")} JSONB NOT NULL
73
+ )
74
+ `, r.add(t));
75
+ }), a = (e) => s.mapError((t) => new c({
76
+ provider: p,
77
+ operation: e,
78
+ cause: t instanceof Error ? `${t.name}: ${t.message}` : String(t)
79
+ }));
80
+ return {
81
+ tables: t,
82
+ primaryKey: n,
83
+ upsert: (t, r) => s.gen(function* () {
84
+ yield* i(t);
85
+ let a = h(t), o = String(r[n]), s = JSON.stringify(r);
86
+ yield* e`
87
+ INSERT INTO ${e(a)} (${e("id")}, ${e("data")})
88
+ VALUES (${o}, ${s})
89
+ ON CONFLICT (${e("id")}) DO UPDATE SET ${e("data")} = ${s}
90
+ `;
91
+ }).pipe(a("mirror.upsert")),
92
+ remove: (t, n) => s.gen(function* () {
93
+ yield* i(t);
94
+ let r = h(t), a = String(n);
95
+ yield* e`DELETE FROM ${e(r)} WHERE ${e("id")} = ${a}`;
96
+ }).pipe(a("mirror.remove"))
97
+ };
98
+ }, x = (e, t = {}) => {
99
+ let n = e, r = t.mirrorTables ?? [], i = r.length > 0 ? b(n, r, t.mirrorPrimaryKey ?? "id") : void 0;
100
+ return {
101
+ info: {
102
+ provider: p,
103
+ capabilities: {
104
+ track: !0,
105
+ aggregate: !0,
106
+ timeseries: !0,
107
+ topN: !0,
108
+ mirror: i !== void 0
109
+ },
110
+ detail: {
111
+ table: m,
112
+ ...r.length > 0 ? { mirrorTables: r } : {}
113
+ }
114
+ },
115
+ track: (e) => s.gen(function* () {
116
+ let t = e.occurredAt ?? /* @__PURE__ */ new Date(), r = JSON.stringify(e.properties), i = e.subjectId ?? null, a = e.tenantId ?? null;
117
+ yield* n`
118
+ INSERT INTO ${n(m)} (${n("name")}, ${n("subjectId")}, ${n("tenantId")}, ${n("properties")}, ${n("occurredAt")})
119
+ VALUES (${e.name}, ${i}, ${a}, ${r}, ${t})
120
+ `;
121
+ }).pipe(g("track")),
122
+ aggregate: (e) => s.gen(function* () {
123
+ let t = v(n, e.metric), r = _(n, e.event, e.range, e.filter, e.tenantId), i = (yield* n`
124
+ SELECT ${t} AS ${n("value")} FROM ${n(m)} ${r}
125
+ `)[0]?.value ?? 0;
126
+ return typeof i == "number" ? i : Number(i ?? 0);
127
+ }).pipe(g("aggregate")),
128
+ timeseries: (e) => s.gen(function* () {
129
+ let t = v(n, e.metric), r = f(n, "occurredAt", e.bucket), i = _(n, e.event, e.range, e.filter, e.tenantId);
130
+ return (yield* n`
131
+ SELECT ${r} AS ${n("bucket_start")}, ${t} AS ${n("value")}
132
+ FROM ${n(m)} ${i}
133
+ GROUP BY ${r}
134
+ ORDER BY ${r} ASC
135
+ `).map((e) => ({
136
+ bucketStart: e.bucket_start instanceof Date ? e.bucket_start : new Date(e.bucket_start),
137
+ value: typeof e.value == "number" ? e.value : Number(e.value ?? 0)
138
+ }));
139
+ }).pipe(g("timeseries")),
140
+ topN: (e) => s.gen(function* () {
141
+ let t = y(n, e.metric), r = u(n, "properties", e.groupBy), i = _(n, e.event, e.range, e.filter, e.tenantId), a = Math.max(1, Math.floor(e.n));
142
+ return (yield* n.onDialectOrElse({
143
+ mssql: () => n`
144
+ SELECT TOP (${a}) ${r} AS ${n("key")}, ${t} AS ${n("value")}
145
+ FROM ${n(m)} ${i}
146
+ GROUP BY ${r}
147
+ ORDER BY ${t} DESC
148
+ `,
149
+ orElse: () => n`
150
+ SELECT ${r} AS ${n("key")}, ${t} AS ${n("value")}
151
+ FROM ${n(m)} ${i}
152
+ GROUP BY ${r}
153
+ ORDER BY ${t} DESC
154
+ LIMIT ${a}
155
+ `
156
+ })).filter((e) => e.key !== null).map((e) => ({
157
+ key: e.key,
158
+ value: typeof e.value == "number" ? e.value : Number(e.value ?? 0)
159
+ }));
160
+ }).pipe(g("topN")),
161
+ ...i === void 0 ? {} : { mirror: i }
162
+ };
163
+ }, S = (e = {}) => (n({
164
+ table: "_voltro_events",
165
+ timeColumn: "occurredAt",
166
+ ttlMs: r(process.env.VOLTRO_EVENTS_TTL_HOURS, 24 * 365)
167
+ }), {
168
+ kind: "postgres-analytics",
169
+ options: e,
170
+ build: (t) => x(e.sqlClient ?? t, {
171
+ ...e.mirrorTables === void 0 ? {} : { mirrorTables: e.mirrorTables },
172
+ ...e.mirrorPrimaryKey === void 0 ? {} : { mirrorPrimaryKey: e.mirrorPrimaryKey }
173
+ }),
174
+ tables: [l]
175
+ });
176
+ //#endregion
177
+ export { l as _voltroEventsTable, S as postgresAnalytics };
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@voltro/plugin-analytics-postgres",
3
+ "version": "0.1.0",
4
+ "description": "First-party AnalyticsSink that stores events in the main DataStore (works on every SQL dialect: postgres / mysql / mariadb / mssql / sqlite). Lite version — ceiling ~10M events/day before queries get slow.",
5
+ "keywords": [
6
+ "voltro",
7
+ "typescript",
8
+ "framework"
9
+ ],
10
+ "license": "SEE LICENSE IN LICENSE",
11
+ "homepage": "https://voltro.dev",
12
+ "bugs": {
13
+ "email": "support@voltro.dev"
14
+ },
15
+ "author": {
16
+ "name": "Voltro UG",
17
+ "url": "https://voltro.dev"
18
+ },
19
+ "type": "module",
20
+ "exports": {
21
+ ".": {
22
+ "types": "./dist/index.d.ts",
23
+ "import": "./dist/index.js",
24
+ "default": "./dist/index.js"
25
+ }
26
+ },
27
+ "main": "./dist/index.js",
28
+ "module": "./dist/index.js",
29
+ "types": "./dist/index.d.ts",
30
+ "sideEffects": false,
31
+ "engines": {
32
+ "node": ">=24.0.0"
33
+ },
34
+ "dependencies": {
35
+ "@effect/sql": "^0.51.1",
36
+ "@voltro/database": "0.1.0",
37
+ "@voltro/runtime": "0.1.0"
38
+ },
39
+ "peerDependencies": {
40
+ "effect": "^3.21.4"
41
+ },
42
+ "publishConfig": {
43
+ "access": "public"
44
+ }
45
+ }