diff --git a/src/healthCheck.ts b/src/healthCheck.ts deleted file mode 100644 index 7ddbd5f..0000000 --- a/src/healthCheck.ts +++ /dev/null @@ -1,43 +0,0 @@ -import http from "node:http"; -import util from "node:util"; -import type Pulsar from "pulsar-client"; -import type { HealthCheckConfig } from "./types"; - -const createHealthCheckServer = ( - { port }: HealthCheckConfig, - producer: Pulsar.Producer, - hfpConsumer: Pulsar.Consumer, - partialApcConsumer: Pulsar.Consumer, -) => { - let isHealthSetToOk = false; - let server: http.Server | undefined = http.createServer((req, res) => { - if (req.url === "/healthz") { - if ( - isHealthSetToOk && - producer.isConnected() && - hfpConsumer.isConnected() && - partialApcConsumer.isConnected() - ) { - res.writeHead(204); - } else { - res.writeHead(500); - } - } else { - res.writeHead(404); - } - res.end(); - }); - server.listen(port); - const setHealth = (isOk: boolean) => { - isHealthSetToOk = isOk; - }; - const closeHealthCheckServer = async () => { - if (server && server.listening) { - await util.promisify(server.close.bind(server))(); - server = undefined; - } - }; - return { closeHealthCheckServer, setHealth }; -}; - -export default createHealthCheckServer; diff --git a/src/util/healthCheck.ts b/src/util/healthCheck.ts new file mode 100644 index 0000000..32a3453 --- /dev/null +++ b/src/util/healthCheck.ts @@ -0,0 +1,49 @@ +import http from "node:http"; +import util from "node:util"; +import type { + HealthCheckConfig, + HealthCheckServer, + HealthCheckStatus, + RuntimeResources, +} from "../types"; + +const isHealthy = ( + isHealthSetToOk: boolean, + resources: Partial, +) => + isHealthSetToOk && + resources.producer?.isConnected() && + resources.hfpConsumer?.isConnected() && + resources.partialApcConsumer?.isConnected(); + +const createHealthCheckServer = ( + { port }: HealthCheckConfig, + resources: Partial, +): HealthCheckServer => { + let isHealthSetToOk = false; + let server: http.Server | undefined = http.createServer((req, res) => { + if (req.url === "/healthz") { + if (isHealthy(isHealthSetToOk, resources)) { + res.writeHead(204); + } else { + res.writeHead(500); + } + } else { + res.writeHead(404); + } + res.end(); + }); + server.listen(port); + const setHealth = (status: HealthCheckStatus) => { + isHealthSetToOk = status === "ok"; + }; + const close = async (): Promise => { + if (server && server.listening) { + await util.promisify(server.close.bind(server))(); + server = undefined; + } + }; + return { close, setHealth }; +}; + +export default createHealthCheckServer;