@byline/analytics-postgres 4.16.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,373 @@
1
+ Mozilla Public License Version 2.0
2
+ ==================================
3
+
4
+ 1. Definitions
5
+ --------------
6
+
7
+ 1.1. "Contributor"
8
+ means each individual or legal entity that creates, contributes to
9
+ the creation of, or owns Covered Software.
10
+
11
+ 1.2. "Contributor Version"
12
+ means the combination of the Contributions of others (if any) used
13
+ by a Contributor and that particular Contributor's Contribution.
14
+
15
+ 1.3. "Contribution"
16
+ means Covered Software of a particular Contributor.
17
+
18
+ 1.4. "Covered Software"
19
+ means Source Code Form to which the initial Contributor has attached
20
+ the notice in Exhibit A, the Executable Form of such Source Code
21
+ Form, and Modifications of such Source Code Form, in each case
22
+ including portions thereof.
23
+
24
+ 1.5. "Incompatible With Secondary Licenses"
25
+ means
26
+
27
+ (a) that the initial Contributor has attached the notice described
28
+ in Exhibit B to the Covered Software; or
29
+
30
+ (b) that the Covered Software was made available under the terms of
31
+ version 1.1 or earlier of the License, but not also under the
32
+ terms of a Secondary License.
33
+
34
+ 1.6. "Executable Form"
35
+ means any form of the work other than Source Code Form.
36
+
37
+ 1.7. "Larger Work"
38
+ means a work that combines Covered Software with other material, in
39
+ a separate file or files, that is not Covered Software.
40
+
41
+ 1.8. "License"
42
+ means this document.
43
+
44
+ 1.9. "Licensable"
45
+ means having the right to grant, to the maximum extent possible,
46
+ whether at the time of the initial grant or subsequently, any and
47
+ all of the rights conveyed by this License.
48
+
49
+ 1.10. "Modifications"
50
+ means any of the following:
51
+
52
+ (a) any file in Source Code Form that results from an addition to,
53
+ deletion from, or modification of the contents of Covered
54
+ Software; or
55
+
56
+ (b) any new file in Source Code Form that contains any Covered
57
+ Software.
58
+
59
+ 1.11. "Patent Claims" of a Contributor
60
+ means any patent claim(s), including without limitation, method,
61
+ process, and apparatus claims, in any patent Licensable by such
62
+ Contributor that would be infringed, but for the grant of the
63
+ License, by the making, using, selling, offering for sale, having
64
+ made, import, or transfer of either its Contributions or its
65
+ Contributor Version.
66
+
67
+ 1.12. "Secondary License"
68
+ means either the GNU General Public License, Version 2.0, the GNU
69
+ Lesser General Public License, Version 2.1, the GNU Affero General
70
+ Public License, Version 3.0, or any later versions of those
71
+ licenses.
72
+
73
+ 1.13. "Source Code Form"
74
+ means the form of the work preferred for making modifications.
75
+
76
+ 1.14. "You" (or "Your")
77
+ means an individual or a legal entity exercising rights under this
78
+ License. For legal entities, "You" includes any entity that
79
+ controls, is controlled by, or is under common control with You. For
80
+ purposes of this definition, "control" means (a) the power, direct
81
+ or indirect, to cause the direction or management of such entity,
82
+ whether by contract or otherwise, or (b) ownership of more than
83
+ fifty percent (50%) of the outstanding shares or beneficial
84
+ ownership of such entity.
85
+
86
+ 2. License Grants and Conditions
87
+ --------------------------------
88
+
89
+ 2.1. Grants
90
+
91
+ Each Contributor hereby grants You a world-wide, royalty-free,
92
+ non-exclusive license:
93
+
94
+ (a) under intellectual property rights (other than patent or trademark)
95
+ Licensable by such Contributor to use, reproduce, make available,
96
+ modify, display, perform, distribute, and otherwise exploit its
97
+ Contributions, either on an unmodified basis, with Modifications, or
98
+ as part of a Larger Work; and
99
+
100
+ (b) under Patent Claims of such Contributor to make, use, sell, offer
101
+ for sale, have made, import, and otherwise transfer either its
102
+ Contributions or its Contributor Version.
103
+
104
+ 2.2. Effective Date
105
+
106
+ The licenses granted in Section 2.1 with respect to any Contribution
107
+ become effective for each Contribution on the date the Contributor first
108
+ distributes such Contribution.
109
+
110
+ 2.3. Limitations on Grant Scope
111
+
112
+ The licenses granted in this Section 2 are the only rights granted under
113
+ this License. No additional rights or licenses will be implied from the
114
+ distribution or licensing of Covered Software under this License.
115
+ Notwithstanding Section 2.1(b) above, no patent license is granted by a
116
+ Contributor:
117
+
118
+ (a) for any code that a Contributor has removed from Covered Software;
119
+ or
120
+
121
+ (b) for infringements caused by: (i) Your and any other third party's
122
+ modifications of Covered Software, or (ii) the combination of its
123
+ Contributions with other software (except as part of its Contributor
124
+ Version); or
125
+
126
+ (c) under Patent Claims infringed by Covered Software in the absence of
127
+ its Contributions.
128
+
129
+ This License does not grant any rights in the trademarks, service marks,
130
+ or logos of any Contributor (except as may be necessary to comply with
131
+ the notice requirements in Section 3.4).
132
+
133
+ 2.4. Subsequent Licenses
134
+
135
+ No Contributor makes additional grants as a result of Your choice to
136
+ distribute the Covered Software under a subsequent version of this
137
+ License (see Section 10.2) or under the terms of a Secondary License (if
138
+ permitted under the terms of Section 3.3).
139
+
140
+ 2.5. Representation
141
+
142
+ Each Contributor represents that the Contributor believes its
143
+ Contributions are its original creation(s) or it has sufficient rights
144
+ to grant the rights to its Contributions conveyed by this License.
145
+
146
+ 2.6. Fair Use
147
+
148
+ This License is not intended to limit any rights You have under
149
+ applicable copyright doctrines of fair use, fair dealing, or other
150
+ equivalents.
151
+
152
+ 2.7. Conditions
153
+
154
+ Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
155
+ in Section 2.1.
156
+
157
+ 3. Responsibilities
158
+ -------------------
159
+
160
+ 3.1. Distribution of Source Form
161
+
162
+ All distribution of Covered Software in Source Code Form, including any
163
+ Modifications that You create or to which You contribute, must be under
164
+ the terms of this License. You must inform recipients that the Source
165
+ Code Form of the Covered Software is governed by the terms of this
166
+ License, and how they can obtain a copy of this License. You may not
167
+ attempt to alter or restrict the recipients' rights in the Source Code
168
+ Form.
169
+
170
+ 3.2. Distribution of Executable Form
171
+
172
+ If You distribute Covered Software in Executable Form then:
173
+
174
+ (a) such Covered Software must also be made available in Source Code
175
+ Form, as described in Section 3.1, and You must inform recipients of
176
+ the Executable Form how they can obtain a copy of such Source Code
177
+ Form by reasonable means in a timely manner, at a charge no more
178
+ than the cost of distribution to the recipient; and
179
+
180
+ (b) You may distribute such Executable Form under the terms of this
181
+ License, or sublicense it under different terms, provided that the
182
+ license for the Executable Form does not attempt to limit or alter
183
+ the recipients' rights in the Source Code Form under this License.
184
+
185
+ 3.3. Distribution of a Larger Work
186
+
187
+ You may create and distribute a Larger Work under terms of Your choice,
188
+ provided that You also comply with the requirements of this License for
189
+ the Covered Software. If the Larger Work is a combination of Covered
190
+ Software with a work governed by one or more Secondary Licenses, and the
191
+ Covered Software is not Incompatible With Secondary Licenses, this
192
+ License permits You to additionally distribute such Covered Software
193
+ under the terms of such Secondary License(s), so that the recipient of
194
+ the Larger Work may, at their option, further distribute the Covered
195
+ Software under the terms of either this License or such Secondary
196
+ License(s).
197
+
198
+ 3.4. Notices
199
+
200
+ You may not remove or alter the substance of any license notices
201
+ (including copyright notices, patent notices, disclaimers of warranty,
202
+ or limitations of liability) contained within the Source Code Form of
203
+ the Covered Software, except that You may alter any license notices to
204
+ the extent required to remedy known factual inaccuracies.
205
+
206
+ 3.5. Application of Additional Terms
207
+
208
+ You may choose to offer, and to charge a fee for, warranty, support,
209
+ indemnity or liability obligations to one or more recipients of Covered
210
+ Software. However, You may do so only on Your own behalf, and not on
211
+ behalf of any Contributor. You must make it absolutely clear that any
212
+ such warranty, support, indemnity, or liability obligation is offered by
213
+ You alone, and You hereby agree to indemnify every Contributor for any
214
+ liability incurred by such Contributor as a result of warranty, support,
215
+ indemnity or liability terms You offer. You may include additional
216
+ disclaimers of warranty and limitations of liability specific to any
217
+ jurisdiction.
218
+
219
+ 4. Inability to Comply Due to Statute or Regulation
220
+ ---------------------------------------------------
221
+
222
+ If it is impossible for You to comply with any of the terms of this
223
+ License with respect to some or all of the Covered Software due to
224
+ statute, judicial order, or regulation then You must: (a) comply with
225
+ the terms of this License to the maximum extent possible; and (b)
226
+ describe the limitations and the code they affect. Such description must
227
+ be placed in a text file included with all distributions of the Covered
228
+ Software under this License. Except to the extent prohibited by statute
229
+ or regulation, such description must be sufficiently detailed for a
230
+ recipient of ordinary skill to be able to understand it.
231
+
232
+ 5. Termination
233
+ --------------
234
+
235
+ 5.1. The rights granted under this License will terminate automatically
236
+ if You fail to comply with any of its terms. However, if You become
237
+ compliant, then the rights granted under this License from a particular
238
+ Contributor are reinstated (a) provisionally, unless and until such
239
+ Contributor explicitly and finally terminates Your grants, and (b) on an
240
+ ongoing basis, if such Contributor fails to notify You of the
241
+ non-compliance by some reasonable means prior to 60 days after You have
242
+ come back into compliance. Moreover, Your grants from a particular
243
+ Contributor are reinstated on an ongoing basis if such Contributor
244
+ notifies You of the non-compliance by some reasonable means, this is the
245
+ first time You have received notice of non-compliance with this License
246
+ from such Contributor, and You become compliant prior to 30 days after
247
+ Your receipt of the notice.
248
+
249
+ 5.2. If You initiate litigation against any entity by asserting a patent
250
+ infringement claim (excluding declaratory judgment actions,
251
+ counter-claims, and cross-claims) alleging that a Contributor Version
252
+ directly or indirectly infringes any patent, then the rights granted to
253
+ You by any and all Contributors for the Covered Software under Section
254
+ 2.1 of this License shall terminate.
255
+
256
+ 5.3. In the event of termination under Sections 5.1 or 5.2 above, all
257
+ end user license agreements (excluding distributors and resellers) which
258
+ have been validly granted by You or Your distributors under this License
259
+ prior to termination shall survive termination.
260
+
261
+ ************************************************************************
262
+ * *
263
+ * 6. Disclaimer of Warranty *
264
+ * ------------------------- *
265
+ * *
266
+ * Covered Software is provided under this License on an "as is" *
267
+ * basis, without warranty of any kind, either expressed, implied, or *
268
+ * statutory, including, without limitation, warranties that the *
269
+ * Covered Software is free of defects, merchantable, fit for a *
270
+ * particular purpose or non-infringing. The entire risk as to the *
271
+ * quality and performance of the Covered Software is with You. *
272
+ * Should any Covered Software prove defective in any respect, You *
273
+ * (not any Contributor) assume the cost of any necessary servicing, *
274
+ * repair, or correction. This disclaimer of warranty constitutes an *
275
+ * essential part of this License. No use of any Covered Software is *
276
+ * authorized under this License except under this disclaimer. *
277
+ * *
278
+ ************************************************************************
279
+
280
+ ************************************************************************
281
+ * *
282
+ * 7. Limitation of Liability *
283
+ * -------------------------- *
284
+ * *
285
+ * Under no circumstances and under no legal theory, whether tort *
286
+ * (including negligence), contract, or otherwise, shall any *
287
+ * Contributor, or anyone who distributes Covered Software as *
288
+ * permitted above, be liable to You for any direct, indirect, *
289
+ * special, incidental, or consequential damages of any character *
290
+ * including, without limitation, damages for lost profits, loss of *
291
+ * goodwill, work stoppage, computer failure or malfunction, or any *
292
+ * and all other commercial damages or losses, even if such party *
293
+ * shall have been informed of the possibility of such damages. This *
294
+ * limitation of liability shall not apply to liability for death or *
295
+ * personal injury resulting from such party's negligence to the *
296
+ * extent applicable law prohibits such limitation. Some *
297
+ * jurisdictions do not allow the exclusion or limitation of *
298
+ * incidental or consequential damages, so this exclusion and *
299
+ * limitation may not apply to You. *
300
+ * *
301
+ ************************************************************************
302
+
303
+ 8. Litigation
304
+ -------------
305
+
306
+ Any litigation relating to this License may be brought only in the
307
+ courts of a jurisdiction where the defendant maintains its principal
308
+ place of business and such litigation shall be governed by laws of that
309
+ jurisdiction, without reference to its conflict-of-law provisions.
310
+ Nothing in this Section shall prevent a party's ability to bring
311
+ cross-claims or counter-claims.
312
+
313
+ 9. Miscellaneous
314
+ ----------------
315
+
316
+ This License represents the complete agreement concerning the subject
317
+ matter hereof. If any provision of this License is held to be
318
+ unenforceable, such provision shall be reformed only to the extent
319
+ necessary to make it enforceable. Any law or regulation which provides
320
+ that the language of a contract shall be construed against the drafter
321
+ shall not be used to construe this License against a Contributor.
322
+
323
+ 10. Versions of the License
324
+ ---------------------------
325
+
326
+ 10.1. New Versions
327
+
328
+ Mozilla Foundation is the license steward. Except as provided in Section
329
+ 10.3, no one other than the license steward has the right to modify or
330
+ publish new versions of this License. Each version will be given a
331
+ distinguishing version number.
332
+
333
+ 10.2. Effect of New Versions
334
+
335
+ You may distribute the Covered Software under the terms of the version
336
+ of the License under which You originally received the Covered Software,
337
+ or under the terms of any subsequent version published by the license
338
+ steward.
339
+
340
+ 10.3. Modified Versions
341
+
342
+ If you create software not governed by this License, and you want to
343
+ create a new license for such software, you may create and use a
344
+ modified version of this License if you rename the license and remove
345
+ any references to the name of the license steward (except to note that
346
+ such modified license differs from this License).
347
+
348
+ 10.4. Distributing Source Code Form that is Incompatible With Secondary
349
+ Licenses
350
+
351
+ If You choose to distribute Source Code Form that is Incompatible With
352
+ Secondary Licenses under the terms of this version of the License, the
353
+ notice described in Exhibit B of this License must be attached.
354
+
355
+ Exhibit A - Source Code License Notice
356
+ -------------------------------------------
357
+
358
+ This Source Code is subject to the terms of the Mozilla Public
359
+ License, v. 2.0. If a copy of the MPL was not distributed with this
360
+ file, You can obtain one at http://mozilla.org/MPL/2.0/.
361
+
362
+ If it is not possible or desirable to put the notice in a particular
363
+ file, then You may include the notice in a location (such as a LICENSE
364
+ file in a relevant directory) where a recipient would be likely to look
365
+ for such a notice.
366
+
367
+ You may add additional accurate notices of copyright ownership.
368
+
369
+ Exhibit B - "Incompatible With Secondary Licenses" Notice
370
+ ---------------------------------------------------------
371
+
372
+ This Source Code is "Incompatible With Secondary Licenses", as
373
+ defined by the Mozilla Public License, v. 2.0.
package/README.md ADDED
@@ -0,0 +1,23 @@
1
+ # @byline/analytics-postgres
2
+
3
+ The PostgreSQL `AnalyticsStore` for `@byline/analytics`. It reuses the host
4
+ application's existing `pg.Pool` and owns its raw-event, salt, aggregate, and
5
+ rollup-state tables.
6
+
7
+ ## Schema and migrations
8
+
9
+ The driver follows `@byline/search-postgres`: numbered SQL files under
10
+ `migrations/` are the DBA-reviewable source of truth, an embedded byte-matched
11
+ copy makes `migrate()` safe inside Nitro/Rollup server bundles, and
12
+ `byline_analytics_migrations` records applied versions independently of the
13
+ application's Drizzle stream.
14
+
15
+ ```ts
16
+ import { migrate, postgresAnalyticsStore } from '@byline/analytics-postgres'
17
+
18
+ await migrate(db.pool)
19
+ const store = postgresAnalyticsStore({ pool: db.pool })
20
+ ```
21
+
22
+ Production deployments should run `migrate()` as a deliberate release step.
23
+ `autoMigrate: true` is available for local development.
@@ -0,0 +1,17 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import type { AnalyticsStore } from '@byline/analytics';
9
+ import type { Pool } from 'pg';
10
+ export { type MigrateOptions, type MigrateResult, migrate } from './migrate.js';
11
+ export { PostgresAnalyticsStore } from './postgres-analytics-store.js';
12
+ export interface PostgresAnalyticsStoreOptions {
13
+ pool: Pool;
14
+ autoMigrate?: boolean;
15
+ log?: (message: string) => void;
16
+ }
17
+ export declare function postgresAnalyticsStore(options: PostgresAnalyticsStoreOptions): AnalyticsStore;
package/dist/index.js ADDED
@@ -0,0 +1,23 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { migrate } from './migrate.js';
9
+ import { PostgresAnalyticsStore } from './postgres-analytics-store.js';
10
+ export { migrate } from './migrate.js';
11
+ export { PostgresAnalyticsStore } from './postgres-analytics-store.js';
12
+ export function postgresAnalyticsStore(options) {
13
+ if (options.autoMigrate === true) {
14
+ void migrate(options.pool, { log: options.log }).catch((error) => {
15
+ const message = `[analytics-postgres] autoMigrate failed: ${error.message}`;
16
+ if (options.log)
17
+ options.log(message);
18
+ else
19
+ console.error(message);
20
+ });
21
+ }
22
+ return new PostgresAnalyticsStore(options.pool);
23
+ }
@@ -0,0 +1,16 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import type { Pool } from 'pg';
9
+ export interface MigrateOptions {
10
+ log?: (message: string) => void;
11
+ }
12
+ export interface MigrateResult {
13
+ applied: number[];
14
+ }
15
+ /** Apply pending driver-owned migrations transactionally and bundle-safely. */
16
+ export declare function migrate(pool: Pool, options?: MigrateOptions): Promise<MigrateResult>;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { MIGRATIONS } from './migrations-data.js';
9
+ const MIGRATION_LOCK = 1_682_231_441;
10
+ /** Apply pending driver-owned migrations transactionally and bundle-safely. */
11
+ export async function migrate(pool, options = {}) {
12
+ const client = await pool.connect();
13
+ const applied = [];
14
+ let locked = false;
15
+ try {
16
+ await client.query('SELECT pg_advisory_lock($1)', [MIGRATION_LOCK]);
17
+ locked = true;
18
+ await client.query(`
19
+ CREATE TABLE IF NOT EXISTS byline_analytics_migrations (
20
+ version integer PRIMARY KEY,
21
+ applied_at timestamptz NOT NULL DEFAULT now()
22
+ )
23
+ `);
24
+ const rows = await client.query('SELECT version FROM byline_analytics_migrations');
25
+ const done = new Set(rows.rows.map((row) => Number(row.version)));
26
+ for (const migration of [...MIGRATIONS].sort((left, right) => left.version - right.version)) {
27
+ if (done.has(migration.version))
28
+ continue;
29
+ await client.query('BEGIN');
30
+ try {
31
+ await client.query(migration.sql);
32
+ await client.query('INSERT INTO byline_analytics_migrations (version) VALUES ($1)', [
33
+ migration.version,
34
+ ]);
35
+ await client.query('COMMIT');
36
+ applied.push(migration.version);
37
+ options.log?.(`[analytics-postgres] applied migration ${migration.name}`);
38
+ }
39
+ catch (error) {
40
+ await client.query('ROLLBACK');
41
+ throw new Error(`[analytics-postgres] migration ${migration.name} failed: ${error.message}`, { cause: error });
42
+ }
43
+ }
44
+ return { applied };
45
+ }
46
+ finally {
47
+ try {
48
+ if (locked)
49
+ await client.query('SELECT pg_advisory_unlock($1)', [MIGRATION_LOCK]);
50
+ }
51
+ finally {
52
+ client.release();
53
+ }
54
+ }
55
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export interface EmbeddedMigration {
9
+ version: number;
10
+ name: string;
11
+ sql: string;
12
+ }
13
+ /** Bundle-safe mirror of the DBA-reviewable numbered SQL files. */
14
+ export declare const MIGRATIONS: EmbeddedMigration[];
@@ -0,0 +1,86 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ /** Bundle-safe mirror of the DBA-reviewable numbered SQL files. */
9
+ export const MIGRATIONS = [
10
+ {
11
+ version: 1,
12
+ name: '0001_init.sql',
13
+ sql: `-- @byline/analytics-postgres — 0001_init
14
+ --
15
+ -- Driver-owned raw events, daily salts, bounded daily aggregates, and rollup
16
+ -- cursor. The migration runner records this file in
17
+ -- byline_analytics_migrations; these tables are independent of the host
18
+ -- application's Drizzle migration stream.
19
+
20
+ CREATE TABLE IF NOT EXISTS byline_analytics_event (
21
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
22
+ occurred_at timestamptz NOT NULL,
23
+ kind text NOT NULL CHECK (kind IN ('page', 'download')),
24
+ source text NOT NULL CHECK (source IN ('beacon', 'redirect', 'cdnlog')),
25
+ path text NOT NULL CHECK (char_length(path) <= 512 AND path <> '__other__'),
26
+ visitor_hash char(64) NOT NULL CHECK (visitor_hash ~ '^[0-9a-f]{64}$'),
27
+ referrer_host text CHECK (
28
+ referrer_host IS NULL OR
29
+ (char_length(referrer_host) <= 255 AND referrer_host <> '__other__')
30
+ ),
31
+ country char(2) CHECK (country IS NULL OR country ~ '^[A-Z]{2}$')
32
+ );
33
+
34
+ CREATE INDEX IF NOT EXISTS byline_analytics_event_occurred_at_idx
35
+ ON byline_analytics_event (occurred_at);
36
+
37
+ CREATE TABLE IF NOT EXISTS byline_analytics_salt (
38
+ day date PRIMARY KEY,
39
+ salt bytea NOT NULL CHECK (octet_length(salt) = 32)
40
+ );
41
+
42
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_path (
43
+ day date NOT NULL,
44
+ kind text NOT NULL CHECK (kind IN ('page', 'download')),
45
+ path text NOT NULL,
46
+ views bigint NOT NULL CHECK (views >= 0),
47
+ visitors bigint NOT NULL CHECK (visitors >= 0),
48
+ PRIMARY KEY (day, kind, path)
49
+ );
50
+
51
+ CREATE INDEX IF NOT EXISTS byline_analytics_daily_path_day_idx
52
+ ON byline_analytics_daily_path (day);
53
+
54
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_site (
55
+ day date PRIMARY KEY,
56
+ views bigint NOT NULL CHECK (views >= 0),
57
+ visitors bigint NOT NULL CHECK (visitors >= 0),
58
+ downloads bigint NOT NULL CHECK (downloads >= 0)
59
+ );
60
+
61
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_referrer (
62
+ day date NOT NULL,
63
+ referrer_host text NOT NULL,
64
+ views bigint NOT NULL CHECK (views >= 0),
65
+ visitors bigint NOT NULL CHECK (visitors >= 0),
66
+ PRIMARY KEY (day, referrer_host)
67
+ );
68
+
69
+ CREATE INDEX IF NOT EXISTS byline_analytics_daily_referrer_day_idx
70
+ ON byline_analytics_daily_referrer (day);
71
+
72
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_country (
73
+ day date NOT NULL,
74
+ country char(2) NOT NULL,
75
+ views bigint NOT NULL CHECK (views >= 0),
76
+ visitors bigint NOT NULL CHECK (visitors >= 0),
77
+ PRIMARY KEY (day, country)
78
+ );
79
+
80
+ CREATE TABLE IF NOT EXISTS byline_analytics_rollup_state (
81
+ singleton smallint PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),
82
+ last_complete_day date
83
+ );
84
+ `,
85
+ },
86
+ ];
@@ -0,0 +1,8 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ export {};
@@ -0,0 +1,30 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { readdirSync, readFileSync } from 'node:fs';
9
+ import { dirname, join } from 'node:path';
10
+ import { fileURLToPath } from 'node:url';
11
+ import { describe, expect, it } from 'vitest';
12
+ import { MIGRATIONS } from './migrations-data.js';
13
+ const migrationsDir = join(dirname(fileURLToPath(import.meta.url)), '../migrations');
14
+ describe('embedded analytics migrations', () => {
15
+ const sqlFiles = readdirSync(migrationsDir)
16
+ .filter((file) => file.endsWith('.sql'))
17
+ .sort();
18
+ it('embeds exactly the SQL files that ship', () => {
19
+ expect(MIGRATIONS.map((migration) => migration.name).sort()).toEqual(sqlFiles);
20
+ });
21
+ it.each(sqlFiles)('matches %s byte-for-byte after trimming', (name) => {
22
+ const embedded = MIGRATIONS.find((migration) => migration.name === name);
23
+ expect(embedded?.sql.trim()).toBe(readFileSync(join(migrationsDir, name), 'utf8').trim());
24
+ });
25
+ it('derives every version from its filename', () => {
26
+ for (const migration of MIGRATIONS) {
27
+ expect(migration.version).toBe(Number.parseInt(migration.name.split('_')[0] ?? '', 10));
28
+ }
29
+ });
30
+ });
@@ -0,0 +1,25 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { type AnalyticsCountryTotal, type AnalyticsDateRange, type AnalyticsDeleteEventsOptions, type AnalyticsEvent, type AnalyticsLimitQuery, type AnalyticsPathTotal, type AnalyticsPruneOptions, type AnalyticsPruneResult, type AnalyticsRankedTotals, type AnalyticsReferrerTotal, type AnalyticsRollupDayOptions, type AnalyticsStore, type AnalyticsSummaryDay, type AnalyticsTopQuery } from '@byline/analytics';
9
+ import type { Pool } from 'pg';
10
+ export declare class PostgresAnalyticsStore implements AnalyticsStore {
11
+ readonly pool: Pool;
12
+ constructor(pool: Pool);
13
+ getOrCreateDailySalt(day: string, candidate: Uint8Array): Promise<Uint8Array>;
14
+ insertEvent(event: AnalyticsEvent): Promise<void>;
15
+ getRollupCursor(): Promise<string | null>;
16
+ getEarliestEventDay(): Promise<string | null>;
17
+ getEarliestReportDay(): Promise<string | null>;
18
+ rebuildDay(options: AnalyticsRollupDayOptions): Promise<void>;
19
+ prune(options: AnalyticsPruneOptions): Promise<AnalyticsPruneResult>;
20
+ getSummary(range: AnalyticsDateRange): Promise<AnalyticsSummaryDay[]>;
21
+ getTopPaths(query: Required<AnalyticsTopQuery>): Promise<AnalyticsRankedTotals<AnalyticsPathTotal>>;
22
+ getReferrers(query: Required<AnalyticsLimitQuery>): Promise<AnalyticsRankedTotals<AnalyticsReferrerTotal>>;
23
+ getCountries(range: AnalyticsDateRange): Promise<AnalyticsCountryTotal[]>;
24
+ deleteEvents(options: AnalyticsDeleteEventsOptions): Promise<number>;
25
+ }
@@ -0,0 +1,365 @@
1
+ /**
2
+ * This Source Code is subject to the terms of the Mozilla Public
3
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
4
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5
+ *
6
+ * Copyright (c) Infonomic Company Limited
7
+ */
8
+ import { addAnalyticsDays, assertAnalyticsDay, startOfAnalyticsDay, } from '@byline/analytics';
9
+ export class PostgresAnalyticsStore {
10
+ pool;
11
+ constructor(pool) {
12
+ this.pool = pool;
13
+ }
14
+ async getOrCreateDailySalt(day, candidate) {
15
+ assertAnalyticsDay(day);
16
+ const result = await this.pool.query(`INSERT INTO byline_analytics_salt (day, salt)
17
+ VALUES ($1::date, $2)
18
+ ON CONFLICT (day) DO UPDATE
19
+ SET salt = byline_analytics_salt.salt
20
+ RETURNING salt`, [day, Buffer.from(candidate)]);
21
+ const salt = result.rows[0]?.salt;
22
+ if (salt == null)
23
+ throw new Error('[analytics-postgres] daily salt upsert returned no row');
24
+ return Uint8Array.from(salt);
25
+ }
26
+ async insertEvent(event) {
27
+ await this.pool.query(`INSERT INTO byline_analytics_event
28
+ (occurred_at, kind, source, path, visitor_hash, referrer_host, country)
29
+ VALUES ($1, $2, $3, $4, $5, $6, $7)`, [
30
+ event.occurredAt,
31
+ event.kind,
32
+ event.source,
33
+ event.path,
34
+ event.visitorHash,
35
+ event.referrerHost,
36
+ event.country,
37
+ ]);
38
+ }
39
+ async getRollupCursor() {
40
+ const result = await this.pool.query(`SELECT last_complete_day::text AS last_complete_day
41
+ FROM byline_analytics_rollup_state WHERE singleton = 1`);
42
+ return result.rows[0]?.last_complete_day ?? null;
43
+ }
44
+ async getEarliestEventDay() {
45
+ const result = await this.pool.query(`SELECT min((occurred_at AT TIME ZONE 'UTC')::date)::text AS day
46
+ FROM byline_analytics_event`);
47
+ return result.rows[0]?.day ?? null;
48
+ }
49
+ async getEarliestReportDay() {
50
+ const result = await this.pool.query(`SELECT min(day)::text AS day
51
+ FROM (
52
+ SELECT day FROM byline_analytics_daily_site
53
+ UNION ALL
54
+ SELECT (occurred_at AT TIME ZONE 'UTC')::date AS day
55
+ FROM byline_analytics_event
56
+ ) reportable_days`);
57
+ return result.rows[0]?.day ?? null;
58
+ }
59
+ async rebuildDay(options) {
60
+ const day = assertAnalyticsDay(options.day);
61
+ const from = startOfAnalyticsDay(day);
62
+ const to = startOfAnalyticsDay(addAnalyticsDays(day, 1));
63
+ const client = await this.pool.connect();
64
+ try {
65
+ await client.query('BEGIN');
66
+ await deleteDailyRows(client, day);
67
+ await insertPathRollups(client, day, from, to, options.pathCardinalityCap);
68
+ await insertSiteRollup(client, day, from, to);
69
+ await insertReferrerRollups(client, day, from, to, options.referrerCardinalityCap);
70
+ await insertCountryRollups(client, day, from, to);
71
+ if (options.advanceCursor) {
72
+ await client.query(`INSERT INTO byline_analytics_rollup_state (singleton, last_complete_day)
73
+ VALUES (1, $1::date)
74
+ ON CONFLICT (singleton) DO UPDATE
75
+ SET last_complete_day = GREATEST(
76
+ byline_analytics_rollup_state.last_complete_day,
77
+ EXCLUDED.last_complete_day
78
+ )`, [day]);
79
+ }
80
+ await client.query('COMMIT');
81
+ }
82
+ catch (error) {
83
+ await client.query('ROLLBACK');
84
+ throw error;
85
+ }
86
+ finally {
87
+ client.release();
88
+ }
89
+ }
90
+ async prune(options) {
91
+ const client = await this.pool.connect();
92
+ try {
93
+ await client.query('BEGIN');
94
+ const events = await client.query('DELETE FROM byline_analytics_event WHERE occurred_at < $1', [options.eventsBefore]);
95
+ const salts = await client.query('DELETE FROM byline_analytics_salt WHERE day < $1::date', [
96
+ options.saltsBefore,
97
+ ]);
98
+ const paths = options.pathAggregatesBefore == null
99
+ ? null
100
+ : await client.query('DELETE FROM byline_analytics_daily_path WHERE day < $1::date', [
101
+ options.pathAggregatesBefore,
102
+ ]);
103
+ const referrers = options.referrerAggregatesBefore == null
104
+ ? null
105
+ : await client.query('DELETE FROM byline_analytics_daily_referrer WHERE day < $1::date', [
106
+ options.referrerAggregatesBefore,
107
+ ]);
108
+ await client.query('COMMIT');
109
+ return {
110
+ events: events.rowCount ?? 0,
111
+ salts: salts.rowCount ?? 0,
112
+ pathAggregates: paths?.rowCount ?? 0,
113
+ referrerAggregates: referrers?.rowCount ?? 0,
114
+ };
115
+ }
116
+ catch (error) {
117
+ await client.query('ROLLBACK');
118
+ throw error;
119
+ }
120
+ finally {
121
+ client.release();
122
+ }
123
+ }
124
+ async getSummary(range) {
125
+ const result = await this.pool.query(summarySql, [range.from, range.to]);
126
+ return result.rows.map((row) => ({
127
+ day: row.day,
128
+ views: count(row.views),
129
+ visitors: count(row.visitors),
130
+ downloads: count(row.downloads),
131
+ }));
132
+ }
133
+ async getTopPaths(query) {
134
+ const result = await this.pool.query(topPathsSql, [
135
+ query.from,
136
+ query.to,
137
+ query.kind,
138
+ query.limit,
139
+ ]);
140
+ return {
141
+ rows: result.rows.map((row) => ({
142
+ path: row.path,
143
+ views: count(row.views),
144
+ visitors: count(row.visitors),
145
+ })),
146
+ total: count(result.rows[0]?.total ?? 0),
147
+ };
148
+ }
149
+ async getReferrers(query) {
150
+ const result = await this.pool.query(referrersSql, [
151
+ query.from,
152
+ query.to,
153
+ query.limit,
154
+ ]);
155
+ return {
156
+ rows: result.rows.map((row) => ({
157
+ referrerHost: row.referrer_host,
158
+ views: count(row.views),
159
+ visitors: count(row.visitors),
160
+ })),
161
+ total: count(result.rows[0]?.total ?? 0),
162
+ };
163
+ }
164
+ async getCountries(range) {
165
+ const result = await this.pool.query(countriesSql, [range.from, range.to]);
166
+ return result.rows.map((row) => ({
167
+ country: row.country,
168
+ views: count(row.views),
169
+ visitors: count(row.visitors),
170
+ }));
171
+ }
172
+ async deleteEvents(options) {
173
+ const params = [options.from, options.to];
174
+ const visitor = options.visitorHash == null ? '' : ` AND visitor_hash = $${params.push(options.visitorHash)}`;
175
+ const result = await this.pool.query(`DELETE FROM byline_analytics_event
176
+ WHERE occurred_at >= $1 AND occurred_at < $2${visitor}`, params);
177
+ return result.rowCount ?? 0;
178
+ }
179
+ }
180
+ async function deleteDailyRows(client, day) {
181
+ for (const table of [
182
+ 'byline_analytics_daily_path',
183
+ 'byline_analytics_daily_site',
184
+ 'byline_analytics_daily_referrer',
185
+ 'byline_analytics_daily_country',
186
+ ]) {
187
+ await client.query(`DELETE FROM ${table} WHERE day = $1::date`, [day]);
188
+ }
189
+ }
190
+ async function insertPathRollups(client, day, from, to, cap) {
191
+ await client.query(`WITH grouped AS (
192
+ SELECT kind, path, count(*) AS views, count(DISTINCT visitor_hash) AS visitors
193
+ FROM byline_analytics_event
194
+ WHERE occurred_at >= $2 AND occurred_at < $3
195
+ GROUP BY kind, path
196
+ ), ranked AS (
197
+ SELECT *, row_number() OVER (PARTITION BY kind ORDER BY views DESC, path ASC) AS rank
198
+ FROM grouped
199
+ )
200
+ INSERT INTO byline_analytics_daily_path (day, kind, path, views, visitors)
201
+ SELECT $1::date, kind, path, views, visitors FROM ranked WHERE rank <= $4`, [day, from, to, cap]);
202
+ await client.query(`WITH grouped AS (
203
+ SELECT kind, path, count(*) AS views
204
+ FROM byline_analytics_event
205
+ WHERE occurred_at >= $2 AND occurred_at < $3
206
+ GROUP BY kind, path
207
+ ), ranked AS (
208
+ SELECT kind, path,
209
+ row_number() OVER (PARTITION BY kind ORDER BY views DESC, path ASC) AS rank
210
+ FROM grouped
211
+ )
212
+ INSERT INTO byline_analytics_daily_path (day, kind, path, views, visitors)
213
+ SELECT $1::date, event.kind, '__other__', count(*), count(DISTINCT event.visitor_hash)
214
+ FROM byline_analytics_event event
215
+ JOIN ranked ON ranked.kind = event.kind AND ranked.path = event.path
216
+ WHERE event.occurred_at >= $2 AND event.occurred_at < $3 AND ranked.rank > $4
217
+ GROUP BY event.kind`, [day, from, to, cap]);
218
+ }
219
+ async function insertSiteRollup(client, day, from, to) {
220
+ await client.query(`INSERT INTO byline_analytics_daily_site (day, views, visitors, downloads)
221
+ SELECT $1::date,
222
+ count(*) FILTER (WHERE kind = 'page'),
223
+ count(DISTINCT visitor_hash) FILTER (WHERE kind = 'page'),
224
+ count(*) FILTER (WHERE kind = 'download')
225
+ FROM byline_analytics_event
226
+ WHERE occurred_at >= $2 AND occurred_at < $3`, [day, from, to]);
227
+ }
228
+ async function insertReferrerRollups(client, day, from, to, cap) {
229
+ await client.query(`WITH grouped AS (
230
+ SELECT referrer_host, count(*) AS views, count(DISTINCT visitor_hash) AS visitors
231
+ FROM byline_analytics_event
232
+ WHERE occurred_at >= $2 AND occurred_at < $3
233
+ AND kind = 'page' AND referrer_host IS NOT NULL
234
+ GROUP BY referrer_host
235
+ ), ranked AS (
236
+ SELECT *, row_number() OVER (ORDER BY views DESC, referrer_host ASC) AS rank
237
+ FROM grouped
238
+ )
239
+ INSERT INTO byline_analytics_daily_referrer (day, referrer_host, views, visitors)
240
+ SELECT $1::date, referrer_host, views, visitors FROM ranked WHERE rank <= $4`, [day, from, to, cap]);
241
+ await client.query(`WITH grouped AS (
242
+ SELECT referrer_host, count(*) AS views
243
+ FROM byline_analytics_event
244
+ WHERE occurred_at >= $2 AND occurred_at < $3
245
+ AND kind = 'page' AND referrer_host IS NOT NULL
246
+ GROUP BY referrer_host
247
+ ), ranked AS (
248
+ SELECT referrer_host, row_number() OVER (ORDER BY views DESC, referrer_host ASC) AS rank
249
+ FROM grouped
250
+ )
251
+ INSERT INTO byline_analytics_daily_referrer (day, referrer_host, views, visitors)
252
+ SELECT $1::date, '__other__', count(*), count(DISTINCT event.visitor_hash)
253
+ FROM byline_analytics_event event
254
+ JOIN ranked ON ranked.referrer_host = event.referrer_host
255
+ WHERE event.occurred_at >= $2 AND event.occurred_at < $3
256
+ AND event.kind = 'page' AND ranked.rank > $4
257
+ HAVING count(*) > 0`, [day, from, to, cap]);
258
+ }
259
+ async function insertCountryRollups(client, day, from, to) {
260
+ await client.query(`INSERT INTO byline_analytics_daily_country (day, country, views, visitors)
261
+ SELECT $1::date, country, count(*), count(DISTINCT visitor_hash)
262
+ FROM byline_analytics_event
263
+ WHERE occurred_at >= $2 AND occurred_at < $3
264
+ AND kind = 'page' AND country IS NOT NULL
265
+ GROUP BY country`, [day, from, to]);
266
+ }
267
+ const summarySql = `WITH state AS (
268
+ SELECT last_complete_day FROM byline_analytics_rollup_state WHERE singleton = 1
269
+ ), days AS (
270
+ SELECT generate_series($1::date, $2::date, interval '1 day')::date AS day
271
+ ), rolled AS (
272
+ SELECT site.day, site.views, site.visitors, site.downloads
273
+ FROM byline_analytics_daily_site site, state
274
+ WHERE site.day BETWEEN $1::date AND $2::date AND site.day <= state.last_complete_day
275
+ ), raw AS (
276
+ SELECT (event.occurred_at AT TIME ZONE 'UTC')::date AS day,
277
+ count(*) FILTER (WHERE event.kind = 'page') AS views,
278
+ count(DISTINCT event.visitor_hash) FILTER (WHERE event.kind = 'page') AS visitors,
279
+ count(*) FILTER (WHERE event.kind = 'download') AS downloads
280
+ FROM byline_analytics_event event
281
+ LEFT JOIN state ON true
282
+ WHERE event.occurred_at >= ($1::date::timestamp AT TIME ZONE 'UTC')
283
+ AND event.occurred_at < (($2::date + 1)::timestamp AT TIME ZONE 'UTC')
284
+ AND (state.last_complete_day IS NULL OR
285
+ (event.occurred_at AT TIME ZONE 'UTC')::date > state.last_complete_day)
286
+ GROUP BY (event.occurred_at AT TIME ZONE 'UTC')::date
287
+ )
288
+ SELECT days.day::text AS day,
289
+ coalesce(rolled.views, raw.views, 0) AS views,
290
+ coalesce(rolled.visitors, raw.visitors, 0) AS visitors,
291
+ coalesce(rolled.downloads, raw.downloads, 0) AS downloads
292
+ FROM days
293
+ LEFT JOIN rolled USING (day)
294
+ LEFT JOIN raw USING (day)
295
+ ORDER BY days.day`;
296
+ const topPathsSql = `WITH state AS (
297
+ SELECT last_complete_day FROM byline_analytics_rollup_state WHERE singleton = 1
298
+ ), per_day AS (
299
+ SELECT path.day, path.path, path.views, path.visitors
300
+ FROM byline_analytics_daily_path path, state
301
+ WHERE path.day BETWEEN $1::date AND $2::date
302
+ AND path.day <= state.last_complete_day AND path.kind = $3
303
+ UNION ALL
304
+ SELECT (event.occurred_at AT TIME ZONE 'UTC')::date, event.path,
305
+ count(*), count(DISTINCT event.visitor_hash)
306
+ FROM byline_analytics_event event
307
+ LEFT JOIN state ON true
308
+ WHERE event.occurred_at >= ($1::date::timestamp AT TIME ZONE 'UTC')
309
+ AND event.occurred_at < (($2::date + 1)::timestamp AT TIME ZONE 'UTC')
310
+ AND event.kind = $3
311
+ AND (state.last_complete_day IS NULL OR
312
+ (event.occurred_at AT TIME ZONE 'UTC')::date > state.last_complete_day)
313
+ GROUP BY (event.occurred_at AT TIME ZONE 'UTC')::date, event.path
314
+ )
315
+ SELECT path, sum(views) AS views, sum(visitors) AS visitors,
316
+ count(*) OVER () AS total
317
+ FROM per_day GROUP BY path ORDER BY views DESC, path ASC LIMIT $4`;
318
+ const referrersSql = `WITH state AS (
319
+ SELECT last_complete_day FROM byline_analytics_rollup_state WHERE singleton = 1
320
+ ), per_day AS (
321
+ SELECT ref.day, ref.referrer_host, ref.views, ref.visitors
322
+ FROM byline_analytics_daily_referrer ref, state
323
+ WHERE ref.day BETWEEN $1::date AND $2::date AND ref.day <= state.last_complete_day
324
+ UNION ALL
325
+ SELECT (event.occurred_at AT TIME ZONE 'UTC')::date, event.referrer_host,
326
+ count(*), count(DISTINCT event.visitor_hash)
327
+ FROM byline_analytics_event event
328
+ LEFT JOIN state ON true
329
+ WHERE event.occurred_at >= ($1::date::timestamp AT TIME ZONE 'UTC')
330
+ AND event.occurred_at < (($2::date + 1)::timestamp AT TIME ZONE 'UTC')
331
+ AND event.kind = 'page' AND event.referrer_host IS NOT NULL
332
+ AND (state.last_complete_day IS NULL OR
333
+ (event.occurred_at AT TIME ZONE 'UTC')::date > state.last_complete_day)
334
+ GROUP BY (event.occurred_at AT TIME ZONE 'UTC')::date, event.referrer_host
335
+ )
336
+ SELECT referrer_host, sum(views) AS views, sum(visitors) AS visitors,
337
+ count(*) OVER () AS total
338
+ FROM per_day GROUP BY referrer_host ORDER BY views DESC, referrer_host ASC LIMIT $3`;
339
+ const countriesSql = `WITH state AS (
340
+ SELECT last_complete_day FROM byline_analytics_rollup_state WHERE singleton = 1
341
+ ), per_day AS (
342
+ SELECT country.day, country.country, country.views, country.visitors
343
+ FROM byline_analytics_daily_country country, state
344
+ WHERE country.day BETWEEN $1::date AND $2::date AND country.day <= state.last_complete_day
345
+ UNION ALL
346
+ SELECT (event.occurred_at AT TIME ZONE 'UTC')::date, event.country,
347
+ count(*), count(DISTINCT event.visitor_hash)
348
+ FROM byline_analytics_event event
349
+ LEFT JOIN state ON true
350
+ WHERE event.occurred_at >= ($1::date::timestamp AT TIME ZONE 'UTC')
351
+ AND event.occurred_at < (($2::date + 1)::timestamp AT TIME ZONE 'UTC')
352
+ AND event.kind = 'page' AND event.country IS NOT NULL
353
+ AND (state.last_complete_day IS NULL OR
354
+ (event.occurred_at AT TIME ZONE 'UTC')::date > state.last_complete_day)
355
+ GROUP BY (event.occurred_at AT TIME ZONE 'UTC')::date, event.country
356
+ )
357
+ SELECT country, sum(views) AS views, sum(visitors) AS visitors
358
+ FROM per_day GROUP BY country ORDER BY views DESC, country ASC`;
359
+ function count(value) {
360
+ const parsed = typeof value === 'number' ? value : Number(value);
361
+ if (!Number.isSafeInteger(parsed) || parsed < 0) {
362
+ throw new Error(`[analytics-postgres] count is outside JavaScript's safe integer range: ${value}`);
363
+ }
364
+ return parsed;
365
+ }
@@ -0,0 +1,71 @@
1
+ -- @byline/analytics-postgres — 0001_init
2
+ --
3
+ -- Driver-owned raw events, daily salts, bounded daily aggregates, and rollup
4
+ -- cursor. The migration runner records this file in
5
+ -- byline_analytics_migrations; these tables are independent of the host
6
+ -- application's Drizzle migration stream.
7
+
8
+ CREATE TABLE IF NOT EXISTS byline_analytics_event (
9
+ id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
10
+ occurred_at timestamptz NOT NULL,
11
+ kind text NOT NULL CHECK (kind IN ('page', 'download')),
12
+ source text NOT NULL CHECK (source IN ('beacon', 'redirect', 'cdnlog')),
13
+ path text NOT NULL CHECK (char_length(path) <= 512 AND path <> '__other__'),
14
+ visitor_hash char(64) NOT NULL CHECK (visitor_hash ~ '^[0-9a-f]{64}$'),
15
+ referrer_host text CHECK (
16
+ referrer_host IS NULL OR
17
+ (char_length(referrer_host) <= 255 AND referrer_host <> '__other__')
18
+ ),
19
+ country char(2) CHECK (country IS NULL OR country ~ '^[A-Z]{2}$')
20
+ );
21
+
22
+ CREATE INDEX IF NOT EXISTS byline_analytics_event_occurred_at_idx
23
+ ON byline_analytics_event (occurred_at);
24
+
25
+ CREATE TABLE IF NOT EXISTS byline_analytics_salt (
26
+ day date PRIMARY KEY,
27
+ salt bytea NOT NULL CHECK (octet_length(salt) = 32)
28
+ );
29
+
30
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_path (
31
+ day date NOT NULL,
32
+ kind text NOT NULL CHECK (kind IN ('page', 'download')),
33
+ path text NOT NULL,
34
+ views bigint NOT NULL CHECK (views >= 0),
35
+ visitors bigint NOT NULL CHECK (visitors >= 0),
36
+ PRIMARY KEY (day, kind, path)
37
+ );
38
+
39
+ CREATE INDEX IF NOT EXISTS byline_analytics_daily_path_day_idx
40
+ ON byline_analytics_daily_path (day);
41
+
42
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_site (
43
+ day date PRIMARY KEY,
44
+ views bigint NOT NULL CHECK (views >= 0),
45
+ visitors bigint NOT NULL CHECK (visitors >= 0),
46
+ downloads bigint NOT NULL CHECK (downloads >= 0)
47
+ );
48
+
49
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_referrer (
50
+ day date NOT NULL,
51
+ referrer_host text NOT NULL,
52
+ views bigint NOT NULL CHECK (views >= 0),
53
+ visitors bigint NOT NULL CHECK (visitors >= 0),
54
+ PRIMARY KEY (day, referrer_host)
55
+ );
56
+
57
+ CREATE INDEX IF NOT EXISTS byline_analytics_daily_referrer_day_idx
58
+ ON byline_analytics_daily_referrer (day);
59
+
60
+ CREATE TABLE IF NOT EXISTS byline_analytics_daily_country (
61
+ day date NOT NULL,
62
+ country char(2) NOT NULL,
63
+ views bigint NOT NULL CHECK (views >= 0),
64
+ visitors bigint NOT NULL CHECK (visitors >= 0),
65
+ PRIMARY KEY (day, country)
66
+ );
67
+
68
+ CREATE TABLE IF NOT EXISTS byline_analytics_rollup_state (
69
+ singleton smallint PRIMARY KEY DEFAULT 1 CHECK (singleton = 1),
70
+ last_complete_day date
71
+ );
package/package.json ADDED
@@ -0,0 +1,74 @@
1
+ {
2
+ "name": "@byline/analytics-postgres",
3
+ "private": false,
4
+ "license": "MPL-2.0",
5
+ "version": "4.16.0",
6
+ "engines": {
7
+ "node": ">=20.9.0"
8
+ },
9
+ "description": "PostgreSQL storage driver for Byline analytics",
10
+ "keywords": [
11
+ "cms",
12
+ "analytics",
13
+ "postgres",
14
+ "privacy"
15
+ ],
16
+ "homepage": "https://github.com/Byline-CMS/bylinecms.dev",
17
+ "bugs": {
18
+ "url": "https://github.com/Byline-CMS/bylinecms.dev/issues"
19
+ },
20
+ "repository": {
21
+ "type": "git",
22
+ "url": "git+https://github.com/Byline-CMS/bylinecms.dev.git",
23
+ "directory": "packages/analytics-postgres"
24
+ },
25
+ "type": "module",
26
+ "main": "dist/index.js",
27
+ "index": "dist/index.js",
28
+ "types": "dist/index.d.ts",
29
+ "exports": {
30
+ ".": {
31
+ "types": "./dist/index.d.ts",
32
+ "import": "./dist/index.js",
33
+ "require": "./dist/index.js"
34
+ },
35
+ "./package.json": "./package.json"
36
+ },
37
+ "files": [
38
+ "dist",
39
+ "migrations"
40
+ ],
41
+ "dependencies": {
42
+ "@byline/analytics": "4.16.0"
43
+ },
44
+ "peerDependencies": {
45
+ "pg": "^8.21.0"
46
+ },
47
+ "devDependencies": {
48
+ "@biomejs/biome": "2.5.9",
49
+ "@types/node": "^26.2.0",
50
+ "@types/pg": "^8.23.1",
51
+ "chokidar": "^5.0.0",
52
+ "chokidar-cli": "^3.0.0",
53
+ "dotenv": "^17.4.2",
54
+ "npm-run-all": "^4.1.5",
55
+ "pg": "^8.23.0",
56
+ "tsc-alias": "^1.9.2",
57
+ "typescript": "^7.0.2",
58
+ "vitest": "^4.1.11",
59
+ "@byline/analytics-conformance": "0.0.1"
60
+ },
61
+ "publishConfig": {
62
+ "access": "public"
63
+ },
64
+ "scripts": {
65
+ "dev": "chokidar 'src/**/*' -c 'npm-run-all build'",
66
+ "build": "tsc -p tsconfig.json && tsc-alias",
67
+ "clean": "node scripts/clean.js node_modules dist build .turbo",
68
+ "lint": "biome check --write --unsafe --diagnostic-level=error",
69
+ "test": "vitest run --mode=node",
70
+ "test:integration": "vitest run --mode=integration",
71
+ "test:watch": "vitest --mode=node",
72
+ "typecheck": "tsc --noEmit"
73
+ }
74
+ }