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/backend/metrics.ts
Views: 687
import { Counter, Gauge, Histogram } from "prom-client";12type Aspect = "db" | "database" | "server" | "llm";34function withPrefix(aspect: Aspect, name: string): string {5return `cocalc_${aspect}_${name}`;6}78const cache: any = {};910export function newCounter(11aspect: Aspect,12name: string,13help: string,14labelNames: string[] = [],15) {16name = withPrefix(aspect, name);17const key = `counter-${name}`;18if (cache[key] != null) {19return cache[key];20}21// a prometheus counter -- https://github.com/siimon/prom-client#counter22// use it like counter.labels(labelA, labelB).inc([positive number or default is 1])23if (!name.endsWith("_total")) {24throw Error(25`Counter metric names have to end in [_unit]_total but got '${name}' -- https://prometheus.io/docs/practices/naming/`,26);27}28const C = new Counter({29name,30help,31labelNames,32});33cache[key] = C;34return C;35}3637export function newGauge(38aspect: Aspect,39name: string,40help,41labelNames: string[] = [],42) {43name = withPrefix(aspect, name);44const key = `gauge-${name}`;45if (cache[key] != null) {46return cache[key];47}48const G = new Gauge({49name,50help,51labelNames,52});53cache[key] = G;54return G;55}5657export function newHistogram(58aspect: Aspect,59name: string,60help,61config: { buckets?: number[]; labels?: string[] } = {},62) {63name = withPrefix(aspect, name);64const key = `hist-${name}`;65if (cache[key] != null) {66return cache[key];67}68// invoked as histogram.observe(value)69if (!config.buckets) {70config.buckets = [0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10];71}72if (!config.labels) {73config.labels = [];74}75const H = new Histogram({76name,77help,78labelNames: config.labels,79buckets: config.buckets,80});81cache[key] = H;82return H;83}848586