@blamejs/core 0.7.18 → 0.7.20

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 (169) hide show
  1. package/CHANGELOG.md +427 -423
  2. package/README.md +150 -150
  3. package/bin/blamejs.js +0 -0
  4. package/index.js +310 -308
  5. package/lib/api-key.js +660 -660
  6. package/lib/api-snapshot.js +338 -338
  7. package/lib/app-shutdown.js +385 -385
  8. package/lib/app.js +365 -365
  9. package/lib/archive.js +250 -250
  10. package/lib/atomic-file.js +544 -544
  11. package/lib/audit-chain.js +177 -177
  12. package/lib/audit-sign.js +344 -344
  13. package/lib/audit-tools.js +677 -677
  14. package/lib/audit.js +766 -766
  15. package/lib/auth/jwt-external.js +365 -0
  16. package/lib/auth/jwt.js +337 -311
  17. package/lib/auth/lockout.js +436 -436
  18. package/lib/auth/oauth.js +721 -721
  19. package/lib/auth/passkey.js +181 -181
  20. package/lib/auth/password.js +628 -594
  21. package/lib/backup/bundle.js +217 -217
  22. package/lib/backup/crypto.js +176 -176
  23. package/lib/backup/index.js +515 -515
  24. package/lib/backup/manifest.js +282 -282
  25. package/lib/break-glass.js +1338 -1338
  26. package/lib/bundler.js +441 -441
  27. package/lib/cache-redis.js +256 -256
  28. package/lib/cache.js +1206 -1206
  29. package/lib/canonical-json.js +115 -115
  30. package/lib/chain-writer.js +234 -234
  31. package/lib/cli-helpers.js +206 -206
  32. package/lib/cli.js +2334 -2334
  33. package/lib/cluster-provider-db.js +317 -317
  34. package/lib/cluster-storage.js +226 -226
  35. package/lib/cluster.js +703 -703
  36. package/lib/config-drift.js +301 -301
  37. package/lib/consent.js +222 -222
  38. package/lib/constants.js +191 -191
  39. package/lib/cookies.js +350 -315
  40. package/lib/credential-hash.js +322 -322
  41. package/lib/crypto.js +266 -266
  42. package/lib/csv.js +275 -275
  43. package/lib/db-declare-row-policy.js +267 -267
  44. package/lib/db-declare-view.js +420 -420
  45. package/lib/db-query.js +406 -406
  46. package/lib/db-schema.js +319 -319
  47. package/lib/db.js +1288 -1288
  48. package/lib/deprecate.js +222 -222
  49. package/lib/dev.js +335 -335
  50. package/lib/dual-control.js +473 -473
  51. package/lib/error-page.js +420 -420
  52. package/lib/external-db-migrate.js +441 -441
  53. package/lib/external-db.js +1061 -1061
  54. package/lib/file-type.js +273 -273
  55. package/lib/forms.js +422 -422
  56. package/lib/framework-error.js +293 -293
  57. package/lib/framework-schema.js +717 -717
  58. package/lib/handlers.js +350 -350
  59. package/lib/http-client-cookie-jar.js +508 -508
  60. package/lib/http-client.js +1195 -1195
  61. package/lib/i18n.js +878 -878
  62. package/lib/jobs.js +185 -185
  63. package/lib/log-stream-cloudwatch.js +369 -369
  64. package/lib/log-stream-local.js +146 -146
  65. package/lib/log-stream-otlp-grpc.js +410 -410
  66. package/lib/log-stream-otlp.js +286 -286
  67. package/lib/log-stream-syslog.js +302 -302
  68. package/lib/log-stream-webhook.js +199 -199
  69. package/lib/log-stream.js +330 -330
  70. package/lib/log.js +500 -500
  71. package/lib/mail-bounce.js +528 -528
  72. package/lib/mail-dkim.js +369 -369
  73. package/lib/mail.js +981 -981
  74. package/lib/metrics.js +683 -683
  75. package/lib/middleware/api-encrypt.js +936 -936
  76. package/lib/middleware/attach-user.js +157 -157
  77. package/lib/middleware/bearer-auth.js +152 -0
  78. package/lib/middleware/body-parser.js +1170 -1170
  79. package/lib/middleware/bot-guard.js +178 -178
  80. package/lib/middleware/compression.js +452 -452
  81. package/lib/middleware/cors.js +314 -314
  82. package/lib/middleware/csp-nonce.js +348 -348
  83. package/lib/middleware/csrf-protect.js +399 -316
  84. package/lib/middleware/db-role-for.js +264 -264
  85. package/lib/middleware/fetch-metadata.js +129 -0
  86. package/lib/middleware/health.js +392 -392
  87. package/lib/middleware/index.js +85 -79
  88. package/lib/middleware/rate-limit.js +358 -358
  89. package/lib/middleware/request-id.js +61 -61
  90. package/lib/middleware/request-log.js +168 -168
  91. package/lib/middleware/require-auth.js +104 -104
  92. package/lib/middleware/security-headers.js +121 -116
  93. package/lib/middleware/sse.js +166 -166
  94. package/lib/migrations.js +383 -383
  95. package/lib/mtls-ca.js +518 -518
  96. package/lib/mtls-engine-default.js +481 -481
  97. package/lib/network-dns.js +632 -632
  98. package/lib/network-heartbeat.js +290 -290
  99. package/lib/network-nts.js +574 -574
  100. package/lib/network-proxy.js +265 -265
  101. package/lib/network-tls.js +328 -328
  102. package/lib/network.js +233 -233
  103. package/lib/notify.js +612 -612
  104. package/lib/ntp-check.js +229 -229
  105. package/lib/numeric-bounds.js +111 -111
  106. package/lib/object-store/azure-blob-bucket-ops.js +349 -349
  107. package/lib/object-store/azure-blob.js +488 -488
  108. package/lib/object-store/gcs-bucket-ops.js +351 -351
  109. package/lib/object-store/gcs.js +519 -519
  110. package/lib/object-store/http-put.js +153 -153
  111. package/lib/object-store/index.js +197 -197
  112. package/lib/object-store/sigv4-bucket-ops.js +1092 -1092
  113. package/lib/object-store/sigv4.js +903 -903
  114. package/lib/observability.js +151 -151
  115. package/lib/otel-export.js +269 -269
  116. package/lib/pagination.js +464 -464
  117. package/lib/parsers/index.js +80 -80
  118. package/lib/parsers/safe-env.js +642 -642
  119. package/lib/parsers/safe-ini.js +292 -292
  120. package/lib/parsers/safe-toml.js +784 -784
  121. package/lib/parsers/safe-xml.js +390 -390
  122. package/lib/parsers/safe-yaml.js +1015 -1015
  123. package/lib/permissions.js +708 -708
  124. package/lib/pqc-agent.js +87 -87
  125. package/lib/pqc-gate.js +279 -279
  126. package/lib/protobuf-encoder.js +190 -190
  127. package/lib/protocol-dispatcher.js +161 -161
  128. package/lib/pubsub-redis.js +167 -167
  129. package/lib/pubsub.js +429 -429
  130. package/lib/queue-local.js +476 -476
  131. package/lib/queue-redis.js +745 -745
  132. package/lib/queue-sqs.js +319 -319
  133. package/lib/queue.js +695 -695
  134. package/lib/redis-client.js +519 -519
  135. package/lib/request-helpers.js +340 -340
  136. package/lib/restore-bundle.js +237 -237
  137. package/lib/restore-rollback.js +259 -259
  138. package/lib/restore.js +409 -409
  139. package/lib/retry.js +376 -376
  140. package/lib/router.js +748 -748
  141. package/lib/safe-async.js +735 -735
  142. package/lib/safe-buffer.js +237 -237
  143. package/lib/safe-json.js +541 -541
  144. package/lib/safe-schema.js +1266 -1266
  145. package/lib/safe-url.js +159 -159
  146. package/lib/scheduler.js +706 -706
  147. package/lib/security-assert.js +373 -373
  148. package/lib/seeders.js +618 -618
  149. package/lib/session.js +535 -478
  150. package/lib/slug.js +269 -269
  151. package/lib/ssrf-guard.js +401 -401
  152. package/lib/static.js +7 -5
  153. package/lib/storage.js +471 -471
  154. package/lib/subject.js +281 -281
  155. package/lib/template.js +791 -791
  156. package/lib/testing.js +798 -798
  157. package/lib/time.js +310 -310
  158. package/lib/totp.js +302 -302
  159. package/lib/tracing.js +494 -494
  160. package/lib/uuid.js +132 -132
  161. package/lib/validate-opts.js +340 -340
  162. package/lib/vault/index.js +308 -308
  163. package/lib/vault/rotate.js +784 -784
  164. package/lib/vault/wrap.js +296 -296
  165. package/lib/vendor/noble-ciphers.cjs +9 -9
  166. package/lib/webhook.js +595 -595
  167. package/lib/websocket.js +1048 -1048
  168. package/package.json +77 -77
  169. package/sbom.cyclonedx.json +7 -7
@@ -1,385 +1,385 @@
1
- "use strict";
2
- /**
3
- * app-shutdown — graceful-shutdown orchestrator.
4
- *
5
- * SIGTERM is the contract between Kubernetes / systemd / docker stop
6
- * and the framework. Production rolling restarts depend on the
7
- * server draining cleanly: stop accepting new traffic, finish in-
8
- * flight requests, drain jobs, close DB, release the cluster lease.
9
- * Without orchestration each subsystem's shutdown races every other
10
- * subsystem's; the result is dropped requests, half-completed jobs,
11
- * stuck cluster leases that block the next pod from acquiring.
12
- *
13
- * This module ships a phase-ordered orchestrator. Each phase is
14
- * named, time-bounded, and best-effort — a phase failure logs an
15
- * issue but doesn't block subsequent phases (we still want to close
16
- * the DB and release the lease even if jobs draining timed out).
17
- *
18
- * Standard phase order:
19
- *
20
- * 1. beforeStop operator hook (run before anything else)
21
- * 2. mark-draining health.markShuttingDown() so /readyz → 503
22
- * and the LB starts draining the pod
23
- * 3. stop-accepting flip the orchestrator's `draining` flag —
24
- * middleware (orchestrator.middleware())
25
- * refuses new requests with 503
26
- * 4. drain-in-flight wait for the in-flight counter to reach 0
27
- * (tracked via the same middleware) up to
28
- * phaseTimeoutMs
29
- * 5. afterDrain operator hook (run after in-flight drained)
30
- * 6. scheduler scheduler.stop() if registered
31
- * 7. jobs jobs.shutdown() / queue.shutdown() — let
32
- * current handlers finish, refuse new lease
33
- * 8. websockets router.closeWebSockets() if HTTP server
34
- * 9. http-server server.close() — waits for keepalive
35
- * connections to drain
36
- * 10. cluster cluster.shutdown() — release lease cleanly
37
- * so the next pod can acquire it without
38
- * waiting out the lease TTL
39
- * 11. db db.close() — flushes encrypted-at-rest
40
- * snapshot, closes SQLite handle
41
- * 12. external-db externalDb.shutdown() — drain pool
42
- *
43
- * Custom phases can be added via opts.phases; each entry is
44
- * { name, run: async fn, timeoutMs? }. The orchestrator runs them
45
- * in array order. The standard phase set above is added by
46
- * createApp via the components map; standalone callers build their
47
- * own.
48
- *
49
- * var orchestrator = b.appShutdown.create({
50
- * graceMs: 30000,
51
- * phases: [
52
- * { name: "beforeStop", run: async function () { ... } },
53
- * { name: "drain-in-flight", run: orchestrator.waitInFlight, timeoutMs: 10000 },
54
- * { name: "db", run: function () { db.close(); } },
55
- * ],
56
- * installSignalHandlers: true, // SIGTERM + SIGINT auto-call shutdown
57
- * });
58
- *
59
- * var result = await orchestrator.shutdown();
60
- * // → { ok, phases: [{ name, ms, ok, error? }, ...], totalMs, draining }
61
- *
62
- * // Mounted as middleware to refuse new requests during drain +
63
- * // track in-flight count.
64
- * router.use(orchestrator.middleware());
65
- *
66
- * orchestrator.draining(); // true once shutdown() has been called
67
- * orchestrator.inFlight(); // current in-flight count
68
- *
69
- * Idempotency: shutdown() is idempotent. Calling it twice returns
70
- * the same Promise. Signal handlers fire it via `installSignalHandlers`
71
- * so SIGTERM + SIGINT both route through the same orchestration.
72
- *
73
- * Per-phase timeouts: each phase has a budget. If a phase doesn't
74
- * complete within timeoutMs it's marked failed and the orchestrator
75
- * moves to the next phase. Default = remaining grace divided by
76
- * remaining phases (so a slow phase doesn't starve later ones).
77
- *
78
- * Tracing integration: when b.tracing has an active registry, each
79
- * phase runs inside a span named "shutdown.<phase>" so operators see
80
- * which phase took how long in their tracing exporter.
81
- */
82
-
83
- var safeAsync = require("./safe-async");
84
- var nb = require("./numeric-bounds");
85
- var tracing = null;
86
- try { tracing = require("./tracing"); } catch (_e) { /* tracing optional */ }
87
- var { defineClass } = require("./framework-error");
88
- var { boot } = require("./log");
89
- var C = require("./constants");
90
-
91
- var AppShutdownError = defineClass("AppShutdownError", { alwaysPermanent: true });
92
- var log = boot("app-shutdown");
93
-
94
- var DEFAULT_GRACE_MS = C.TIME.seconds(30);
95
-
96
- function create(opts) {
97
- opts = opts || {};
98
- nb.requirePositiveFiniteIntIfPresent(opts.graceMs,
99
- "app-shutdown.create: opts.graceMs", AppShutdownError, "app-shutdown/bad-grace-ms");
100
- var graceMs = opts.graceMs !== undefined ? opts.graceMs : DEFAULT_GRACE_MS;
101
- var phases = Array.isArray(opts.phases) ? opts.phases.slice() : [];
102
- var installSignalHandlers = !!opts.installSignalHandlers;
103
- for (var i = 0; i < phases.length; i++) {
104
- if (!phases[i] || typeof phases[i].name !== "string" || typeof phases[i].run !== "function") {
105
- throw new AppShutdownError("app-shutdown/bad-phase",
106
- "phases[" + i + "] must be { name: string, run: function, timeoutMs?: number }");
107
- }
108
- }
109
-
110
- var draining = false;
111
- var inFlightCount = 0;
112
- var inFlightWaiters = [];
113
- var shutdownPromise = null;
114
- var startTime = null;
115
- var signalsInstalled = false;
116
- var signalHandlers = {};
117
-
118
- function _drainComplete() {
119
- var pending = inFlightWaiters;
120
- inFlightWaiters = [];
121
- for (var i = 0; i < pending.length; i++) pending[i]();
122
- }
123
-
124
- function _trackResEnd(res) {
125
- var origEnd = res.end;
126
- res.end = function () {
127
- try { return origEnd.apply(res, arguments); }
128
- finally {
129
- inFlightCount--;
130
- if (inFlightCount === 0 && draining && inFlightWaiters.length > 0) {
131
- _drainComplete();
132
- }
133
- }
134
- };
135
- }
136
-
137
- function middleware() {
138
- return function shutdownGuard(req, res, next) {
139
- if (draining) {
140
- // Refuse new requests with 503 once the orchestrator has
141
- // started shutting down. Cache-Control: no-store so probes
142
- // don't get a stale 503 served from a CDN.
143
- if (typeof res.writeHead === "function") {
144
- var body = JSON.stringify({ error: "service-shutting-down" });
145
- res.writeHead(503, {
146
- "Content-Type": "application/json; charset=utf-8",
147
- "Content-Length": Buffer.byteLength(body),
148
- "Cache-Control": "no-store",
149
- "Connection": "close",
150
- });
151
- res.end(body);
152
- }
153
- return;
154
- }
155
- inFlightCount++;
156
- _trackResEnd(res);
157
- return next();
158
- };
159
- }
160
-
161
- // Wait for inFlightCount to hit 0. Resolves immediately if already 0.
162
- // Caller-supplied timeout via the phase wrapper.
163
- function waitInFlight() {
164
- if (inFlightCount === 0) return Promise.resolve();
165
- return new Promise(function (resolve) { inFlightWaiters.push(resolve); });
166
- }
167
-
168
- // Run a single phase with a budget. Returns { name, ms, ok, error? }.
169
- async function _runPhase(phase, budgetMs, span) {
170
- var phaseStart = Date.now();
171
- var result = { name: phase.name, ms: 0, ok: true };
172
- var timeoutMs = typeof phase.timeoutMs === "number" && phase.timeoutMs > 0
173
- ? Math.min(phase.timeoutMs, budgetMs) : budgetMs;
174
- try {
175
- await safeAsync.withTimeout(
176
- Promise.resolve().then(function () { return phase.run(); }),
177
- timeoutMs,
178
- { name: "shutdown." + phase.name }
179
- );
180
- } catch (e) {
181
- result.ok = false;
182
- result.error = (e && e.message) || String(e);
183
- log.error("shutdown phase '" + phase.name + "' failed: " + result.error);
184
- }
185
- result.ms = Date.now() - phaseStart;
186
- if (span && typeof span.setAttribute === "function") {
187
- span.setAttribute("shutdown.phase.ok", result.ok);
188
- span.setAttribute("shutdown.phase.ms", result.ms);
189
- }
190
- return result;
191
- }
192
-
193
- function shutdown() {
194
- if (shutdownPromise) return shutdownPromise;
195
- draining = true;
196
- startTime = Date.now();
197
- shutdownPromise = (async function () {
198
- var phaseResults = [];
199
- var remainingPhases = phases.length;
200
- for (var i = 0; i < phases.length; i++) {
201
- var elapsed = Date.now() - startTime;
202
- var remainingMs = Math.max(0, graceMs - elapsed);
203
- var perPhaseBudget = remainingPhases > 0 ? Math.floor(remainingMs / remainingPhases) : remainingMs;
204
- // Each phase wrapped in a tracing span if a registry is active.
205
- var phaseResult;
206
- if (tracing && typeof tracing.tap === "function") {
207
- phaseResult = await tracing.tap("shutdown." + phases[i].name, null, function (s) {
208
- return _runPhase(phases[i], perPhaseBudget, s);
209
- });
210
- } else {
211
- phaseResult = await _runPhase(phases[i], perPhaseBudget, null);
212
- }
213
- phaseResults.push(phaseResult);
214
- remainingPhases--;
215
- }
216
- // Allow any straggling in-flight resolvers to drop refs.
217
- _drainComplete();
218
- var totalMs = Date.now() - startTime;
219
- var allOk = phaseResults.every(function (p) { return p.ok; });
220
- log("shutdown complete in " + totalMs + "ms (" +
221
- phaseResults.filter(function (p) { return p.ok; }).length + "/" +
222
- phaseResults.length + " phases ok)");
223
- return { ok: allOk, phases: phaseResults, totalMs: totalMs, draining: true };
224
- })();
225
- return shutdownPromise;
226
- }
227
-
228
- function _signalCallback(sig) {
229
- return function () {
230
- log("received " + sig + " — initiating graceful shutdown");
231
- shutdown().then(function (result) {
232
- if (process.exitCode === undefined || process.exitCode === 0) {
233
- process.exitCode = result.ok ? 0 : 1;
234
- }
235
- }).catch(function (e) {
236
- log.error("shutdown threw unexpectedly: " + ((e && e.message) || String(e)));
237
- process.exitCode = 1;
238
- });
239
- };
240
- }
241
-
242
- function installSignals() {
243
- if (signalsInstalled) return;
244
- signalsInstalled = true;
245
- signalHandlers.SIGTERM = _signalCallback("SIGTERM");
246
- signalHandlers.SIGINT = _signalCallback("SIGINT");
247
- process.on("SIGTERM", signalHandlers.SIGTERM);
248
- process.on("SIGINT", signalHandlers.SIGINT);
249
- }
250
-
251
- function uninstallSignals() {
252
- if (!signalsInstalled) return;
253
- process.removeListener("SIGTERM", signalHandlers.SIGTERM);
254
- process.removeListener("SIGINT", signalHandlers.SIGINT);
255
- signalsInstalled = false;
256
- signalHandlers = {};
257
- }
258
-
259
- if (installSignalHandlers) installSignals();
260
-
261
- return {
262
- shutdown: shutdown,
263
- middleware: middleware,
264
- waitInFlight: waitInFlight,
265
- draining: function () { return draining; },
266
- inFlight: function () { return inFlightCount; },
267
- addPhase: function (phase) {
268
- if (!phase || typeof phase.name !== "string" || typeof phase.run !== "function") {
269
- throw new AppShutdownError("app-shutdown/bad-phase",
270
- "addPhase requires { name: string, run: function, timeoutMs?: number }");
271
- }
272
- if (shutdownPromise) {
273
- throw new AppShutdownError("app-shutdown/already-started",
274
- "cannot addPhase after shutdown() has started");
275
- }
276
- phases.push(phase);
277
- },
278
- installSignals: installSignals,
279
- uninstallSignals: uninstallSignals,
280
- _resetForTest: function () {
281
- uninstallSignals();
282
- shutdownPromise = null;
283
- draining = false;
284
- inFlightCount = 0;
285
- inFlightWaiters = [];
286
- },
287
- };
288
- }
289
-
290
- // Standard phase builder — given a components map, returns a phases
291
- // array suitable for create({ phases }). Used by createApp; operators
292
- // with custom topology call this directly to get the same ordering
293
- // then prepend / append their own phases.
294
- function standardPhases(components) {
295
- components = components || {};
296
- var phases = [];
297
-
298
- if (components.health && typeof components.health.markShuttingDown === "function") {
299
- phases.push({
300
- name: "mark-draining",
301
- run: function () { components.health.markShuttingDown(); },
302
- timeoutMs: C.TIME.seconds(1),
303
- });
304
- }
305
-
306
- // The drain-in-flight phase needs the orchestrator's own
307
- // waitInFlight; it's added by createApp using addPhase after the
308
- // orchestrator instance exists. This function emits the phases that
309
- // don't need orchestrator references.
310
-
311
- if (components.scheduler && typeof components.scheduler.stop === "function") {
312
- phases.push({
313
- name: "scheduler",
314
- run: function () { return components.scheduler.stop(); },
315
- timeoutMs: C.TIME.seconds(5),
316
- });
317
- }
318
-
319
- if (components.jobs && typeof components.jobs.shutdown === "function") {
320
- phases.push({
321
- name: "jobs",
322
- run: function () { return components.jobs.shutdown({ timeoutMs: C.TIME.seconds(5) }); },
323
- timeoutMs: C.TIME.seconds(8),
324
- });
325
- } else if (components.queue && typeof components.queue.shutdown === "function") {
326
- phases.push({
327
- name: "queue",
328
- run: function () { return components.queue.shutdown({ timeoutMs: C.TIME.seconds(5) }); },
329
- timeoutMs: C.TIME.seconds(8),
330
- });
331
- }
332
-
333
- if (components.router && typeof components.router.closeWebSockets === "function") {
334
- phases.push({
335
- name: "websockets",
336
- run: function () { return components.router.closeWebSockets({ timeoutMs: C.TIME.seconds(3) }); },
337
- timeoutMs: C.TIME.seconds(5),
338
- });
339
- }
340
-
341
- if (components.server && typeof components.server.close === "function") {
342
- phases.push({
343
- name: "http-server",
344
- run: function () {
345
- return new Promise(function (resolve) {
346
- components.server.close(function () { resolve(); });
347
- });
348
- },
349
- timeoutMs: C.TIME.seconds(10),
350
- });
351
- }
352
-
353
- if (components.cluster && typeof components.cluster.shutdown === "function") {
354
- phases.push({
355
- name: "cluster",
356
- run: function () { return components.cluster.shutdown(); },
357
- timeoutMs: C.TIME.seconds(5),
358
- });
359
- }
360
-
361
- if (components.db && typeof components.db.close === "function") {
362
- phases.push({
363
- name: "db",
364
- run: function () { components.db.close(); },
365
- timeoutMs: C.TIME.seconds(5),
366
- });
367
- }
368
-
369
- if (components.externalDb && typeof components.externalDb.shutdown === "function") {
370
- phases.push({
371
- name: "external-db",
372
- run: function () { return components.externalDb.shutdown(); },
373
- timeoutMs: C.TIME.seconds(5),
374
- });
375
- }
376
-
377
- return phases;
378
- }
379
-
380
- module.exports = {
381
- create: create,
382
- standardPhases: standardPhases,
383
- AppShutdownError: AppShutdownError,
384
- DEFAULT_GRACE_MS: DEFAULT_GRACE_MS,
385
- };
1
+ "use strict";
2
+ /**
3
+ * app-shutdown — graceful-shutdown orchestrator.
4
+ *
5
+ * SIGTERM is the contract between Kubernetes / systemd / docker stop
6
+ * and the framework. Production rolling restarts depend on the
7
+ * server draining cleanly: stop accepting new traffic, finish in-
8
+ * flight requests, drain jobs, close DB, release the cluster lease.
9
+ * Without orchestration each subsystem's shutdown races every other
10
+ * subsystem's; the result is dropped requests, half-completed jobs,
11
+ * stuck cluster leases that block the next pod from acquiring.
12
+ *
13
+ * This module ships a phase-ordered orchestrator. Each phase is
14
+ * named, time-bounded, and best-effort — a phase failure logs an
15
+ * issue but doesn't block subsequent phases (we still want to close
16
+ * the DB and release the lease even if jobs draining timed out).
17
+ *
18
+ * Standard phase order:
19
+ *
20
+ * 1. beforeStop operator hook (run before anything else)
21
+ * 2. mark-draining health.markShuttingDown() so /readyz → 503
22
+ * and the LB starts draining the pod
23
+ * 3. stop-accepting flip the orchestrator's `draining` flag —
24
+ * middleware (orchestrator.middleware())
25
+ * refuses new requests with 503
26
+ * 4. drain-in-flight wait for the in-flight counter to reach 0
27
+ * (tracked via the same middleware) up to
28
+ * phaseTimeoutMs
29
+ * 5. afterDrain operator hook (run after in-flight drained)
30
+ * 6. scheduler scheduler.stop() if registered
31
+ * 7. jobs jobs.shutdown() / queue.shutdown() — let
32
+ * current handlers finish, refuse new lease
33
+ * 8. websockets router.closeWebSockets() if HTTP server
34
+ * 9. http-server server.close() — waits for keepalive
35
+ * connections to drain
36
+ * 10. cluster cluster.shutdown() — release lease cleanly
37
+ * so the next pod can acquire it without
38
+ * waiting out the lease TTL
39
+ * 11. db db.close() — flushes encrypted-at-rest
40
+ * snapshot, closes SQLite handle
41
+ * 12. external-db externalDb.shutdown() — drain pool
42
+ *
43
+ * Custom phases can be added via opts.phases; each entry is
44
+ * { name, run: async fn, timeoutMs? }. The orchestrator runs them
45
+ * in array order. The standard phase set above is added by
46
+ * createApp via the components map; standalone callers build their
47
+ * own.
48
+ *
49
+ * var orchestrator = b.appShutdown.create({
50
+ * graceMs: 30000,
51
+ * phases: [
52
+ * { name: "beforeStop", run: async function () { ... } },
53
+ * { name: "drain-in-flight", run: orchestrator.waitInFlight, timeoutMs: 10000 },
54
+ * { name: "db", run: function () { db.close(); } },
55
+ * ],
56
+ * installSignalHandlers: true, // SIGTERM + SIGINT auto-call shutdown
57
+ * });
58
+ *
59
+ * var result = await orchestrator.shutdown();
60
+ * // → { ok, phases: [{ name, ms, ok, error? }, ...], totalMs, draining }
61
+ *
62
+ * // Mounted as middleware to refuse new requests during drain +
63
+ * // track in-flight count.
64
+ * router.use(orchestrator.middleware());
65
+ *
66
+ * orchestrator.draining(); // true once shutdown() has been called
67
+ * orchestrator.inFlight(); // current in-flight count
68
+ *
69
+ * Idempotency: shutdown() is idempotent. Calling it twice returns
70
+ * the same Promise. Signal handlers fire it via `installSignalHandlers`
71
+ * so SIGTERM + SIGINT both route through the same orchestration.
72
+ *
73
+ * Per-phase timeouts: each phase has a budget. If a phase doesn't
74
+ * complete within timeoutMs it's marked failed and the orchestrator
75
+ * moves to the next phase. Default = remaining grace divided by
76
+ * remaining phases (so a slow phase doesn't starve later ones).
77
+ *
78
+ * Tracing integration: when b.tracing has an active registry, each
79
+ * phase runs inside a span named "shutdown.<phase>" so operators see
80
+ * which phase took how long in their tracing exporter.
81
+ */
82
+
83
+ var safeAsync = require("./safe-async");
84
+ var nb = require("./numeric-bounds");
85
+ var tracing = null;
86
+ try { tracing = require("./tracing"); } catch (_e) { /* tracing optional */ }
87
+ var { defineClass } = require("./framework-error");
88
+ var { boot } = require("./log");
89
+ var C = require("./constants");
90
+
91
+ var AppShutdownError = defineClass("AppShutdownError", { alwaysPermanent: true });
92
+ var log = boot("app-shutdown");
93
+
94
+ var DEFAULT_GRACE_MS = C.TIME.seconds(30);
95
+
96
+ function create(opts) {
97
+ opts = opts || {};
98
+ nb.requirePositiveFiniteIntIfPresent(opts.graceMs,
99
+ "app-shutdown.create: opts.graceMs", AppShutdownError, "app-shutdown/bad-grace-ms");
100
+ var graceMs = opts.graceMs !== undefined ? opts.graceMs : DEFAULT_GRACE_MS;
101
+ var phases = Array.isArray(opts.phases) ? opts.phases.slice() : [];
102
+ var installSignalHandlers = !!opts.installSignalHandlers;
103
+ for (var i = 0; i < phases.length; i++) {
104
+ if (!phases[i] || typeof phases[i].name !== "string" || typeof phases[i].run !== "function") {
105
+ throw new AppShutdownError("app-shutdown/bad-phase",
106
+ "phases[" + i + "] must be { name: string, run: function, timeoutMs?: number }");
107
+ }
108
+ }
109
+
110
+ var draining = false;
111
+ var inFlightCount = 0;
112
+ var inFlightWaiters = [];
113
+ var shutdownPromise = null;
114
+ var startTime = null;
115
+ var signalsInstalled = false;
116
+ var signalHandlers = {};
117
+
118
+ function _drainComplete() {
119
+ var pending = inFlightWaiters;
120
+ inFlightWaiters = [];
121
+ for (var i = 0; i < pending.length; i++) pending[i]();
122
+ }
123
+
124
+ function _trackResEnd(res) {
125
+ var origEnd = res.end;
126
+ res.end = function () {
127
+ try { return origEnd.apply(res, arguments); }
128
+ finally {
129
+ inFlightCount--;
130
+ if (inFlightCount === 0 && draining && inFlightWaiters.length > 0) {
131
+ _drainComplete();
132
+ }
133
+ }
134
+ };
135
+ }
136
+
137
+ function middleware() {
138
+ return function shutdownGuard(req, res, next) {
139
+ if (draining) {
140
+ // Refuse new requests with 503 once the orchestrator has
141
+ // started shutting down. Cache-Control: no-store so probes
142
+ // don't get a stale 503 served from a CDN.
143
+ if (typeof res.writeHead === "function") {
144
+ var body = JSON.stringify({ error: "service-shutting-down" });
145
+ res.writeHead(503, {
146
+ "Content-Type": "application/json; charset=utf-8",
147
+ "Content-Length": Buffer.byteLength(body),
148
+ "Cache-Control": "no-store",
149
+ "Connection": "close",
150
+ });
151
+ res.end(body);
152
+ }
153
+ return;
154
+ }
155
+ inFlightCount++;
156
+ _trackResEnd(res);
157
+ return next();
158
+ };
159
+ }
160
+
161
+ // Wait for inFlightCount to hit 0. Resolves immediately if already 0.
162
+ // Caller-supplied timeout via the phase wrapper.
163
+ function waitInFlight() {
164
+ if (inFlightCount === 0) return Promise.resolve();
165
+ return new Promise(function (resolve) { inFlightWaiters.push(resolve); });
166
+ }
167
+
168
+ // Run a single phase with a budget. Returns { name, ms, ok, error? }.
169
+ async function _runPhase(phase, budgetMs, span) {
170
+ var phaseStart = Date.now();
171
+ var result = { name: phase.name, ms: 0, ok: true };
172
+ var timeoutMs = typeof phase.timeoutMs === "number" && phase.timeoutMs > 0
173
+ ? Math.min(phase.timeoutMs, budgetMs) : budgetMs;
174
+ try {
175
+ await safeAsync.withTimeout(
176
+ Promise.resolve().then(function () { return phase.run(); }),
177
+ timeoutMs,
178
+ { name: "shutdown." + phase.name }
179
+ );
180
+ } catch (e) {
181
+ result.ok = false;
182
+ result.error = (e && e.message) || String(e);
183
+ log.error("shutdown phase '" + phase.name + "' failed: " + result.error);
184
+ }
185
+ result.ms = Date.now() - phaseStart;
186
+ if (span && typeof span.setAttribute === "function") {
187
+ span.setAttribute("shutdown.phase.ok", result.ok);
188
+ span.setAttribute("shutdown.phase.ms", result.ms);
189
+ }
190
+ return result;
191
+ }
192
+
193
+ function shutdown() {
194
+ if (shutdownPromise) return shutdownPromise;
195
+ draining = true;
196
+ startTime = Date.now();
197
+ shutdownPromise = (async function () {
198
+ var phaseResults = [];
199
+ var remainingPhases = phases.length;
200
+ for (var i = 0; i < phases.length; i++) {
201
+ var elapsed = Date.now() - startTime;
202
+ var remainingMs = Math.max(0, graceMs - elapsed);
203
+ var perPhaseBudget = remainingPhases > 0 ? Math.floor(remainingMs / remainingPhases) : remainingMs;
204
+ // Each phase wrapped in a tracing span if a registry is active.
205
+ var phaseResult;
206
+ if (tracing && typeof tracing.tap === "function") {
207
+ phaseResult = await tracing.tap("shutdown." + phases[i].name, null, function (s) {
208
+ return _runPhase(phases[i], perPhaseBudget, s);
209
+ });
210
+ } else {
211
+ phaseResult = await _runPhase(phases[i], perPhaseBudget, null);
212
+ }
213
+ phaseResults.push(phaseResult);
214
+ remainingPhases--;
215
+ }
216
+ // Allow any straggling in-flight resolvers to drop refs.
217
+ _drainComplete();
218
+ var totalMs = Date.now() - startTime;
219
+ var allOk = phaseResults.every(function (p) { return p.ok; });
220
+ log("shutdown complete in " + totalMs + "ms (" +
221
+ phaseResults.filter(function (p) { return p.ok; }).length + "/" +
222
+ phaseResults.length + " phases ok)");
223
+ return { ok: allOk, phases: phaseResults, totalMs: totalMs, draining: true };
224
+ })();
225
+ return shutdownPromise;
226
+ }
227
+
228
+ function _signalCallback(sig) {
229
+ return function () {
230
+ log("received " + sig + " — initiating graceful shutdown");
231
+ shutdown().then(function (result) {
232
+ if (process.exitCode === undefined || process.exitCode === 0) {
233
+ process.exitCode = result.ok ? 0 : 1;
234
+ }
235
+ }).catch(function (e) {
236
+ log.error("shutdown threw unexpectedly: " + ((e && e.message) || String(e)));
237
+ process.exitCode = 1;
238
+ });
239
+ };
240
+ }
241
+
242
+ function installSignals() {
243
+ if (signalsInstalled) return;
244
+ signalsInstalled = true;
245
+ signalHandlers.SIGTERM = _signalCallback("SIGTERM");
246
+ signalHandlers.SIGINT = _signalCallback("SIGINT");
247
+ process.on("SIGTERM", signalHandlers.SIGTERM);
248
+ process.on("SIGINT", signalHandlers.SIGINT);
249
+ }
250
+
251
+ function uninstallSignals() {
252
+ if (!signalsInstalled) return;
253
+ process.removeListener("SIGTERM", signalHandlers.SIGTERM);
254
+ process.removeListener("SIGINT", signalHandlers.SIGINT);
255
+ signalsInstalled = false;
256
+ signalHandlers = {};
257
+ }
258
+
259
+ if (installSignalHandlers) installSignals();
260
+
261
+ return {
262
+ shutdown: shutdown,
263
+ middleware: middleware,
264
+ waitInFlight: waitInFlight,
265
+ draining: function () { return draining; },
266
+ inFlight: function () { return inFlightCount; },
267
+ addPhase: function (phase) {
268
+ if (!phase || typeof phase.name !== "string" || typeof phase.run !== "function") {
269
+ throw new AppShutdownError("app-shutdown/bad-phase",
270
+ "addPhase requires { name: string, run: function, timeoutMs?: number }");
271
+ }
272
+ if (shutdownPromise) {
273
+ throw new AppShutdownError("app-shutdown/already-started",
274
+ "cannot addPhase after shutdown() has started");
275
+ }
276
+ phases.push(phase);
277
+ },
278
+ installSignals: installSignals,
279
+ uninstallSignals: uninstallSignals,
280
+ _resetForTest: function () {
281
+ uninstallSignals();
282
+ shutdownPromise = null;
283
+ draining = false;
284
+ inFlightCount = 0;
285
+ inFlightWaiters = [];
286
+ },
287
+ };
288
+ }
289
+
290
+ // Standard phase builder — given a components map, returns a phases
291
+ // array suitable for create({ phases }). Used by createApp; operators
292
+ // with custom topology call this directly to get the same ordering
293
+ // then prepend / append their own phases.
294
+ function standardPhases(components) {
295
+ components = components || {};
296
+ var phases = [];
297
+
298
+ if (components.health && typeof components.health.markShuttingDown === "function") {
299
+ phases.push({
300
+ name: "mark-draining",
301
+ run: function () { components.health.markShuttingDown(); },
302
+ timeoutMs: C.TIME.seconds(1),
303
+ });
304
+ }
305
+
306
+ // The drain-in-flight phase needs the orchestrator's own
307
+ // waitInFlight; it's added by createApp using addPhase after the
308
+ // orchestrator instance exists. This function emits the phases that
309
+ // don't need orchestrator references.
310
+
311
+ if (components.scheduler && typeof components.scheduler.stop === "function") {
312
+ phases.push({
313
+ name: "scheduler",
314
+ run: function () { return components.scheduler.stop(); },
315
+ timeoutMs: C.TIME.seconds(5),
316
+ });
317
+ }
318
+
319
+ if (components.jobs && typeof components.jobs.shutdown === "function") {
320
+ phases.push({
321
+ name: "jobs",
322
+ run: function () { return components.jobs.shutdown({ timeoutMs: C.TIME.seconds(5) }); },
323
+ timeoutMs: C.TIME.seconds(8),
324
+ });
325
+ } else if (components.queue && typeof components.queue.shutdown === "function") {
326
+ phases.push({
327
+ name: "queue",
328
+ run: function () { return components.queue.shutdown({ timeoutMs: C.TIME.seconds(5) }); },
329
+ timeoutMs: C.TIME.seconds(8),
330
+ });
331
+ }
332
+
333
+ if (components.router && typeof components.router.closeWebSockets === "function") {
334
+ phases.push({
335
+ name: "websockets",
336
+ run: function () { return components.router.closeWebSockets({ timeoutMs: C.TIME.seconds(3) }); },
337
+ timeoutMs: C.TIME.seconds(5),
338
+ });
339
+ }
340
+
341
+ if (components.server && typeof components.server.close === "function") {
342
+ phases.push({
343
+ name: "http-server",
344
+ run: function () {
345
+ return new Promise(function (resolve) {
346
+ components.server.close(function () { resolve(); });
347
+ });
348
+ },
349
+ timeoutMs: C.TIME.seconds(10),
350
+ });
351
+ }
352
+
353
+ if (components.cluster && typeof components.cluster.shutdown === "function") {
354
+ phases.push({
355
+ name: "cluster",
356
+ run: function () { return components.cluster.shutdown(); },
357
+ timeoutMs: C.TIME.seconds(5),
358
+ });
359
+ }
360
+
361
+ if (components.db && typeof components.db.close === "function") {
362
+ phases.push({
363
+ name: "db",
364
+ run: function () { components.db.close(); },
365
+ timeoutMs: C.TIME.seconds(5),
366
+ });
367
+ }
368
+
369
+ if (components.externalDb && typeof components.externalDb.shutdown === "function") {
370
+ phases.push({
371
+ name: "external-db",
372
+ run: function () { return components.externalDb.shutdown(); },
373
+ timeoutMs: C.TIME.seconds(5),
374
+ });
375
+ }
376
+
377
+ return phases;
378
+ }
379
+
380
+ module.exports = {
381
+ create: create,
382
+ standardPhases: standardPhases,
383
+ AppShutdownError: AppShutdownError,
384
+ DEFAULT_GRACE_MS: DEFAULT_GRACE_MS,
385
+ };