refactor(server): metric repo (#8278)

* refactor

* redundant `implements`

* simplify

* remove `enabled`
This commit is contained in:
Mert
2024-03-25 19:15:11 -04:00
committed by GitHub
parent c56c04a82b
commit c45e28ab53
4 changed files with 79 additions and 34 deletions

View File

@@ -1,31 +1,48 @@
import { Inject } from '@nestjs/common';
import { Injectable } from '@nestjs/common';
import { MetricOptions } from '@opentelemetry/api';
import { MetricService } from 'nestjs-otel';
import { CustomMetricOptions, IMetricRepository } from 'src/interfaces/metric.interface';
import { IMetricGroupRepository, IMetricRepository, MetricGroupOptions } from 'src/interfaces/metric.interface';
import { apiMetrics, hostMetrics, jobMetrics, repoMetrics } from 'src/utils/instrumentation';
export class MetricRepository implements IMetricRepository {
constructor(@Inject(MetricService) private readonly metricService: MetricService) {}
class MetricGroupRepository implements IMetricGroupRepository {
private enabled = false;
constructor(private readonly metricService: MetricService) {}
addToCounter(name: string, value: number, options?: CustomMetricOptions): void {
if (options?.enabled === false) {
return;
addToCounter(name: string, value: number, options?: MetricOptions): void {
if (this.enabled) {
this.metricService.getCounter(name, options).add(value);
}
this.metricService.getCounter(name, options).add(value);
}
updateGauge(name: string, value: number, options?: CustomMetricOptions): void {
if (options?.enabled === false) {
return;
addToGauge(name: string, value: number, options?: MetricOptions): void {
if (this.enabled) {
this.metricService.getUpDownCounter(name, options).add(value);
}
this.metricService.getUpDownCounter(name, options).add(value);
}
updateHistogram(name: string, value: number, options?: CustomMetricOptions): void {
if (options?.enabled === false) {
return;
addToHistogram(name: string, value: number, options?: MetricOptions): void {
if (this.enabled) {
this.metricService.getHistogram(name, options).record(value);
}
}
this.metricService.getHistogram(name, options).record(value);
configure(options: MetricGroupOptions): this {
this.enabled = options.enabled;
return this;
}
}
@Injectable()
export class MetricRepository implements IMetricRepository {
api: MetricGroupRepository;
host: MetricGroupRepository;
jobs: MetricGroupRepository;
repo: MetricGroupRepository;
constructor(metricService: MetricService) {
this.api = new MetricGroupRepository(metricService).configure({ enabled: apiMetrics });
this.host = new MetricGroupRepository(metricService).configure({ enabled: hostMetrics });
this.jobs = new MetricGroupRepository(metricService).configure({ enabled: jobMetrics });
this.repo = new MetricGroupRepository(metricService).configure({ enabled: repoMetrics });
}
}