@breautek/storm
Version:
Object-Oriented REST API framework
89 lines (86 loc) • 3.23 kB
JavaScript
"use strict";
/*
Copyright 2017-2026 Norman Breau
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
Object.defineProperty(exports, "__esModule", { value: true });
exports.PrometheusServer = void 0;
const tslib_1 = require("tslib");
const http = tslib_1.__importStar(require("node:http"));
const MetricStore_1 = require("./MetricStore");
const TAG = 'PrometheusServer';
const RETRY_DELAY = 5000;
class PrometheusServer {
constructor(app) {
this.$app = app;
this.$socket = null;
this.$isClosing = false;
this.$retryTimer = null;
let config = app.getConfig();
this.$bind = config.prometheus?.bind || '127.0.0.1';
this.$port = config.prometheus?.port;
if (!this.$port) {
app.getLogger().warn(TAG, 'Using default port algorithm for Prometheus. Better to explicitly set a port via --prometheus-port.');
this.$port = app.getDefaultPortForPrometheus();
}
}
start() {
this.$app.getLogger().info(TAG, 'Initializing Prometheus');
void this.$createSocket();
}
$createSocket() {
if (this.$isClosing) {
return Promise.resolve();
}
return new Promise((resolve, reject) => {
this.$socket = http.createServer(async (req, res) => {
let data = await MetricStore_1.MetricStore.getInstance().getMetrics();
res.setHeader('Content-Type', data.type);
res.end(data.content);
});
this.$socket.once('error', (err) => {
this.$socket = null;
resolve();
if (this.$isClosing) {
return;
}
this.$app.getLogger().error(TAG, 'Prometheus Socket Error');
this.$app.getLogger().error(TAG, err);
this.$retryTimer = setTimeout(() => {
void this.$createSocket();
}, RETRY_DELAY);
});
this.$socket.listen(this.$port, this.$bind, null, () => {
this.$app.getLogger().info(TAG, `Prometheus Server bounded`);
resolve();
});
});
}
async close() {
this.$isClosing = true;
clearTimeout(this.$retryTimer);
return new Promise((resolve, reject) => {
if (!this.$socket) {
resolve();
return;
}
this.$socket.close((err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
}
exports.PrometheusServer = PrometheusServer;
//# sourceMappingURL=PrometheusServer.js.map