Makes healthcheck data a server polling thing.
This commit is contained in:
65
src/lib/server/serviceDataPolling.ts
Normal file
65
src/lib/server/serviceDataPolling.ts
Normal 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);
|
||||
}
|
||||
Reference in New Issue
Block a user