// Copyright (c) Catgirl Enterprises - Licensed under MIT // Check LICENSE in repository root for more information. import { createServer, Server } from "http"; import IConfig from "./interfaces/IConfig"; import IMetric from "./interfaces/IMetric"; import FunkyArray from "funky-array"; export default class SimpleProm { static instance?:SimpleProm; public config:IConfig; public selfHostServer?:Server; private metrics:FunkyArray; private constructor(config:IConfig) { SimpleProm.instance?.end(); SimpleProm.instance = this; this.config = config; this.metrics = new FunkyArray(); if (this.config.selfHost) { this.config.selfHostPort = this.config.selfHostPort ?? 9100; this.selfHostServer = createServer(async (req, res) => { if (req.url?.startsWith("/metrics")) { return res.end(await this.getMetricText()); } res.end("SimpleProm exporter"); }); this.selfHostServer.listen(this.config.selfHostPort); } } static init(config:IConfig) { return new SimpleProm(config); } public addMetric(metric:IMetric) { return this.metrics.set(metric.name, metric); } public removeMetric(metric:IMetric) { this.metrics.remove(metric.name); } public async getMetricText() { let metricText = ""; await this.metrics.forEach(metric => metricText += metric); return metricText; } public end() { if (this.selfHostServer) { this.selfHostServer.close(); this.selfHostServer.closeAllConnections(); } } }