@n8io/baseline-shutdown 0.0.0-stage → 2.1.0

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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nate Clark
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,43 @@
1
- # Temporary Holding Version
1
+ # @n8io/baseline-shutdown
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Graceful shutdown in a fixed order: stop taking work, let running work finish, then close resources one by one.
4
+
5
+ ```sh
6
+ pnpm add @n8io/baseline-shutdown
7
+ ```
8
+
9
+ ## Exports
10
+
11
+ - `shutdownHandle({ intakes, resources, deadlineMs?, drainDelayMs? })`: owns `SIGTERM`, `SIGINT`, `uncaughtException` and `unhandledRejection`, and exits the process: 0 when every step closed in time, 1 otherwise or after a crash.
12
+ 1. Waits `drainDelayMs` (default 5 s; pass 0 outside production) while readiness answers 503.
13
+ 2. Closes every intake (HTTP server, live streams, Consumers) at once.
14
+ 3. Closes each resource (queue, pools, clients, health, telemetry last) in order.
15
+ 4. Gives up at `deadlineMs` (default 25 s), keeping the last 5 s for the resources.
16
+ - `ShutdownHandle`: `isShuttingDown()`, for `/readyz`.
17
+ - `ShutdownStep`: `{ name, close }`.
18
+
19
+ ## Example
20
+
21
+ ```ts
22
+ import { httpServerClose } from "@n8io/baseline-http";
23
+ import { shutdownHandle } from "@n8io/baseline-shutdown";
24
+ import { telemetryShutdown } from "@n8io/baseline-telemetry";
25
+
26
+ const shutdown = shutdownHandle({
27
+ drainDelayMs: envLocal ? 0 : 5_000,
28
+ intakes: [
29
+ { close: () => httpServerClose(server), name: "http" },
30
+ { close: () => liveHub.close(), name: "live" },
31
+ ],
32
+ resources: [
33
+ { close: () => queue.stop(), name: "queue" },
34
+ { close: () => pgPool.end(), name: "database" },
35
+ { close: () => health.close(), name: "health" },
36
+ { close: () => telemetryShutdown(), name: "telemetry" },
37
+ ],
38
+ });
39
+ ```
40
+
41
+ ## Needs
42
+
43
+ Nothing beyond `@n8io/baseline-logger`, which it logs each failed step through. No env.
@@ -0,0 +1,15 @@
1
+ export type ShutdownStep = {
2
+ name: string;
3
+ close: () => Promise<void>;
4
+ };
5
+ type ShutdownOptions = {
6
+ deadlineMs?: number;
7
+ drainDelayMs?: number;
8
+ intakes: ShutdownStep[];
9
+ resources: ShutdownStep[];
10
+ };
11
+ export type ShutdownHandle = {
12
+ isShuttingDown(): boolean;
13
+ };
14
+ export declare const shutdownHandle: ({ deadlineMs, drainDelayMs, intakes, resources }: ShutdownOptions) => ShutdownHandle;
15
+ export {};
package/dist/index.js ADDED
@@ -0,0 +1,72 @@
1
+ import { logger } from "@n8io/baseline-logger";
2
+ // src/index.ts
3
+ const RESOURCE_RESERVE_MS = 5e3;
4
+ const TIMED_OUT = Symbol("timedOut");
5
+ const timeout = (ms) => new Promise((resolve) => {
6
+ setTimeout(() => resolve(TIMED_OUT), Math.max(0, ms));
7
+ });
8
+ const stepClose = async (kind, step) => {
9
+ try {
10
+ await step.close();
11
+ return true;
12
+ } catch (error) {
13
+ logger.error({ err: error }, `${kind} ${step.name} failed to close`);
14
+ return false;
15
+ }
16
+ };
17
+ const shutdownHandle = ({ deadlineMs = 25e3, drainDelayMs = 5e3, intakes, resources }) => {
18
+ let shuttingDown = false;
19
+ let crashed = false;
20
+ const shutdownRun = async (drainMs) => {
21
+ let clean = true;
22
+ const cutoff = timeout(deadlineMs - RESOURCE_RESERVE_MS);
23
+ const deadline = timeout(deadlineMs);
24
+ await Promise.race([timeout(drainMs), cutoff]);
25
+ const open = new Set(intakes);
26
+ const intakesDone = Promise.all(intakes.map(async (intake) => {
27
+ const closed = await stepClose("Intake", intake);
28
+ open.delete(intake);
29
+ return closed;
30
+ }));
31
+ const intakeResult = await Promise.race([intakesDone, cutoff]);
32
+ if (intakeResult === TIMED_OUT) {
33
+ clean = false;
34
+ for (const intake of open) logger.warn(`Intake ${intake.name} still open at the cutoff`);
35
+ } else if (intakeResult.includes(false)) clean = false;
36
+ for (const [index, resource] of resources.entries()) {
37
+ const closed = await Promise.race([stepClose("Resource", resource), deadline]);
38
+ if (closed === TIMED_OUT) {
39
+ clean = false;
40
+ for (const left of resources.slice(index)) logger.error(`Resource ${left.name} still open at the deadline`);
41
+ break;
42
+ }
43
+ if (!closed) clean = false;
44
+ }
45
+ return clean;
46
+ };
47
+ const shutdownExit = async (drainMs) => {
48
+ const code = await shutdownRun(drainMs).catch(() => false) && !crashed ? 0 : 1;
49
+ logger.info({ code }, "Shutdown finished");
50
+ process.exit(code);
51
+ };
52
+ const start = (drainMs) => {
53
+ if (shuttingDown) return false;
54
+ shuttingDown = true;
55
+ shutdownExit(drainMs);
56
+ return true;
57
+ };
58
+ const onSignal = (signal) => {
59
+ if (start(drainDelayMs)) logger.info(`Shutdown started on ${signal}`);
60
+ };
61
+ const onCrash = (error) => {
62
+ logger.fatal({ err: error }, "Crashed, shutting down");
63
+ crashed = true;
64
+ start(0);
65
+ };
66
+ process.on("SIGTERM", onSignal);
67
+ process.on("SIGINT", onSignal);
68
+ process.on("uncaughtException", onCrash);
69
+ process.on("unhandledRejection", onCrash);
70
+ return { isShuttingDown: () => shuttingDown };
71
+ };
72
+ export { shutdownHandle };
package/package.json CHANGED
@@ -1,6 +1,37 @@
1
1
  {
2
2
  "name": "@n8io/baseline-shutdown",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2.1.0",
4
+ "description": "Graceful shutdown: drain, close intakes together, then resources in order.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=26"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/n8io/baseline.git",
13
+ "directory": "packages/shutdown"
14
+ },
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ }
20
+ },
21
+ "files": [
22
+ "dist",
23
+ "README.md"
24
+ ],
25
+ "publishConfig": {
26
+ "access": "public",
27
+ "registry": "https://registry.npmjs.org"
28
+ },
29
+ "dependencies": {
30
+ "@n8io/baseline-logger": "^2.1.0"
31
+ },
32
+ "scripts": {
33
+ "build": "tsdown",
34
+ "check": "tsc --noEmit && pnpm pack --out dist/package.tgz && publint dist/package.tgz --strict && attw dist/package.tgz --profile esm-only",
35
+ "test": "vitest run"
36
+ }
6
37
  }