Makes healthcheck data a server polling thing.

This commit is contained in:
2023-09-21 10:57:37 +02:00
parent e0be278630
commit 3311594f1e
7 changed files with 96 additions and 83 deletions

View File

@@ -0,0 +1,65 @@
import type { Config, ServiceConfig } from '$lib/config';
import type { AsyncServiceHandler, ServiceData, ServiceHandler } from '$lib/services/service';
import { getServiceHandler } from '$lib/services/services';
import { serverConfig } from './config';
export const serviceData: Array<Array<unknown>> = [];
function isPromise(p: any): boolean {
return typeof p === 'object' && typeof p.then === 'function';
}
async function pollGeneric(upstream: ServiceData, url: string): Promise<ServiceData> {
upstream.status = undefined;
return fetch(url).then((resp: Response): ServiceData => {
upstream.status = resp.ok ? 'online' : 'offline';
return upstream;
});
}
function wrapHandler(handler: ServiceHandler): AsyncServiceHandler {
return async (config: ServiceConfig): Promise<ServiceData> => {
const value = handler(config);
if (isPromise(value) === true) {
return (value as Promise<ServiceData>).then((data: ServiceData) => {
if (data.status != undefined) {
return data;
}
return pollGeneric(data, config.url);
});
}
return pollGeneric(value as ServiceData, config.url);
};
}
function pollServices() {
const config: Config = serverConfig();
for (const [i, group] of config.services.entries()) {
for (const [j, service] of group.items.entries()) {
const handler: ServiceHandler =
getServiceHandler(service.type || '') ||
(() => {
return {} as ServiceData;
});
wrapHandler(handler)(service).then((data: ServiceData) => {
serviceData[i][j] = data;
});
}
}
}
export function initializeServiceData() {
const config = serverConfig();
serviceData.length = config.services.length;
for (let i = 0; i < serviceData.length; i++) {
serviceData[i] = [];
}
}
export function initServicePolling() {
initializeServiceData();
pollServices();
setInterval(pollServices, 30000);
}