Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Real-time collaboration for Jupyter Notebooks, Linux Terminals, LaTeX, VS Code, R IDE, and more,
all in one place.
Path: blob/master/src/packages/database/postgres/record-connect-error.ts
Views: 687
/*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;2324function recordDisconnected() {25L.debug("disconnected");26const now = Date.now();27try {28getStatusGauge().labels("disconnected").set(now);29} catch (err) {30L.debug("issue with database status gauge", err);31}32if (lastDisconnected == null) {33lastDisconnected = now;34}35}3637function recordConnected() {38L.debug("connected");39try {40getStatusGauge().labels("connected").set(Date.now());41} catch (err) {42L.debug("issue with database status gauge", err);43}44lastDisconnected = null;45}4647export function setupRecordConnectErrors(db: PostgreSQL) {48db.on("connect", () => recordConnected());49db.on("disconnect", () => recordDisconnected());50}5152export function howLongDisconnectedMins(): number | undefined {53if (lastDisconnected == null) {54return undefined;55} else {56const last = lastDisconnected;57const now = Date.now();58const dtMin = (now - last) / 1000 / 60;59return dtMin;60}61}626364