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