@voltro/plugin-analytics-postgres 0.81.0 → 0.83.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.
@@ -4551,7 +4551,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
4551
4551
  SOFTWARE.
4552
4552
  ```
4553
4553
 
4554
- ## undici@8.10.0
4554
+ ## undici@8.11.2
4555
4555
 
4556
4556
  License: MIT
4557
4557
 
package/dist/index.d.ts CHANGED
@@ -3,7 +3,10 @@ import { AnalyticsBucket } from '@voltro/runtime';
3
3
  import { AnalyticsEvent } from '@voltro/runtime';
4
4
  import { AnalyticsSinkImpl } from '@voltro/runtime';
5
5
  import { AnalyticsTopEntry } from '@voltro/runtime';
6
+ import { ColumnBuilder } from '@voltro/database';
7
+ import { FieldDefinitions } from '@voltro/database';
6
8
  import { SqlClient } from '@effect/sql';
9
+ import { Table } from '@voltro/database';
7
10
  import { TableLike } from '@voltro/database';
8
11
  import { TimeseriesQuery } from '@voltro/runtime';
9
12
  import { TopNQuery } from '@voltro/runtime';
@@ -16,6 +19,26 @@ export { AnalyticsEvent }
16
19
 
17
20
  export { AnalyticsTopEntry }
18
21
 
22
+ /**
23
+ * One mirror table per entry of `mirrorTables` — declared like `_voltro_events`,
24
+ * so the schema applier creates it and the plan, fingerprint, backups and
25
+ * transfers see it. Never created by the sink at write time.
26
+ *
27
+ * The shape is the one these tables have always had (`id` TEXT primary key,
28
+ * `data` JSON, `version` BIGINT, `is_deleted` BOOLEAN), so a deployment that
29
+ * already holds mirrored rows keeps them: the plan against such a table is
30
+ * empty. The mirror has no backfill, which is why the shape is not modernised.
31
+ */
32
+ export declare const mirrorTable: (sourceTable: string) => Table<string, FieldDefinitions<{
33
+ readonly id: ColumnBuilder<string, "text", boolean>;
34
+ readonly data: ColumnBuilder<unknown, "json", boolean>;
35
+ readonly version: ColumnBuilder<string, "bigint", true>;
36
+ readonly is_deleted: ColumnBuilder<boolean, "boolean", true>;
37
+ }>, false, never>;
38
+
39
+ /** The warehouse copy of a mirrored source table: `_voltro_mirror_<table>`. */
40
+ export declare const mirrorTableName: (sourceTable: string) => string;
41
+
19
42
  /**
20
43
  * Construct the spec. The framework's boot path looks for `kind:
21
44
  * 'postgres-analytics'` in `apiConfig.analytics`, calls `build()` with
@@ -29,14 +52,15 @@ export declare interface PostgresAnalyticsOptions {
29
52
  * the main DataStore is bound to (recommended; events live in the
30
53
  * same DB as your app). Pass a different SqlClient when you want
31
54
  * 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).
55
+ * Postgres while the main app uses MySQL. That database is not the app's,
56
+ * so its schema is yours: apply `postgresAnalyticsTables(options)` there
57
+ * (`applySchema(postgresAnalyticsTables(options), dialect)`).
35
58
  */
36
59
  readonly sqlClient?: SqlClient.SqlClient;
37
60
  /**
38
61
  * Reactive tables to CDC-mirror into the warehouse. Each table gets a
39
- * `_voltro_mirror_<table>` table (`{ id, data }`); the framework
62
+ * `_voltro_mirror_<table>` table (`{ id, data, version, is_deleted }`),
63
+ * declared with the events table so the schema applier creates it; the framework
40
64
  * streams `DataStore` changes into it so analytical queries can JOIN
41
65
  * events against live user data. Empty / omitted → events-only.
42
66
  *
@@ -64,6 +88,13 @@ export declare interface PostgresAnalyticsSpec {
64
88
  }>;
65
89
  }
66
90
 
91
+ /** Every table this sink writes: the events table, plus one mirror table per
92
+ * entry of `mirrorTables`. The framework merges them into the app's declared
93
+ * schema; a separate `sqlClient` database needs them applied there. */
94
+ export declare const postgresAnalyticsTables: (options?: Pick<PostgresAnalyticsOptions, "mirrorTables">) => ReadonlyArray<{
95
+ readonly tableName: string;
96
+ }>;
97
+
67
98
  export { TimeseriesQuery }
68
99
 
69
100
  export { TopNQuery }
package/dist/index.js CHANGED
@@ -1,19 +1,24 @@
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";
1
+ import { bigint as e, boolean as t, id as n, json as r, registerRetention as i, retentionTtlMsFromEnv as a, table as o, text as s, timestamp as c } from "@voltro/database";
2
+ import { Effect as l } from "effect";
3
+ import { AnalyticsError as u } from "@voltro/runtime";
4
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")
5
+ var d = o("_voltro_events", {
6
+ id: n({ scheme: "numeric" }),
7
+ name: s(),
8
+ subjectId: s().nullable(),
9
+ tenantId: s().nullable(),
10
+ properties: r().default(() => ({})),
11
+ occurredAt: c().default("now")
12
12
  }).index(["name", "occurredAt"]).index(["subjectId", "occurredAt"]).index([
13
13
  "tenantId",
14
14
  "name",
15
15
  "occurredAt"
16
- ]), u = (e, t, n) => {
16
+ ]), f = (e) => `_voltro_mirror_${e}`, p = (n) => o(f(n), {
17
+ id: s(),
18
+ data: r(),
19
+ version: e().default("0"),
20
+ is_deleted: t().default(!1)
21
+ }).primaryKey(["id"]).nonReactive(), m = (e, t, n) => {
17
22
  let r = `$.${n}`;
18
23
  return e.onDialectOrElse({
19
24
  mssql: () => e`JSON_VALUE(${e(t)}, ${r})`,
@@ -21,7 +26,7 @@ var l = i("_voltro_events", {
21
26
  sqlite: () => e`json_extract(${e(t)}, ${r})`,
22
27
  orElse: () => e`${e(t)}->>'${e.literal(n)}'`
23
28
  });
24
- }, d = (e, t, n) => {
29
+ }, h = (e, t, n) => {
25
30
  let r = `$.${n}`;
26
31
  return e.onDialectOrElse({
27
32
  mssql: () => e`TRY_CAST(JSON_VALUE(${e(t)}, ${r}) AS DECIMAL(38, 10))`,
@@ -29,86 +34,78 @@ var l = i("_voltro_events", {
29
34
  sqlite: () => e`CAST(json_extract(${e(t)}, ${r}) AS REAL)`,
30
35
  orElse: () => e`(${e(t)}->>'${e.literal(n)}')::numeric`
31
36
  });
32
- }, f = (e, t, n) => {
37
+ }, g = (e, t, n) => {
33
38
  let r = e(t);
34
39
  return n === "minute" ? e.onDialectOrElse({
35
40
  mssql: () => e`DATEADD(minute, DATEDIFF(minute, 0, ${r}), 0)`,
36
41
  mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-%d %H:%i:00')`,
37
- sqlite: () => e`strftime('%Y-%m-%dT%H:%M:00', ${r})`,
42
+ sqlite: () => e`strftime('%Y-%m-%dT%H:%M:00Z', ${r})`,
38
43
  orElse: () => e`date_trunc('minute', ${r})`
39
44
  }) : n === "hour" ? e.onDialectOrElse({
40
45
  mssql: () => e`DATEADD(hour, DATEDIFF(hour, 0, ${r}), 0)`,
41
46
  mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-%d %H:00:00')`,
42
- sqlite: () => e`strftime('%Y-%m-%dT%H:00:00', ${r})`,
47
+ sqlite: () => e`strftime('%Y-%m-%dT%H:00:00Z', ${r})`,
43
48
  orElse: () => e`date_trunc('hour', ${r})`
44
49
  }) : n === "day" ? e.onDialectOrElse({
45
50
  mssql: () => e`DATEADD(day, DATEDIFF(day, 0, ${r}), 0)`,
46
51
  mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-%d 00:00:00')`,
47
- sqlite: () => e`strftime('%Y-%m-%dT00:00:00', ${r})`,
52
+ sqlite: () => e`strftime('%Y-%m-%dT00:00:00Z', ${r})`,
48
53
  orElse: () => e`date_trunc('day', ${r})`
49
54
  }) : n === "week" ? e.onDialectOrElse({
50
55
  mssql: () => e`DATEADD(week, DATEDIFF(week, 0, ${r}), 0)`,
51
56
  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')`,
57
+ sqlite: () => e`strftime('%Y-%m-%dT00:00:00Z', ${r}, '-6 days', 'weekday 1')`,
53
58
  orElse: () => e`date_trunc('week', ${r})`
54
59
  }) : e.onDialectOrElse({
55
60
  mssql: () => e`DATEADD(month, DATEDIFF(month, 0, ${r}), 0)`,
56
61
  mysql: () => e`DATE_FORMAT(${r}, '%Y-%m-01 00:00:00')`,
57
- sqlite: () => e`strftime('%Y-%m-01T00:00:00', ${r})`,
62
+ sqlite: () => e`strftime('%Y-%m-01T00:00:00Z', ${r})`,
58
63
  orElse: () => e`date_trunc('month', ${r})`
59
64
  });
60
- }, p = "postgres-analytics", m = "_voltro_events", h = (e) => `_voltro_mirror_${e}`, g = (e) => s.mapError((t) => new c({
61
- provider: p,
65
+ }, _ = "postgres-analytics", v = "_voltro_events", y = (e, t) => e.onDialectOrElse({
66
+ sqlite: () => t.toISOString(),
67
+ orElse: () => t
68
+ }), b = (e) => l.mapError((t) => new u({
69
+ provider: _,
62
70
  operation: e,
63
71
  cause: t instanceof Error ? `${t.name}: ${t.message}` : String(t)
64
- })), _ = (e, t, n, r, i) => {
72
+ })), x = (e, t, n, r, i) => {
65
73
  let a = e("name"), o = e("occurredAt");
66
- return e`WHERE ${a} = ${t} AND ${o} >= ${n.from}${n.to === void 0 ? e`` : e` AND ${o} < ${n.to}`}${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
- ${e("version")} BIGINT NOT NULL DEFAULT 0,
74
- ${e("is_deleted")} BOOLEAN NOT NULL DEFAULT false
75
- )
76
- `, r.add(t));
77
- }), a = (e) => s.mapError((t) => new c({
78
- provider: p,
74
+ return e`WHERE ${a} = ${t} AND ${o} >= ${y(e, n.from)}${n.to === void 0 ? e`` : e` AND ${o} < ${y(e, n.to)}`}${r !== void 0 && Object.keys(r).length > 0 ? e` AND ${e.and(Object.entries(r).map(([t, n]) => e`${m(e, "properties", t)} = ${n}`))}` : e``}${i == null ? e`` : e` AND ${e("tenantId")} = ${i}`}`;
75
+ }, S = (e, t) => t === "count" ? e`COUNT(*)` : t === "unique" ? e`COUNT(DISTINCT ${e("subjectId")})` : "sum" in t ? e`COALESCE(SUM(${h(e, "properties", t.sum)}), 0)` : e`AVG(${h(e, "properties", t.avg)})`, C = (e, t) => t === "count" ? e`COUNT(*)` : e`COALESCE(SUM(${h(e, "properties", t.sum)}), 0)`, w = (e, t, n) => {
76
+ let r = (e) => l.mapError((t) => new u({
77
+ provider: _,
79
78
  operation: e,
80
79
  cause: t instanceof Error ? `${t.name}: ${t.message}` : String(t)
81
- })), o = (t, n, r, a, o) => s.gen(function* () {
82
- yield* i(t);
83
- let s = h(t);
80
+ })), i = (t, n, r, i, a) => l.gen(function* () {
81
+ let o = f(t);
84
82
  yield* e`
85
- INSERT INTO ${e(s)} (${e("id")}, ${e("data")}, ${e("version")}, ${e("is_deleted")})
86
- VALUES (${n}, ${r}, ${a}, ${o})
83
+ INSERT INTO ${e(o)} (${e("id")}, ${e("data")}, ${e("version")}, ${e("is_deleted")})
84
+ VALUES (${n}, ${r}, ${i}, ${a})
87
85
  ON CONFLICT (${e("id")}) DO UPDATE SET
88
86
  ${e("data")} = ${r},
89
- ${e("version")} = ${a},
90
- ${e("is_deleted")} = ${o}
91
- WHERE ${e(s)}.${e("version")} < ${a}
87
+ ${e("version")} = ${i},
88
+ ${e("is_deleted")} = ${a}
89
+ WHERE ${e(o)}.${e("version")} < ${i}
92
90
  `;
93
91
  });
94
92
  return {
95
93
  tables: t,
96
94
  primaryKey: n,
97
- upsert: ({ table: e, row: t, version: r }) => o(e, String(t[n]), JSON.stringify(t), r, !1).pipe(a("mirror.upsert")),
98
- remove: ({ table: e, primaryKeyValue: t, version: n }) => o(e, String(t), "{}", n, !0).pipe(a("mirror.remove")),
99
- maxVersion: ({ table: t, primaryKeyValue: n }) => s.gen(function* () {
100
- yield* i(t);
101
- let r = h(t), a = (yield* e`
95
+ upsert: ({ table: e, row: t, version: a }) => i(e, String(t[n]), JSON.stringify(t), a, !1).pipe(r("mirror.upsert")),
96
+ remove: ({ table: e, primaryKeyValue: t, version: n }) => i(e, String(t), "{}", n, !0).pipe(r("mirror.remove")),
97
+ maxVersion: ({ table: t, primaryKeyValue: n }) => l.gen(function* () {
98
+ let r = f(t), i = (yield* e`
102
99
  SELECT ${e("version")} AS version FROM ${e(r)} WHERE ${e("id")} = ${String(n)}
103
100
  `)[0]?.version;
104
- return a == null ? null : Number(a);
105
- }).pipe(a("mirror.maxVersion"))
101
+ return i == null ? null : Number(i);
102
+ }).pipe(r("mirror.maxVersion"))
106
103
  };
107
- }, x = (e, t = {}) => {
108
- let n = e, r = t.mirrorTables ?? [], i = r.length > 0 ? b(n, r, t.mirrorPrimaryKey ?? "id") : void 0;
104
+ }, T = (e, t = {}) => {
105
+ let n = e, r = t.mirrorTables ?? [], i = r.length > 0 ? w(n, r, t.mirrorPrimaryKey ?? "id") : void 0;
109
106
  return {
110
107
  info: {
111
- provider: p,
108
+ provider: _,
112
109
  capabilities: {
113
110
  track: !0,
114
111
  aggregate: !0,
@@ -117,47 +114,47 @@ var l = i("_voltro_events", {
117
114
  mirror: i !== void 0
118
115
  },
119
116
  detail: {
120
- table: m,
117
+ table: v,
121
118
  ...r.length > 0 ? { mirrorTables: r } : {}
122
119
  }
123
120
  },
124
- track: (e) => s.gen(function* () {
125
- let t = e.occurredAt ?? /* @__PURE__ */ new Date(), r = JSON.stringify(e.properties), i = e.subjectId ?? null, a = e.tenantId ?? null;
121
+ track: (e) => l.gen(function* () {
122
+ let t = y(n, e.occurredAt ?? /* @__PURE__ */ new Date()), r = JSON.stringify(e.properties), i = e.subjectId ?? null, a = e.tenantId ?? null;
126
123
  yield* n`
127
- INSERT INTO ${n(m)} (${n("name")}, ${n("subjectId")}, ${n("tenantId")}, ${n("properties")}, ${n("occurredAt")})
124
+ INSERT INTO ${n(v)} (${n("name")}, ${n("subjectId")}, ${n("tenantId")}, ${n("properties")}, ${n("occurredAt")})
128
125
  VALUES (${e.name}, ${i}, ${a}, ${r}, ${t})
129
126
  `;
130
- }).pipe(g("track")),
131
- aggregate: (e) => s.gen(function* () {
132
- let t = v(n, e.metric), r = _(n, e.event, e.range, e.filter, e.tenantId), i = (yield* n`
133
- SELECT ${t} AS ${n("value")} FROM ${n(m)} ${r}
127
+ }).pipe(b("track")),
128
+ aggregate: (e) => l.gen(function* () {
129
+ let t = S(n, e.metric), r = x(n, e.event, e.range, e.filter, e.tenantId), i = (yield* n`
130
+ SELECT ${t} AS ${n("value")} FROM ${n(v)} ${r}
134
131
  `)[0]?.value ?? 0;
135
132
  return typeof i == "number" ? i : Number(i ?? 0);
136
- }).pipe(g("aggregate")),
137
- timeseries: (e) => s.gen(function* () {
138
- let t = v(n, e.metric), r = f(n, "occurredAt", e.bucket), i = _(n, e.event, e.range, e.filter, e.tenantId);
133
+ }).pipe(b("aggregate")),
134
+ timeseries: (e) => l.gen(function* () {
135
+ let t = S(n, e.metric), r = g(n, "occurredAt", e.bucket), i = x(n, e.event, e.range, e.filter, e.tenantId);
139
136
  return (yield* n`
140
137
  SELECT ${r} AS ${n("bucket_start")}, ${t} AS ${n("value")}
141
- FROM ${n(m)} ${i}
138
+ FROM ${n(v)} ${i}
142
139
  GROUP BY ${r}
143
140
  ORDER BY ${r} ASC
144
141
  `).map((e) => ({
145
142
  bucketStart: e.bucket_start instanceof Date ? e.bucket_start : new Date(e.bucket_start),
146
143
  value: typeof e.value == "number" ? e.value : Number(e.value ?? 0)
147
144
  }));
148
- }).pipe(g("timeseries")),
149
- topN: (e) => s.gen(function* () {
150
- 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));
145
+ }).pipe(b("timeseries")),
146
+ topN: (e) => l.gen(function* () {
147
+ let t = C(n, e.metric), r = m(n, "properties", e.groupBy), i = x(n, e.event, e.range, e.filter, e.tenantId), a = Math.max(1, Math.floor(e.n));
151
148
  return (yield* n.onDialectOrElse({
152
149
  mssql: () => n`
153
150
  SELECT TOP (${a}) ${r} AS ${n("key")}, ${t} AS ${n("value")}
154
- FROM ${n(m)} ${i}
151
+ FROM ${n(v)} ${i}
155
152
  GROUP BY ${r}
156
153
  ORDER BY ${t} DESC
157
154
  `,
158
155
  orElse: () => n`
159
156
  SELECT ${r} AS ${n("key")}, ${t} AS ${n("value")}
160
- FROM ${n(m)} ${i}
157
+ FROM ${n(v)} ${i}
161
158
  GROUP BY ${r}
162
159
  ORDER BY ${t} DESC
163
160
  LIMIT ${a}
@@ -166,22 +163,22 @@ var l = i("_voltro_events", {
166
163
  key: e.key,
167
164
  value: typeof e.value == "number" ? e.value : Number(e.value ?? 0)
168
165
  }));
169
- }).pipe(g("topN")),
166
+ }).pipe(b("topN")),
170
167
  ...i === void 0 ? {} : { mirror: i }
171
168
  };
172
- }, S = (e = {}) => (n({
169
+ }, E = (e = {}) => (i({
173
170
  source: "plugin",
174
171
  table: "_voltro_events",
175
172
  timeColumn: "occurredAt",
176
- ttlMs: r(process.env.VOLTRO_EVENTS_TTL_HOURS, 8760)
173
+ ttlMs: a(process.env.VOLTRO_EVENTS_TTL_HOURS, 8760)
177
174
  }), {
178
175
  kind: "postgres-analytics",
179
176
  options: e,
180
- build: (t) => x(e.sqlClient ?? t, {
177
+ build: (t) => T(e.sqlClient ?? t, {
181
178
  ...e.mirrorTables === void 0 ? {} : { mirrorTables: e.mirrorTables },
182
179
  ...e.mirrorPrimaryKey === void 0 ? {} : { mirrorPrimaryKey: e.mirrorPrimaryKey }
183
180
  }),
184
- tables: [l]
185
- });
181
+ tables: D(e)
182
+ }), D = (e = {}) => [d, ...(e.mirrorTables ?? []).map((e) => p(e))];
186
183
  //#endregion
187
- export { l as _voltroEventsTable, S as postgresAnalytics };
184
+ export { d as _voltroEventsTable, p as mirrorTable, f as mirrorTableName, E as postgresAnalytics, D as postgresAnalyticsTables };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voltro/plugin-analytics-postgres",
3
- "version": "0.81.0",
3
+ "version": "0.83.0",
4
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
5
  "keywords": [
6
6
  "voltro",
@@ -34,8 +34,8 @@
34
34
  },
35
35
  "dependencies": {
36
36
  "@effect/sql": "^0.52.1",
37
- "@voltro/database": "0.81.0",
38
- "@voltro/runtime": "0.81.0"
37
+ "@voltro/database": "0.83.0",
38
+ "@voltro/runtime": "0.83.0"
39
39
  },
40
40
  "peerDependencies": {
41
41
  "effect": "^3.22.2"