@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/src/writer.ts ADDED
@@ -0,0 +1,78 @@
1
+ import { getStatisticsConnection } from './database.js';
2
+ import type { StatisticsRow } from './rows.js';
3
+
4
+ /**
5
+ * The number of statistics rows written per statement, and the number of source ids checked per
6
+ * query while reconciling deletes.
7
+ */
8
+ export const batchSize = 500;
9
+
10
+ /** What identifies a row when no other key is given. `members` is keyed per period as well. */
11
+ export const defaultKeyColumns = ['id'];
12
+
13
+ export function buildUpsertQuery(table: string, columns: string[], escapeId: (value: string) => string, keyColumns: string[] = defaultKeyColumns): string {
14
+ const assignments = columns
15
+ .filter(column => !keyColumns.includes(column))
16
+ .map(column => `${escapeId(column)} = new.${escapeId(column)}`);
17
+
18
+ // The row alias is the MySQL 8 replacement for VALUES(col), which is deprecated.
19
+ return `INSERT INTO ${escapeId(table)} (${columns.map(escapeId).join(', ')}) VALUES ? AS new`
20
+ + (assignments.length > 0 ? ` ON DUPLICATE KEY UPDATE ${assignments.join(', ')}` : '');
21
+ }
22
+
23
+ /**
24
+ * Write rows, replacing the ones that are already there. Running the same batch twice is a no-op, so
25
+ * a run that crashed halfway can simply be repeated.
26
+ */
27
+ export async function upsertRows(table: string, columns: string[], rows: StatisticsRow[], keyColumns: string[] = defaultKeyColumns): Promise<number> {
28
+ if (rows.length === 0) {
29
+ return 0;
30
+ }
31
+
32
+ const connection = getStatisticsConnection();
33
+ const query = buildUpsertQuery(table, columns, value => connection.escapeId(value), keyColumns);
34
+
35
+ for (let index = 0; index < rows.length; index += batchSize) {
36
+ const batch = rows.slice(index, index + batchSize).map(row => columns.map(column => row[column] ?? null));
37
+ await connection.insert(query, [batch]);
38
+ }
39
+
40
+ return rows.length;
41
+ }
42
+
43
+ export async function deleteRows(table: string, ids: string[]): Promise<number> {
44
+ if (ids.length === 0) {
45
+ return 0;
46
+ }
47
+
48
+ const connection = getStatisticsConnection();
49
+ const [result] = await connection.delete(`DELETE FROM ${connection.escapeId(table)} WHERE \`id\` IN (?)`, [ids]);
50
+ return result.affectedRows;
51
+ }
52
+
53
+ /**
54
+ * The ids a source still holds in a statistics table, in pages, so reconciling never keeps the whole
55
+ * table in memory.
56
+ *
57
+ * Scoped to one source on purpose: the rows an import produced have no counterpart in the main
58
+ * database, so reconciling them against it would delete every one of them on the first night.
59
+ */
60
+ export async function* iterateIds(table: string, source: string): AsyncGenerator<string[]> {
61
+ const connection = getStatisticsConnection();
62
+ let cursor = '';
63
+
64
+ for (;;) {
65
+ const [rows] = await connection.select(
66
+ `SELECT \`id\` FROM ${connection.escapeId(table)} WHERE \`source\` = ? AND \`id\` > ? ORDER BY \`id\` ASC LIMIT ${batchSize}`,
67
+ [source, cursor],
68
+ { nestTables: false },
69
+ );
70
+ const ids = (rows as unknown as { id: string }[]).map(row => row.id);
71
+ if (ids.length === 0) {
72
+ return;
73
+ }
74
+
75
+ yield ids;
76
+ cursor = ids[ids.length - 1];
77
+ }
78
+ }
package/stamhoofd.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ import '@stamhoofd/types/global';
2
+ import type { StatisticsEnvironment } from '@stamhoofd/types/Environment';
3
+
4
+ export {};
5
+
6
+ /**
7
+ * Stamhoofd uses a global variable to store some configurations. We don't use process.env because we can only store
8
+ * strings into those files. And we need objects for our localized domains (different domains for each locale).
9
+ * Having to encode and decode those values would be inefficient.
10
+ *
11
+ * So we use our own global configuration variable: STAMHOOFD. Available everywhere and contains
12
+ * other information depending on the environment (frontend/backend/shared). TypeScript will
13
+ * always suggest the possible keys.
14
+ */
15
+ declare global {
16
+ const STAMHOOFD: StatisticsEnvironment;
17
+ }
@@ -0,0 +1,29 @@
1
+ import { TestUtils } from '@stamhoofd/test-utils';
2
+ import path from 'path';
3
+
4
+ // Dates are stored and compared in UTC everywhere else in the repo; a date column read back in
5
+ // another zone lands a day off.
6
+ process.env.TZ = 'UTC';
7
+
8
+ if (new Date().getTimezoneOffset() !== 0) {
9
+ throw new Error('Process should always run in UTC timezone');
10
+ }
11
+
12
+ const modelsPath = require.resolve('@stamhoofd/models');
13
+
14
+ export async function setup() {
15
+ TestUtils.globalSetup();
16
+
17
+ const { Database, Migration } = await import('@simonbackx/simple-database');
18
+ const { endStatisticsConnection } = await import('../src/database.js');
19
+ const { runStatisticsMigrations } = await import('../src/schema.js');
20
+
21
+ // The sync reads the source tables, so the main database has to be migrated as well.
22
+ if (!await Migration.runAll(path.dirname(modelsPath) + '/migrations')) {
23
+ throw new Error('Migrations failed');
24
+ }
25
+
26
+ await runStatisticsMigrations();
27
+ await endStatisticsConnection();
28
+ await Database.end();
29
+ };
@@ -0,0 +1,24 @@
1
+ import { Column, Database } from '@simonbackx/simple-database';
2
+ import { endStatisticsConnection } from '../src/database.js';
3
+ import { Version } from '@stamhoofd/structures';
4
+ import { TestUtils } from '@stamhoofd/test-utils';
5
+
6
+ Error.stackTraceLimit = 100;
7
+
8
+ // Set version of saved structures
9
+ Column.setJSONVersion(Version);
10
+
11
+ // Set timezone!
12
+ process.env.TZ = 'UTC';
13
+
14
+ // Quick check
15
+ if (new Date().getTimezoneOffset() !== 0) {
16
+ throw new Error('Process should always run in UTC timezone');
17
+ }
18
+
19
+ afterAll(async () => {
20
+ await endStatisticsConnection();
21
+ await Database.end();
22
+ });
23
+
24
+ TestUtils.setup();
@@ -0,0 +1,17 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "compilerOptions": {
4
+ "rootDir": ".",
5
+ "outDir": "dist"
6
+ },
7
+ "include": [
8
+ "./index.ts",
9
+ "./migrations.ts",
10
+ "./src",
11
+ "./stamhoofd.d.ts"
12
+ ],
13
+ "exclude": [
14
+ "./src/**/*.spec.ts",
15
+ "./src/**/*.test.ts"
16
+ ]
17
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,12 @@
1
+ {
2
+ "extends": "../../../tsconfig.base.json",
3
+ "files": [],
4
+ "references": [
5
+ {
6
+ "path": "./tsconfig.build.json"
7
+ },
8
+ {
9
+ "path": "./tsconfig.test.json"
10
+ }
11
+ ]
12
+ }
@@ -0,0 +1,18 @@
1
+ {
2
+ "extends": "../../../tsconfig.test.json",
3
+ "compilerOptions": {
4
+ "rootDir": ".",
5
+ "outDir": "dist",
6
+ "noEmit": true
7
+ },
8
+ "references": [
9
+ { "path": "./tsconfig.build.json" }
10
+ ],
11
+ "include": [
12
+ "./stamhoofd.d.ts",
13
+ "../../../jest-extended.d.ts",
14
+ "./src/**/*.spec.ts",
15
+ "./src/**/*.test.ts",
16
+ "./tests"
17
+ ]
18
+ }
@@ -0,0 +1,18 @@
1
+ import { defineConfig } from 'vitest/config';
2
+
3
+ export default defineConfig({
4
+ test: {
5
+ include: ['**/*.test.ts'], // only match TypeScript sources, so compiled copies in dist are never picked up
6
+ globalSetup: './tests/vitest.global.setup.ts',
7
+ setupFiles: ['./tests/vitest.setup.ts'],
8
+ watch: false,
9
+ globals: true,
10
+ root: import.meta.dirname,
11
+ isolate: true,
12
+ coverage: {
13
+ provider: 'v8',
14
+ include: ['src/**'],
15
+ reporter: ['text', 'html', 'lcov'],
16
+ },
17
+ },
18
+ });