Path: blob/master/src/packages/database/postgres/record-connect-error.ts
1503 views
/*1* This file is part of CoCalc: Copyright © 2022 Sagemath, Inc.2* License: MS-RSL – see LICENSE.md for details3*/45import getLogger from "@cocalc/backend/logger";6import { newGauge } from "@cocalc/backend/metrics";7import { PostgreSQL } from "./types";89function getStatusGauge() {10return newGauge(11"database",12"db_latest_connection_ts_total",13"Last time the connect/disconnect event was emitted",14["status"],15);16}1718const L = getLogger("db:record-connect-error");1920// timestamp when the *first* disconnect event happend21// a "connect" event will reset this to null22let lastDisconnected: number | null = null;2324// ATTN: do not move/rename this function, since it is referenced in postgres-base.coffee25export function recordDisconnected() {26L.debug("disconnected");27const now = Date.now();28try {29getStatusGauge().labels("disconnected").set(now);30} catch (err) {31L.debug("issue with database status gauge", err);32}33if (lastDisconnected == null) {34lastDisconnected = now;35}36}3738// ATTN: do not move/rename this function, since it is referenced in postgres-base.coffee39export function recordConnected() {40L.debug("connected");41try {42getStatusGauge().labels("connected").set(Date.now());43} catch (err) {44L.debug("issue with database status gauge", err);45}46lastDisconnected = null;47}4849export function setupRecordConnectErrors(_db: PostgreSQL) {50// These event listeners are not robust. Somehow, a "removeAllListeners" or similar must trimp them up51// The problem arises when the database connection is dropped, reconnected, and dropped again:52// After the 2nd connection drop, the "disconnect" event is attempted to emit, but never appears here.53//db.on("connect", () => recordConnected());54//db.on("disconnect", () => recordDisconnected());55}5657export function howLongDisconnectedMins(): number | undefined {58if (lastDisconnected == null) {59return undefined;60} else {61const last = lastDisconnected;62const now = Date.now();63const dtMin = (now - last) / 1000 / 60;64return dtMin;65}66}676869