-
-
Notifications
You must be signed in to change notification settings - Fork 740
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
chore: add a class to handle aggreggation queries
- Loading branch information
1 parent
5d61b39
commit f02fe87
Showing
2 changed files
with
64 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
import { createGauge, type Gauge } from './util/metrics'; | ||
|
||
type RestrictedRecord<T extends string[]> = Record<T[number], string>; | ||
type Query<R> = () => Promise<R | undefined | null>; | ||
type MapResult<R> = (result: R) => { | ||
count: number; | ||
labels: RestrictedRecord<GaugeDefinition<R>['labelNames']>; | ||
}; | ||
|
||
type GaugeDefinition<T> = { | ||
name: string; | ||
help: string; | ||
labelNames: string[]; | ||
query: Query<T>; | ||
map: MapResult<T>; | ||
}; | ||
|
||
export class DbMetricsMonitor { | ||
private tasks: (() => Promise<void>)[] = []; | ||
private gauges: Record<string, Gauge<string>> = {}; | ||
|
||
constructor() {} | ||
|
||
registerGaugeDbMetric<T>(definition: GaugeDefinition<T>) { | ||
const gauge = createGauge(definition); | ||
this.gauges[definition.name] = gauge; | ||
this.tasks.push(async () => { | ||
const result = await definition.query(); | ||
if (result) { | ||
const { count, labels } = definition.map(result); | ||
gauge.reset(); | ||
gauge.labels(labels).set(count); | ||
} | ||
}); | ||
} | ||
|
||
refreshDbMetrics = async () => { | ||
for (const task of this.tasks) { | ||
await task(); | ||
} | ||
}; | ||
|
||
async getLastValue(name: string): Promise<number | undefined> { | ||
try { | ||
return (await this.gauges[name].gauge.get()).values[0].value; | ||
} catch (e) { | ||
return undefined; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters