@uptimizr/db-postgres 0.0.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.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or Derivative
95
+ Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and do
117
+ not modify the License. You may add Your own attribution notices
118
+ within Derivative Works that You distribute, alongside or as an
119
+ addendum to the NOTICE text from the Work, provided that such
120
+ additional attribution notices cannot be construed as modifying
121
+ the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions for
125
+ use, reproduction, or distribution of Your modifications, or for any
126
+ such Derivative Works as a whole, provided Your use, reproduction,
127
+ and distribution of the Work otherwise complies with the conditions
128
+ stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Uptimizr Contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,118 @@
1
+ # @uptimizr/db-postgres
2
+
3
+ Optional **single-tenant PostgreSQL store** for the Uptimizr collector — for
4
+ self-hosters who already run Postgres and want a familiar, multi-writer
5
+ relational backend instead of the default single-file DuckDB store (ADR 0020,
6
+ issue #84).
7
+
8
+ It is a **re-home + dialect emitter, not a rewrite**: every analytics
9
+ aggregation is authored once in [`@uptimizr/db`](../db) against the
10
+ dialect-agnostic query layer, and this package renders them to Postgres SQL via
11
+ the shared `postgresDialect`, plus a pooled [`pg`](https://node-postgres.com)
12
+ client, schema/migrations, and metadata helpers that satisfy the same
13
+ `CollectorStore` contract as DuckDB and ClickHouse.
14
+
15
+ ## When to use it
16
+
17
+ Stay on the default DuckDB store unless you hit its single read-write process
18
+ ceiling. Choose Postgres when you want **several collector instances** sharing
19
+ one store, or when Postgres is simply the database your team already operates
20
+ (managed Postgres, RDS, Cloud SQL, Supabase, Neon, …). Choose
21
+ [`@uptimizr/db-clickhouse`](../db-clickhouse) instead for high-volume ingestion
22
+ and large historical ranges.
23
+
24
+ ## Usage
25
+
26
+ Select it via the collector's `COLLECTOR_STORE` env var:
27
+
28
+ ```bash
29
+ COLLECTOR_STORE=postgres \
30
+ POSTGRES_URL=postgresql://uptimizr:uptimizr@localhost:5432/uptimizr \
31
+ pnpm --filter @uptimizr/collector-server start
32
+ ```
33
+
34
+ | Variable | Purpose |
35
+ | ---------------------------------- | -------------------------------------------------------------------------------------- |
36
+ | `POSTGRES_URL` (or `DATABASE_URL`) | libpq connection URI (`?sslmode=require` etc. apply). The database must already exist. |
37
+ | `POSTGRES_SCHEMA` | Schema the store's tables live in (default `public`; created on first boot). |
38
+ | `POSTGRES_POOL_MAX` | Maximum pooled connections per collector process (default `10`). |
39
+
40
+ A local Postgres is available via [`infra/docker`](../../../infra/docker)
41
+ (`pnpm stack:up` starts a `postgres:16` service). The schema is migrated on store
42
+ creation — migrations are idempotent, forward-only (ADR 0007) and serialized
43
+ behind an advisory lock, so several instances may boot concurrently against one
44
+ database. Postgres 14+ is supported (tested against 16).
45
+
46
+ ## Scope
47
+
48
+ - **Single-tenant only** — no `org_id`, no tenant isolation. The multi-writer
49
+ rollups and scale tuning remain the scale tier; this package is the
50
+ single-instance relational adapter.
51
+ - No stubbed features — the full analytics surface (heatmaps, perf percentiles,
52
+ click↔gaze rays, funnels) returns results identical to DuckDB on the
53
+ cross-engine parity fixtures.
54
+
55
+ ## Row-store fit gaps and how they are closed
56
+
57
+ | Gap | Postgres rendering |
58
+ | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
59
+ | No `ASOF JOIN` | `Dialect.asofJoin(spec)` renders `[INNER\|LEFT] JOIN LATERAL (SELECT * FROM <right> WHERE keys… AND ts <= left.ts ORDER BY ts DESC LIMIT 1) ON TRUE` (`renderNearestRowJoin`). Same rows as a native ASOF join; one indexed lookup per left row instead of a single merge pass — fine at self-host scale, slower than DuckDB/ClickHouse on very large sessions. The `(project_id, session_id, ts)` index exists for exactly this. |
60
+ | No MergeTree rollups | `perf_daily` / `events_daily` are plain views recomputed at query time; the `-Merge` combinators reduce to `sum`/`avg`/`percentile_cont` pass-throughs, as on DuckDB. |
61
+ | 1-indexed arrays | Same convention as DuckDB and ClickHouse, so `position[1]` in the shared SQL is untouched; `arrayLength` → `cardinality`, `vectorNorm` → `sqrt(sum(v*v))` over `unnest`. |
62
+ | `quantile` / `avgIf` / `any` | `percentile_cont(q) WITHIN GROUP (ORDER BY …)`, `avg(…) FILTER (WHERE …)`, `min(…)` (a deterministic "any" that also works before PG 16's `any_value`). |
63
+ | JSON extraction, no `TRY_CAST` | `payload` is `jsonb`; `jsonText` → `#>>`, `jsonInt`/`jsonFloat` regex-guard the cast so absent / non-numeric keys yield NULL exactly like DuckDB's `TRY_CAST`. The payload round-trips replay-complete (`jsonb` is value-lossless for JSON numbers/strings; key order is irrelevant). |
64
+ | Parameters | The dialect emits named `$name::type` placeholders (explicit casts, so Postgres never infers a parameter type); `runPostgresQuery` rewrites them to positional `$1…$n` with the shared `toPositionalParams`. |
65
+ | `count()` / `length(array)` | Not valid Postgres — the shared SQL now uses `count(*)` and `Dialect.arrayLength`. |
66
+ | Timestamps | `timestamp` (without time zone) holding wall-clock UTC, bound as naive-UTC literals; epoch extraction, `::date` and bucketing are session-`TimeZone`-independent and identical to the other engines. |
67
+
68
+ ### Documented divergences
69
+
70
+ None on the parity fixtures: all 68 `PARITY_CASES` match the golden and DuckDB,
71
+ and every `build*` aggregation (69, across base / filtered / spatial option
72
+ variants) matches DuckDB row-for-row. Two engine behaviours differ only where
73
+ the query layer already declares them unspecified: ties on the right-hand
74
+ timestamp of an ASOF join are broken arbitrarily on every engine, and
75
+ `anyValue` picks an arbitrary group member on DuckDB/ClickHouse but the minimum
76
+ on Postgres (callers only use it on values constant within the group).
77
+
78
+ ## Reusable relational helpers (for the SQL Server port, #85)
79
+
80
+ The engine-neutral pieces live in `@uptimizr/db` (`src/query/relational.ts`) and
81
+ are re-exported from its root:
82
+
83
+ - `renderNearestRowJoin(spec, tokens)` — the ASOF emulation; SQL Server reuses
84
+ it with `{ inner: "CROSS APPLY", left: "OUTER APPLY", onTrue: "",
85
+ selectPrefix: "SELECT TOP 1", selectSuffix: "" }`.
86
+ - `renderNativeAsofJoin(spec)` — the DuckDB / ClickHouse rendering.
87
+ - `toPositionalParams(sql, params, render)` — named → positional rewriting
88
+ (`@p1…` for `mssql`).
89
+ - The query-time rollup strategy (plain views named `perf_daily` /
90
+ `events_daily` with `*_state` columns) and the `jsonb`-style regex-guarded
91
+ numeric extraction pattern are documented in `migrations.ts` and
92
+ `postgresDialect.ts` respectively and port 1:1.
93
+
94
+ ## Layout
95
+
96
+ | File | Responsibility |
97
+ | ------------------ | ----------------------------------------------------------------------- |
98
+ | `client.ts` | Pooled `pg` wrapper (UTC session, schema search path, plain-JS values). |
99
+ | `migrations.ts` | Forward-only DDL (events, node_samples, metadata, query-time views). |
100
+ | `events.ts` | Batched multi-row inserts + replay-complete session reads. |
101
+ | `projects.ts` | Project + API-key metadata (SHA-256 hashes). |
102
+ | `sceneRegistry.ts` | Per-`(project, scene)` representation upserts/reads (`ON CONFLICT`). |
103
+ | `queries.ts` | `runPostgresQuery` — executes a rendered `QuerySpec`. |
104
+
105
+ The `CollectorStore` itself is assembled from these building blocks in the
106
+ collector server (`oss/apps/collector-server/src/postgresStore.ts`,
107
+ `createPostgresStore`), mirroring the DuckDB and ClickHouse stores — this
108
+ package stays a store-agnostic toolkit.
109
+
110
+ ## Tests
111
+
112
+ - `dialect.test.ts` — pure unit checks (no server).
113
+ - `postgresParity.test.ts` / `postgresStore.test.ts` — live suites that probe
114
+ `POSTGRES_URL` (or `DATABASE_URL`) first and **skip when no server is
115
+ reachable**, so the default `pnpm test` stays Docker-free. They use throwaway
116
+ schemas that are dropped on teardown.
117
+
118
+ Licensed Apache-2.0.
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Postgres client — the optional single-tenant relational store (ADR 0020, #84).
3
+ *
4
+ * A thin wrapper over `pg`'s connection pool that centralizes connection
5
+ * settings and exposes the small surface the store needs: positional-parameter
6
+ * queries, DDL commands, and transactions. Mirrors the shape of the DuckDB and
7
+ * ClickHouse clients so the store assembly reads the same across engines.
8
+ *
9
+ * Postgres is a networked, multi-writer server safe for concurrent statements,
10
+ * so there is no single-writer serialization here — several collector instances
11
+ * can share one database, which is the point of this store.
12
+ *
13
+ * Value coercion: `pg` returns `int8` (`count(*)`, epoch-ms casts) and `numeric`
14
+ * (`avg`/`sum` over integers) as **strings**, and parses `date`/`timestamp`
15
+ * columns into local-time `Date`s. The pool installs type parsers so those come
16
+ * back as plain JS numbers / naive-UTC strings instead, matching the rows the
17
+ * DuckDB client returns (and the row shapes the query layer's types declare).
18
+ */
19
+ import type { PostgresSettings } from "@uptimizr/db";
20
+ /** A row of plain-JS values returned by a query. */
21
+ export type PostgresRow = Record<string, unknown>;
22
+ /** The statement surface available both on the pool and inside a transaction. */
23
+ export interface PostgresExecutor {
24
+ /** Run a positional-parameter (`$1…$n`) query and return all rows. */
25
+ query<T = PostgresRow>(sql: string, values?: readonly unknown[]): Promise<T[]>;
26
+ /** Run a DDL/maintenance statement, ignoring any result set. */
27
+ command(sql: string): Promise<void>;
28
+ }
29
+ export interface PostgresClient extends PostgresExecutor {
30
+ /** Run `fn` inside one transaction (committed on success, rolled back on throw). */
31
+ transaction<T>(fn: (tx: PostgresExecutor) => Promise<T>): Promise<T>;
32
+ /** Drain the pool and release every connection. */
33
+ close(): Promise<void>;
34
+ }
35
+ /**
36
+ * Guard an operator-supplied identifier (the `POSTGRES_SCHEMA` name) before
37
+ * interpolating it into DDL / `search_path`. It comes from trusted env, not
38
+ * request input, but a strict allow-list keeps the statements injection-proof.
39
+ */
40
+ export declare function assertSafeIdentifier(name: string, what?: string): string;
41
+ /**
42
+ * Create a pooled Postgres client from {@link PostgresSettings}. Every
43
+ * connection pins `TimeZone=UTC` and `search_path` to the configured schema, so
44
+ * `now()`-based defaults and unqualified table names behave identically across
45
+ * collector instances regardless of the server's defaults. The schema itself is
46
+ * created by {@link migratePostgres} on first boot.
47
+ */
48
+ export declare function createPostgresClient(settings: PostgresSettings): PostgresClient;
49
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../src/client.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;GAiBG;AAGH,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,cAAc,CAAC;AAErD,oDAAoD;AACpD,MAAM,MAAM,WAAW,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAElD,iFAAiF;AACjF,MAAM,WAAW,gBAAgB;IAC/B,sEAAsE;IACtE,KAAK,CAAC,CAAC,GAAG,WAAW,EAAE,GAAG,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,SAAS,OAAO,EAAE,GAAG,OAAO,CAAC,CAAC,EAAE,CAAC,CAAC;IAC/E,gEAAgE;IAChE,OAAO,CAAC,GAAG,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACrC;AAED,MAAM,WAAW,cAAe,SAAQ,gBAAgB;IACtD,oFAAoF;IACpF,WAAW,CAAC,CAAC,EAAE,EAAE,EAAE,CAAC,EAAE,EAAE,gBAAgB,KAAK,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IACrE,mDAAmD;IACnD,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;CACxB;AAyCD;;;;GAIG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,SAAyB,GAAG,MAAM,CAQxF;AAgBD;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,QAAQ,EAAE,gBAAgB,GAAG,cAAc,CAqC/E"}
package/dist/client.js ADDED
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Postgres client — the optional single-tenant relational store (ADR 0020, #84).
3
+ *
4
+ * A thin wrapper over `pg`'s connection pool that centralizes connection
5
+ * settings and exposes the small surface the store needs: positional-parameter
6
+ * queries, DDL commands, and transactions. Mirrors the shape of the DuckDB and
7
+ * ClickHouse clients so the store assembly reads the same across engines.
8
+ *
9
+ * Postgres is a networked, multi-writer server safe for concurrent statements,
10
+ * so there is no single-writer serialization here — several collector instances
11
+ * can share one database, which is the point of this store.
12
+ *
13
+ * Value coercion: `pg` returns `int8` (`count(*)`, epoch-ms casts) and `numeric`
14
+ * (`avg`/`sum` over integers) as **strings**, and parses `date`/`timestamp`
15
+ * columns into local-time `Date`s. The pool installs type parsers so those come
16
+ * back as plain JS numbers / naive-UTC strings instead, matching the rows the
17
+ * DuckDB client returns (and the row shapes the query layer's types declare).
18
+ */
19
+ import pg from "pg";
20
+ // Postgres type OIDs whose default `pg` parsing is replaced (see module doc).
21
+ const OID_INT8 = 20;
22
+ const OID_NUMERIC = 1700;
23
+ const OID_INT8_ARRAY = 1016;
24
+ const OID_NUMERIC_ARRAY = 1231;
25
+ const OID_DATE = 1082;
26
+ const OID_TIMESTAMP = 1114;
27
+ const OID_TIMESTAMPTZ = 1184;
28
+ const identity = (value) => value;
29
+ /**
30
+ * Build the per-pool type-parser table: 64-bit integers and numerics (scalar
31
+ * and array) become JS numbers; date/timestamp columns stay the naive text
32
+ * Postgres renders (`YYYY-MM-DD`, `YYYY-MM-DD HH:MM:SS[.fff]`) — the store never
33
+ * relies on `pg`'s local-time `Date` interpretation of a naive timestamp.
34
+ */
35
+ function buildTypeParsers() {
36
+ const numericArray = (oid) => {
37
+ const parseStrings = pg.types.getTypeParser(oid, "text");
38
+ return (value) => parseStrings(value).map((v) => (v === null ? null : Number(v)));
39
+ };
40
+ const overrides = new Map([
41
+ [OID_INT8, Number],
42
+ [OID_NUMERIC, Number],
43
+ [OID_INT8_ARRAY, numericArray(OID_INT8_ARRAY)],
44
+ [OID_NUMERIC_ARRAY, numericArray(OID_NUMERIC_ARRAY)],
45
+ [OID_DATE, identity],
46
+ [OID_TIMESTAMP, identity],
47
+ [OID_TIMESTAMPTZ, identity],
48
+ ]);
49
+ return {
50
+ getTypeParser(oid, format) {
51
+ const override = format === "binary" ? undefined : overrides.get(oid);
52
+ return override ?? pg.types.getTypeParser(oid, format);
53
+ },
54
+ };
55
+ }
56
+ /**
57
+ * Guard an operator-supplied identifier (the `POSTGRES_SCHEMA` name) before
58
+ * interpolating it into DDL / `search_path`. It comes from trusted env, not
59
+ * request input, but a strict allow-list keeps the statements injection-proof.
60
+ */
61
+ export function assertSafeIdentifier(name, what = "Postgres schema name") {
62
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
63
+ throw new Error(`Invalid ${what} ${JSON.stringify(name)}: ` +
64
+ "expected letters, digits and underscores (starting with a letter or underscore).");
65
+ }
66
+ return name;
67
+ }
68
+ function makeExecutor(run) {
69
+ return {
70
+ async query(sql, values) {
71
+ const result = await run(sql, values);
72
+ return result.rows;
73
+ },
74
+ async command(sql) {
75
+ await run(sql);
76
+ },
77
+ };
78
+ }
79
+ /**
80
+ * Create a pooled Postgres client from {@link PostgresSettings}. Every
81
+ * connection pins `TimeZone=UTC` and `search_path` to the configured schema, so
82
+ * `now()`-based defaults and unqualified table names behave identically across
83
+ * collector instances regardless of the server's defaults. The schema itself is
84
+ * created by {@link migratePostgres} on first boot.
85
+ */
86
+ export function createPostgresClient(settings) {
87
+ const schema = assertSafeIdentifier(settings.schema);
88
+ const pool = new pg.Pool({
89
+ connectionString: settings.url,
90
+ max: settings.poolMax,
91
+ types: buildTypeParsers(),
92
+ // libpq startup options: UTC wall clock + the store's schema first in the
93
+ // search path (public stays reachable for extensions).
94
+ options: `-c TimeZone=UTC -c search_path=${schema},public`,
95
+ });
96
+ // A connection dropped by the server while idle would otherwise surface as an
97
+ // unhandled 'error' event and crash the process; the pool replaces it lazily.
98
+ pool.on("error", () => { });
99
+ const executor = makeExecutor((sql, values) => pool.query(sql, values ? [...values] : undefined));
100
+ return {
101
+ ...executor,
102
+ async transaction(fn) {
103
+ const conn = await pool.connect();
104
+ try {
105
+ await conn.query("BEGIN");
106
+ const tx = makeExecutor((sql, values) => conn.query(sql, values ? [...values] : undefined));
107
+ const result = await fn(tx);
108
+ await conn.query("COMMIT");
109
+ return result;
110
+ }
111
+ catch (error) {
112
+ await conn.query("ROLLBACK").catch(() => { });
113
+ throw error;
114
+ }
115
+ finally {
116
+ conn.release();
117
+ }
118
+ },
119
+ async close() {
120
+ await pool.end();
121
+ },
122
+ };
123
+ }
124
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file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AK,CAAC,KAAK;YACT,MAAM,IAAI,CAAC,GAAG,EAAE,CAAC;QACnB,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,34 @@
1
+ import { type SessionMeta } from "@uptimizr/db";
2
+ import { type AnyEvent } from "@uptimizr/schema";
3
+ import type { PostgresClient } from "./client.js";
4
+ export type { SessionMeta };
5
+ /**
6
+ * Batched insert of validated events. Reuses the shared {@link toEventRow} mapper
7
+ * so the promoted columns match the DuckDB store exactly; `ts` is bound as the
8
+ * naive-UTC literal every engine accepts and `payload` lands in `jsonb`.
9
+ *
10
+ * `node_transform` events (ADR 0027) are split out into the dedicated
11
+ * `node_samples` table rather than the wide `events` table. Both inserts run in
12
+ * one transaction, so a batch is never partially applied.
13
+ */
14
+ export declare function insertEvents(client: PostgresClient, events: readonly AnyEvent[]): Promise<void>;
15
+ /**
16
+ * Ordered read of a single session's events for replay/timeline. Returns
17
+ * fully-parsed, schema-validated events in `ts` order, merging the wide `events`
18
+ * table with the dedicated `node_samples` table (ADR 0027 §9). Gated upstream by
19
+ * `ENABLE_RAW_SESSION_RETENTION` (ADR 0003) — this function does not enforce it.
20
+ */
21
+ export declare function getSessionEvents(client: PostgresClient, projectId: string, sessionId: string): Promise<AnyEvent[]>;
22
+ /**
23
+ * Streaming counterpart to {@link getSessionEvents}: yields one validated event
24
+ * at a time in `ts` order (the path behind the collector's NDJSON replay
25
+ * response, ADR 0015). The session is read as one ordered result set; node
26
+ * samples are merged in by `ts` before yielding.
27
+ */
28
+ export declare function streamSessionEvents(client: PostgresClient, projectId: string, sessionId: string): AsyncGenerator<AnyEvent>;
29
+ /**
30
+ * Read a session's stored metadata (`device`/`scene`/`user`) from its
31
+ * `session_start` event. Returns `null` when the session has no start event.
32
+ */
33
+ export declare function getSessionMeta(client: PostgresClient, projectId: string, sessionId: string): Promise<SessionMeta | null>;
34
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA,OAAO,EAML,KAAK,WAAW,EACjB,MAAM,cAAc,CAAC;AACtB,OAAO,EAAkB,KAAK,QAAQ,EAA2B,MAAM,kBAAkB,CAAC;AAC1F,OAAO,KAAK,EAAE,cAAc,EAAoB,MAAM,aAAa,CAAC;AAEpE,YAAY,EAAE,WAAW,EAAE,CAAC;AA8F5B;;;;;;;;GAQG;AACH,wBAAsB,YAAY,CAChC,MAAM,EAAE,cAAc,EACtB,MAAM,EAAE,SAAS,QAAQ,EAAE,GAC1B,OAAO,CAAC,IAAI,CAAC,CAiBf;AAkGD;;;;;GAKG;AACH,wBAAsB,gBAAgB,CACpC,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,QAAQ,EAAE,CAAC,CAIrB;AAED;;;;;GAKG;AACH,wBAAuB,mBAAmB,CACxC,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,cAAc,CAAC,QAAQ,CAAC,CAK1B;AAED;;;GAGG;AACH,wBAAsB,cAAc,CAClC,MAAM,EAAE,cAAc,EACtB,SAAS,EAAE,MAAM,EACjB,SAAS,EAAE,MAAM,GAChB,OAAO,CAAC,WAAW,GAAG,IAAI,CAAC,CAqB7B"}