@autofleet/nitur 2.2.0-1 → 2.2.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/lib/alive-endpoint/middleware.cjs +1 -1
  2. package/lib/alive-endpoint/middleware.js +1 -1
  3. package/lib/fastify.cjs +1 -1
  4. package/lib/fastify.d.cts +1 -6
  5. package/lib/fastify.d.ts +1 -6
  6. package/lib/fastify.js +1 -1
  7. package/lib/health-manager/health-check-handlers.cjs +2 -0
  8. package/lib/health-manager/health-check-handlers.cjs.map +1 -0
  9. package/lib/health-manager/health-check-handlers.js +2 -0
  10. package/lib/health-manager/health-check-handlers.js.map +1 -0
  11. package/lib/health-manager/health-manager.cjs +2 -0
  12. package/lib/health-manager/health-manager.cjs.map +1 -0
  13. package/lib/health-manager/health-manager.d.cts +82 -0
  14. package/lib/health-manager/health-manager.d.ts +82 -0
  15. package/lib/health-manager/health-manager.js +2 -0
  16. package/lib/health-manager/health-manager.js.map +1 -0
  17. package/lib/health-manager/shutdown-handlers.cjs +2 -0
  18. package/lib/health-manager/shutdown-handlers.cjs.map +1 -0
  19. package/lib/health-manager/shutdown-handlers.js +2 -0
  20. package/lib/health-manager/shutdown-handlers.js.map +1 -0
  21. package/lib/health-manager/types.cjs +2 -0
  22. package/lib/health-manager/types.cjs.map +1 -0
  23. package/lib/health-manager/types.d.cts +110 -0
  24. package/lib/health-manager/types.d.ts +110 -0
  25. package/lib/health-manager/types.js +2 -0
  26. package/lib/health-manager/types.js.map +1 -0
  27. package/lib/index.cjs +1 -1
  28. package/lib/index.d.cts +3 -6
  29. package/lib/index.d.ts +3 -6
  30. package/lib/index.js +1 -1
  31. package/lib/utils.cjs +2 -0
  32. package/lib/utils.cjs.map +1 -0
  33. package/lib/utils.js +2 -0
  34. package/lib/utils.js.map +1 -0
  35. package/package.json +11 -14
  36. package/lib/health-check/checkers.cjs +0 -2
  37. package/lib/health-check/checkers.cjs.map +0 -1
  38. package/lib/health-check/checkers.d.cts +0 -44
  39. package/lib/health-check/checkers.d.ts +0 -44
  40. package/lib/health-check/checkers.js +0 -2
  41. package/lib/health-check/checkers.js.map +0 -1
  42. package/lib/health-check/express-adapter.cjs +0 -2
  43. package/lib/health-check/express-adapter.cjs.map +0 -1
  44. package/lib/health-check/express-adapter.d.cts +0 -23
  45. package/lib/health-check/express-adapter.d.ts +0 -23
  46. package/lib/health-check/express-adapter.js +0 -2
  47. package/lib/health-check/express-adapter.js.map +0 -1
  48. package/lib/health-check/fastify-adapter.cjs +0 -2
  49. package/lib/health-check/fastify-adapter.cjs.map +0 -1
  50. package/lib/health-check/fastify-adapter.d.cts +0 -28
  51. package/lib/health-check/fastify-adapter.d.ts +0 -28
  52. package/lib/health-check/fastify-adapter.js +0 -2
  53. package/lib/health-check/fastify-adapter.js.map +0 -1
  54. package/lib/health-check/index.cjs +0 -1
  55. package/lib/health-check/index.js +0 -1
  56. package/lib/health-check/manager.cjs +0 -2
  57. package/lib/health-check/manager.cjs.map +0 -1
  58. package/lib/health-check/manager.d.cts +0 -53
  59. package/lib/health-check/manager.d.ts +0 -53
  60. package/lib/health-check/manager.js +0 -2
  61. package/lib/health-check/manager.js.map +0 -1
  62. package/lib/health-check/setup.cjs +0 -2
  63. package/lib/health-check/setup.cjs.map +0 -1
  64. package/lib/health-check/setup.d.cts +0 -69
  65. package/lib/health-check/setup.d.ts +0 -69
  66. package/lib/health-check/setup.js +0 -2
  67. package/lib/health-check/setup.js.map +0 -1
  68. package/lib/health-check/types.d.cts +0 -157
  69. package/lib/health-check/types.d.ts +0 -157
@@ -1,2 +1,2 @@
1
- const e=require(`./base.cjs`),t=require(`../logger.cjs`);function n(n){let r=n.logger??t.logger;return async(t,i)=>{try{let t=await e.systemAliveCheck(n);return i.json(t),!0}catch(e){return i.status(500).json({err:e}),r.error(`Error on alive endpoint`,{err:e}),!1}}}exports.aliveEndpointMiddleware=n;
1
+ const e=require(`../logger.cjs`),t=require(`./base.cjs`);function n(n){let r=n.logger??e.logger;return async(e,i)=>{try{let e=await t.systemAliveCheck(n);return i.json(e),!0}catch(e){return i.status(500).json({err:e}),r.error(`Error on alive endpoint`,{err:e}),!1}}}exports.aliveEndpointMiddleware=n;
2
2
  //# sourceMappingURL=middleware.cjs.map
@@ -1,2 +1,2 @@
1
- import{systemAliveCheck as e}from"./base.js";import{logger as t}from"../logger.js";function n(n){let r=n.logger??t;return async(t,i)=>{try{let t=await e(n);return i.json(t),!0}catch(e){return i.status(500).json({err:e}),r.error(`Error on alive endpoint`,{err:e}),!1}}}export{n as aliveEndpointMiddleware};
1
+ import{logger as e}from"../logger.js";import{systemAliveCheck as t}from"./base.js";function n(n){let r=n.logger??e;return async(e,i)=>{try{let e=await t(n);return i.json(e),!0}catch(e){return i.status(500).json({err:e}),r.error(`Error on alive endpoint`,{err:e}),!1}}}export{n as aliveEndpointMiddleware};
2
2
  //# sourceMappingURL=middleware.js.map
package/lib/fastify.cjs CHANGED
@@ -1 +1 @@
1
- const e=require(`./alive-endpoint/base.cjs`),t=require(`./health-check/checkers.cjs`),n=require(`./health-check/manager.cjs`),r=require(`./health-check/setup.cjs`),i=require(`./health-check/fastify-adapter.cjs`);require(`./health-check/index.cjs`),exports.HealthCheckManager=n.HealthCheckManager,exports.createBasicHealthCheck=t.createBasicHealthCheck,exports.createElasticsearchHealthCheck=t.createElasticsearchHealthCheck,exports.createRabbitMQHealthCheck=t.createRabbitMQHealthCheck,exports.createRedisHealthChecks=t.createRedisHealthChecks,exports.createSequelizeHealthCheck=t.createSequelizeHealthCheck,exports.setupFastifyHealthCheck=i.setupFastifyHealthCheck,exports.setupHealthCheck=r.setupHealthCheck,exports.systemAliveCheck=e.systemAliveCheck,exports.withTimeout=t.withTimeout;
1
+ const e=require(`./alive-endpoint/base.cjs`);exports.systemAliveCheck=e.systemAliveCheck;
package/lib/fastify.d.cts CHANGED
@@ -1,7 +1,2 @@
1
1
  import { systemAliveCheck } from "./alive-endpoint/base.cjs";
2
- import { ElasticsearchClient, GracefulShutdownConfig, HealthCheck, HealthCheckResult, HealthStatus, LivenessConfig, NamedHealthCheck, NamedShutdownHook, RabbitMQClient, ReadinessConfig, RedisClient, ResourceCheckConfig, SequelizeClient, ShutdownHook } from "./health-check/types.cjs";
3
- import { HealthCheckManager } from "./health-check/manager.cjs";
4
- import { HealthCheckSetup, HealthCheckSetupConfig, setupHealthCheck } from "./health-check/setup.cjs";
5
- import { FastifyHealthCheckConfig, setupFastifyHealthCheck } from "./health-check/fastify-adapter.cjs";
6
- import { createBasicHealthCheck, createElasticsearchHealthCheck, createRabbitMQHealthCheck, createRedisHealthChecks, createSequelizeHealthCheck, withTimeout } from "./health-check/checkers.cjs";
7
- export { type ElasticsearchClient, type FastifyHealthCheckConfig, type GracefulShutdownConfig, type HealthCheck, HealthCheckManager, type HealthCheckResult, type HealthCheckSetup, type HealthCheckSetupConfig, type HealthStatus, type LivenessConfig, type NamedHealthCheck, type NamedShutdownHook, type RabbitMQClient, type ReadinessConfig, type RedisClient, type ResourceCheckConfig, type SequelizeClient, type ShutdownHook, createBasicHealthCheck, createElasticsearchHealthCheck, createRabbitMQHealthCheck, createRedisHealthChecks, createSequelizeHealthCheck, setupFastifyHealthCheck, setupHealthCheck, systemAliveCheck, withTimeout };
2
+ export { systemAliveCheck };
package/lib/fastify.d.ts CHANGED
@@ -1,7 +1,2 @@
1
1
  import { systemAliveCheck } from "./alive-endpoint/base.js";
2
- import { ElasticsearchClient, GracefulShutdownConfig, HealthCheck, HealthCheckResult, HealthStatus, LivenessConfig, NamedHealthCheck, NamedShutdownHook, RabbitMQClient, ReadinessConfig, RedisClient, ResourceCheckConfig, SequelizeClient, ShutdownHook } from "./health-check/types.js";
3
- import { HealthCheckManager } from "./health-check/manager.js";
4
- import { HealthCheckSetup, HealthCheckSetupConfig, setupHealthCheck } from "./health-check/setup.js";
5
- import { FastifyHealthCheckConfig, setupFastifyHealthCheck } from "./health-check/fastify-adapter.js";
6
- import { createBasicHealthCheck, createElasticsearchHealthCheck, createRabbitMQHealthCheck, createRedisHealthChecks, createSequelizeHealthCheck, withTimeout } from "./health-check/checkers.js";
7
- export { type ElasticsearchClient, type FastifyHealthCheckConfig, type GracefulShutdownConfig, type HealthCheck, HealthCheckManager, type HealthCheckResult, type HealthCheckSetup, type HealthCheckSetupConfig, type HealthStatus, type LivenessConfig, type NamedHealthCheck, type NamedShutdownHook, type RabbitMQClient, type ReadinessConfig, type RedisClient, type ResourceCheckConfig, type SequelizeClient, type ShutdownHook, createBasicHealthCheck, createElasticsearchHealthCheck, createRabbitMQHealthCheck, createRedisHealthChecks, createSequelizeHealthCheck, setupFastifyHealthCheck, setupHealthCheck, systemAliveCheck, withTimeout };
2
+ export { systemAliveCheck };
package/lib/fastify.js CHANGED
@@ -1 +1 @@
1
- import{systemAliveCheck as e}from"./alive-endpoint/base.js";import{createBasicHealthCheck as t,createElasticsearchHealthCheck as n,createRabbitMQHealthCheck as r,createRedisHealthChecks as i,createSequelizeHealthCheck as a,withTimeout as o}from"./health-check/checkers.js";import{HealthCheckManager as s}from"./health-check/manager.js";import{setupHealthCheck as c}from"./health-check/setup.js";import{setupFastifyHealthCheck as l}from"./health-check/fastify-adapter.js";import"./health-check/index.js";export{s as HealthCheckManager,t as createBasicHealthCheck,n as createElasticsearchHealthCheck,r as createRabbitMQHealthCheck,i as createRedisHealthChecks,a as createSequelizeHealthCheck,l as setupFastifyHealthCheck,c as setupHealthCheck,e as systemAliveCheck,o as withTimeout};
1
+ import{systemAliveCheck as e}from"./alive-endpoint/base.js";export{e as systemAliveCheck};
@@ -0,0 +1,2 @@
1
+ const e=require(`./types.cjs`),t={[e.CLIENT_TYPES.REDIS]:async({client:e,name:t})=>{try{await e.ping()}catch(e){throw Error(`Redis instance '${t}' ping failed: ${e instanceof Error?e.message:String(e)}`)}},[e.CLIENT_TYPES.SEQUELIZE]:async({client:e,name:t})=>{try{let[[t]]=await e.query(`SELECT 1 as status`);if(!t||t.status!==1)throw Error(`Unexpected query result`)}catch(e){throw Error(`Sequelize instance '${t}' health check failed: ${e instanceof Error?e.message:String(e)}`)}},[e.CLIENT_TYPES.ELASTIC_SEARCH]:async({client:e,name:t})=>{try{if(!await e.ping())throw Error(`Elasticsearch ping returned false`)}catch(e){throw Error(`Elasticsearch instance '${t}' health check failed: ${e instanceof Error?e.message:String(e)}`)}},[e.CLIENT_TYPES.RABBIT]:async({client:e,name:t})=>{try{if(!await e.isConnected())throw Error(`RabbitMQ is not connected`)}catch(e){throw Error(`RabbitMQ instance '${t}' health check failed: ${e instanceof Error?e.message:String(e)}`)}}};exports.DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP=t;
2
+ //# sourceMappingURL=health-check-handlers.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health-check-handlers.cjs","names":["DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP: Partial<Record<ClientType, (options: { client: any, name: string }) => any>>","CLIENT_TYPES"],"sources":["../../src/health-manager/health-check-handlers.ts"],"sourcesContent":["import type {\n RedisClient,\n SequelizeClient,\n ElasticsearchClient,\n RabbitMQClient,\n ClientType,\n} from './types';\nimport { CLIENT_TYPES } from './types';\n\nexport const DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP: Partial<Record<ClientType, (options: { client: any, name: string }) => any>> = {\n [CLIENT_TYPES.REDIS]: async ({ client, name }: { client: RedisClient, name: string }) => {\n try {\n await client.ping();\n } catch (error) {\n throw new Error(`Redis instance '${name}' ping failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n [CLIENT_TYPES.SEQUELIZE]: async ({ client, name }: { client: SequelizeClient, name: string }) => {\n try {\n const [[result]] = await client.query('SELECT 1 as status');\n if (!result || (result).status !== 1) {\n throw new Error('Unexpected query result');\n }\n } catch (error) {\n throw new Error(`Sequelize instance '${name}' health check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n [CLIENT_TYPES.ELASTIC_SEARCH]: async ({ client, name }: { client: ElasticsearchClient, name: string }) => {\n try {\n const isAlive = await client.ping();\n if (!isAlive) {\n throw new Error('Elasticsearch ping returned false');\n }\n } catch (error) {\n throw new Error(`Elasticsearch instance '${name}' health check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n [CLIENT_TYPES.RABBIT]: async ({ client, name }: { client: RabbitMQClient, name: string }) => {\n try {\n const isConnected = await client.isConnected();\n if (!isConnected) {\n throw new Error('RabbitMQ is not connected');\n }\n } catch (error) {\n throw new Error(`RabbitMQ instance '${name}' health check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n};"],"mappings":"+BASaA,EAAoH,EAC9HC,EAAAA,aAAa,OAAQ,MAAO,CAAE,SAAQ,UAAkD,CACvF,GAAI,CACF,MAAM,EAAO,MAAM,OACZ,EAAO,CACd,MAAU,MAAM,mBAAmB,EAAK,iBAAiB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,IAGrHA,EAAAA,aAAa,WAAY,MAAO,CAAE,SAAQ,UAAsD,CAC/F,GAAI,CACF,GAAM,CAAC,CAAC,IAAW,MAAM,EAAO,MAAM,qBAAqB,CAC3D,GAAI,CAAC,GAAW,EAAQ,SAAW,EACjC,MAAU,MAAM,0BAA0B,OAErC,EAAO,CACd,MAAU,MAAM,uBAAuB,EAAK,yBAAyB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,IAGjIA,EAAAA,aAAa,gBAAiB,MAAO,CAAE,SAAQ,UAA0D,CACxG,GAAI,CAEF,GAAI,CADY,MAAM,EAAO,MAAM,CAEjC,MAAU,MAAM,oCAAoC,OAE/C,EAAO,CACd,MAAU,MAAM,2BAA2B,EAAK,yBAAyB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,IAGrIA,EAAAA,aAAa,QAAS,MAAO,CAAE,SAAQ,UAAqD,CAC3F,GAAI,CAEF,GAAI,CADgB,MAAM,EAAO,aAAa,CAE5C,MAAU,MAAM,4BAA4B,OAEvC,EAAO,CACd,MAAU,MAAM,sBAAsB,EAAK,yBAAyB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,GAGlI"}
@@ -0,0 +1,2 @@
1
+ import{CLIENT_TYPES as e}from"./types.js";const t={[e.REDIS]:async({client:e,name:t})=>{try{await e.ping()}catch(e){throw Error(`Redis instance '${t}' ping failed: ${e instanceof Error?e.message:String(e)}`)}},[e.SEQUELIZE]:async({client:e,name:t})=>{try{let[[t]]=await e.query(`SELECT 1 as status`);if(!t||t.status!==1)throw Error(`Unexpected query result`)}catch(e){throw Error(`Sequelize instance '${t}' health check failed: ${e instanceof Error?e.message:String(e)}`)}},[e.ELASTIC_SEARCH]:async({client:e,name:t})=>{try{if(!await e.ping())throw Error(`Elasticsearch ping returned false`)}catch(e){throw Error(`Elasticsearch instance '${t}' health check failed: ${e instanceof Error?e.message:String(e)}`)}},[e.RABBIT]:async({client:e,name:t})=>{try{if(!await e.isConnected())throw Error(`RabbitMQ is not connected`)}catch(e){throw Error(`RabbitMQ instance '${t}' health check failed: ${e instanceof Error?e.message:String(e)}`)}}};export{t as DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP};
2
+ //# sourceMappingURL=health-check-handlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health-check-handlers.js","names":["DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP: Partial<Record<ClientType, (options: { client: any, name: string }) => any>>"],"sources":["../../src/health-manager/health-check-handlers.ts"],"sourcesContent":["import type {\n RedisClient,\n SequelizeClient,\n ElasticsearchClient,\n RabbitMQClient,\n ClientType,\n} from './types';\nimport { CLIENT_TYPES } from './types';\n\nexport const DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP: Partial<Record<ClientType, (options: { client: any, name: string }) => any>> = {\n [CLIENT_TYPES.REDIS]: async ({ client, name }: { client: RedisClient, name: string }) => {\n try {\n await client.ping();\n } catch (error) {\n throw new Error(`Redis instance '${name}' ping failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n [CLIENT_TYPES.SEQUELIZE]: async ({ client, name }: { client: SequelizeClient, name: string }) => {\n try {\n const [[result]] = await client.query('SELECT 1 as status');\n if (!result || (result).status !== 1) {\n throw new Error('Unexpected query result');\n }\n } catch (error) {\n throw new Error(`Sequelize instance '${name}' health check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n [CLIENT_TYPES.ELASTIC_SEARCH]: async ({ client, name }: { client: ElasticsearchClient, name: string }) => {\n try {\n const isAlive = await client.ping();\n if (!isAlive) {\n throw new Error('Elasticsearch ping returned false');\n }\n } catch (error) {\n throw new Error(`Elasticsearch instance '${name}' health check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n [CLIENT_TYPES.RABBIT]: async ({ client, name }: { client: RabbitMQClient, name: string }) => {\n try {\n const isConnected = await client.isConnected();\n if (!isConnected) {\n throw new Error('RabbitMQ is not connected');\n }\n } catch (error) {\n throw new Error(`RabbitMQ instance '${name}' health check failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n },\n};"],"mappings":"0CASA,MAAaA,EAAoH,EAC9H,EAAa,OAAQ,MAAO,CAAE,SAAQ,UAAkD,CACvF,GAAI,CACF,MAAM,EAAO,MAAM,OACZ,EAAO,CACd,MAAU,MAAM,mBAAmB,EAAK,iBAAiB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,IAGrH,EAAa,WAAY,MAAO,CAAE,SAAQ,UAAsD,CAC/F,GAAI,CACF,GAAM,CAAC,CAAC,IAAW,MAAM,EAAO,MAAM,qBAAqB,CAC3D,GAAI,CAAC,GAAW,EAAQ,SAAW,EACjC,MAAU,MAAM,0BAA0B,OAErC,EAAO,CACd,MAAU,MAAM,uBAAuB,EAAK,yBAAyB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,IAGjI,EAAa,gBAAiB,MAAO,CAAE,SAAQ,UAA0D,CACxG,GAAI,CAEF,GAAI,CADY,MAAM,EAAO,MAAM,CAEjC,MAAU,MAAM,oCAAoC,OAE/C,EAAO,CACd,MAAU,MAAM,2BAA2B,EAAK,yBAAyB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,IAGrI,EAAa,QAAS,MAAO,CAAE,SAAQ,UAAqD,CAC3F,GAAI,CAEF,GAAI,CADgB,MAAM,EAAO,aAAa,CAE5C,MAAU,MAAM,4BAA4B,OAEvC,EAAO,CACd,MAAU,MAAM,sBAAsB,EAAK,yBAAyB,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,GAGlI"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`./health-check-handlers.cjs`),n=require(`./shutdown-handlers.cjs`),r=require(`../utils.cjs`);let i=require(`node:timers/promises`),a=require(`@autofleet/errors`);var o=class{constructor(e){this.DEFAULT_CLIENT_OPTIONS={includeInLivenessCheck:!0,includeInReadinessCheck:!0},this.DEFAULT_SERVER_OPTIONS={runDefaultShutdownHandler:!0,name:`server`},this.DEFAULT_CONFIG={shutdownDelayMs:5e3,useExit0:!0,shouldSetupSignalHandlers:!0,livenessPeriodMs:1e4,readinessPeriodMs:5e3,enableLivenessOptimization:!0},this.isShuttingDown=!1,this.isReady=!1,this.livenessOptimizationEnabled=!1,this.clientsMap=new Map,this.livenessChecks=[],this.readinessChecks=[],this.config={...this.DEFAULT_CONFIG,...e.config??{}},this.logger=e.logger,e.server&&this.attachServer(e.server),this.storeClientsWithDefaults(e),this.initializeHealthChecks(),this.config.shouldSetupSignalHandlers&&this.setupSignalHandlers()}storeClientsWithDefaults(e){let r=e.clients;r&&Object.entries(r).forEach(([e,r])=>{if(!r)return;let i=(Array.isArray(r)?r:[r]).map(r=>{let i={...this.DEFAULT_CLIENT_OPTIONS,name:e,...r.options},a=t.DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP[e],o=r.healthCheck??(a?()=>a({client:r.connection,name:i.name}):void 0),s=n.DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP[e],c=r.shutdown??(s?e=>s({client:r.connection,signal:e,name:i.name}):void 0);return{connection:r.connection,healthCheck:o,shutdown:c,options:i}});this.clientsMap.set(e,i)})}setupSignalHandlers(){this.logger.info(`Setting up global signal listeners for graceful shutdown`),process.on(`SIGTERM`,async()=>{await this.shutdown(`SIGTERM`)}),process.on(`SIGINT`,async()=>{await this.shutdown(`SIGINT`)})}initializeHealthChecks(){let e=!0;this.clientsMap.forEach(t=>{t.forEach(t=>{if(!t.healthCheck)return;let n=t.options?.includeInLivenessCheck??!0,r=t.options?.includeInReadinessCheck??!0;(!n||!r)&&(e=!1),n&&this.livenessChecks.push(t.healthCheck),r&&this.readinessChecks.push(t.healthCheck)})}),this.livenessOptimizationEnabled=(this.config.enableLivenessOptimization??!0)&&e,this.livenessOptimizationEnabled&&this.logger.info(`Liveness check optimization enabled - liveness checks will be skipped when pod is ready`)}attachServer(e){this.server={server:e.server,shutdown:e.shutdown??(async()=>n.defaultServerShutdownHandler(e.server)),options:{...this.DEFAULT_SERVER_OPTIONS,...e.options??{}}}}async aliveCheck(){if(this.isShuttingDown||this.livenessOptimizationEnabled&&this.isReady)return{statusCode:200,status:`ok`};try{let e=Promise.all(this.livenessChecks.map(e=>e()));return await Promise.race([e,r.timeoutPromise(this.config.livenessPeriodMs??1e4,`Liveness check timed out`)]),{statusCode:200,status:`ok`}}catch(e){throw new a.ServiceUnavailableError(e instanceof Error?e.message:String(e))}}async readyCheck(){if(this.isShuttingDown)throw this.isReady=!1,new a.ServiceUnavailableError(`Application is shutting down`);try{let e=Promise.all(this.readinessChecks.map(e=>e()));return await Promise.race([e,r.timeoutPromise(this.config.readinessPeriodMs??5e3,`Readiness check timed out`)]),this.isReady=!0,{statusCode:200,status:`ok`}}catch(e){throw this.isReady=!1,new a.ServiceUnavailableError(e instanceof Error?e.message:String(e))}}async shutdown(e=`MANUAL`){if(this.isShuttingDown){this.logger.warn(`Shutdown already in progress`);return}let{shutdownDelayMs:t,useExit0:n,onShutdown:r,beforeShutdown:a}=this.config;this.isShuttingDown=!0,this.isReady=!1,this.logger.info(`${e} received: setting readiness state to false`),await a?.(),this.logger.info(`Waiting ${t}ms before shutdown...`),await(0,i.setTimeout)(t),this.logger.info(`Executing shutdown hooks...`);let o=[];this.clientsMap.forEach(e=>{e.forEach(e=>{e.shutdown&&o.push(e.shutdown())})}),await Promise.allSettled(o),await r?.(),this.server?.options?.runDefaultShutdownHandler&&(this.logger.info(`Shutting down server...`),await this.server?.shutdown?.()),this.logger.info(`Shutdown process completed`),n&&(this.logger.info(`Exiting process after ${e}`),process.exit(0))}};exports.HealthManager=o;
2
+ //# sourceMappingURL=health-manager.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health-manager.cjs","names":["client","DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP","DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP","defaultServerShutdownHandler","timeoutPromise","ServiceUnavailableError","shutdownPromises: Promise<any>[]"],"sources":["../../src/health-manager/health-manager.ts"],"sourcesContent":["import { setTimeout } from 'node:timers/promises';\nimport { ServiceUnavailableError } from '@autofleet/errors';\nimport type {\n ClientConfig,\n HealthManagerConfig,\n HealthManagerOptions,\n ClientType,\n ServerConfig,\n} from './types';\nimport { DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP } from './health-check-handlers';\nimport { DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP, defaultServerShutdownHandler } from './shutdown-handlers';\nimport { timeoutPromise } from '../utils';\n\n/**\n * Manages application health state and graceful shutdown for Kubernetes liveness/readiness probes\n *\n * Features:\n * - Provides /alive (liveness) and /ready (readiness) endpoint handlers\n * - Auto-registers SIGTERM/SIGINT handlers for graceful shutdown\n * - Manages ready state during shutdown to fail readiness probes\n */\nexport class HealthManager {\n private readonly DEFAULT_CLIENT_OPTIONS = {\n includeInLivenessCheck: true,\n includeInReadinessCheck: true,\n };\n\n private readonly DEFAULT_SERVER_OPTIONS = {\n runDefaultShutdownHandler: true,\n name: 'server',\n };\n\n private readonly DEFAULT_CONFIG: HealthManagerConfig = {\n shutdownDelayMs: 5_000,\n useExit0: true,\n shouldSetupSignalHandlers: true,\n livenessPeriodMs: 10_000,\n readinessPeriodMs: 5_000,\n enableLivenessOptimization: true,\n };\n\n private isShuttingDown: boolean = false;\n private isReady: boolean = false;\n private livenessOptimizationEnabled: boolean = false;\n\n private config: HealthManagerConfig;\n\n private clientsMap: Map<string, ClientConfig<any>[]> = new Map();\n private server: Required<ServerConfig> | undefined;\n\n private livenessChecks: Array<() => Promise<void>> = [];\n private readinessChecks: Array<() => Promise<void>> = [];\n\n private logger: any;\n\n /**\n * Creates a new HealthManager instance\n *\n * @param params Configuration options for health checks and shutdown behavior\n */\n constructor(params: HealthManagerOptions) {\n this.config = {\n ...this.DEFAULT_CONFIG,\n ...(params.config ?? {}),\n };\n\n this.logger = params.logger;\n if (params.server) {\n this.attachServer(params.server);\n }\n\n this.storeClientsWithDefaults(params);\n\n this.initializeHealthChecks();\n\n if (this.config.shouldSetupSignalHandlers) {\n this.setupSignalHandlers();\n }\n }\n\n /**\n * Store clients with default health check and shutdown functions\n * @private\n */\n private storeClientsWithDefaults(params: HealthManagerOptions): void {\n const clients = params.clients;\n if (!clients) {\n return;\n }\n\n Object.entries(clients).forEach(([type, client]) => {\n if (!client) {\n return;\n }\n\n const clientsArray = Array.isArray(client) ? client : [client];\n\n // Apply default values to each client config\n const clientsWithDefaults = clientsArray.map((client) => {\n const options = {\n ...this.DEFAULT_CLIENT_OPTIONS,\n name: type,\n ...client.options,\n };\n\n const defaultHealthCheck = DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP[type as ClientType];\n const healthCheck = client.healthCheck ?? (defaultHealthCheck ? () => defaultHealthCheck({ client: client.connection, name: options.name }) : undefined);\n\n const defaultShutdown = DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP[type as ClientType];\n const shutdown = client.shutdown ?? (defaultShutdown ? (signal?: string) => defaultShutdown({ client: client.connection, signal, name: options.name }) : undefined);\n\n return {\n connection: client.connection,\n healthCheck,\n shutdown,\n options,\n };\n });\n\n this.clientsMap.set(type, clientsWithDefaults);\n });\n }\n\n /**\n * Register SIGTERM and SIGINT listeners handlers\n * @private\n */\n private setupSignalHandlers(): void {\n this.logger.info('Setting up global signal listeners for graceful shutdown');\n\n process.on('SIGTERM', async () => {\n await this.shutdown('SIGTERM');\n });\n\n process.on('SIGINT', async () => {\n await this.shutdown('SIGINT');\n });\n }\n\n /**\n * Initialize health check arrays based on configured clients\n * @private\n */\n private initializeHealthChecks(): void {\n let allClientsInBothChecks = true;\n\n this.clientsMap.forEach((clients) => {\n clients.forEach((client) => {\n if (!client.healthCheck) {\n return;\n }\n\n const includeInLiveness = client.options?.includeInLivenessCheck ?? true;\n const includeInReadiness = client.options?.includeInReadinessCheck ?? true;\n\n // Check if all clients are included in both checks\n if (!includeInLiveness || !includeInReadiness) {\n allClientsInBothChecks = false;\n }\n\n if (includeInLiveness) {\n this.livenessChecks.push(client.healthCheck);\n }\n\n if (includeInReadiness) {\n this.readinessChecks.push(client.healthCheck);\n }\n });\n });\n\n // Enable optimization if configured and all clients are in both checks\n this.livenessOptimizationEnabled =\n (this.config.enableLivenessOptimization ?? true) &&\n allClientsInBothChecks;\n\n if (this.livenessOptimizationEnabled) {\n this.logger.info('Liveness check optimization enabled - liveness checks will be skipped when pod is ready');\n }\n }\n\n /**\n * Attach an HTTP or HTTPS server to be managed during shutdown\n * @param serverConfig \n */\n attachServer(serverConfig: ServerConfig): void {\n this.server = {\n server: serverConfig.server,\n shutdown: serverConfig.shutdown ?? (async () => defaultServerShutdownHandler(serverConfig.server)),\n options: {\n ...this.DEFAULT_SERVER_OPTIONS,\n ...(serverConfig.options ?? {}),\n },\n };\n }\n\n /**\n * Performs health checks for all configured clients\n *\n * @returns Promise that resolves to { status: 'ok' } on success\n * @throws Error with statusCode 503 if any health check fails\n */\n async aliveCheck(): Promise<{ status: string, statusCode: number }> {\n if (this.isShuttingDown) {\n return { statusCode: 200, status: 'ok' };\n }\n\n // Skip liveness check if optimization is enabled and pod is already ready\n if (this.livenessOptimizationEnabled && this.isReady) {\n return { statusCode: 200, status: 'ok' };\n }\n\n try {\n const livenessPromises = Promise.all(this.livenessChecks.map(check => check()));\n\n await Promise.race([\n livenessPromises,\n timeoutPromise(this.config.livenessPeriodMs ?? 10_000, 'Liveness check timed out'),\n ]);\n\n return { statusCode: 200, status: 'ok' };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ServiceUnavailableError(message);\n }\n }\n\n /**\n * Performs readiness check\n *\n * @returns Promise that resolves to { status: 'ok' } if ready\n * @throws Error with statusCode 503 if not ready or health check fails\n */\n async readyCheck(): Promise<{ status: string, statusCode: number }> {\n if (this.isShuttingDown) {\n this.isReady = false;\n throw new ServiceUnavailableError('Application is shutting down');\n }\n\n try {\n const readinessPromises = Promise.all(this.readinessChecks.map(check => check()));\n\n await Promise.race([\n readinessPromises,\n timeoutPromise(this.config.readinessPeriodMs ?? 5_000, 'Readiness check timed out'),\n ]);\n this.isReady = true;\n\n return { statusCode: 200, status: 'ok' };\n } catch (error) {\n this.isReady = false;\n const message = error instanceof Error ? error.message : String(error);\n throw new ServiceUnavailableError(message);\n }\n }\n\n /**\n * Manually trigger graceful shutdown\n * Can be called manually or via signal handlers\n *\n * @param signal - Signal name (e.g., 'SIGTERM', 'SIGINT', 'MANUAL')\n */\n async shutdown(signal: string = 'MANUAL'): Promise<void> {\n if (this.isShuttingDown) {\n this.logger.warn('Shutdown already in progress');\n return;\n }\n\n const { shutdownDelayMs, useExit0, onShutdown, beforeShutdown } = this.config;\n\n this.isShuttingDown = true;\n this.isReady = false;\n\n this.logger.info(`${signal} received: setting readiness state to false`);\n\n await beforeShutdown?.();\n\n this.logger.info(`Waiting ${shutdownDelayMs}ms before shutdown...`);\n await setTimeout(shutdownDelayMs)\n\n this.logger.info('Executing shutdown hooks...');\n\n const shutdownPromises: Promise<any>[] = [];\n this.clientsMap.forEach((clients) => {\n clients.forEach((client) => {\n if (client.shutdown) {\n shutdownPromises.push(client.shutdown());\n }\n });\n });\n\n await Promise.allSettled(shutdownPromises);\n\n await onShutdown?.();\n\n if (this.server?.options?.runDefaultShutdownHandler) {\n this.logger.info('Shutting down server...');\n await this.server?.shutdown?.();\n }\n\n this.logger.info('Shutdown process completed');\n\n if (useExit0) {\n this.logger.info(`Exiting process after ${signal}`);\n process.exit(0);\n }\n }\n}"],"mappings":"iOAqBA,IAAa,EAAb,KAA2B,CAuCzB,YAAY,EAA8B,6BAtCA,CACxC,uBAAwB,GACxB,wBAAyB,GAC1B,6BAEyC,CACxC,0BAA2B,GAC3B,KAAM,SACP,qBAEsD,CACrD,gBAAiB,IACjB,SAAU,GACV,0BAA2B,GAC3B,iBAAkB,IAClB,kBAAmB,IACnB,2BAA4B,GAC7B,qBAEiC,gBACP,oCACoB,mBAIQ,IAAI,wBAGN,EAAE,sBACD,EAAE,CAUtD,KAAK,OAAS,CACZ,GAAG,KAAK,eACR,GAAI,EAAO,QAAU,EAAE,CACxB,CAED,KAAK,OAAS,EAAO,OACjB,EAAO,QACT,KAAK,aAAa,EAAO,OAAO,CAGlC,KAAK,yBAAyB,EAAO,CAErC,KAAK,wBAAwB,CAEzB,KAAK,OAAO,2BACd,KAAK,qBAAqB,CAQ9B,yBAAiC,EAAoC,CACnE,IAAM,EAAU,EAAO,QAClB,GAIL,OAAO,QAAQ,EAAQ,CAAC,SAAS,CAAC,EAAM,KAAY,CAClD,GAAI,CAAC,EACH,OAMF,IAAM,GAHe,MAAM,QAAQ,EAAO,CAAG,EAAS,CAAC,EAAO,EAGrB,IAAK,GAAW,CACvD,IAAM,EAAU,CACd,GAAG,KAAK,uBACR,KAAM,EACN,GAAGA,EAAO,QACX,CAEK,EAAqBC,EAAAA,oCAAoC,GACzD,EAAcD,EAAO,cAAgB,MAA2B,EAAmB,CAAE,OAAQA,EAAO,WAAY,KAAM,EAAQ,KAAM,CAAC,CAAG,IAAA,IAExI,EAAkBE,EAAAA,qCAAqC,GACvD,EAAWF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K,QAAQ,SAAS,4BACxB,KAAK,OAAO,KAAK,0BAA0B,CAC3C,MAAM,KAAK,QAAQ,YAAY,EAGjC,KAAK,OAAO,KAAK,6BAA6B,CAE1C,IACF,KAAK,OAAO,KAAK,yBAAyB,IAAS,CACnD,QAAQ,KAAK,EAAE"}
@@ -0,0 +1,82 @@
1
+ import { HealthManagerOptions, ServerConfig } from "./types.cjs";
2
+
3
+ //#region src/health-manager/health-manager.d.ts
4
+
5
+ /**
6
+ * Manages application health state and graceful shutdown for Kubernetes liveness/readiness probes
7
+ *
8
+ * Features:
9
+ * - Provides /alive (liveness) and /ready (readiness) endpoint handlers
10
+ * - Auto-registers SIGTERM/SIGINT handlers for graceful shutdown
11
+ * - Manages ready state during shutdown to fail readiness probes
12
+ */
13
+ declare class HealthManager {
14
+ private readonly DEFAULT_CLIENT_OPTIONS;
15
+ private readonly DEFAULT_SERVER_OPTIONS;
16
+ private readonly DEFAULT_CONFIG;
17
+ private isShuttingDown;
18
+ private isReady;
19
+ private livenessOptimizationEnabled;
20
+ private config;
21
+ private clientsMap;
22
+ private server;
23
+ private livenessChecks;
24
+ private readinessChecks;
25
+ private logger;
26
+ /**
27
+ * Creates a new HealthManager instance
28
+ *
29
+ * @param params Configuration options for health checks and shutdown behavior
30
+ */
31
+ constructor(params: HealthManagerOptions);
32
+ /**
33
+ * Store clients with default health check and shutdown functions
34
+ * @private
35
+ */
36
+ private storeClientsWithDefaults;
37
+ /**
38
+ * Register SIGTERM and SIGINT listeners handlers
39
+ * @private
40
+ */
41
+ private setupSignalHandlers;
42
+ /**
43
+ * Initialize health check arrays based on configured clients
44
+ * @private
45
+ */
46
+ private initializeHealthChecks;
47
+ /**
48
+ * Attach an HTTP or HTTPS server to be managed during shutdown
49
+ * @param serverConfig
50
+ */
51
+ attachServer(serverConfig: ServerConfig): void;
52
+ /**
53
+ * Performs health checks for all configured clients
54
+ *
55
+ * @returns Promise that resolves to { status: 'ok' } on success
56
+ * @throws Error with statusCode 503 if any health check fails
57
+ */
58
+ aliveCheck(): Promise<{
59
+ status: string;
60
+ statusCode: number;
61
+ }>;
62
+ /**
63
+ * Performs readiness check
64
+ *
65
+ * @returns Promise that resolves to { status: 'ok' } if ready
66
+ * @throws Error with statusCode 503 if not ready or health check fails
67
+ */
68
+ readyCheck(): Promise<{
69
+ status: string;
70
+ statusCode: number;
71
+ }>;
72
+ /**
73
+ * Manually trigger graceful shutdown
74
+ * Can be called manually or via signal handlers
75
+ *
76
+ * @param signal - Signal name (e.g., 'SIGTERM', 'SIGINT', 'MANUAL')
77
+ */
78
+ shutdown(signal?: string): Promise<void>;
79
+ }
80
+ //#endregion
81
+ export { HealthManager };
82
+ //# sourceMappingURL=health-manager.d.cts.map
@@ -0,0 +1,82 @@
1
+ import { HealthManagerOptions, ServerConfig } from "./types.js";
2
+
3
+ //#region src/health-manager/health-manager.d.ts
4
+
5
+ /**
6
+ * Manages application health state and graceful shutdown for Kubernetes liveness/readiness probes
7
+ *
8
+ * Features:
9
+ * - Provides /alive (liveness) and /ready (readiness) endpoint handlers
10
+ * - Auto-registers SIGTERM/SIGINT handlers for graceful shutdown
11
+ * - Manages ready state during shutdown to fail readiness probes
12
+ */
13
+ declare class HealthManager {
14
+ private readonly DEFAULT_CLIENT_OPTIONS;
15
+ private readonly DEFAULT_SERVER_OPTIONS;
16
+ private readonly DEFAULT_CONFIG;
17
+ private isShuttingDown;
18
+ private isReady;
19
+ private livenessOptimizationEnabled;
20
+ private config;
21
+ private clientsMap;
22
+ private server;
23
+ private livenessChecks;
24
+ private readinessChecks;
25
+ private logger;
26
+ /**
27
+ * Creates a new HealthManager instance
28
+ *
29
+ * @param params Configuration options for health checks and shutdown behavior
30
+ */
31
+ constructor(params: HealthManagerOptions);
32
+ /**
33
+ * Store clients with default health check and shutdown functions
34
+ * @private
35
+ */
36
+ private storeClientsWithDefaults;
37
+ /**
38
+ * Register SIGTERM and SIGINT listeners handlers
39
+ * @private
40
+ */
41
+ private setupSignalHandlers;
42
+ /**
43
+ * Initialize health check arrays based on configured clients
44
+ * @private
45
+ */
46
+ private initializeHealthChecks;
47
+ /**
48
+ * Attach an HTTP or HTTPS server to be managed during shutdown
49
+ * @param serverConfig
50
+ */
51
+ attachServer(serverConfig: ServerConfig): void;
52
+ /**
53
+ * Performs health checks for all configured clients
54
+ *
55
+ * @returns Promise that resolves to { status: 'ok' } on success
56
+ * @throws Error with statusCode 503 if any health check fails
57
+ */
58
+ aliveCheck(): Promise<{
59
+ status: string;
60
+ statusCode: number;
61
+ }>;
62
+ /**
63
+ * Performs readiness check
64
+ *
65
+ * @returns Promise that resolves to { status: 'ok' } if ready
66
+ * @throws Error with statusCode 503 if not ready or health check fails
67
+ */
68
+ readyCheck(): Promise<{
69
+ status: string;
70
+ statusCode: number;
71
+ }>;
72
+ /**
73
+ * Manually trigger graceful shutdown
74
+ * Can be called manually or via signal handlers
75
+ *
76
+ * @param signal - Signal name (e.g., 'SIGTERM', 'SIGINT', 'MANUAL')
77
+ */
78
+ shutdown(signal?: string): Promise<void>;
79
+ }
80
+ //#endregion
81
+ export { HealthManager };
82
+ //# sourceMappingURL=health-manager.d.ts.map
@@ -0,0 +1,2 @@
1
+ import{DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP as e}from"./health-check-handlers.js";import{DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP as t,defaultServerShutdownHandler as n}from"./shutdown-handlers.js";import{timeoutPromise as r}from"../utils.js";import{setTimeout as i}from"node:timers/promises";import{ServiceUnavailableError as a}from"@autofleet/errors";var o=class{constructor(e){this.DEFAULT_CLIENT_OPTIONS={includeInLivenessCheck:!0,includeInReadinessCheck:!0},this.DEFAULT_SERVER_OPTIONS={runDefaultShutdownHandler:!0,name:`server`},this.DEFAULT_CONFIG={shutdownDelayMs:5e3,useExit0:!0,shouldSetupSignalHandlers:!0,livenessPeriodMs:1e4,readinessPeriodMs:5e3,enableLivenessOptimization:!0},this.isShuttingDown=!1,this.isReady=!1,this.livenessOptimizationEnabled=!1,this.clientsMap=new Map,this.livenessChecks=[],this.readinessChecks=[],this.config={...this.DEFAULT_CONFIG,...e.config??{}},this.logger=e.logger,e.server&&this.attachServer(e.server),this.storeClientsWithDefaults(e),this.initializeHealthChecks(),this.config.shouldSetupSignalHandlers&&this.setupSignalHandlers()}storeClientsWithDefaults(n){let r=n.clients;r&&Object.entries(r).forEach(([n,r])=>{if(!r)return;let i=(Array.isArray(r)?r:[r]).map(r=>{let i={...this.DEFAULT_CLIENT_OPTIONS,name:n,...r.options},a=e[n],o=r.healthCheck??(a?()=>a({client:r.connection,name:i.name}):void 0),s=t[n],c=r.shutdown??(s?e=>s({client:r.connection,signal:e,name:i.name}):void 0);return{connection:r.connection,healthCheck:o,shutdown:c,options:i}});this.clientsMap.set(n,i)})}setupSignalHandlers(){this.logger.info(`Setting up global signal listeners for graceful shutdown`),process.on(`SIGTERM`,async()=>{await this.shutdown(`SIGTERM`)}),process.on(`SIGINT`,async()=>{await this.shutdown(`SIGINT`)})}initializeHealthChecks(){let e=!0;this.clientsMap.forEach(t=>{t.forEach(t=>{if(!t.healthCheck)return;let n=t.options?.includeInLivenessCheck??!0,r=t.options?.includeInReadinessCheck??!0;(!n||!r)&&(e=!1),n&&this.livenessChecks.push(t.healthCheck),r&&this.readinessChecks.push(t.healthCheck)})}),this.livenessOptimizationEnabled=(this.config.enableLivenessOptimization??!0)&&e,this.livenessOptimizationEnabled&&this.logger.info(`Liveness check optimization enabled - liveness checks will be skipped when pod is ready`)}attachServer(e){this.server={server:e.server,shutdown:e.shutdown??(async()=>n(e.server)),options:{...this.DEFAULT_SERVER_OPTIONS,...e.options??{}}}}async aliveCheck(){if(this.isShuttingDown||this.livenessOptimizationEnabled&&this.isReady)return{statusCode:200,status:`ok`};try{let e=Promise.all(this.livenessChecks.map(e=>e()));return await Promise.race([e,r(this.config.livenessPeriodMs??1e4,`Liveness check timed out`)]),{statusCode:200,status:`ok`}}catch(e){throw new a(e instanceof Error?e.message:String(e))}}async readyCheck(){if(this.isShuttingDown)throw this.isReady=!1,new a(`Application is shutting down`);try{let e=Promise.all(this.readinessChecks.map(e=>e()));return await Promise.race([e,r(this.config.readinessPeriodMs??5e3,`Readiness check timed out`)]),this.isReady=!0,{statusCode:200,status:`ok`}}catch(e){throw this.isReady=!1,new a(e instanceof Error?e.message:String(e))}}async shutdown(e=`MANUAL`){if(this.isShuttingDown){this.logger.warn(`Shutdown already in progress`);return}let{shutdownDelayMs:t,useExit0:n,onShutdown:r,beforeShutdown:a}=this.config;this.isShuttingDown=!0,this.isReady=!1,this.logger.info(`${e} received: setting readiness state to false`),await a?.(),this.logger.info(`Waiting ${t}ms before shutdown...`),await i(t),this.logger.info(`Executing shutdown hooks...`);let o=[];this.clientsMap.forEach(e=>{e.forEach(e=>{e.shutdown&&o.push(e.shutdown())})}),await Promise.allSettled(o),await r?.(),this.server?.options?.runDefaultShutdownHandler&&(this.logger.info(`Shutting down server...`),await this.server?.shutdown?.()),this.logger.info(`Shutdown process completed`),n&&(this.logger.info(`Exiting process after ${e}`),process.exit(0))}};export{o as HealthManager};
2
+ //# sourceMappingURL=health-manager.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"health-manager.js","names":["client","shutdownPromises: Promise<any>[]"],"sources":["../../src/health-manager/health-manager.ts"],"sourcesContent":["import { setTimeout } from 'node:timers/promises';\nimport { ServiceUnavailableError } from '@autofleet/errors';\nimport type {\n ClientConfig,\n HealthManagerConfig,\n HealthManagerOptions,\n ClientType,\n ServerConfig,\n} from './types';\nimport { DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP } from './health-check-handlers';\nimport { DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP, defaultServerShutdownHandler } from './shutdown-handlers';\nimport { timeoutPromise } from '../utils';\n\n/**\n * Manages application health state and graceful shutdown for Kubernetes liveness/readiness probes\n *\n * Features:\n * - Provides /alive (liveness) and /ready (readiness) endpoint handlers\n * - Auto-registers SIGTERM/SIGINT handlers for graceful shutdown\n * - Manages ready state during shutdown to fail readiness probes\n */\nexport class HealthManager {\n private readonly DEFAULT_CLIENT_OPTIONS = {\n includeInLivenessCheck: true,\n includeInReadinessCheck: true,\n };\n\n private readonly DEFAULT_SERVER_OPTIONS = {\n runDefaultShutdownHandler: true,\n name: 'server',\n };\n\n private readonly DEFAULT_CONFIG: HealthManagerConfig = {\n shutdownDelayMs: 5_000,\n useExit0: true,\n shouldSetupSignalHandlers: true,\n livenessPeriodMs: 10_000,\n readinessPeriodMs: 5_000,\n enableLivenessOptimization: true,\n };\n\n private isShuttingDown: boolean = false;\n private isReady: boolean = false;\n private livenessOptimizationEnabled: boolean = false;\n\n private config: HealthManagerConfig;\n\n private clientsMap: Map<string, ClientConfig<any>[]> = new Map();\n private server: Required<ServerConfig> | undefined;\n\n private livenessChecks: Array<() => Promise<void>> = [];\n private readinessChecks: Array<() => Promise<void>> = [];\n\n private logger: any;\n\n /**\n * Creates a new HealthManager instance\n *\n * @param params Configuration options for health checks and shutdown behavior\n */\n constructor(params: HealthManagerOptions) {\n this.config = {\n ...this.DEFAULT_CONFIG,\n ...(params.config ?? {}),\n };\n\n this.logger = params.logger;\n if (params.server) {\n this.attachServer(params.server);\n }\n\n this.storeClientsWithDefaults(params);\n\n this.initializeHealthChecks();\n\n if (this.config.shouldSetupSignalHandlers) {\n this.setupSignalHandlers();\n }\n }\n\n /**\n * Store clients with default health check and shutdown functions\n * @private\n */\n private storeClientsWithDefaults(params: HealthManagerOptions): void {\n const clients = params.clients;\n if (!clients) {\n return;\n }\n\n Object.entries(clients).forEach(([type, client]) => {\n if (!client) {\n return;\n }\n\n const clientsArray = Array.isArray(client) ? client : [client];\n\n // Apply default values to each client config\n const clientsWithDefaults = clientsArray.map((client) => {\n const options = {\n ...this.DEFAULT_CLIENT_OPTIONS,\n name: type,\n ...client.options,\n };\n\n const defaultHealthCheck = DEFAULT_CLIENT_HEALTHCHECK_FUNC_MAP[type as ClientType];\n const healthCheck = client.healthCheck ?? (defaultHealthCheck ? () => defaultHealthCheck({ client: client.connection, name: options.name }) : undefined);\n\n const defaultShutdown = DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP[type as ClientType];\n const shutdown = client.shutdown ?? (defaultShutdown ? (signal?: string) => defaultShutdown({ client: client.connection, signal, name: options.name }) : undefined);\n\n return {\n connection: client.connection,\n healthCheck,\n shutdown,\n options,\n };\n });\n\n this.clientsMap.set(type, clientsWithDefaults);\n });\n }\n\n /**\n * Register SIGTERM and SIGINT listeners handlers\n * @private\n */\n private setupSignalHandlers(): void {\n this.logger.info('Setting up global signal listeners for graceful shutdown');\n\n process.on('SIGTERM', async () => {\n await this.shutdown('SIGTERM');\n });\n\n process.on('SIGINT', async () => {\n await this.shutdown('SIGINT');\n });\n }\n\n /**\n * Initialize health check arrays based on configured clients\n * @private\n */\n private initializeHealthChecks(): void {\n let allClientsInBothChecks = true;\n\n this.clientsMap.forEach((clients) => {\n clients.forEach((client) => {\n if (!client.healthCheck) {\n return;\n }\n\n const includeInLiveness = client.options?.includeInLivenessCheck ?? true;\n const includeInReadiness = client.options?.includeInReadinessCheck ?? true;\n\n // Check if all clients are included in both checks\n if (!includeInLiveness || !includeInReadiness) {\n allClientsInBothChecks = false;\n }\n\n if (includeInLiveness) {\n this.livenessChecks.push(client.healthCheck);\n }\n\n if (includeInReadiness) {\n this.readinessChecks.push(client.healthCheck);\n }\n });\n });\n\n // Enable optimization if configured and all clients are in both checks\n this.livenessOptimizationEnabled =\n (this.config.enableLivenessOptimization ?? true) &&\n allClientsInBothChecks;\n\n if (this.livenessOptimizationEnabled) {\n this.logger.info('Liveness check optimization enabled - liveness checks will be skipped when pod is ready');\n }\n }\n\n /**\n * Attach an HTTP or HTTPS server to be managed during shutdown\n * @param serverConfig \n */\n attachServer(serverConfig: ServerConfig): void {\n this.server = {\n server: serverConfig.server,\n shutdown: serverConfig.shutdown ?? (async () => defaultServerShutdownHandler(serverConfig.server)),\n options: {\n ...this.DEFAULT_SERVER_OPTIONS,\n ...(serverConfig.options ?? {}),\n },\n };\n }\n\n /**\n * Performs health checks for all configured clients\n *\n * @returns Promise that resolves to { status: 'ok' } on success\n * @throws Error with statusCode 503 if any health check fails\n */\n async aliveCheck(): Promise<{ status: string, statusCode: number }> {\n if (this.isShuttingDown) {\n return { statusCode: 200, status: 'ok' };\n }\n\n // Skip liveness check if optimization is enabled and pod is already ready\n if (this.livenessOptimizationEnabled && this.isReady) {\n return { statusCode: 200, status: 'ok' };\n }\n\n try {\n const livenessPromises = Promise.all(this.livenessChecks.map(check => check()));\n\n await Promise.race([\n livenessPromises,\n timeoutPromise(this.config.livenessPeriodMs ?? 10_000, 'Liveness check timed out'),\n ]);\n\n return { statusCode: 200, status: 'ok' };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new ServiceUnavailableError(message);\n }\n }\n\n /**\n * Performs readiness check\n *\n * @returns Promise that resolves to { status: 'ok' } if ready\n * @throws Error with statusCode 503 if not ready or health check fails\n */\n async readyCheck(): Promise<{ status: string, statusCode: number }> {\n if (this.isShuttingDown) {\n this.isReady = false;\n throw new ServiceUnavailableError('Application is shutting down');\n }\n\n try {\n const readinessPromises = Promise.all(this.readinessChecks.map(check => check()));\n\n await Promise.race([\n readinessPromises,\n timeoutPromise(this.config.readinessPeriodMs ?? 5_000, 'Readiness check timed out'),\n ]);\n this.isReady = true;\n\n return { statusCode: 200, status: 'ok' };\n } catch (error) {\n this.isReady = false;\n const message = error instanceof Error ? error.message : String(error);\n throw new ServiceUnavailableError(message);\n }\n }\n\n /**\n * Manually trigger graceful shutdown\n * Can be called manually or via signal handlers\n *\n * @param signal - Signal name (e.g., 'SIGTERM', 'SIGINT', 'MANUAL')\n */\n async shutdown(signal: string = 'MANUAL'): Promise<void> {\n if (this.isShuttingDown) {\n this.logger.warn('Shutdown already in progress');\n return;\n }\n\n const { shutdownDelayMs, useExit0, onShutdown, beforeShutdown } = this.config;\n\n this.isShuttingDown = true;\n this.isReady = false;\n\n this.logger.info(`${signal} received: setting readiness state to false`);\n\n await beforeShutdown?.();\n\n this.logger.info(`Waiting ${shutdownDelayMs}ms before shutdown...`);\n await setTimeout(shutdownDelayMs)\n\n this.logger.info('Executing shutdown hooks...');\n\n const shutdownPromises: Promise<any>[] = [];\n this.clientsMap.forEach((clients) => {\n clients.forEach((client) => {\n if (client.shutdown) {\n shutdownPromises.push(client.shutdown());\n }\n });\n });\n\n await Promise.allSettled(shutdownPromises);\n\n await onShutdown?.();\n\n if (this.server?.options?.runDefaultShutdownHandler) {\n this.logger.info('Shutting down server...');\n await this.server?.shutdown?.();\n }\n\n this.logger.info('Shutdown process completed');\n\n if (useExit0) {\n this.logger.info(`Exiting process after ${signal}`);\n process.exit(0);\n }\n }\n}"],"mappings":"4VAqBA,IAAa,EAAb,KAA2B,CAuCzB,YAAY,EAA8B,6BAtCA,CACxC,uBAAwB,GACxB,wBAAyB,GAC1B,6BAEyC,CACxC,0BAA2B,GAC3B,KAAM,SACP,qBAEsD,CACrD,gBAAiB,IACjB,SAAU,GACV,0BAA2B,GAC3B,iBAAkB,IAClB,kBAAmB,IACnB,2BAA4B,GAC7B,qBAEiC,gBACP,oCACoB,mBAIQ,IAAI,wBAGN,EAAE,sBACD,EAAE,CAUtD,KAAK,OAAS,CACZ,GAAG,KAAK,eACR,GAAI,EAAO,QAAU,EAAE,CACxB,CAED,KAAK,OAAS,EAAO,OACjB,EAAO,QACT,KAAK,aAAa,EAAO,OAAO,CAGlC,KAAK,yBAAyB,EAAO,CAErC,KAAK,wBAAwB,CAEzB,KAAK,OAAO,2BACd,KAAK,qBAAqB,CAQ9B,yBAAiC,EAAoC,CACnE,IAAM,EAAU,EAAO,QAClB,GAIL,OAAO,QAAQ,EAAQ,CAAC,SAAS,CAAC,EAAM,KAAY,CAClD,GAAI,CAAC,EACH,OAMF,IAAM,GAHe,MAAM,QAAQ,EAAO,CAAG,EAAS,CAAC,EAAO,EAGrB,IAAK,GAAW,CACvD,IAAM,EAAU,CACd,GAAG,KAAK,uBACR,KAAM,EACN,GAAGA,EA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AK,EAAO,UAAU,CAAC,EAE1C,EACF,CAEF,MAAM,QAAQ,WAAW,EAAiB,CAE1C,MAAM,KAAc,CAEhB,KAAK,QAAQ,SAAS,4BACxB,KAAK,OAAO,KAAK,0BAA0B,CAC3C,MAAM,KAAK,QAAQ,YAAY,EAGjC,KAAK,OAAO,KAAK,6BAA6B,CAE1C,IACF,KAAK,OAAO,KAAK,yBAAyB,IAAS,CACnD,QAAQ,KAAK,EAAE"}
@@ -0,0 +1,2 @@
1
+ const e=require(`../_virtual/rolldown_runtime.cjs`),t=require(`../logger.cjs`),n=require(`./types.cjs`);let r=require(`http-terminator`);const i={[n.CLIENT_TYPES.REDIS]:async e=>{try{await e.client.quit?.()}catch(n){throw t.logger.error(`Failed to shutdown redis client '${e.name}': ${n instanceof Error?n.message:String(n)}`),n}},[n.CLIENT_TYPES.SEQUELIZE]:async e=>{try{await e.client.close?.()}catch(n){throw t.logger.error(`Failed to shutdown sequelize client '${e.name}': ${n instanceof Error?n.message:String(n)}`),n}},[n.CLIENT_TYPES.ELASTIC_SEARCH]:async e=>{try{await e.client.close?.()}catch(n){throw t.logger.error(`Failed to shutdown elasticsearch client '${e.name}': ${n instanceof Error?n.message:String(n)}`),n}},[n.CLIENT_TYPES.RABBIT]:async e=>{try{await e.client.gracefulShutdown?.(e.signal)}catch(n){throw t.logger.error(`Failed to shutdown rabbit client '${e.name}': ${n instanceof Error?n.message:String(n)}`),n}},[n.CLIENT_TYPES.EVENTS]:async e=>{try{await e.client.exitHandler?.()}catch(n){throw t.logger.error(`Failed to shutdown events client '${e.name}': ${n instanceof Error?n.message:String(n)}`),n}}},a=async e=>{try{await(0,r.createHttpTerminator)({server:e}).terminate()}catch(e){throw t.logger.error(`Failed to shutdown server: ${e instanceof Error?e.message:String(e)}`),e}};exports.DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP=i,exports.defaultServerShutdownHandler=a;
2
+ //# sourceMappingURL=shutdown-handlers.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shutdown-handlers.cjs","names":["DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP: Record<ClientType, (client: any, signal?: string) => Promise<void>>","CLIENT_TYPES"],"sources":["../../src/health-manager/shutdown-handlers.ts"],"sourcesContent":["import {\n createHttpTerminator,\n} from 'http-terminator';\nimport type { Server as HttpServer } from 'node:http';\nimport type { Server as HttpsServer } from 'node:https';\nimport type { ClientType } from './types';\nimport { CLIENT_TYPES } from './types';\nimport { logger } from '../logger';\nimport { P } from 'vitest/dist/chunks/worker.d.DadbA89M';\n\nexport const DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP: Record<ClientType, (client: any, signal?: string) => Promise<void>> = {\n [CLIENT_TYPES.REDIS]: async (options: { client: any, name: string }) => {\n try {\n await options.client.quit?.();\n } catch (error) {\n logger.error(`Failed to shutdown redis client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.SEQUELIZE]: async (options: { client: any, name: string }) => {\n try {\n await options.client.close?.();\n } catch (error) {\n logger.error(`Failed to shutdown sequelize client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.ELASTIC_SEARCH]: async (options: { client: any, name: string }) => {\n try {\n await options.client.close?.();\n } catch (error) {\n logger.error(`Failed to shutdown elasticsearch client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.RABBIT]: async (options: { client: any, signal?: string, name: string }) => {\n try {\n await options.client.gracefulShutdown?.(options.signal);\n } catch (error) {\n logger.error(`Failed to shutdown rabbit client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.EVENTS]: async (options: { client: any, name: string }) => {\n try {\n await options.client.exitHandler?.();\n } catch (error) {\n logger.error(`Failed to shutdown events client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n};\n\nexport const defaultServerShutdownHandler = async (server: HttpServer | HttpsServer): Promise<void> => {\n try {\n const httpTerminator = createHttpTerminator({\n server,\n });\n await httpTerminator.terminate();\n } catch (error) {\n logger.error(`Failed to shutdown server: ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n};"],"mappings":"yIAUA,MAAaA,EAA4G,EACtHC,EAAAA,aAAa,OAAQ,KAAO,IAA2C,CACtE,GAAI,CACF,MAAM,EAAQ,OAAO,QAAQ,OACtB,EAAO,CAEd,MADA,EAAA,OAAO,MAAM,oCAAoC,EAAQ,KAAK,KAAK,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,CACtH,KAGTA,EAAAA,aAAa,WAAY,KAAO,IAA2C,CAC1E,GAAI,CACF,MAAM,EAAQ,OAAO,SAAS,OACvB,EAAO,CAEd,MADA,EAAA,OAAO,MAAM,wCAAwC,EAAQ,KAAK,KAAK,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,CAC1H,KAGTA,EAAAA,aAAa,gBAAiB,KAAO,IAA2C,CAC/E,GAAI,CACF,MAAM,EAAQ,OAAO,SAAS,OACvB,EAAO,CAEd,MADA,EAAA,OAAO,MAAM,4CAA4C,EAAQ,KAAK,KAAK,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,CAC9H,KAGTA,EAAAA,aAAa,QAAS,KAAO,IAA4D,CACxF,GAAI,CACF,MAAM,EAAQ,OAAO,mBAAmB,EAAQ,OAAO,OAChD,EAAO,CAEd,MADA,EAAA,OAAO,MAAM,qCAAqC,EAAQ,KAAK,KAAK,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,CACvH,KAGTA,EAAAA,aAAa,QAAS,KAAO,IAA2C,CACvE,GAAI,CACF,MAAM,EAAQ,OAAO,eAAe,OAC7B,EAAO,CAEd,MADA,EAAA,OAAO,MAAM,qCAAqC,EAAQ,KAAK,KAAK,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,CACvH,IAGX,CAEY,EAA+B,KAAO,IAAoD,CACrG,GAAI,CAIF,MAAA,EAAA,EAAA,sBAH4C,CAC1C,SACD,CAAC,CACmB,WAAW,OACzB,EAAO,CAEd,MADA,EAAA,OAAO,MAAM,8BAA8B,aAAiB,MAAQ,EAAM,QAAU,OAAO,EAAM,GAAG,CAC9F"}
@@ -0,0 +1,2 @@
1
+ import{logger as e}from"../logger.js";import{CLIENT_TYPES as t}from"./types.js";import{createHttpTerminator as n}from"http-terminator";const r={[t.REDIS]:async t=>{try{await t.client.quit?.()}catch(n){throw e.error(`Failed to shutdown redis client '${t.name}': ${n instanceof Error?n.message:String(n)}`),n}},[t.SEQUELIZE]:async t=>{try{await t.client.close?.()}catch(n){throw e.error(`Failed to shutdown sequelize client '${t.name}': ${n instanceof Error?n.message:String(n)}`),n}},[t.ELASTIC_SEARCH]:async t=>{try{await t.client.close?.()}catch(n){throw e.error(`Failed to shutdown elasticsearch client '${t.name}': ${n instanceof Error?n.message:String(n)}`),n}},[t.RABBIT]:async t=>{try{await t.client.gracefulShutdown?.(t.signal)}catch(n){throw e.error(`Failed to shutdown rabbit client '${t.name}': ${n instanceof Error?n.message:String(n)}`),n}},[t.EVENTS]:async t=>{try{await t.client.exitHandler?.()}catch(n){throw e.error(`Failed to shutdown events client '${t.name}': ${n instanceof Error?n.message:String(n)}`),n}}},i=async t=>{try{await n({server:t}).terminate()}catch(t){throw e.error(`Failed to shutdown server: ${t instanceof Error?t.message:String(t)}`),t}};export{r as DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP,i as defaultServerShutdownHandler};
2
+ //# sourceMappingURL=shutdown-handlers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"shutdown-handlers.js","names":["DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP: Record<ClientType, (client: any, signal?: string) => Promise<void>>"],"sources":["../../src/health-manager/shutdown-handlers.ts"],"sourcesContent":["import {\n createHttpTerminator,\n} from 'http-terminator';\nimport type { Server as HttpServer } from 'node:http';\nimport type { Server as HttpsServer } from 'node:https';\nimport type { ClientType } from './types';\nimport { CLIENT_TYPES } from './types';\nimport { logger } from '../logger';\nimport { P } from 'vitest/dist/chunks/worker.d.DadbA89M';\n\nexport const DEFAULT_CLIENT_SHUTDOWN_HANDLERS_MAP: Record<ClientType, (client: any, signal?: string) => Promise<void>> = {\n [CLIENT_TYPES.REDIS]: async (options: { client: any, name: string }) => {\n try {\n await options.client.quit?.();\n } catch (error) {\n logger.error(`Failed to shutdown redis client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.SEQUELIZE]: async (options: { client: any, name: string }) => {\n try {\n await options.client.close?.();\n } catch (error) {\n logger.error(`Failed to shutdown sequelize client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.ELASTIC_SEARCH]: async (options: { client: any, name: string }) => {\n try {\n await options.client.close?.();\n } catch (error) {\n logger.error(`Failed to shutdown elasticsearch client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.RABBIT]: async (options: { client: any, signal?: string, name: string }) => {\n try {\n await options.client.gracefulShutdown?.(options.signal);\n } catch (error) {\n logger.error(`Failed to shutdown rabbit client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n [CLIENT_TYPES.EVENTS]: async (options: { client: any, name: string }) => {\n try {\n await options.client.exitHandler?.();\n } catch (error) {\n logger.error(`Failed to shutdown events client '${options.name}': ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n },\n};\n\nexport const defaultServerShutdownHandler = async (server: HttpServer | HttpsServer): Promise<void> => {\n try {\n const httpTerminator = createHttpTerminator({\n server,\n });\n await httpTerminator.terminate();\n } catch (error) {\n logger.error(`Failed to shutdown server: ${error instanceof Error ? error.message : String(error)}`);\n throw error;\n }\n};"],"mappings":"uIAUA,MAAaA,EAA4G,EACtH,EAAa,OAAQ,KAAO,IAA2C,CACtE,G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ENT_TYPES=e;
2
+ //# sourceMappingURL=types.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.cjs","names":[],"sources":["../../src/health-manager/types.ts"],"sourcesContent":["import type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { Server as HttpServer } from 'node:http';\nimport type { Server as HttpsServer } from 'node:https';\n\n\n/**\n * Configuration for a single client (e.g., rabbit, sequelize, redis, elasticsearch)\n * Allows custom health checks and shutdown logic\n */\nexport interface ClientConfig<T = any> {\n /** The actual connection instance */\n connection: T;\n\n /** Custom health check function (optional) - will be called during alive/ready checks */\n healthCheck?: () => Promise<void>;\n\n /** Custom shutdown function (optional) - will be called during graceful shutdown */\n shutdown?: () => Promise<void>;\n\n /** Additional options specific to the client (optional) */\n options?: {\n /** Whether to include this client in liveness checks (default: true) */\n includeInLivenessCheck?: boolean;\n\n /** Whether to include this client in readiness checks (default: true) */\n includeInReadinessCheck?: boolean;\n\n /** Custom name for this client (used in logging) */\n name?: string;\n };\n}\n\n/** Configuration for an HTTP or HTTPS server managed by HealthManager */\nexport interface ServerConfig {\n /** The HTTP or HTTPS server instance */\n server: HttpServer | HttpsServer;\n\n /** Custom shutdown function for the server (optional) */\n shutdown?: () => Promise<void>;\n\n /** Additional options specific to the server (optional) */\n options?: {\n /** Custom name for this server (used in logging) */\n name?: string;\n\n /** Whether to skip the default shutdown handler for this server */\n runDefaultShutdownHandler?: boolean;\n\n }\n}\n\n/**\n * General configuration options for the HealthManager\n */\nexport interface HealthManagerConfig {\n /**\n * Delay in milliseconds before shutting down after SIGTERM/SIGINT\n * This gives time for load balancers to stop routing traffic. Should be equal to or greater than readiness probe interval.\n * @default 5000\n */\n shutdownDelayMs?: number;\n\n /**\n * Whether to call process.exit(0) after shutdown sequence completes\n * @default true\n */\n useExit0?: boolean;\n\n /** Whether to auto-setup SIGTERM/SIGINT handlers for graceful shutdown\n * @default true\n */\n shouldSetupSignalHandlers?: boolean;\n\n /**\n * Global shutdown hook called before all clients are shut down\n * @default undefined\n */\n beforeShutdown?: (() => Promise<void>) | undefined;\n\n /**\n * Global shutdown hook called after all clients are shut down\n * @default undefined\n */\n onShutdown?: (() => Promise<void>) | undefined;\n\n /** The interval in milliseconds at which the liveness checks are repeated (optional)\n * * @default 10_000 \n */\n livenessPeriodMs?: number;\n\n /** The interval in milliseconds at which the readiness checks are repeated (optional)\n * * @default 5_000\n */\n readinessPeriodMs?: number;\n\n /**\n * Enable liveness check optimization - if true and all clients are in both liveness and readiness checks,\n * liveness checks will be skipped when pod is already ready (readiness check passed)\n * @default true\n */\n enableLivenessOptimization?: boolean;\n}\n\n/**\n * List of clients and general configuration for HealthManager\n */\nexport interface HealthManagerOptions {\n /** Client configurations */\n clients?: {\n /** RabbitMQ client configuration - can be a single config or array of configs */\n rabbit?: ClientConfig<any> | ClientConfig<any>[];\n\n /** Sequelize instance configuration - can be a single config or array of configs */\n sequelize?: ClientConfig<any> | ClientConfig<any>[];\n\n /** Redis client configuration - can be a single config or array of configs */\n redis?: ClientConfig<any> | ClientConfig<any>[];\n\n /** Elasticsearch client configuration - can be a single config or array of configs */\n elasticsearch?: ClientConfig<any> | ClientConfig<any>[];\n };\n\n /** General configuration options */\n config?: HealthManagerConfig;\n\n /** Logger instance for logging messages */\n logger: LoggerInstanceManager;\n\n /** Optional HTTP or HTTPS server instance to manage during shutdown */\n server?: ServerConfig\n}\n\nexport interface RedisClient {\n ping: () => Promise<string | void>;\n}\n\n/**\n * Sequelize database interface\n */\nexport interface SequelizeClient {\n query(sql: string | { query: string; values: unknown[]; }): Promise<any>;\n}\n\n/**\n * Elasticsearch client interface\n */\nexport interface ElasticsearchClient {\n ping: () => Promise<boolean>;\n}\n\nexport interface EventsClient {\n exitHandler: () => Promise<void>;\n}\n\n/**\n * RabbitMQ client interface\n */\nexport interface RabbitMQClient {\n isConnected: () => Promise<boolean> | boolean;\n}\n\nexport const CLIENT_TYPES = {\n RABBIT: 'rabbit',\n SEQUELIZE: 'sequelize',\n REDIS: 'redis',\n ELASTIC_SEARCH: 'elasticsearch',\n EVENTS: 'events',\n} as const;\n\nexport type ClientType = typeof CLIENT_TYPES[keyof typeof CLIENT_TYPES];\n"],"mappings":"AAiKA,MAAa,EAAe,CAC1B,OAAQ,SACR,UAAW,YACX,MAAO,QACP,eAAgB,gBAChB,OAAQ,SACT"}
@@ -0,0 +1,110 @@
1
+ import { LoggerInstanceManager } from "@autofleet/logger";
2
+ import { Server } from "node:http";
3
+ import { Server as Server$1 } from "node:https";
4
+
5
+ //#region src/health-manager/types.d.ts
6
+
7
+ /**
8
+ * Configuration for a single client (e.g., rabbit, sequelize, redis, elasticsearch)
9
+ * Allows custom health checks and shutdown logic
10
+ */
11
+ interface ClientConfig<T = any> {
12
+ /** The actual connection instance */
13
+ connection: T;
14
+ /** Custom health check function (optional) - will be called during alive/ready checks */
15
+ healthCheck?: () => Promise<void>;
16
+ /** Custom shutdown function (optional) - will be called during graceful shutdown */
17
+ shutdown?: () => Promise<void>;
18
+ /** Additional options specific to the client (optional) */
19
+ options?: {
20
+ /** Whether to include this client in liveness checks (default: true) */
21
+ includeInLivenessCheck?: boolean;
22
+ /** Whether to include this client in readiness checks (default: true) */
23
+ includeInReadinessCheck?: boolean;
24
+ /** Custom name for this client (used in logging) */
25
+ name?: string;
26
+ };
27
+ }
28
+ /** Configuration for an HTTP or HTTPS server managed by HealthManager */
29
+ interface ServerConfig {
30
+ /** The HTTP or HTTPS server instance */
31
+ server: Server | Server$1;
32
+ /** Custom shutdown function for the server (optional) */
33
+ shutdown?: () => Promise<void>;
34
+ /** Additional options specific to the server (optional) */
35
+ options?: {
36
+ /** Custom name for this server (used in logging) */
37
+ name?: string;
38
+ /** Whether to skip the default shutdown handler for this server */
39
+ runDefaultShutdownHandler?: boolean;
40
+ };
41
+ }
42
+ /**
43
+ * General configuration options for the HealthManager
44
+ */
45
+ interface HealthManagerConfig {
46
+ /**
47
+ * Delay in milliseconds before shutting down after SIGTERM/SIGINT
48
+ * This gives time for load balancers to stop routing traffic. Should be equal to or greater than readiness probe interval.
49
+ * @default 5000
50
+ */
51
+ shutdownDelayMs?: number;
52
+ /**
53
+ * Whether to call process.exit(0) after shutdown sequence completes
54
+ * @default true
55
+ */
56
+ useExit0?: boolean;
57
+ /** Whether to auto-setup SIGTERM/SIGINT handlers for graceful shutdown
58
+ * @default true
59
+ */
60
+ shouldSetupSignalHandlers?: boolean;
61
+ /**
62
+ * Global shutdown hook called before all clients are shut down
63
+ * @default undefined
64
+ */
65
+ beforeShutdown?: (() => Promise<void>) | undefined;
66
+ /**
67
+ * Global shutdown hook called after all clients are shut down
68
+ * @default undefined
69
+ */
70
+ onShutdown?: (() => Promise<void>) | undefined;
71
+ /** The interval in milliseconds at which the liveness checks are repeated (optional)
72
+ * * @default 10_000
73
+ */
74
+ livenessPeriodMs?: number;
75
+ /** The interval in milliseconds at which the readiness checks are repeated (optional)
76
+ * * @default 5_000
77
+ */
78
+ readinessPeriodMs?: number;
79
+ /**
80
+ * Enable liveness check optimization - if true and all clients are in both liveness and readiness checks,
81
+ * liveness checks will be skipped when pod is already ready (readiness check passed)
82
+ * @default true
83
+ */
84
+ enableLivenessOptimization?: boolean;
85
+ }
86
+ /**
87
+ * List of clients and general configuration for HealthManager
88
+ */
89
+ interface HealthManagerOptions {
90
+ /** Client configurations */
91
+ clients?: {
92
+ /** RabbitMQ client configuration - can be a single config or array of configs */
93
+ rabbit?: ClientConfig<any> | ClientConfig<any>[];
94
+ /** Sequelize instance configuration - can be a single config or array of configs */
95
+ sequelize?: ClientConfig<any> | ClientConfig<any>[];
96
+ /** Redis client configuration - can be a single config or array of configs */
97
+ redis?: ClientConfig<any> | ClientConfig<any>[];
98
+ /** Elasticsearch client configuration - can be a single config or array of configs */
99
+ elasticsearch?: ClientConfig<any> | ClientConfig<any>[];
100
+ };
101
+ /** General configuration options */
102
+ config?: HealthManagerConfig;
103
+ /** Logger instance for logging messages */
104
+ logger: LoggerInstanceManager;
105
+ /** Optional HTTP or HTTPS server instance to manage during shutdown */
106
+ server?: ServerConfig;
107
+ }
108
+ //#endregion
109
+ export { HealthManagerOptions, ServerConfig };
110
+ //# sourceMappingURL=types.d.cts.map
@@ -0,0 +1,110 @@
1
+ import { LoggerInstanceManager } from "@autofleet/logger";
2
+ import { Server } from "node:http";
3
+ import { Server as Server$1 } from "node:https";
4
+
5
+ //#region src/health-manager/types.d.ts
6
+
7
+ /**
8
+ * Configuration for a single client (e.g., rabbit, sequelize, redis, elasticsearch)
9
+ * Allows custom health checks and shutdown logic
10
+ */
11
+ interface ClientConfig<T = any> {
12
+ /** The actual connection instance */
13
+ connection: T;
14
+ /** Custom health check function (optional) - will be called during alive/ready checks */
15
+ healthCheck?: () => Promise<void>;
16
+ /** Custom shutdown function (optional) - will be called during graceful shutdown */
17
+ shutdown?: () => Promise<void>;
18
+ /** Additional options specific to the client (optional) */
19
+ options?: {
20
+ /** Whether to include this client in liveness checks (default: true) */
21
+ includeInLivenessCheck?: boolean;
22
+ /** Whether to include this client in readiness checks (default: true) */
23
+ includeInReadinessCheck?: boolean;
24
+ /** Custom name for this client (used in logging) */
25
+ name?: string;
26
+ };
27
+ }
28
+ /** Configuration for an HTTP or HTTPS server managed by HealthManager */
29
+ interface ServerConfig {
30
+ /** The HTTP or HTTPS server instance */
31
+ server: Server | Server$1;
32
+ /** Custom shutdown function for the server (optional) */
33
+ shutdown?: () => Promise<void>;
34
+ /** Additional options specific to the server (optional) */
35
+ options?: {
36
+ /** Custom name for this server (used in logging) */
37
+ name?: string;
38
+ /** Whether to skip the default shutdown handler for this server */
39
+ runDefaultShutdownHandler?: boolean;
40
+ };
41
+ }
42
+ /**
43
+ * General configuration options for the HealthManager
44
+ */
45
+ interface HealthManagerConfig {
46
+ /**
47
+ * Delay in milliseconds before shutting down after SIGTERM/SIGINT
48
+ * This gives time for load balancers to stop routing traffic. Should be equal to or greater than readiness probe interval.
49
+ * @default 5000
50
+ */
51
+ shutdownDelayMs?: number;
52
+ /**
53
+ * Whether to call process.exit(0) after shutdown sequence completes
54
+ * @default true
55
+ */
56
+ useExit0?: boolean;
57
+ /** Whether to auto-setup SIGTERM/SIGINT handlers for graceful shutdown
58
+ * @default true
59
+ */
60
+ shouldSetupSignalHandlers?: boolean;
61
+ /**
62
+ * Global shutdown hook called before all clients are shut down
63
+ * @default undefined
64
+ */
65
+ beforeShutdown?: (() => Promise<void>) | undefined;
66
+ /**
67
+ * Global shutdown hook called after all clients are shut down
68
+ * @default undefined
69
+ */
70
+ onShutdown?: (() => Promise<void>) | undefined;
71
+ /** The interval in milliseconds at which the liveness checks are repeated (optional)
72
+ * * @default 10_000
73
+ */
74
+ livenessPeriodMs?: number;
75
+ /** The interval in milliseconds at which the readiness checks are repeated (optional)
76
+ * * @default 5_000
77
+ */
78
+ readinessPeriodMs?: number;
79
+ /**
80
+ * Enable liveness check optimization - if true and all clients are in both liveness and readiness checks,
81
+ * liveness checks will be skipped when pod is already ready (readiness check passed)
82
+ * @default true
83
+ */
84
+ enableLivenessOptimization?: boolean;
85
+ }
86
+ /**
87
+ * List of clients and general configuration for HealthManager
88
+ */
89
+ interface HealthManagerOptions {
90
+ /** Client configurations */
91
+ clients?: {
92
+ /** RabbitMQ client configuration - can be a single config or array of configs */
93
+ rabbit?: ClientConfig<any> | ClientConfig<any>[];
94
+ /** Sequelize instance configuration - can be a single config or array of configs */
95
+ sequelize?: ClientConfig<any> | ClientConfig<any>[];
96
+ /** Redis client configuration - can be a single config or array of configs */
97
+ redis?: ClientConfig<any> | ClientConfig<any>[];
98
+ /** Elasticsearch client configuration - can be a single config or array of configs */
99
+ elasticsearch?: ClientConfig<any> | ClientConfig<any>[];
100
+ };
101
+ /** General configuration options */
102
+ config?: HealthManagerConfig;
103
+ /** Logger instance for logging messages */
104
+ logger: LoggerInstanceManager;
105
+ /** Optional HTTP or HTTPS server instance to manage during shutdown */
106
+ server?: ServerConfig;
107
+ }
108
+ //#endregion
109
+ export { HealthManagerOptions, ServerConfig };
110
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,2 @@
1
+ const e={RABBIT:`rabbit`,SEQUELIZE:`sequelize`,REDIS:`redis`,ELASTIC_SEARCH:`elasticsearch`,EVENTS:`events`};export{e as CLIENT_TYPES};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","names":[],"sources":["../../src/health-manager/types.ts"],"sourcesContent":["import type { LoggerInstanceManager } from '@autofleet/logger';\nimport type { Server as HttpServer } from 'node:http';\nimport type { Server as HttpsServer } from 'node:https';\n\n\n/**\n * Configuration for a single client (e.g., rabbit, sequelize, redis, elasticsearch)\n * Allows custom health checks and shutdown logic\n */\nexport interface ClientConfig<T = any> {\n /** The actual connection instance */\n connection: T;\n\n /** Custom health check function (optional) - will be called during alive/ready checks */\n healthCheck?: () => Promise<void>;\n\n /** Custom shutdown function (optional) - will be called during graceful shutdown */\n shutdown?: () => Promise<void>;\n\n /** Additional options specific to the client (optional) */\n options?: {\n /** Whether to include this client in liveness checks (default: true) */\n includeInLivenessCheck?: boolean;\n\n /** Whether to include this client in readiness checks (default: true) */\n includeInReadinessCheck?: boolean;\n\n /** Custom name for this client (used in logging) */\n name?: string;\n };\n}\n\n/** Configuration for an HTTP or HTTPS server managed by HealthManager */\nexport interface ServerConfig {\n /** The HTTP or HTTPS server instance */\n server: HttpServer | HttpsServer;\n\n /** Custom shutdown function for the server (optional) */\n shutdown?: () => Promise<void>;\n\n /** Additional options specific to the server (optional) */\n options?: {\n /** Custom name for this server (used in logging) */\n name?: string;\n\n /** Whether to skip the default shutdown handler for this server */\n runDefaultShutdownHandler?: boolean;\n\n }\n}\n\n/**\n * General configuration options for the HealthManager\n */\nexport interface HealthManagerConfig {\n /**\n * Delay in milliseconds before shutting down after SIGTERM/SIGINT\n * This gives time for load balancers to stop routing traffic. Should be equal to or greater than readiness probe interval.\n * @default 5000\n */\n shutdownDelayMs?: number;\n\n /**\n * Whether to call process.exit(0) after shutdown sequence completes\n * @default true\n */\n useExit0?: boolean;\n\n /** Whether to auto-setup SIGTERM/SIGINT handlers for graceful shutdown\n * @default true\n */\n shouldSetupSignalHandlers?: boolean;\n\n /**\n * Global shutdown hook called before all clients are shut down\n * @default undefined\n */\n beforeShutdown?: (() => Promise<void>) | undefined;\n\n /**\n * Global shutdown hook called after all clients are shut down\n * @default undefined\n */\n onShutdown?: (() => Promise<void>) | undefined;\n\n /** The interval in milliseconds at which the liveness checks are repeated (optional)\n * * @default 10_000 \n */\n livenessPeriodMs?: number;\n\n /** The interval in milliseconds at which the readiness checks are repeated (optional)\n * * @default 5_000\n */\n readinessPeriodMs?: number;\n\n /**\n * Enable liveness check optimization - if true and all clients are in both liveness and readiness checks,\n * liveness checks will be skipped when pod is already ready (readiness check passed)\n * @default true\n */\n enableLivenessOptimization?: boolean;\n}\n\n/**\n * List of clients and general configuration for HealthManager\n */\nexport interface HealthManagerOptions {\n /** Client configurations */\n clients?: {\n /** RabbitMQ client configuration - can be a single config or array of configs */\n rabbit?: ClientConfig<any> | ClientConfig<any>[];\n\n /** Sequelize instance configuration - can be a single config or array of configs */\n sequelize?: ClientConfig<any> | ClientConfig<any>[];\n\n /** Redis client configuration - can be a single config or array of configs */\n redis?: ClientConfig<any> | ClientConfig<any>[];\n\n /** Elasticsearch client configuration - can be a single config or array of configs */\n elasticsearch?: ClientConfig<any> | ClientConfig<any>[];\n };\n\n /** General configuration options */\n config?: HealthManagerConfig;\n\n /** Logger instance for logging messages */\n logger: LoggerInstanceManager;\n\n /** Optional HTTP or HTTPS server instance to manage during shutdown */\n server?: ServerConfig\n}\n\nexport interface RedisClient {\n ping: () => Promise<string | void>;\n}\n\n/**\n * Sequelize database interface\n */\nexport interface SequelizeClient {\n query(sql: string | { query: string; values: unknown[]; }): Promise<any>;\n}\n\n/**\n * Elasticsearch client interface\n */\nexport interface ElasticsearchClient {\n ping: () => Promise<boolean>;\n}\n\nexport interface EventsClient {\n exitHandler: () => Promise<void>;\n}\n\n/**\n * RabbitMQ client interface\n */\nexport interface RabbitMQClient {\n isConnected: () => Promise<boolean> | boolean;\n}\n\nexport const CLIENT_TYPES = {\n RABBIT: 'rabbit',\n SEQUELIZE: 'sequelize',\n REDIS: 'redis',\n ELASTIC_SEARCH: 'elasticsearch',\n EVENTS: 'events',\n} as const;\n\nexport type ClientType = typeof CLIENT_TYPES[keyof typeof CLIENT_TYPES];\n"],"mappings":"AAiKA,MAAa,EAAe,CAC1B,OAAQ,SACR,UAAW,YACX,MAAO,QACP,eAAgB,gBAChB,OAAQ,SACT"}