Skip to content

Commit 30def87

Browse files
authored
Merge pull request #59 from DevelopmentFinanceObservatory/dev
release: website dev to main
2 parents bf8609c + bca1a71 commit 30def87

21 files changed

Lines changed: 1881 additions & 83 deletions

‎db/account-export.ts‎

Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import fs from 'node:fs/promises';
2+
3+
import type { BigQuery, TableField } from '@google-cloud/bigquery';
4+
import type { Pool } from 'pg';
5+
6+
/**
7+
* The account export, which the event export Job (db/export-events.ts) runs
8+
* before the event export: copies the Postgres view `account_daily`
9+
* (migration 0020) into the BigQuery table `account_daily`, replacing the
10+
* whole table in one load job, so a failed run leaves the previous table.
11+
* The view counts new accounts per UTC day and organisation, for every day
12+
* from the first account's through yesterday's, and the rows hold no email
13+
* address or user id.
14+
*/
15+
16+
/** One `account_daily` row. */
17+
export type AccountRow = {
18+
// UTC, 2026-10-20
19+
day: string;
20+
// Null on a day without new accounts, its one row
21+
organisation: string | null;
22+
accounts: number;
23+
};
24+
25+
export const ACCOUNT_SCHEMA: TableField[] = [
26+
{
27+
name: 'day',
28+
type: 'DATE',
29+
mode: 'REQUIRED',
30+
description: 'The UTC day the accounts were created',
31+
},
32+
{
33+
name: 'organisation',
34+
type: 'STRING',
35+
description:
36+
'The lower-cased email domain once it holds at least 3 accounts, ' +
37+
'`Personal email` for a webmail domain, `Other organisations` for any other. ' +
38+
'NULL on a day without new accounts, whose one row has 0 accounts',
39+
},
40+
{
41+
name: 'accounts',
42+
type: 'INT64',
43+
mode: 'REQUIRED',
44+
description: 'The accounts created that day in that organisation, 0 on a day without any',
45+
},
46+
];
47+
48+
/** Every row of the view, oldest day first. */
49+
export const readAccountDaily = async (pool: Pool): Promise<AccountRow[]> => {
50+
const { rows } = await pool.query<AccountRow>(
51+
`SELECT to_char(day, 'YYYY-MM-DD') AS day, organisation, accounts
52+
FROM account_daily
53+
ORDER BY day, organisation`,
54+
);
55+
56+
return rows;
57+
};
58+
59+
/** Replaces the BigQuery table `account_daily` with the rows in `file`, one JSON object a line. */
60+
export const bigQueryAccountTable =
61+
({ datasetId, bigquery }: { datasetId: string; bigquery: BigQuery }) =>
62+
async (file: string): Promise<void> => {
63+
// Creates the table when it does not exist. Resolves once the load
64+
// job is done, and throws if it failed.
65+
await bigquery
66+
.dataset(datasetId)
67+
.table('account_daily')
68+
.load(file, {
69+
sourceFormat: 'NEWLINE_DELIMITED_JSON',
70+
writeDisposition: 'WRITE_TRUNCATE',
71+
schema: { fields: ACCOUNT_SCHEMA },
72+
});
73+
};
74+
75+
/**
76+
* One account export run. Writes every row to `scratchFile`, then replaces
77+
* the table with it. The view holds a row for every day since the first
78+
* account's, so a read with no rows is a fault (a wrong database, an
79+
* emptied table) unless every account is from today, and rejects with the
80+
* table kept.
81+
*/
82+
export const runAccountExport = async ({
83+
read,
84+
replace,
85+
scratchFile,
86+
log,
87+
}: {
88+
read: () => Promise<AccountRow[]>;
89+
replace: (file: string) => Promise<void>;
90+
scratchFile: string;
91+
log: (line: string) => void;
92+
}): Promise<void> => {
93+
const rows = await read();
94+
95+
if (rows.length === 0) {
96+
throw new Error('account export: account_daily read no rows, table kept');
97+
}
98+
99+
try {
100+
await fs.writeFile(scratchFile, rows.map((row) => `${JSON.stringify(row)}\n`).join(''));
101+
await replace(scratchFile);
102+
} finally {
103+
await fs.rm(scratchFile, { force: true });
104+
}
105+
106+
log(`account_daily: ${rows.length} rows loaded`);
107+
};

‎db/export-events.ts‎

Lines changed: 28 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import os from 'node:os';
22
import path from 'node:path';
3+
import { BigQuery } from '@google-cloud/bigquery';
4+
import { bigQueryAccountTable, readAccountDaily, runAccountExport } from './account-export';
35
import {
46
buildRuntimePool,
57
connectCloudSqlRuntime,
@@ -10,7 +12,9 @@ import { bigQueryWarehouse, pgEventSource, readExportEnv, runExport } from './ev
1012

1113
// The event export Job's command (`node dist/export-events.cjs`, see
1214
// deploy/Dockerfile). It reads the database as the runtime does, through
13-
// WEBSITE_DB_* over the Cloud SQL connector, or DATABASE_URL locally.
15+
// WEBSITE_DB_* over the Cloud SQL connector, or DATABASE_URL locally. It
16+
// runs the account export, then the event export, and fails when either
17+
// fails, so a failing one leaves the other's tables current.
1418
async function main(): Promise<void> {
1519
const settings = readExportEnv();
1620
const connection = resolveRuntimeConnection();
@@ -27,15 +31,36 @@ async function main(): Promise<void> {
2731
// task timeout, so a hung read ends before the next hourly run starts.
2832
const pool = buildRuntimePool(process.env, { max: 1, statement_timeout: 300_000 });
2933

34+
const bigquery = new BigQuery({ projectId: settings.projectId });
35+
const log = (line: string) => console.log(line);
36+
3037
try {
38+
let accountFailure: Error | null = null;
39+
40+
try {
41+
await runAccountExport({
42+
read: () => readAccountDaily(pool),
43+
replace: bigQueryAccountTable({ datasetId: settings.datasetId, bigquery }),
44+
scratchFile: path.join(os.tmpdir(), `account-export-${process.pid}.ndjson`),
45+
log,
46+
});
47+
} catch (error) {
48+
accountFailure = new Error('account export failed', { cause: error });
49+
console.error('ERROR:', error instanceof Error ? error.stack : error);
50+
}
51+
3152
await runExport({
3253
source: pgEventSource(pool),
33-
warehouse: bigQueryWarehouse(settings),
54+
warehouse: bigQueryWarehouse({ ...settings, bigquery }),
3455
hmacKey: settings.hmacKey,
3556
today: new Date().toISOString().slice(0, 10),
3657
scratchFile: path.join(os.tmpdir(), `event-export-${process.pid}.ndjson`),
37-
log: (line) => console.log(line),
58+
log,
3859
});
60+
61+
if (accountFailure !== null) {
62+
throw accountFailure;
63+
}
3964
} finally {
4065
// The pool first, so its connections close over the connector's tunnel.
4166
await pool.end();

‎db/migrate-local.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import path from 'node:path';
22
import { Pool } from 'pg';
33
import { applyMigrations } from './apply-migrations.ts';
44
import { ensureDatabaseRoles, type AdminConnection } from './local-roles.ts';
5+
import { syncWebmailDomains } from './webmail-domains.ts';
56

67
const MIGRATIONS_FOLDER = path.resolve(import.meta.dirname, 'migrations');
78

@@ -65,6 +66,7 @@ async function main(): Promise<void> {
6566
runtimeDbUser: RUNTIME_USER,
6667
migratorDbUser: MIGRATOR_USER,
6768
});
69+
await syncWebmailDomains(migratorPool);
6870

6971
console.log('local migrations applied');
7072
} finally {

‎db/migrate.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import path from 'node:path';
22
import { applyMigrations } from './apply-migrations';
33
import { buildMigratorPool, readMigratorEnv } from './connection';
4+
import { syncWebmailDomains } from './webmail-domains';
45

56
// Resolved from cwd, not `__dirname`. The compiled bundle
67
// (dist/migrate.cjs) and the migrations directory (db/migrations) are
@@ -19,6 +20,7 @@ async function main(): Promise<void> {
1920
runtimeDbUser: env.runtimeDbUser,
2021
migratorDbUser: env.migratorDbUser,
2122
});
23+
await syncWebmailDomains(pool);
2224

2325
console.log('migrations applied');
2426
} finally {
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
CREATE TABLE "webmail_domain" (
2+
"domain" text PRIMARY KEY NOT NULL
3+
);
4+
--> statement-breakpoint
5+
-- The event export Job (db/export-events.ts) also copies new accounts per
6+
-- UTC day and organisation into BigQuery. It reads them through this view,
7+
-- which runs with the migrator's rights, its owner's, so
8+
-- `website_export_reader` gets SELECT on the view alone and no email
9+
-- address or user id leaves Postgres. An organisation is the lower-cased
10+
-- domain after the last `@` once that domain holds at least 3 accounts in
11+
-- all, `Personal email` for a domain in `webmail_domain`, and
12+
-- `Other organisations` for every other domain. The view holds every UTC
13+
-- day from the first account's through yesterday's, so each day it holds
14+
-- is complete, and a day without new accounts is one row with a NULL
15+
-- organisation and 0 accounts. `created_at` is a timestamp without time
16+
-- zone holding UTC, the time zone of the service and of Cloud SQL, so its
17+
-- date is the UTC day. Today is taken in UTC too, whatever the session's
18+
-- time zone. db/migrate.ts fills `webmail_domain` after the migrations,
19+
-- so a run whose fill fails leaves it empty. While it is empty the view
20+
-- holds no rows, and the export fails with the BigQuery table kept,
21+
-- so webmail domains never show by name.
22+
CREATE VIEW "account_daily" AS
23+
WITH account AS (
24+
SELECT "created_at"::date AS day, lower(substring("email" FROM '[^@]*$')) AS domain
25+
FROM "user"
26+
),
27+
labelled AS (
28+
SELECT day,
29+
CASE
30+
WHEN domain IN (SELECT "domain" FROM "webmail_domain") THEN 'Personal email'
31+
WHEN count(*) OVER (PARTITION BY domain) >= 3 THEN domain
32+
ELSE 'Other organisations'
33+
END AS organisation
34+
FROM account
35+
),
36+
counted AS (
37+
SELECT day, organisation, count(*)::int AS accounts
38+
FROM labelled
39+
GROUP BY day, organisation
40+
),
41+
days AS (
42+
SELECT generate_series(min(day), (now() AT TIME ZONE 'UTC')::date - 1, interval '1 day')::date AS day
43+
FROM account
44+
WHERE EXISTS (SELECT 1 FROM "webmail_domain")
45+
)
46+
SELECT days.day, counted.organisation, coalesce(counted.accounts, 0) AS accounts
47+
FROM days
48+
LEFT JOIN counted USING (day);
49+
--> statement-breakpoint
50+
GRANT SELECT ON "account_daily" TO website_export_reader;

0 commit comments

Comments
 (0)