@mgcrea/fastify-graceful-exit
Version:
Graceful exit for your fastify application
1 lines • 2.92 kB
Source Map (JSON)
{"version":3,"sources":["../src/index.ts","../src/plugin.ts"],"sourcesContent":["import fastifyPlugin from \"fastify-plugin\";\nimport { plugin } from \"./plugin\";\n\nexport type { FastifyGracefulExitOptions } from \"./plugin\";\n\nexport default fastifyPlugin(plugin, {\n fastify: \">=4\",\n name: \"fastify-graceful-exit\",\n});\n","/* eslint-disable @typescript-eslint/no-misused-promises */\nimport type { FastifyPluginAsync } from \"fastify\";\n\nexport type FastifyGracefulExitOptions = {\n logBindings?: Record<string, unknown>;\n timeout?: number;\n};\n\nexport const plugin: FastifyPluginAsync<FastifyGracefulExitOptions> = async (\n fastify,\n options = {},\n // eslint-disable-next-line @typescript-eslint/require-await\n): Promise<void> => {\n const { logBindings = { plugin: \"fastify-graceful-exit\" }, timeout = 3000 } = options;\n const { log } = fastify;\n let closePromise: Promise<undefined> | null = null;\n // Gracefully close\n const gracefullyClose = async (signal: string) => {\n if (closePromise) {\n return closePromise;\n }\n log.warn(logBindings, `Fastify is gracefully closing from signal=\"${signal}\" ...`);\n // Exit after a 3s timeout\n setTimeout(() => {\n log.warn(logBindings, `Failed to gracefully close before timeout`);\n process.exit(1);\n }, timeout);\n closePromise = fastify.close();\n await closePromise;\n process.exit(0);\n };\n process.on(\"uncaughtException\", async (err) => {\n log.error({ err }, `Uncaught Exception: ${err.message}`);\n await gracefullyClose(\"uncaughtException\");\n });\n process.on(\"unhandledRejection\", async (reason, _promise) => {\n log.error({ reason }, `Unhandled Rejection: ${String(reason)}`);\n await gracefullyClose(\"unhandledRejection\");\n });\n process.on(\"SIGTERM\", gracefullyClose);\n // Handle Ctrl+C\n process.on(\"SIGINT\", gracefullyClose);\n // Handle nodemon-like restarts\n process.on(\"SIGUSR2\", gracefullyClose);\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,4BAA0B;;;ACQnB,IAAM,SAAyD,OACpE,SACA,UAAU,CAAC,MAEO;AAClB,QAAM,EAAE,cAAc,EAAE,QAAQ,wBAAwB,GAAG,UAAU,IAAK,IAAI;AAC9E,QAAM,EAAE,IAAI,IAAI;AAChB,MAAI,eAA0C;AAE9C,QAAM,kBAAkB,OAAO,WAAmB;AAChD,QAAI,cAAc;AAChB,aAAO;AAAA,IACT;AACA,QAAI,KAAK,aAAa,8CAA8C,MAAM,OAAO;AAEjF,eAAW,MAAM;AACf,UAAI,KAAK,aAAa,2CAA2C;AACjE,cAAQ,KAAK,CAAC;AAAA,IAChB,GAAG,OAAO;AACV,mBAAe,QAAQ,MAAM;AAC7B,UAAM;AACN,YAAQ,KAAK,CAAC;AAAA,EAChB;AACA,UAAQ,GAAG,qBAAqB,OAAO,QAAQ;AAC7C,QAAI,MAAM,EAAE,IAAI,GAAG,uBAAuB,IAAI,OAAO,EAAE;AACvD,UAAM,gBAAgB,mBAAmB;AAAA,EAC3C,CAAC;AACD,UAAQ,GAAG,sBAAsB,OAAO,QAAQ,aAAa;AAC3D,QAAI,MAAM,EAAE,OAAO,GAAG,wBAAwB,OAAO,MAAM,CAAC,EAAE;AAC9D,UAAM,gBAAgB,oBAAoB;AAAA,EAC5C,CAAC;AACD,UAAQ,GAAG,WAAW,eAAe;AAErC,UAAQ,GAAG,UAAU,eAAe;AAEpC,UAAQ,GAAG,WAAW,eAAe;AACvC;;;ADvCA,IAAO,kBAAQ,sBAAAA,SAAc,QAAQ;AAAA,EACnC,SAAS;AAAA,EACT,MAAM;AACR,CAAC;","names":["fastifyPlugin"]}