Compare commits

..

6 Commits

Author SHA1 Message Date
Elijah Duffy
805e7e6bbc node: configure publish 2025-12-24 18:49:20 -08:00
Elijah Duffy
ea3b90aca2 node: redesign readiness check system & improve event loop lag check 2025-12-24 18:47:03 -08:00
Elijah Duffy
a6d9d72322 node: add initial standard checks 2025-12-24 18:29:28 -08:00
Elijah Duffy
ae664da0e4 node: use performance.now for readiness duration 2025-12-24 18:29:19 -08:00
Elijah Duffy
d88c1c0c49 node: implement live & ready check helpers 2025-12-24 18:12:57 -08:00
Elijah Duffy
85b698d940 node: fix eslint, typescript, dev dependencies 2025-12-24 18:12:28 -08:00
10 changed files with 366 additions and 76 deletions

View File

@@ -1,17 +0,0 @@
module.exports = {
root: true,
env: {
node: true,
es2021: true,
},
parser: '@typescript-eslint/parser',
plugins: ['@typescript-eslint', 'prettier'],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
rules: {
'prettier/prettier': 'error',
},
};

View File

@@ -1,10 +0,0 @@
module.exports = {
root: true,
extends: ['../../.eslintrc.cjs'],
parserOptions: {
project: './tsconfig.json',
},
rules: {
// package-level overrides
},
};

View File

@@ -0,0 +1,14 @@
import js from '@eslint/js';
import globals from 'globals';
import tseslint from 'typescript-eslint';
import { defineConfig } from 'eslint/config';
export default defineConfig([
{
files: ['**/*.{js,mjs,cjs,ts,mts,cts}'],
plugins: { js },
extends: ['js/recommended'],
languageOptions: { globals: globals.browser },
},
tseslint.configs.recommended,
]);

View File

@@ -1,7 +1,14 @@
{
"name": "@health/node",
"repository": {
"type": "git",
"url": "https://gitea.auvem.com/end/health.git"
},
"publishConfig": {
"registry": "https://gitea.auvem.com/api/packages/end/npm/"
},
"version": "0.1.0",
"private": true,
"license": "MIT",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
@@ -14,6 +21,13 @@
"test": "echo \"No tests configured\" && exit 0",
"check": "npm run lint && npm run build"
},
"dependencies": {},
"devDependencies": {}
"devDependencies": {
"@eslint/js": "^9.39.2",
"@types/node": "^25.0.3",
"eslint": "^9.39.2",
"globals": "^16.5.0",
"jiti": "^2.6.1",
"typescript": "^5.9.3",
"typescript-eslint": "^8.50.1"
}
}

40
node-health/src/checks.ts Normal file
View File

@@ -0,0 +1,40 @@
import { monitorEventLoopDelay } from 'node:perf_hooks';
import { ReadinessCheck, ReadinessFunctionReturn, ReadinessStatus } from './readiness';
/**
* Builds a readiness check function that monitors event loop lag.
* @param options - Configuration options for the event loop lag check.
* @param options.degradedMs - Threshold in milliseconds for degraded status (default: 200).
* @param options.failMs - Threshold in milliseconds for error status (default: 1000).
* @param options.histResetMs - Interval in milliseconds to reset the histogram (default: 60000).
* @param options.percentile - Percentile to monitor (default: 50).
* @returns A ReadinessFunction that checks event loop lag.
*/
export const buildEventLoopLagCheck = (options: {
degradedMs?: number;
failMs?: number;
histResetMs?: number;
percentile?: number;
}): ReadinessCheck => {
const { degradedMs = 200, failMs = 1000, histResetMs = 60000, percentile = 50 } = options;
const hist = monitorEventLoopDelay({ resolution: 10 });
hist.enable();
setInterval(() => {
hist.reset();
}, histResetMs).unref();
return {
name: 'event-loop-lag',
fn: async (): Promise<ReadinessFunctionReturn> => {
const lag = hist.percentile(percentile) / 1e6; // Convert from nanoseconds to milliseconds
const status: ReadinessStatus = lag < degradedMs ? 'ok' : lag < failMs ? 'degraded' : 'error';
return {
status,
message: `Event loop lag is ${lag.toFixed(2)} ms`,
};
},
timeout: 500,
};
};

View File

@@ -1,30 +1,2 @@
/**
* Simple liveness & readiness helpers
*/
export type ReadinessResult = {
ok: boolean;
details: { name: string; ok: boolean; error?: string }[];
};
export function liveness() {
return {
status: 'ok',
timestamp: Date.now(),
};
}
export async function readiness(
checks: Array<{ name: string; fn: () => Promise<boolean> | boolean }>
): Promise<ReadinessResult> {
const results: ReadinessResult['details'] = [];
for (const c of checks) {
try {
const r = await Promise.resolve(c.fn());
results.push({ name: c.name, ok: !!r });
} catch (err: any) {
results.push({ name: c.name, ok: false, error: err?.message ?? String(err) });
}
}
return { ok: results.every((r) => r.ok), details: results };
}
export * from './liveness';
export * from './readiness';

View File

@@ -0,0 +1,31 @@
/**
* Type representing the result of a liveness check.
*/
export type LivenessResult = {
/** Status of the service (always 'ok'). */
status: 'ok';
/** Timestamp of the liveness check in milliseconds since the Unix epoch. */
timestamp: number;
};
/**
* Liveness check - indicates if the service is running.
* @returns A LivenessResult object.
*/
export function liveness() {
return {
status: 'ok',
timestamp: Date.now(),
} as LivenessResult;
}
/**
* Handler for liveness HTTP requests.
* @returns A Response object with LivenessResult in JSON format and status 200.
*/
export const handleLiveness = (): Response => {
return new Response(JSON.stringify(liveness()), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
};

View File

@@ -0,0 +1,251 @@
/** Return type of a readiness check function */
export type ReadinessFunctionReturn = {
/** Status of the readiness check */
status: ReadinessStatus;
/** Optional message providing additional information about the readiness check */
message?: string;
};
/** Function that performs a readiness check */
export type ReadinessFunction = (check: ReadinessCheck) => Promise<ReadinessFunctionReturn>;
/** Status of a readiness check */
export type ReadinessStatus = 'ok' | 'error' | 'degraded';
const aggregateStatus = (statuses: ReadinessStatus[]): ReadinessStatus => {
if (statuses.includes('error')) return 'error';
if (statuses.includes('degraded')) return 'degraded';
return 'ok';
};
/** Represents a readiness check with an optional timeout */
export type ReadinessCheck = {
/** Name of the readiness check */
name: string;
/** Function that performs the readiness check */
fn: ReadinessFunction;
/** Timeout in milliseconds for the readiness check (default: 5000) */
timeout?: number;
};
/** Result of a system readiness check */
export type ReadinessResult = {
/**
* Status of the system readiness check, aggregated as the worst status
* among individual checks. 'unknown' is a special case indicating that
* no checks were performed, used by ScheduledReadiness before the first run.
* */
status: ReadinessStatus | 'unknown';
/** Start time of the system readiness check in milliseconds since the Unix epoch */
start: number;
/** Duration of the system readiness check in milliseconds */
duration: number;
/** Details of individual readiness checks */
details: ReadinessDetail[];
};
/** Detail of an individual readiness check */
export type ReadinessDetail = {
/** Name of the readiness check */
name: string;
/** Status of the readiness check */
status: ReadinessStatus;
/** Duration of the readiness check in milliseconds */
duration: number;
/** Message providing additional information about the readiness check */
message?: string;
};
/**
* Performs a readiness check by executing the provided readiness functions.
* @param checks - An array of readiness functions to execute.
* @returns A Promise that resolves to a ReadinessResult object.
*/
export const readiness = async (checks: ReadinessCheck[]): Promise<ReadinessResult> => {
const start = Date.now();
const t0 = performance.now();
const details: ReadinessDetail[] = [];
for (const check of checks) {
const checkt0 = performance.now();
try {
const result = await withTimeout(
check.fn(check),
check.timeout ?? 5000,
`Readiness check '${check.name}' timed out after ${check.timeout ?? 5000} ms`,
);
details.push({
name: check.name,
status: result.status,
message: result.message,
duration: performance.now() - checkt0,
});
} catch (err) {
details.push({
name: check.name,
status: 'error',
message: err instanceof Error ? err.message : String(err),
duration: performance.now() - checkt0,
});
}
}
const duration = performance.now() - t0;
return {
status: aggregateStatus(details.map((d) => d.status)),
start,
duration,
details,
};
};
/**
* Creates a handler function for readiness HTTP requests. Warning: this runs all
* checks on each request and may be slow.
* @param checks - An array of readiness functions to execute.
* @returns A function that returns a Response object with ReadinessResult in JSON format.
*/
export const createReadinessHandler = (checks: ReadinessCheck[]): (() => Promise<Response>) => {
return async () => {
const result = await readiness(checks);
return respondWithResult(result);
};
};
/**
* Class that schedules periodic readiness checks.
*/
export class ScheduledReadiness {
private checks: ReadinessCheck[];
private interval: number;
private started: boolean = false;
private timer: NodeJS.Timeout | null = null;
private latestResult: ReadinessResult | null = null;
private nextResult: Promise<ReadinessResult> | null = null;
/**
* Creates an instance of ScheduledReadiness.
* @param checks - An array of readiness functions to execute.
* @param interval - Interval in milliseconds between readiness checks.
*/
constructor(checks: ReadinessCheck[], interval: number) {
this.checks = checks;
this.interval = interval;
}
/** Starts the scheduled readiness checks */
async start() {
if (this.started) return; // Already started
this.started = true;
const runCheck = async () => {
// Prevent concurrent runs
if (this.nextResult) return;
this.nextResult = readiness(this.checks);
try {
this.latestResult = await this.nextResult;
} finally {
this.nextResult = null;
}
};
await runCheck(); // Initial run
this.timer = setInterval(runCheck, this.interval);
}
/** Stops the scheduled readiness checks */
stop() {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
this.started = false;
}
/** Gets the next readiness result, waiting if a check is in progress */
async getNextResult(): Promise<ReadinessResult | null> {
if (this.nextResult) {
return await this.nextResult;
}
return this.latestResult;
}
/** Gets the latest readiness result without waiting */
getResult(): ReadinessResult | null {
return this.latestResult;
}
/**
* Sets the interval for readiness checks and restarts the timer if already started.
* @param ms - Interval in milliseconds.
*/
setInterval(ms: number) {
this.interval = ms;
if (this.timer) {
this.stop();
this.start();
}
}
/**
* Creates a handler function for readiness HTTP requests using the latest scheduled result.
* Scheduled handler always returns the most recent result, or 'unknown' if no checks have run yet.
* @returns A function that returns a Response object with ReadinessResult in JSON format.
*/
createHandler(): () => Promise<Response> {
return async () => {
const result = await this.getNextResult();
if (!result) {
return new Response(
JSON.stringify({
status: 'unknown',
start: Date.now(),
duration: 0,
details: [],
} as ReadinessResult),
{
status: httpStatusFromReadiness('unknown'),
headers: { 'Content-Type': 'application/json' },
},
);
}
return respondWithResult(result);
};
}
}
/** Returns a Response object with the given ReadinessResult in JSON format */
const respondWithResult = (result: ReadinessResult) => {
return new Response(JSON.stringify(result), {
status: httpStatusFromReadiness(result.status),
headers: { 'Content-Type': 'application/json' },
});
};
/** Returns the HTTP status code corresponding to a given readiness status */
const httpStatusFromReadiness = (status: ReadinessStatus | 'unknown'): number => {
if (status === 'ok') return 200;
if (status === 'degraded') return 200; // 206 could also be suitable, but let's avoid false alarms
if (status === 'error') return 503;
return 200; // unknown, treat as ok to avoid false alarms
};
const withTimeout = async <T>(
promise: Promise<T>,
ms: number,
timeoutMessage: string,
): Promise<T> => {
let timeoutHandle: NodeJS.Timeout;
const timeoutPromise = new Promise<never>((_, reject) => {
timeoutHandle = setTimeout(() => {
reject(new Error(timeoutMessage));
}, ms);
});
return Promise.race([promise, timeoutPromise]).finally(() => {
clearTimeout(timeoutHandle);
});
};

View File

@@ -1,6 +1,16 @@
{
"extends": "../tsconfig.base.json",
"compilerOptions": {
"lib": ["es2023"],
"target": "es2023",
"module": "node20",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"rootDir": "src",
"outDir": "dist",
"composite": false

View File

@@ -1,15 +0,0 @@
{
"compilerOptions": {
"target": "ES2021",
"module": "ES2020",
"moduleResolution": "node",
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true
}
}