CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutSign UpSign In
sagemathinc

Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.

GitHub Repository: sagemathinc/cocalc
Path: blob/master/src/packages/database/postgres/record-connect-error.ts
Views: 687
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
function recordDisconnected() {
26
L.debug("disconnected");
27
const now = Date.now();
28
try {
29
getStatusGauge().labels("disconnected").set(now);
30
} catch (err) {
31
L.debug("issue with database status gauge", err);
32
}
33
if (lastDisconnected == null) {
34
lastDisconnected = now;
35
}
36
}
37
38
function recordConnected() {
39
L.debug("connected");
40
try {
41
getStatusGauge().labels("connected").set(Date.now());
42
} catch (err) {
43
L.debug("issue with database status gauge", err);
44
}
45
lastDisconnected = null;
46
}
47
48
export function setupRecordConnectErrors(db: PostgreSQL) {
49
db.on("connect", () => recordConnected());
50
db.on("disconnect", () => recordDisconnected());
51
}
52
53
export function howLongDisconnectedMins(): number | undefined {
54
if (lastDisconnected == null) {
55
return undefined;
56
} else {
57
const last = lastDisconnected;
58
const now = Date.now();
59
const dtMin = (now - last) / 1000 / 60;
60
return dtMin;
61
}
62
}
63
64