Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/api/src/libs/pgp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { ISSLConfig } from 'pg-promise/typescript/pg-subset.js';

import config from '#config';
import logger from '#libs/logger';
import { recordQuery } from '#libs/queryStats';

export const ssl: ISSLConfig = {
rejectUnauthorized: true,
Expand All @@ -16,6 +17,8 @@ if (config.dbCa) {

export const pgp = pgpromise({
error: (_err, e) => {
recordQuery(e.queryFilePath, 0, true);

if (e.cn) {
logger.error(e.cn);
}
Expand All @@ -32,6 +35,9 @@ export const pgp = pgpromise({
logger.error(e.ctx);
}
},
receive: (e) => {
recordQuery(e.ctx.queryFilePath, e.result?.duration ?? 0, false);
},
});

/**
Expand Down
58 changes: 58 additions & 0 deletions apps/api/src/libs/queryStats.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import logger from '#libs/logger';

type Tally = { ms: number; n: number };

type Entry = { error: Tally; ok: Tally };

const REPORT_INTERVAL_MS = 60_000;

const tallies = new Map<string, Entry>();

const empty = (): Entry => ({
error: { ms: 0, n: 0 },
ok: { ms: 0, n: 0 },
});

const mean = (tally: Tally): number =>
tally.n ? Math.round(tally.ms / tally.n) : 0;

const shortPath = (path: string): string =>
path.replace(/^.*[/\\]sql[/\\]/, '');

export const recordQuery = (
queryFilePath: string | undefined,
ms: number,
failed: boolean,
): void => {
const label = queryFilePath ? shortPath(queryFilePath) : 'adhoc';
const entry = tallies.get(label) ?? empty();
const tally = failed ? entry.error : entry.ok;

tally.ms += ms;
tally.n += 1;
tallies.set(label, entry);
};

const report = (): void => {
for (const [label, entry] of tallies) {
const calls = entry.ok.n + entry.error.n;

if (!calls) continue;

logger.info(
{
calls,
db_ms: Math.round(entry.ok.ms + entry.error.ms),
error_n: entry.error.n,
label,
ok_mean_ms: mean(entry.ok),
ok_n: entry.ok.n,
},
'query stats',
);
}

tallies.clear();
};

setInterval(report, REPORT_INTERVAL_MS).unref();
Loading