Merge branch 'pass-lifetime-fixes' into 'main'
[ProtonMail-WebClient.git] / packages / metrics / lib / Metric.ts
bloba00f24cdc35ff4a6a1f35a83e8e2fc28e656b60a
1 import type IMetricsRequestService from './types/IMetricsRequestService';
2 import type MetricSchema from './types/MetricSchema';
3 import type MetricVersions from './types/MetricVersions';
5 /**
6  * Custom regex based on the following
7  * - https://prometheus.io/docs/concepts/data_model/#metric-names-and-labels
8  * - https://gitlab.protontech.ch/proton/be/json-schema-registry
9  */
10 const metricRegexp = /^[a-zA-Z]+(?:_[a-zA-Z0-9]+)*$/;
12 function validateMetricName(name: string) {
13     return metricRegexp.test(name);
16 abstract class Metric<D extends MetricSchema> {
17     private name: string;
19     private version: MetricVersions;
21     private requestService: IMetricsRequestService;
23     constructor(config: { name: string; version: MetricVersions }, requestService: IMetricsRequestService) {
24         this.name = config.name;
25         this.version = config.version;
26         this.requestService = requestService;
28         if (!validateMetricName(this.name)) {
29             throw new Error(`Invalid metric name ${this.name}`);
30         }
31     }
33     protected addToRequestQueue(data: D) {
34         this.requestService.report({
35             Name: this.name,
36             Version: this.version,
37             Timestamp: Math.round(Date.now() / 1000),
38             Data: data,
39         });
40     }
43 export default Metric;