@stamhoofd/backend-statistics-syncer 2.148.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.md ADDED
@@ -0,0 +1,32 @@
1
+ Free Use License for Non-Profit Organizations
2
+
3
+ Copyright 2020 Codawood BV
4
+
5
+ Permission is hereby granted, free of charge, to any non-profit organization with fewer than 2,000 members (each, a “Licensee”), to use this software and associated documentation files (the “Software”), subject to the following conditions:
6
+
7
+ 1. Eligibility:
8
+ This license applies only if neither the Licensee nor, if applicable, its parent or umbrella organization, is already subject to an existing license for this project. For the purposes of this license, a “parent or umbrella organization” means any organization with which the Licensee is affiliated, coordinated, or represented as part of a larger collective, including but not limited to national associations or federations.
9
+
10
+ 2. Modifications:
11
+ Modifications to the Software are permitted only if they are published publicly under the MIT License, covering only the modifications; the original Software remains under this license and may not be sublicensed without a separate agreement. Any modification made by a Licensee (other than modifications by the original author, its representatives, or the copyright owner) shall be deemed to be distributed under the MIT License. Submission of modifications through publicly accessible channels, including but not limited to pull requests on code repositories such as GitHub, shall be considered an explicit acknowledgment and grant by the Licensee that such modifications are made available under the MIT License. Licensees may not sublicense, transfer, or assign the rights granted under this license except as expressly permitted herein.
12
+
13
+ 3. Precedence of Existing Licenses:
14
+ If the Licensee, or its parent or umbrella organization, is already subject to an existing license for this project, that license shall take precedence, and no additional free license is granted. Nothing in this license shall be construed to override any pre-existing exclusive license agreement.
15
+
16
+ 4. Data Protection / GDPR Responsibility:
17
+ Licensees are solely responsible for ensuring that any processing of personal data using this software complies with applicable data protection laws, including the EU General Data Protection Regulation (GDPR).
18
+
19
+ 5. Termination and Revocation:
20
+ The copyright holders may revoke this license at any time, at their sole discretion.
21
+
22
+ 6. Governing Law:
23
+ This license shall be governed by and construed in accordance with the laws of Belgium, without regard to conflict of law principles.
24
+
25
+ 7. Third-Party Licenses:
26
+ Certain files or components included in the Software may be governed by separate licenses, including open-source licenses, or contributed by third parties under different terms. Such files are not automatically covered by this license. Licensees are responsible for reviewing and complying with any additional license terms that apply to these files.
27
+
28
+ For the purposes of this license, a “non-profit organization” means an entity recognized as non-profit under applicable law in its jurisdiction, which does not distribute profits to its members or owners.
29
+
30
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31
+
32
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
package/README.md ADDED
@@ -0,0 +1,37 @@
1
+ # Statistics syncer
2
+
3
+ Keeps the platform statistics database up to date: the separate, de-identified database that Metabase
4
+ reports on. It runs the nightly sync from the main administration.
5
+
6
+ It is deliberately its own service. The sync reads the whole administration in one pass, and the cron
7
+ scheduler has no distributed lock, so running it inside the API would mean one full pass per API
8
+ instance, competing with request handling. It runs on a replica server and pushes to the statistics
9
+ database on the Metabase server, so it holds two connections: `STAMHOOFD.stamhoofdDatabase` for the
10
+ administration it reads, `STAMHOOFD.statisticsDatabase` for the schema it writes.
11
+
12
+ It owns the schema it writes into: `src/migrations/` holds the migrations of the statistics database,
13
+ `src/schema.ts` runs them and `src/database.ts` connects to it. That database keeps a migration
14
+ history of its own, in its own `migrations` table, so it can be moved to another server without
15
+ dragging the main one along.
16
+
17
+ The report read off the schema lives in `@stamhoofd/metabase`. It depends on nothing here: it is a
18
+ shared package, so the dependency could only run the wrong way.
19
+
20
+ ## Running
21
+
22
+ ```bash
23
+ yarn start # boot the service
24
+ yarn migrations # migrate the statistics database (part of `yarn migrate` from the repo root)
25
+ ```
26
+
27
+ Wherever this service runs, it syncs: there is nothing to switch off in configuration, so deploy it
28
+ only for a platform that has statistics to report on. In development it runs on every cron tick;
29
+ elsewhere once a night between 03:00 and 05:00 (see `src/crons.ts`).
30
+
31
+ `STAMHOOFD.IMPORTED_UNTIL` marks how far back the numbers come from an external import instead of from
32
+ this administration; periods ending before it are frozen and left to that import.
33
+
34
+ A period the administration has locked stops being synced as well, one run later: the run that first
35
+ sees the lock still writes the changes and the deletions of that day, and settles the period at the
36
+ end if it came through in full. Unlocking a period brings it back into the sync, unless it ended more
37
+ than a year ago.
package/index.ts ADDED
@@ -0,0 +1,21 @@
1
+ import backendEnv from '@stamhoofd/backend-env';
2
+
3
+ process.title = 'stamhoofd-statistics-syncer';
4
+ backendEnv.load({ service: 'statistics-syncer' }).catch((error) => {
5
+ console.error('Failed to load environment:', error);
6
+ process.exit(1);
7
+ }).then(async () => {
8
+ if (STAMHOOFD.environment === 'development') {
9
+ const { run } = await import('./src/migrate.js');
10
+ await run();
11
+ }
12
+ const { boot } = await import('./src/boot.js');
13
+
14
+ boot({ killProcess: true }).catch((error) => {
15
+ console.error('unhandledRejection', error);
16
+ process.exit(1);
17
+ });
18
+ }).catch((error) => {
19
+ console.error('Failed to start the statistics service:', error);
20
+ process.exit(1);
21
+ });
package/migrations.ts ADDED
@@ -0,0 +1,14 @@
1
+ import backendEnv from '@stamhoofd/backend-env';
2
+
3
+ process.title = 'stamhoofd-statistics-syncer-migrations';
4
+ backendEnv.load({ service: 'statistics-syncer' }).catch((error) => {
5
+ console.error('Failed to load environment:', error);
6
+ process.exit(1);
7
+ }).then(async () => {
8
+ const { run } = await import('./src/migrate.js');
9
+ await run();
10
+ process.exit(0);
11
+ }).catch((error) => {
12
+ console.error('Failed to run migrations:', error);
13
+ process.exit(1);
14
+ });
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@stamhoofd/backend-statistics-syncer",
3
+ "version": "2.148.0",
4
+ "type": "module",
5
+ "main": "./dist/index.js",
6
+ "exports": {
7
+ ".": {
8
+ "require": "./dist/index.js"
9
+ }
10
+ },
11
+ "scripts": {
12
+ "build": "tsc --build tsconfig.build.json && mkdir -p ./dist/src/migrations && rsync --delete --exclude='*.ts' --exclude='*.js' --exclude='*.map' -r --checksum ./src/migrations/ ./dist/src/migrations/",
13
+ "build:full": "yarn -s clear && yarn -s build",
14
+ "clear": "rm -rf ./dist && rm -f *.tsbuildinfo",
15
+ "dev": "wait-on ../../shared/middleware/dist/index.js && concurrently -r 'yarn -s build --watch --preserveWatchOutput' \"wait-on ./dist/index.js && nodemon --quiet --inspect=5859 --watch dist --watch '../../../shared/*/dist/' --watch '../../shared/*/dist/' --ext .ts,.json,.sql,.js --watch .env.json --delay 1000ms --exec 'node --enable-source-maps ./dist/index.js' --signal SIGTERM\"",
16
+ "dev:build": "yarn -s build",
17
+ "dev:full": "yarn -s dev",
18
+ "lint": "eslint",
19
+ "migrations": "yarn -s build:full && node ./dist/migrations.js",
20
+ "start": "yarn -s build && node --enable-source-maps ./dist/index.js",
21
+ "typecheck": "tsc --build tsconfig.test.json",
22
+ "test": "vitest",
23
+ "test:coverage": "vitest --coverage"
24
+ },
25
+ "dependencies": {
26
+ "@simonbackx/simple-database": "1.39.0",
27
+ "@simonbackx/simple-encoding": "2.26.11",
28
+ "@simonbackx/simple-errors": "1.5.0",
29
+ "@simonbackx/simple-logging": "1.0.1",
30
+ "@stamhoofd/backend-env": "2.148.0",
31
+ "@stamhoofd/crons": "2.148.0",
32
+ "@stamhoofd/logging": "2.148.0",
33
+ "@stamhoofd/models": "2.148.0",
34
+ "@stamhoofd/queues": "2.148.0",
35
+ "@stamhoofd/sql": "2.148.0",
36
+ "@stamhoofd/structures": "2.148.0",
37
+ "@stamhoofd/types": "2.148.0",
38
+ "@stamhoofd/utility": "2.148.0",
39
+ "mysql2": "3.23.1"
40
+ },
41
+ "devDependencies": {
42
+ "@stamhoofd/test-utils": "2.148.0",
43
+ "@types/node": "22.20.1",
44
+ "vitest": "4.1.10"
45
+ },
46
+ "license": "UNLICENCED",
47
+ "publishConfig": {
48
+ "access": "public"
49
+ },
50
+ "gitHead": "c60185d35181166ce8ddeefd4dbdd351e3a1d71c"
51
+ }
package/src/boot.ts ADDED
@@ -0,0 +1,84 @@
1
+ import { Column, Database } from '@simonbackx/simple-database';
2
+ import { startCrons, stopCrons, waitForCrons } from '@stamhoofd/crons';
3
+ import { loadLogger } from '@stamhoofd/logging';
4
+ import { Version } from '@stamhoofd/structures';
5
+ import { endStatisticsConnection } from './database.js';
6
+ import { statisticsLanguage } from './rows.js';
7
+
8
+ process.on('unhandledRejection', (error: Error) => {
9
+ console.error('unhandledRejection');
10
+ console.error(error.message, error.stack);
11
+ process.exit(1);
12
+ });
13
+
14
+ // Set version of saved structures
15
+ Column.setJSONVersion(Version);
16
+
17
+ // Set timezone to UTC
18
+ process.env.TZ = 'UTC';
19
+
20
+ // Quick check
21
+ if (new Date().getTimezoneOffset() !== 0) {
22
+ throw new Error('Process should always run in UTC timezone');
23
+ }
24
+
25
+ /**
26
+ * The sync reads models, whose structures reach for the global $t while they decode. Nothing it
27
+ * writes is translated — rows.ts resolves every name it writes itself, never through a structure
28
+ * getter that runs $t — so returning the key is enough to keep decoding from throwing, and this
29
+ * service needs no locales of its own.
30
+ */
31
+ function loadGlobalTranslateFunction() {
32
+ (global as any).$t = (key: string) => key;
33
+ (global as any).$getLanguage = () => statisticsLanguage;
34
+ (global as any).$getCountry = () => 'BE';
35
+ }
36
+
37
+ export const boot = async (options: { killProcess: boolean }) => {
38
+ console.log('Started Statistics.');
39
+ loadLogger();
40
+
41
+ loadGlobalTranslateFunction();
42
+
43
+ const shutdown = async () => {
44
+ console.log('Shutting down...');
45
+ stopCrons();
46
+ await waitForCrons();
47
+
48
+ try {
49
+ await endStatisticsConnection();
50
+ await Database.end();
51
+ } catch (error) {
52
+ console.error('Failed to close the database connections:');
53
+ console.error(error);
54
+ }
55
+
56
+ // Should not be needed, but added for security as sometimes a promise hangs somewhere
57
+ if (options.killProcess) {
58
+ process.exit(0);
59
+ }
60
+ };
61
+
62
+ process.on('SIGTERM', () => {
63
+ console.info('SIGTERM signal received.');
64
+ shutdown().catch((error) => {
65
+ console.error(error);
66
+ process.exit(1);
67
+ });
68
+ });
69
+
70
+ process.on('SIGINT', () => {
71
+ console.info('SIGINT signal received.');
72
+ shutdown().catch((error) => {
73
+ console.error(error);
74
+ process.exit(1);
75
+ });
76
+ });
77
+
78
+ const { statisticsCronOptions } = await import('./crons.js');
79
+
80
+ // This service runs no seeds of its own.
81
+ startCrons(statisticsCronOptions);
82
+
83
+ return { shutdown };
84
+ };
@@ -0,0 +1,46 @@
1
+ import { TestUtils } from '@stamhoofd/test-utils';
2
+ import { shouldRunStatisticsSync, statisticsCronOptions } from './crons.js';
3
+
4
+ describe('Cron.platform-statistics-sync', () => {
5
+ describe('statisticsCronOptions', () => {
6
+ it('keeps running where the main database is read-only', () => {
7
+ // The syncer is deployed on a replica, whose MySQL is read_only. The cron loop checks
8
+ // that flag against the main database and stops before scheduling anything, so this
9
+ // being false means the sync never runs in production.
10
+ expect(statisticsCronOptions.allowReadOnly).toBe(true);
11
+ });
12
+ });
13
+
14
+ describe('shouldRunStatisticsSync', () => {
15
+ it('only runs at night', () => {
16
+ TestUtils.setEnvironment('environment', 'production');
17
+
18
+ for (const hour of [0, 2, 6, 12, 23]) {
19
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 5, hour, 30), lastRun: null })).toBe(false);
20
+ }
21
+
22
+ for (const hour of [3, 4, 5]) {
23
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 5, hour, 30), lastRun: null })).toBe(true);
24
+ }
25
+ });
26
+
27
+ it('runs once a night, and retries within the window until it succeeded', () => {
28
+ TestUtils.setEnvironment('environment', 'production');
29
+
30
+ const firstRun = new Date(2026, 0, 5, 3, 0);
31
+
32
+ // A run that never finished leaves lastRun untouched, so the next tick picks it up again.
33
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 5, 3, 5), lastRun: null })).toBe(true);
34
+
35
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 5, 3, 5), lastRun: firstRun })).toBe(false);
36
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 5, 5, 55), lastRun: firstRun })).toBe(false);
37
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 6, 3, 0), lastRun: firstRun })).toBe(true);
38
+ });
39
+
40
+ it('runs on every tick in development, where waiting for the night is not an option', () => {
41
+ TestUtils.setEnvironment('environment', 'development');
42
+
43
+ expect(shouldRunStatisticsSync({ now: new Date(2026, 0, 5, 14, 0), lastRun: new Date(2026, 0, 5, 13, 59) })).toBe(true);
44
+ });
45
+ });
46
+ });
package/src/crons.ts ADDED
@@ -0,0 +1,43 @@
1
+ import { registerCron } from '@stamhoofd/crons';
2
+ import { runStatisticsCycle } from './sync.js';
3
+
4
+ registerCron('syncPlatformStatistics', syncPlatformStatistics);
5
+
6
+ /**
7
+ * Both passes read the whole administration, which is far more than the five-minute cron cadence is
8
+ * meant for and does not need to be current to the minute: the reports they feed are read by day.
9
+ */
10
+ export function shouldRunStatisticsSync({ now, lastRun }: { now: Date; lastRun: Date | null }): boolean {
11
+ if (STAMHOOFD.environment === 'development') {
12
+ return true;
13
+ }
14
+
15
+ const hour = now.getHours();
16
+ if (hour < 3 || hour > 5) {
17
+ return false;
18
+ }
19
+
20
+ return lastRun === null || lastRun.getTime() <= now.getTime() - 12 * 60 * 60 * 1000;
21
+ }
22
+
23
+ let lastRun: Date | null = null;
24
+
25
+ async function syncPlatformStatistics() {
26
+ if (!shouldRunStatisticsSync({ now: new Date(), lastRun })) {
27
+ return;
28
+ }
29
+
30
+ await runStatisticsCycle();
31
+
32
+ lastRun = new Date();
33
+ }
34
+
35
+ /**
36
+ * How the cron loop is started for this service.
37
+ *
38
+ * `allowReadOnly` is on because the syncer runs on a replica, whose MySQL is `read_only`. That flag
39
+ * guards the main database, and this service never writes to it: it reads the administration and
40
+ * writes through the separate connection to the statistics database, whose watermarks live in
41
+ * `stats_sync_state` there. Switching it off stops the sync from ever running where it is deployed.
42
+ */
43
+ export const statisticsCronOptions = { allowReadOnly: true, allowBeforeSeeds: true };
@@ -0,0 +1,64 @@
1
+ import { TestUtils } from '@stamhoofd/test-utils';
2
+ import type { StatisticsEnvironment } from '@stamhoofd/types/Environment';
3
+ import { getStatisticsDatabaseConfig, getStatisticsPoolOptions } from './database.js';
4
+
5
+ describe('getStatisticsDatabaseConfig', () => {
6
+ it('refuses to migrate the main database, whose tables it would collide with', () => {
7
+ TestUtils.setEnvironment('statisticsDatabase', { ...STAMHOOFD.stamhoofdDatabase });
8
+
9
+ expect(() => getStatisticsDatabaseConfig()).toThrow('has to be a separate one');
10
+ });
11
+
12
+ it('refuses the main database even when it inherits its port instead of naming one', () => {
13
+ TestUtils.setEnvironment('stamhoofdDatabase', { ...STAMHOOFD.stamhoofdDatabase, DB_PORT: 3307 });
14
+ TestUtils.setEnvironment('statisticsDatabase', { ...STAMHOOFD.stamhoofdDatabase, DB_PORT: undefined });
15
+
16
+ expect(() => getStatisticsDatabaseConfig()).toThrow('has to be a separate one');
17
+ });
18
+
19
+ it('accepts the same database name on another server, which is a database of its own', () => {
20
+ TestUtils.setEnvironment('statisticsDatabase', { ...STAMHOOFD.stamhoofdDatabase, DB_HOST: 'statistics.example' });
21
+
22
+ expect(getStatisticsDatabaseConfig().DB_HOST).toBe('statistics.example');
23
+ });
24
+
25
+ it('refuses to run when no statistics database is configured', () => {
26
+ TestUtils.setEnvironment('statisticsDatabase', undefined as unknown as StatisticsEnvironment['statisticsDatabase']);
27
+
28
+ expect(() => getStatisticsDatabaseConfig()).toThrow('is not set');
29
+ });
30
+ });
31
+
32
+ describe('getStatisticsPoolOptions', () => {
33
+ it('follows the port of the main database while both are on one server', () => {
34
+ expect(STAMHOOFD.statisticsDatabase.DB_HOST).toBe(STAMHOOFD.stamhoofdDatabase.DB_HOST);
35
+
36
+ expect(getStatisticsPoolOptions().port).toBeUndefined();
37
+ });
38
+
39
+ it('falls back to the default port on another server, whose ports are its own', () => {
40
+ TestUtils.setEnvironment('statisticsDatabase', { ...STAMHOOFD.statisticsDatabase, DB_HOST: 'statistics.example' });
41
+
42
+ expect(getStatisticsPoolOptions().port).toBe(3306);
43
+ });
44
+
45
+ it('uses the port it was given', () => {
46
+ TestUtils.setEnvironment('statisticsDatabase', { ...STAMHOOFD.statisticsDatabase, DB_HOST: 'statistics.example', DB_PORT: 3399 });
47
+
48
+ expect(getStatisticsPoolOptions().port).toBe(3399);
49
+ });
50
+
51
+ it('encrypts the connection to another server, whose login is created with REQUIRE SSL', () => {
52
+ // The devops grant pins `REQUIRE SSL` on this user, and MySQL refuses it in plaintext: the
53
+ // two have to stay switched on together or the sync cannot connect at all.
54
+ TestUtils.setEnvironment('statisticsDatabase', { ...STAMHOOFD.statisticsDatabase, DB_HOST: 'statistics.example' });
55
+
56
+ expect(getStatisticsPoolOptions().useSSL).toBe(true);
57
+ });
58
+
59
+ it('does not ask for TLS while both databases are on one MySQL', () => {
60
+ expect(STAMHOOFD.statisticsDatabase.DB_HOST).toBe(STAMHOOFD.stamhoofdDatabase.DB_HOST);
61
+
62
+ expect(getStatisticsPoolOptions().useSSL).toBe(false);
63
+ });
64
+ });
@@ -0,0 +1,93 @@
1
+ import { DatabaseInstance } from '@simonbackx/simple-database';
2
+ import type { StatisticsEnvironment } from '@stamhoofd/types/Environment';
3
+
4
+ export type StatisticsDatabaseConfig = StatisticsEnvironment['statisticsDatabase'];
5
+
6
+ const defaultMysqlPort = 3306;
7
+
8
+ export function getStatisticsDatabaseConfig(): StatisticsDatabaseConfig {
9
+ const config = STAMHOOFD.statisticsDatabase;
10
+
11
+ if (!config?.DB_DATABASE) {
12
+ throw new Error('STAMHOOFD.statisticsDatabase is not set: configure the platform statistics database before running migrations');
13
+ }
14
+
15
+ // The statistics migrations create tables that share their names with the main database
16
+ // (members, registrations, groups, ...). Pointed at the main database they would collide with
17
+ // it, so the one configuration that could damage it is refused outright. Each lives on its own
18
+ // server, so it takes a match on the server as well as on the name to be the same database.
19
+ const main = STAMHOOFD.stamhoofdDatabase;
20
+ if (main && config.DB_DATABASE === main.DB_DATABASE && config.DB_HOST === main.DB_HOST && (config.DB_PORT ?? main.DB_PORT) === main.DB_PORT) {
21
+ throw new Error(`STAMHOOFD.statisticsDatabase is the main database (${config.DB_DATABASE} on ${config.DB_HOST}): the platform statistics database has to be a separate one`);
22
+ }
23
+
24
+ return config;
25
+ }
26
+
27
+ /**
28
+ * Whether the statistics database is on a different machine than the process reading the
29
+ * administration. It is wherever this is deployed -- the schema lives next to Metabase -- and it is
30
+ * not in development or in the tests, which put both on the same MySQL.
31
+ */
32
+ function isOnAnotherServer(config: StatisticsDatabaseConfig): boolean {
33
+ return config.DB_HOST !== STAMHOOFD.stamhoofdDatabase?.DB_HOST;
34
+ }
35
+
36
+ /**
37
+ * The port of a statistics database that does not name one. Undefined follows the port the process
38
+ * connects to the main database on, which is only the same server in development and in tests: on
39
+ * another server that port means nothing, so there it falls back to the MySQL default instead of
40
+ * silently reaching for whatever happens to be listening.
41
+ */
42
+ function getStatisticsPort(config: StatisticsDatabaseConfig): number | undefined {
43
+ if (config.DB_PORT !== undefined) {
44
+ return config.DB_PORT;
45
+ }
46
+
47
+ return isOnAnotherServer(config) ? defaultMysqlPort : undefined;
48
+ }
49
+
50
+ /**
51
+ * Where to reach the statistics database. It lives next to Metabase rather than on the server this
52
+ * runs on, so every connection detail is spelled out instead of inherited from the main database.
53
+ */
54
+ export function getStatisticsPoolOptions(): { host: string; user: string; password: string; port: number | undefined; useSSL: boolean } {
55
+ const config = getStatisticsDatabaseConfig();
56
+
57
+ return {
58
+ host: config.DB_HOST,
59
+ user: config.DB_USER,
60
+ password: config.DB_PASS,
61
+ port: getStatisticsPort(config),
62
+
63
+ // The connection leaves the machine, so it is encrypted: the login it connects with is
64
+ // created with REQUIRE SSL, and MySQL refuses it in plaintext. No CA is shipped here, so
65
+ // this buys encryption and not proof of which server answered. Left off where both databases
66
+ // are on the same MySQL, which is development and the tests.
67
+ useSSL: isOnAnotherServer(config),
68
+ };
69
+ }
70
+
71
+ let connection: DatabaseInstance | undefined;
72
+
73
+ /**
74
+ * A connection of its own to the platform statistics database.
75
+ *
76
+ * The shared `Database` stays pointed at the main administration, which the sync reads through the
77
+ * models: the statistics database lives on the Metabase server, so the two are not even the same
78
+ * MySQL to point a single connection at.
79
+ */
80
+ export function getStatisticsConnection(): DatabaseInstance {
81
+ connection ??= new DatabaseInstance({ ...getStatisticsPoolOptions(), database: getStatisticsDatabaseConfig().DB_DATABASE });
82
+ return connection;
83
+ }
84
+
85
+ export async function endStatisticsConnection(): Promise<void> {
86
+ if (!connection) {
87
+ return;
88
+ }
89
+
90
+ const ending = connection;
91
+ connection = undefined;
92
+ await ending.end();
93
+ }
package/src/migrate.ts ADDED
@@ -0,0 +1,44 @@
1
+ import { Column } from '@simonbackx/simple-database';
2
+ import { Version } from '@stamhoofd/structures';
3
+ import { endStatisticsConnection } from './database.js';
4
+ import { runStatisticsMigrations } from './schema.js';
5
+
6
+ Column.setJSONVersion(Version);
7
+ process.env.TZ = 'UTC';
8
+
9
+ if (new Date().getTimezoneOffset() !== 0) {
10
+ throw new Error('Process should always run in UTC timezone');
11
+ }
12
+
13
+ const start = async () => {
14
+ let killSignalReceived = false;
15
+ const handler = () => {
16
+ console.error('Ignoring kill signal during migration');
17
+ killSignalReceived = true;
18
+ };
19
+
20
+ process.on('SIGTERM', handler);
21
+ process.on('SIGINT', handler);
22
+
23
+ try {
24
+ await runStatisticsMigrations();
25
+
26
+ if (killSignalReceived) {
27
+ console.error('Killing process due to received signal during migration');
28
+ process.exit(1);
29
+ }
30
+ } finally {
31
+ process.off('SIGTERM', handler);
32
+ process.off('SIGINT', handler);
33
+
34
+ // These migrations run on the statistics database only: the main one is never connected to.
35
+ await endStatisticsConnection();
36
+ }
37
+ };
38
+
39
+ export async function run() {
40
+ await start().catch((error) => {
41
+ console.error('unhandledRejection', error);
42
+ process.exit(1);
43
+ });
44
+ }