@ultimat3/db 31.28.0 → 31.29.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/README.md +22 -0
- package/package.json +2 -2
- package/src/index.ts +6 -0
- package/src/pg-stats-gauges.ts +131 -0
- package/src/pg-stats-sql.ts +31 -0
package/README.md
CHANGED
|
@@ -222,6 +222,28 @@ too bloated differs per app. `checkDb()` stays the readiness probe `/readyz` rea
|
|
|
222
222
|
| `activity` | `queryVisible: false` (and `query: null`) for a session another role owns when this one lacks `pg_read_all_stats` |
|
|
223
223
|
| Who sees what | whoever runs it sees the SQL text (redacted) of **every session on the app's database role**, and of every role when that role holds `pg_read_all_stats` or is a superuser: other users' requests, background jobs, `psql` sessions. Literals are `?`, statement shape and identifiers are not. Run it with the credentials of someone allowed to see that |
|
|
224
224
|
|
|
225
|
+
## Server health gauges
|
|
226
|
+
|
|
227
|
+
`As of 2026-11`. `startPostgresStatsGauges(executor, intervalMs?)` samples the Postgres server every
|
|
228
|
+
`POSTGRES_STATS_INTERVAL_MS` (15 s) — at once, one round at a time, unref'd — and returns an async stop
|
|
229
|
+
that awaits the round in flight (release it before the pool closes);
|
|
230
|
+
`postgresStatsSampler(executor).sample()` is one round. Run by ONE role (the scheduler): these are server
|
|
231
|
+
facts, and every pod reading them would multiply the load for the same numbers.
|
|
232
|
+
|
|
233
|
+
| Series | What it is |
|
|
234
|
+
|---|---|
|
|
235
|
+
| `db_server_connections` / `db_server_max_connections` | client backends on the whole server, against its `max_connections` |
|
|
236
|
+
| `db_longest_transaction_seconds` | this database's oldest open transaction this role can see (`pg_read_all_stats` widens it), 0 when none |
|
|
237
|
+
| `db_autovacuum_backlog_ratio` | the worst table's dead tuples over its autovacuum trigger (global settings): above 1 it is due |
|
|
238
|
+
| `db_replication_slot_retained_bytes{slot}` | the WAL each of this database's logical slots holds on the primary; a dropped slot reads 0 |
|
|
239
|
+
| `db_stats_sample_ok` | 1 when the last round landed, 0 when it failed and every value above is stale |
|
|
240
|
+
|
|
241
|
+
Two constant catalog statements per round, no user table, no lock. A failed round never rejects
|
|
242
|
+
and logs `db.stats.sample-failed` once per streak; a value the driver did not send as a finite
|
|
243
|
+
number leaves the gauge at its last good value. The gauges are declared on the first sample, so a
|
|
244
|
+
process that samples nothing exposes none. The chart's alert rules read all six; a
|
|
245
|
+
zero autovacuum trigger (threshold 0 over an empty table) is skipped, never a division by zero.
|
|
246
|
+
|
|
225
247
|
## Index access methods
|
|
226
248
|
|
|
227
249
|
`btree` is the default and is never written out; `gin` is what makes `@>` / `<@` / `&&` / `?` on a
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ultimat3/db",
|
|
3
|
-
"version": "31.
|
|
3
|
+
"version": "31.29.0",
|
|
4
4
|
"description": "Postgres access, transactions, migrations and drift detection",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ultimate",
|
|
@@ -45,7 +45,7 @@
|
|
|
45
45
|
"test": "bun test"
|
|
46
46
|
},
|
|
47
47
|
"dependencies": {
|
|
48
|
-
"@ultimat3/core": "31.
|
|
48
|
+
"@ultimat3/core": "31.29.0"
|
|
49
49
|
},
|
|
50
50
|
"peerDependencies": {
|
|
51
51
|
"@electric-sql/pglite": ">=0.5.0"
|
package/src/index.ts
CHANGED
|
@@ -192,6 +192,12 @@ export {
|
|
|
192
192
|
lockHeavyStatements,
|
|
193
193
|
migrationLockHeavy,
|
|
194
194
|
} from './migration-lock-lint';
|
|
195
|
+
export type { PostgresStatsSampler } from './pg-stats-gauges';
|
|
196
|
+
export {
|
|
197
|
+
POSTGRES_STATS_INTERVAL_MS,
|
|
198
|
+
postgresStatsSampler,
|
|
199
|
+
startPostgresStatsGauges,
|
|
200
|
+
} from './pg-stats-gauges';
|
|
195
201
|
export type {
|
|
196
202
|
PgliteClient,
|
|
197
203
|
PgliteDriver,
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Single responsibility: the Postgres server's own health as gauges — connections against
|
|
2
|
+
// `max_connections`, the longest open transaction, the autovacuum backlog and the WAL each logical
|
|
3
|
+
// slot retains — sampled on an interval by ONE role (the scheduler), because a scrape reads gauges
|
|
4
|
+
// synchronously and these are server facts every pod would otherwise read the same of.
|
|
5
|
+
|
|
6
|
+
import type { Gauge, PgExecutor } from '@ultimat3/core';
|
|
7
|
+
import { gauge, logger, renderThrowable } from '@ultimat3/core';
|
|
8
|
+
import { PG_SERVER_STATS_SQL, PG_SLOT_STATS_SQL } from './pg-stats-sql';
|
|
9
|
+
|
|
10
|
+
/** A scrape reads every ~15s; sampling faster costs the server reads nobody sees. */
|
|
11
|
+
export const POSTGRES_STATS_INTERVAL_MS = 15_000;
|
|
12
|
+
|
|
13
|
+
interface Gauges {
|
|
14
|
+
readonly connections: Gauge;
|
|
15
|
+
readonly maxConnections: Gauge;
|
|
16
|
+
readonly longestTransaction: Gauge;
|
|
17
|
+
readonly autovacuumBacklog: Gauge;
|
|
18
|
+
readonly slotRetained: Gauge;
|
|
19
|
+
readonly sampleOk: Gauge;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
let declared: Gauges | undefined;
|
|
23
|
+
|
|
24
|
+
/** On the first sample, never at import: a process that samples nothing declares no series. */
|
|
25
|
+
function gauges(): Gauges {
|
|
26
|
+
declared ??= {
|
|
27
|
+
connections: gauge('db_server_connections', {
|
|
28
|
+
unit: '{connection}',
|
|
29
|
+
description: 'Client connections open on the Postgres server, every database counted',
|
|
30
|
+
}),
|
|
31
|
+
maxConnections: gauge('db_server_max_connections', {
|
|
32
|
+
unit: '{connection}',
|
|
33
|
+
description: "The Postgres server's max_connections",
|
|
34
|
+
}),
|
|
35
|
+
longestTransaction: gauge('db_longest_transaction_seconds', {
|
|
36
|
+
unit: 's',
|
|
37
|
+
description: "Age of this database's oldest open transaction this role can see — 0 when none",
|
|
38
|
+
}),
|
|
39
|
+
autovacuumBacklog: gauge('db_autovacuum_backlog_ratio', {
|
|
40
|
+
unit: '1',
|
|
41
|
+
description: "The worst table's dead tuples over the count that triggers its autovacuum",
|
|
42
|
+
}),
|
|
43
|
+
slotRetained: gauge('db_replication_slot_retained_bytes', {
|
|
44
|
+
unit: 'By',
|
|
45
|
+
description: "WAL the primary keeps for one of this database's logical replication slots",
|
|
46
|
+
}),
|
|
47
|
+
// A failed round leaves every value above at its last good number — a long transaction that
|
|
48
|
+
// began after the sampler died would read as none. This is what says the numbers are stale.
|
|
49
|
+
sampleOk: gauge('db_stats_sample_ok', {
|
|
50
|
+
unit: '1',
|
|
51
|
+
description:
|
|
52
|
+
'Whether the last Postgres stats round landed: 1, or 0 when the values are stale',
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
return declared;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const finite = (row: Readonly<Record<string, unknown>> | undefined, key: string) => {
|
|
59
|
+
const value = row?.[key];
|
|
60
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
/** A value the driver did not send as a finite number writes nothing: the last good one stands. */
|
|
64
|
+
const recordIf = (target: Gauge, value: number | undefined, attributes = {}): void => {
|
|
65
|
+
if (value !== undefined) target.record(value, attributes);
|
|
66
|
+
};
|
|
67
|
+
|
|
68
|
+
export interface PostgresStatsSampler {
|
|
69
|
+
/** One round. Never rejects: a database that cannot be measured is logged, once per streak. */
|
|
70
|
+
sample(): Promise<void>;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function postgresStatsSampler(executor: PgExecutor): PostgresStatsSampler {
|
|
74
|
+
// The slots the last round published: a dropped slot reads 0, never its last size forever.
|
|
75
|
+
let published: ReadonlySet<string> = new Set();
|
|
76
|
+
let failing = false;
|
|
77
|
+
return {
|
|
78
|
+
async sample(): Promise<void> {
|
|
79
|
+
try {
|
|
80
|
+
const [server] = await executor.query<Record<string, unknown>>(PG_SERVER_STATS_SQL, []);
|
|
81
|
+
const slots = await executor.query<Record<string, unknown>>(PG_SLOT_STATS_SQL, []);
|
|
82
|
+
const g = gauges();
|
|
83
|
+
recordIf(g.connections, finite(server, 'connections'));
|
|
84
|
+
recordIf(g.maxConnections, finite(server, 'max_connections'));
|
|
85
|
+
recordIf(g.longestTransaction, finite(server, 'longest_transaction_seconds'));
|
|
86
|
+
recordIf(g.autovacuumBacklog, finite(server, 'autovacuum_backlog_ratio'));
|
|
87
|
+
const seen = new Set<string>();
|
|
88
|
+
for (const row of slots) {
|
|
89
|
+
if (typeof row['slot'] !== 'string') continue;
|
|
90
|
+
seen.add(row['slot']);
|
|
91
|
+
recordIf(g.slotRetained, finite(row, 'retained_bytes'), { slot: row['slot'] });
|
|
92
|
+
}
|
|
93
|
+
for (const slot of published) if (!seen.has(slot)) g.slotRetained.record(0, { slot });
|
|
94
|
+
published = seen;
|
|
95
|
+
g.sampleOk.record(1);
|
|
96
|
+
failing = false;
|
|
97
|
+
} catch (error) {
|
|
98
|
+
gauges().sampleOk.record(0);
|
|
99
|
+
if (failing) return;
|
|
100
|
+
failing = true;
|
|
101
|
+
logger.warn('db.stats.sample-failed', { error: renderThrowable(error) });
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Samples now and every `intervalMs`, one round at a time; returns the stop. Unref'd. The stop is
|
|
109
|
+
* async and awaits the round in flight: release it BEFORE the pool closes, or that round's query
|
|
110
|
+
* meets a closing pool and logs `db.stats.sample-failed` on every shutdown.
|
|
111
|
+
*/
|
|
112
|
+
export function startPostgresStatsGauges(
|
|
113
|
+
executor: PgExecutor,
|
|
114
|
+
intervalMs: number = POSTGRES_STATS_INTERVAL_MS,
|
|
115
|
+
): () => Promise<void> {
|
|
116
|
+
const sampler = postgresStatsSampler(executor);
|
|
117
|
+
let inFlight: Promise<void> | undefined;
|
|
118
|
+
const tick = (): void => {
|
|
119
|
+
if (inFlight !== undefined) return;
|
|
120
|
+
inFlight = sampler.sample().finally(() => {
|
|
121
|
+
inFlight = undefined;
|
|
122
|
+
});
|
|
123
|
+
};
|
|
124
|
+
tick();
|
|
125
|
+
const timer = setInterval(tick, intervalMs);
|
|
126
|
+
timer.unref();
|
|
127
|
+
return async () => {
|
|
128
|
+
clearInterval(timer);
|
|
129
|
+
await inFlight;
|
|
130
|
+
};
|
|
131
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Single responsibility: the two constant catalog reads behind the Postgres stats gauges. Statistics
|
|
2
|
+
// views and settings only — no statement here reads a user table, and none takes a lock.
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* One row. `connections` counts every client backend on the SERVER, because `max_connections` is
|
|
6
|
+
* the server's: another database's sessions spend the same budget. The longest transaction is this
|
|
7
|
+
* database's own; without `pg_read_all_stats` another role's `xact_start` reads null, so it is the
|
|
8
|
+
* longest this role can see. The autovacuum backlog is the worst table's dead tuples over the count
|
|
9
|
+
* that triggers its autovacuum (global settings; a per-table override is not read): above 1 the
|
|
10
|
+
* table is due, and staying above it means autovacuum is not keeping up. A trigger of 0 (threshold
|
|
11
|
+
* 0 over an empty table) is skipped by `nullif`: float8 `0 / 0` raises and took the round with it.
|
|
12
|
+
*/
|
|
13
|
+
export const PG_SERVER_STATS_SQL = `select
|
|
14
|
+
(select count(*) from pg_stat_activity where backend_type = 'client backend')::int as connections,
|
|
15
|
+
current_setting('max_connections')::int as max_connections,
|
|
16
|
+
coalesce((select extract(epoch from max(now() - xact_start)) from pg_stat_activity
|
|
17
|
+
where datname = current_database() and backend_type = 'client backend'
|
|
18
|
+
and xact_start is not null and pid <> pg_backend_pid()), 0)::float8 as longest_transaction_seconds,
|
|
19
|
+
coalesce((select max(s.n_dead_tup / nullif(current_setting('autovacuum_vacuum_threshold')::float8
|
|
20
|
+
+ current_setting('autovacuum_vacuum_scale_factor')::float8 * greatest(c.reltuples, 0), 0))
|
|
21
|
+
from pg_stat_user_tables s join pg_class c on c.oid = s.relid), 0)::float8 as autovacuum_backlog_ratio`;
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* The WAL each of this database's logical slots holds back on the primary: what an inactive or
|
|
25
|
+
* lagging replicator costs in disk. Bounded by `max_replication_slots`. A standby answers no rows —
|
|
26
|
+
* `pg_current_wal_lsn()` is refused during recovery, and a standby retains nothing for a slot.
|
|
27
|
+
*/
|
|
28
|
+
export const PG_SLOT_STATS_SQL = `select slot_name as slot,
|
|
29
|
+
pg_wal_lsn_diff(pg_current_wal_lsn(), restart_lsn)::float8 as retained_bytes
|
|
30
|
+
from pg_replication_slots
|
|
31
|
+
where database = current_database() and restart_lsn is not null and not pg_is_in_recovery()`;
|