Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemathinc
GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/database/postgres/record-connect-error.ts
1503 views
1
/*
2
* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.
3
* License: MS-RSL – see LICENSE.md for details
4
*/
5
6
import getLogger from "@cocalc/backend/logger";
7
import { newGauge } from "@cocalc/backend/metrics";
8
import { PostgreSQL } from "./types";
9
10
function getStatusGauge() {
11
return newGauge(
12
"database",
13
"db_latest_connection_ts_total",
14
"Last time the connect/disconnect event was emitted",
15
["status"],
16
);
17
}
18
19
const L = getLogger("db:record-connect-error");
20
21
// timestamp when the *first* disconnect event happend
22
// a "connect" event will reset this to null
23
let lastDisconnected: number | null = null;
24
25
// ATTN: do not move/rename this function, since it is referenced in postgres-base.coffee
26
export function recordDisconnected() {
27
L.debug("disconnected");
28
const now = Date.now();
29
try {
30
getStatusGauge().labels("disconnected").set(now);
31
} catch (err) {
32
L.debug("issue with database status gauge", err);
33
}
34
if (lastDisconnected == null) {
35
lastDisconnected = now;
36
}
37
}
38
39
// ATTN: do not move/rename this function, since it is referenced in postgres-base.coffee
40
export function recordConnected() {
41
L.debug("connected");
42
try {
43
getStatusGauge().labels("connected").set(Date.now());
44
} catch (err) {
45
L.debug("issue with database status gauge", err);
46
}
47
lastDisconnected = null;
48
}
49
50
export function setupRecordConnectErrors(_db: PostgreSQL) {
51
// These event listeners are not robust. Somehow, a "removeAllListeners" or similar must trimp them up
52
// The problem arises when the database connection is dropped, reconnected, and dropped again:
53
// After the 2nd connection drop, the "disconnect" event is attempted to emit, but never appears here.
54
//db.on("connect", () => recordConnected());
55
//db.on("disconnect", () => recordDisconnected());
56
}
57
58
export function howLongDisconnectedMins(): number | undefined {
59
if (lastDisconnected == null) {
60
return undefined;
61
} else {
62
const last = lastDisconnected;
63
const now = Date.now();
64
const dtMin = (now - last) / 1000 / 60;
65
return dtMin;
66
}
67
}
68
69