webspresso 0.0.103 → 0.0.105
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/.agents/AGENTS.md +6 -0
- package/.agents/ARCHITECTURE.md +23 -0
- package/.agents/CACHE.md +147 -0
- package/.agents/CLI.md +1 -1
- package/.agents/EARLY_HINTS.md +120 -0
- package/.agents/HEALTH.md +118 -0
- package/.agents/LIMITS.md +109 -0
- package/.agents/ORM.md +155 -1
- package/.agents/PLUGINS.md +28 -0
- package/.agents/RESILIENCE.md +235 -0
- package/AGENTS.md +6 -0
- package/README.md +2 -2
- package/bin/commands/add-docker.js +6 -6
- package/bin/commands/dev.js +4 -3
- package/bin/commands/new.js +5 -5
- package/bin/commands/openapi.js +1 -1
- package/bin/commands/start.js +1 -1
- package/bin/utils/orm-map-html.js +2 -8
- package/bin/utils/project.js +2 -2
- package/core/auth/hash.js +5 -4
- package/core/auth/jwt.js +6 -57
- package/core/auth/magic-link.js +4 -5
- package/core/auth/manager.js +3 -5
- package/core/auth/oauth.js +45 -30
- package/core/auth/totp.js +5 -16
- package/core/auth/user-agent.js +1 -21
- package/core/cache/byte-size.js +123 -0
- package/core/cache/index.js +21 -0
- package/core/cache/lru.js +477 -0
- package/core/cache/tagged-lru.js +346 -0
- package/core/commands/registry.js +6 -20
- package/core/content/renderer.js +1 -13
- package/core/early-hints/index.js +267 -0
- package/core/errors/domain.js +48 -0
- package/core/errors/http.js +31 -0
- package/core/errors/index.js +10 -0
- package/core/errors/middleware.js +2 -8
- package/core/errors/normalize.js +88 -2
- package/core/events/discovery.js +6 -24
- package/core/events/dispatcher.js +2 -7
- package/core/forms/form-builder.js +1 -9
- package/core/health/index.js +41 -0
- package/core/health/middleware.js +213 -0
- package/core/health/normalize.js +140 -0
- package/core/health/probes.js +203 -0
- package/core/limits/index.js +34 -0
- package/core/limits/middleware.js +317 -0
- package/core/limits/normalize.js +222 -0
- package/core/orm/batch.js +70 -0
- package/core/orm/cache/fingerprint.js +2 -2
- package/core/orm/cache/memory-provider.js +27 -110
- package/core/orm/index.js +76 -8
- package/core/orm/json-fields.js +22 -8
- package/core/orm/model.js +10 -0
- package/core/orm/query-builder.js +63 -9
- package/core/orm/query-filters.js +393 -0
- package/core/orm/repository.js +318 -19
- package/core/orm/schema-helpers.js +8 -10
- package/core/orm/scopes.js +321 -1
- package/core/orm/transaction.js +10 -2
- package/core/orm/utils.js +4 -86
- package/core/queue/adapters/database.js +4 -8
- package/core/queue/manager.js +55 -41
- package/core/resilience/circuit-breaker.js +391 -0
- package/core/resilience/errors.js +63 -0
- package/core/resilience/index.js +53 -0
- package/core/resilience/registry.js +97 -0
- package/core/resilience/retry.js +203 -0
- package/core/schema-cache.js +9 -2
- package/core/shutdown/http-adapter.js +4 -1
- package/core/shutdown/shutdown-manager.js +132 -31
- package/core/utils/array.js +12 -0
- package/core/utils/base64url.js +8 -0
- package/core/utils/crypto.js +191 -0
- package/core/utils/ensure-leading-slash.js +6 -0
- package/core/utils/escape-html.js +7 -0
- package/core/utils/escape-regexp.js +7 -0
- package/core/utils/fetch.js +121 -0
- package/core/utils/fs.js +144 -0
- package/core/utils/get-client-ip.js +6 -0
- package/core/utils/hmac.js +6 -0
- package/core/utils/html.js +72 -0
- package/core/utils/ip.js +86 -0
- package/core/utils/json.js +98 -0
- package/core/utils/object.js +106 -0
- package/core/utils/random.js +9 -0
- package/core/utils/regex.js +77 -0
- package/core/utils/safe-compare.js +3 -0
- package/core/utils/sha256.js +6 -0
- package/core/utils/string.js +87 -0
- package/core/utils/strip-trailing-slash.js +6 -0
- package/core/utils/time.js +96 -0
- package/core/utils/timeout.js +348 -0
- package/core/utils/url.js +106 -0
- package/core/utils/walk.js +7 -0
- package/index.d.ts +627 -2
- package/index.js +158 -0
- package/package.json +1 -2
- package/plugins/admin-panel/auth.js +15 -7
- package/plugins/admin-panel/client/parts/01-state-api-breadcrumb.js +82 -10
- package/plugins/admin-panel/client/parts/05-rich-text-file-helpers.js +4 -2
- package/plugins/admin-panel/client/parts/08-record-list.js +3 -2
- package/plugins/admin-panel/client/parts/10-export-registry.js +6 -0
- package/plugins/admin-panel/core/api-extensions.js +3 -80
- package/plugins/admin-panel/index.js +1 -1
- package/plugins/admin-panel/lib/login-rate-limiter.js +15 -13
- package/plugins/admin-panel/modules/menu.js +1 -1
- package/plugins/api-key/crypto.js +3 -26
- package/plugins/api-key/scopes.js +5 -7
- package/plugins/audit-log/api-handlers.js +8 -7
- package/plugins/audit-log/middleware.js +11 -2
- package/plugins/audit-log/parse.js +3 -3
- package/plugins/basic-auth/index.js +2 -26
- package/plugins/cors.js +2 -2
- package/plugins/csrf/index.js +7 -23
- package/plugins/dashboard/app.js +2 -2
- package/plugins/dashboard/index.js +5 -5
- package/plugins/data-exchange/record-selection.js +2 -5
- package/plugins/email/api-handlers.js +5 -18
- package/plugins/email/auth-bridge.js +3 -2
- package/plugins/file-manager/admin-component.js +3 -1
- package/plugins/file-manager/core.js +34 -4
- package/plugins/health-check.js +2 -1
- package/plugins/index.js +2 -0
- package/plugins/lazy.js +5 -6
- package/plugins/mcp/auth.js +1 -13
- package/plugins/mcp/discovery.js +18 -17
- package/plugins/mcp/index.js +23 -1
- package/plugins/mcp/transports/sse.js +10 -1
- package/plugins/orm-cache-admin/admin-component.js +3 -2
- package/plugins/polar/src/api.js +11 -3
- package/plugins/polar/src/webhooks.js +7 -13
- package/plugins/rate-limit/index.js +3 -1
- package/plugins/recaptcha/helpers.js +1 -7
- package/plugins/recaptcha/verify.js +37 -23
- package/plugins/redirect/index.js +57 -7
- package/plugins/rest-resources/index.js +1 -207
- package/plugins/rls/index.js +170 -0
- package/plugins/schema-explorer/admin-component.js +4 -2
- package/plugins/schema-explorer.js +40 -29
- package/plugins/seo-checker/index.js +5 -2
- package/plugins/site-analytics/tracking.js +21 -18
- package/plugins/sitemap.js +21 -17
- package/plugins/swagger.js +13 -17
- package/plugins/upload/index.js +4 -3
- package/plugins/upload/orphan-pruner.js +4 -3
- package/plugins/webhooks/crypto.js +6 -28
- package/plugins/webhooks/dispatcher.js +14 -9
- package/plugins/webhooks/index.js +6 -0
- package/plugins/webhooks/matcher.js +28 -17
- package/plugins/webhooks/sender.js +40 -13
- package/src/app-context.js +41 -5
- package/src/dev/banner.js +6 -2
- package/src/dev-reload/index.js +47 -6
- package/src/file-router.js +1 -3
- package/src/helpers.js +180 -33
- package/src/modules/module-discovery.js +1 -9
- package/src/pages/page-loader.js +53 -1
- package/src/plugin-manager.js +90 -17
- package/src/server.js +137 -26
- package/src/services/discovery.js +19 -40
- package/src/services/executor.js +86 -25
- package/src/services/memoize.js +3 -25
- package/src/services/registry.js +6 -0
- package/src/template/precompile.js +8 -19
|
@@ -0,0 +1,203 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Webspresso - Zero-Dependency Retry Engine
|
|
5
|
+
* Exponential backoff with jitter and transient error detection to prevent thundering herd spikes.
|
|
6
|
+
* @module core/resilience/retry
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
const { parseDurationMs } = require('../utils/time');
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Standard transient network error codes that benefit from retries
|
|
13
|
+
*/
|
|
14
|
+
const TRANSIENT_NETWORK_CODES = new Set([
|
|
15
|
+
'ECONNRESET',
|
|
16
|
+
'ETIMEDOUT',
|
|
17
|
+
'EAI_AGAIN',
|
|
18
|
+
'ENOTFOUND',
|
|
19
|
+
'ECONNREFUSED',
|
|
20
|
+
'EPIPE',
|
|
21
|
+
'EHOSTUNREACH',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Default predicate determining if an error is transient and safe to retry
|
|
26
|
+
*
|
|
27
|
+
* @param {Error} error
|
|
28
|
+
* @returns {boolean}
|
|
29
|
+
*/
|
|
30
|
+
function isTransientError(error) {
|
|
31
|
+
if (!error) return false;
|
|
32
|
+
|
|
33
|
+
// 1. Check network error code
|
|
34
|
+
if (error.code && TRANSIENT_NETWORK_CODES.has(error.code)) {
|
|
35
|
+
return true;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// 2. Check HTTP status code (if available)
|
|
39
|
+
const status = error.status || error.statusCode || error.response?.status;
|
|
40
|
+
if (typeof status === 'number') {
|
|
41
|
+
// 429 Too Many Requests, 502 Bad Gateway, 503 Service Unavailable, 504 Gateway Timeout
|
|
42
|
+
if (status === 429 || status === 502 || status === 503 || status === 504) {
|
|
43
|
+
return true;
|
|
44
|
+
}
|
|
45
|
+
// Standard 4xx client errors (400, 401, 403, 404, 422) will not succeed on retry
|
|
46
|
+
if (status >= 400 && status < 500) {
|
|
47
|
+
return false;
|
|
48
|
+
}
|
|
49
|
+
// Internal server errors 500
|
|
50
|
+
if (status >= 500) {
|
|
51
|
+
return true;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// 3. Fallback: Check common error message keywords
|
|
56
|
+
const message = error.message || '';
|
|
57
|
+
if (/timeout|connection reset|temporarily unavailable|network error/i.test(message)) {
|
|
58
|
+
return true;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Calculate exponential backoff delay with optional random jitter
|
|
66
|
+
*
|
|
67
|
+
* @param {number} attempt - Current retry attempt (1-based)
|
|
68
|
+
* @param {number} minTimeoutMs - Initial delay in ms
|
|
69
|
+
* @param {number} maxTimeoutMs - Maximum delay cap in ms
|
|
70
|
+
* @param {number} factor - Backoff factor (e.g. 2)
|
|
71
|
+
* @param {boolean} jitter - Whether to apply full jitter
|
|
72
|
+
* @returns {number} Delay in milliseconds
|
|
73
|
+
*/
|
|
74
|
+
function calculateBackoffDelay(attempt, minTimeoutMs, maxTimeoutMs, factor, jitter) {
|
|
75
|
+
const exponential = minTimeoutMs * Math.pow(factor, attempt - 1);
|
|
76
|
+
const capped = Math.min(maxTimeoutMs, exponential);
|
|
77
|
+
|
|
78
|
+
if (!jitter) {
|
|
79
|
+
return Math.floor(capped);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// Full jitter: uniformly distributed between 0 and capped delay
|
|
83
|
+
return Math.floor(Math.random() * capped);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Sleep helper respecting AbortSignal
|
|
88
|
+
* @private
|
|
89
|
+
*/
|
|
90
|
+
function sleep(ms, signal) {
|
|
91
|
+
return new Promise((resolve, reject) => {
|
|
92
|
+
if (signal?.aborted) {
|
|
93
|
+
return reject(signal.reason || new Error('Aborted'));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
let timer = null;
|
|
97
|
+
const onAbort = () => {
|
|
98
|
+
if (timer) clearTimeout(timer);
|
|
99
|
+
reject(signal.reason || new Error('Aborted'));
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
if (signal) {
|
|
103
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
timer = setTimeout(() => {
|
|
107
|
+
if (signal) signal.removeEventListener('abort', onAbort);
|
|
108
|
+
resolve();
|
|
109
|
+
}, ms);
|
|
110
|
+
|
|
111
|
+
if (typeof timer?.unref === 'function') {
|
|
112
|
+
timer.unref();
|
|
113
|
+
}
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* @typedef {Object} RetryOptions
|
|
119
|
+
* @property {number} [retries=3] - Maximum retry attempts (0 = no retry)
|
|
120
|
+
* @property {number|string} [delay=100] - Initial delay in ms or duration string
|
|
121
|
+
* @property {number|string} [minTimeout=100] - Alias for delay
|
|
122
|
+
* @property {number|string} [maxTimeout=10000] - Max backoff delay cap in ms or duration string
|
|
123
|
+
* @property {number} [factor=2] - Exponential multiplier
|
|
124
|
+
* @property {boolean} [jitter=true] - Whether to apply random jitter
|
|
125
|
+
* @property {function(Error, number): boolean} [shouldRetry] - Error classifier predicate
|
|
126
|
+
* @property {function({ attempt: number, error: Error, delayMs: number }): void} [onRetry] - Notification callback
|
|
127
|
+
* @property {AbortSignal} [signal] - Optional abort signal
|
|
128
|
+
*/
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Execute an async operation with automatic exponential backoff retries.
|
|
132
|
+
*
|
|
133
|
+
* @param {function(number): Promise<*>} asyncFn - Async function to execute (receives attempt index)
|
|
134
|
+
* @param {RetryOptions} [options]
|
|
135
|
+
* @returns {Promise<*>}
|
|
136
|
+
*/
|
|
137
|
+
async function retry(asyncFn, options = {}) {
|
|
138
|
+
const maxRetries = typeof options.retries === 'number' ? Math.max(0, options.retries) : 3;
|
|
139
|
+
|
|
140
|
+
const minTimeoutMs = options.delay !== undefined
|
|
141
|
+
? parseDurationMs(options.delay, 100)
|
|
142
|
+
: (options.minTimeout !== undefined ? parseDurationMs(options.minTimeout, 100) : 100);
|
|
143
|
+
|
|
144
|
+
const maxTimeoutMs = options.maxTimeout !== undefined
|
|
145
|
+
? parseDurationMs(options.maxTimeout, 10000)
|
|
146
|
+
: 10000;
|
|
147
|
+
|
|
148
|
+
const factor = typeof options.factor === 'number' && options.factor >= 1 ? options.factor : 2;
|
|
149
|
+
const jitter = options.jitter !== false;
|
|
150
|
+
const shouldRetry = typeof options.shouldRetry === 'function' ? options.shouldRetry : isTransientError;
|
|
151
|
+
const onRetry = typeof options.onRetry === 'function' ? options.onRetry : null;
|
|
152
|
+
const signal = options.signal || null;
|
|
153
|
+
|
|
154
|
+
let attempt = 0;
|
|
155
|
+
|
|
156
|
+
while (true) {
|
|
157
|
+
attempt++;
|
|
158
|
+
if (signal?.aborted) {
|
|
159
|
+
throw signal.reason || new Error('Aborted');
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
try {
|
|
163
|
+
return await asyncFn(attempt);
|
|
164
|
+
} catch (err) {
|
|
165
|
+
const isLastAttempt = attempt > maxRetries;
|
|
166
|
+
const canRetry = shouldRetry(err, attempt);
|
|
167
|
+
|
|
168
|
+
if (isLastAttempt || !canRetry || signal?.aborted) {
|
|
169
|
+
throw err;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const delayMs = calculateBackoffDelay(attempt, minTimeoutMs, maxTimeoutMs, factor, jitter);
|
|
173
|
+
|
|
174
|
+
if (onRetry) {
|
|
175
|
+
try {
|
|
176
|
+
onRetry({ attempt, error: err, delayMs });
|
|
177
|
+
} catch {
|
|
178
|
+
// Callback must never break retry loop
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
await sleep(delayMs, signal);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* Wrap an async function with retry behavior
|
|
189
|
+
*
|
|
190
|
+
* @param {Function} asyncFn
|
|
191
|
+
* @param {RetryOptions} [options]
|
|
192
|
+
* @returns {Function}
|
|
193
|
+
*/
|
|
194
|
+
function withRetry(asyncFn, options = {}) {
|
|
195
|
+
return (...args) => retry((attempt) => asyncFn(...args), options);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
module.exports = {
|
|
199
|
+
retry,
|
|
200
|
+
withRetry,
|
|
201
|
+
isTransientError,
|
|
202
|
+
calculateBackoffDelay,
|
|
203
|
+
};
|
package/core/schema-cache.js
CHANGED
|
@@ -1,10 +1,17 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
1
3
|
/**
|
|
2
4
|
* Schema Cache
|
|
3
|
-
* Caches compiled Zod schemas per file path
|
|
5
|
+
* Caches compiled Zod schemas per file path using memory-bounded LRU eviction
|
|
4
6
|
* @module core/schema-cache
|
|
5
7
|
*/
|
|
6
8
|
|
|
7
|
-
const
|
|
9
|
+
const { createLruCache } = require('./cache');
|
|
10
|
+
|
|
11
|
+
// 2,000 schemas capacity protects against OOM in dynamic routing/JIT compilation
|
|
12
|
+
const cache = createLruCache({
|
|
13
|
+
maxEntries: 2000,
|
|
14
|
+
});
|
|
8
15
|
|
|
9
16
|
/**
|
|
10
17
|
* Get cached schema for a file path
|
|
@@ -66,6 +66,7 @@ class NodeHttpAdapter {
|
|
|
66
66
|
return new Promise((resolve) => {
|
|
67
67
|
if (!this.server || !this.server.listening) {
|
|
68
68
|
this._closed = true;
|
|
69
|
+
this.destroy();
|
|
69
70
|
return resolve();
|
|
70
71
|
}
|
|
71
72
|
|
|
@@ -73,6 +74,7 @@ class NodeHttpAdapter {
|
|
|
73
74
|
|
|
74
75
|
this.server.close(() => {
|
|
75
76
|
this._closed = true;
|
|
77
|
+
this.destroy();
|
|
76
78
|
resolve();
|
|
77
79
|
});
|
|
78
80
|
});
|
|
@@ -115,13 +117,14 @@ class NodeHttpAdapter {
|
|
|
115
117
|
}
|
|
116
118
|
}
|
|
117
119
|
this.sockets.clear();
|
|
120
|
+
this.destroy();
|
|
118
121
|
}
|
|
119
122
|
|
|
120
123
|
/**
|
|
121
124
|
* Detach all listeners from the server
|
|
122
125
|
*/
|
|
123
126
|
destroy() {
|
|
124
|
-
if (this.server) {
|
|
127
|
+
if (this.server && typeof this.server.removeListener === 'function') {
|
|
125
128
|
this.server.removeListener('connection', this._onConnection);
|
|
126
129
|
this.server.removeListener('secureConnection', this._onSecureConnection);
|
|
127
130
|
}
|
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* @module core/shutdown/shutdown-manager
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
+
const { parseDurationMs } = require('../utils/time');
|
|
9
|
+
|
|
8
10
|
class ShutdownManager {
|
|
9
11
|
/**
|
|
10
12
|
* @param {Object} [options]
|
|
@@ -19,7 +21,7 @@ class ShutdownManager {
|
|
|
19
21
|
this.options = {
|
|
20
22
|
enabled: options.enabled !== false,
|
|
21
23
|
mode: options.mode === 'force' ? 'force' : 'graceful',
|
|
22
|
-
timeout:
|
|
24
|
+
timeout: options.timeout !== undefined ? parseDurationMs(options.timeout, 10_000) : 10_000,
|
|
23
25
|
signals: Array.isArray(options.signals) ? options.signals : ['SIGINT', 'SIGTERM'],
|
|
24
26
|
logger: options.logger === null ? null : (options.logger || console),
|
|
25
27
|
exitOnSignal: options.exitOnSignal !== false,
|
|
@@ -57,8 +59,8 @@ class ShutdownManager {
|
|
|
57
59
|
}
|
|
58
60
|
|
|
59
61
|
set timeout(value) {
|
|
60
|
-
if (
|
|
61
|
-
this.options.timeout = value;
|
|
62
|
+
if (value !== undefined && value !== null) {
|
|
63
|
+
this.options.timeout = parseDurationMs(value, this.options.timeout);
|
|
62
64
|
}
|
|
63
65
|
}
|
|
64
66
|
|
|
@@ -206,18 +208,92 @@ class ShutdownManager {
|
|
|
206
208
|
|
|
207
209
|
this._log('info', `Starting ${modeLabel} shutdown (reason: ${reason})`);
|
|
208
210
|
|
|
209
|
-
|
|
211
|
+
const totalTimeout = isForce ? 0 : Math.max(0, this.options.timeout);
|
|
212
|
+
const startTime = Date.now();
|
|
213
|
+
const deadline = totalTimeout > 0 ? startTime + totalTimeout : 0;
|
|
214
|
+
|
|
215
|
+
const getRemainingTime = () => {
|
|
216
|
+
if (deadline === 0) return 0;
|
|
217
|
+
return Math.max(0, deadline - Date.now());
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
// 1. Run plugin disposers in reverse registration order (terminates SSE streams, WebSockets, devReload clients, and workers)
|
|
221
|
+
if (this._disposers.length > 0) {
|
|
222
|
+
this._log('info', `Disposing ${this._disposers.length} plugins`);
|
|
223
|
+
const reverseDisposers = this._disposers.slice().reverse();
|
|
224
|
+
for (let i = 0; i < reverseDisposers.length; i++) {
|
|
225
|
+
const { name, fn } = reverseDisposers[i];
|
|
226
|
+
const remainingDisposers = reverseDisposers.length - i;
|
|
227
|
+
const remainingMs = getRemainingTime();
|
|
228
|
+
|
|
229
|
+
if (isForce || (deadline > 0 && remainingMs <= 0)) {
|
|
230
|
+
try {
|
|
231
|
+
const res = fn();
|
|
232
|
+
if (res && typeof res.then === 'function') {
|
|
233
|
+
await Promise.race([
|
|
234
|
+
Promise.resolve(res),
|
|
235
|
+
new Promise(r => {
|
|
236
|
+
const t = setTimeout(r, 50);
|
|
237
|
+
if (typeof t.unref === 'function') t.unref();
|
|
238
|
+
})
|
|
239
|
+
]);
|
|
240
|
+
}
|
|
241
|
+
} catch (err) {
|
|
242
|
+
this._log('error', `Error in plugin disposer "${name}":`, err);
|
|
243
|
+
}
|
|
244
|
+
continue;
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
const perDisposerTimeout = Math.min(
|
|
248
|
+
remainingMs,
|
|
249
|
+
Math.max(100, Math.floor(remainingMs / (remainingDisposers + 1)))
|
|
250
|
+
);
|
|
251
|
+
|
|
252
|
+
let timer = null;
|
|
253
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
254
|
+
timer = setTimeout(() => {
|
|
255
|
+
this._log('warn', `Plugin disposer "${name}" timed out after ${perDisposerTimeout}ms`);
|
|
256
|
+
resolve();
|
|
257
|
+
}, perDisposerTimeout);
|
|
258
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
259
|
+
});
|
|
260
|
+
|
|
261
|
+
try {
|
|
262
|
+
await Promise.race([
|
|
263
|
+
Promise.resolve().then(() => fn()),
|
|
264
|
+
timeoutPromise
|
|
265
|
+
]);
|
|
266
|
+
} catch (err) {
|
|
267
|
+
this._log('error', `Error in plugin disposer "${name}":`, err);
|
|
268
|
+
} finally {
|
|
269
|
+
if (timer) clearTimeout(timer);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// 2. Close HTTP server adapters (gracefully drain in-flight HTTP requests)
|
|
210
275
|
if (this._adapters.length > 0) {
|
|
211
276
|
this._log('info', 'Closing HTTP server');
|
|
212
277
|
|
|
213
278
|
for (const adapter of this._adapters) {
|
|
214
|
-
|
|
215
|
-
|
|
279
|
+
const remainingMs = getRemainingTime();
|
|
280
|
+
|
|
281
|
+
if (isForce || (deadline > 0 && remainingMs <= 0)) {
|
|
282
|
+
// Force mode or deadline expired: immediately forceClose
|
|
216
283
|
try {
|
|
217
284
|
if (typeof adapter.forceClose === 'function') {
|
|
218
285
|
adapter.forceClose();
|
|
219
286
|
}
|
|
220
|
-
|
|
287
|
+
const closeRes = adapter.close();
|
|
288
|
+
if (closeRes && typeof closeRes.then === 'function') {
|
|
289
|
+
await Promise.race([
|
|
290
|
+
Promise.resolve(closeRes),
|
|
291
|
+
new Promise(r => {
|
|
292
|
+
const t = setTimeout(r, 100);
|
|
293
|
+
if (typeof t.unref === 'function') t.unref();
|
|
294
|
+
})
|
|
295
|
+
]);
|
|
296
|
+
}
|
|
221
297
|
} catch (err) {
|
|
222
298
|
this._log('error', 'Error force closing adapter:', err);
|
|
223
299
|
}
|
|
@@ -230,15 +306,13 @@ class ShutdownManager {
|
|
|
230
306
|
} catch (e) {}
|
|
231
307
|
|
|
232
308
|
let timer = null;
|
|
233
|
-
let timedOut = false;
|
|
234
|
-
|
|
235
309
|
const closePromise = adapter.close();
|
|
236
310
|
|
|
237
|
-
if (
|
|
311
|
+
if (deadline > 0) {
|
|
312
|
+
const adapterTimeout = getRemainingTime();
|
|
238
313
|
const timeoutPromise = new Promise((resolve) => {
|
|
239
314
|
timer = setTimeout(() => {
|
|
240
|
-
|
|
241
|
-
this._log('warn', `Graceful shutdown timed out after ${this.options.timeout}ms`);
|
|
315
|
+
this._log('warn', `Graceful shutdown timed out with ${adapterTimeout}ms remaining budget`);
|
|
242
316
|
this._log('info', 'Force closing active connections');
|
|
243
317
|
try {
|
|
244
318
|
if (typeof adapter.forceClose === 'function') {
|
|
@@ -248,7 +322,7 @@ class ShutdownManager {
|
|
|
248
322
|
this._log('error', 'Error force closing connections after timeout:', err);
|
|
249
323
|
}
|
|
250
324
|
resolve();
|
|
251
|
-
},
|
|
325
|
+
}, adapterTimeout);
|
|
252
326
|
|
|
253
327
|
if (typeof timer.unref === 'function') {
|
|
254
328
|
timer.unref();
|
|
@@ -264,34 +338,61 @@ class ShutdownManager {
|
|
|
264
338
|
clearTimeout(timer);
|
|
265
339
|
}
|
|
266
340
|
|
|
267
|
-
//
|
|
268
|
-
|
|
341
|
+
// Prevent unhandled rejection without blocking shutdown if timeout won
|
|
342
|
+
closePromise.catch(() => {});
|
|
269
343
|
}
|
|
270
344
|
}
|
|
271
345
|
}
|
|
272
346
|
|
|
273
|
-
//
|
|
347
|
+
// 3. Run application shutdown hooks (app.onShutdown)
|
|
274
348
|
if (this._hooks.length > 0) {
|
|
275
349
|
this._log('info', `Running ${this._hooks.length} shutdown hooks`);
|
|
276
|
-
for (
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
350
|
+
for (let i = 0; i < this._hooks.length; i++) {
|
|
351
|
+
const hook = this._hooks[i];
|
|
352
|
+
const remainingHooks = this._hooks.length - i;
|
|
353
|
+
const remainingMs = getRemainingTime();
|
|
354
|
+
|
|
355
|
+
if (isForce || (deadline > 0 && remainingMs <= 0)) {
|
|
356
|
+
try {
|
|
357
|
+
const res = hook();
|
|
358
|
+
if (res && typeof res.then === 'function') {
|
|
359
|
+
await Promise.race([
|
|
360
|
+
Promise.resolve(res),
|
|
361
|
+
new Promise(r => {
|
|
362
|
+
const t = setTimeout(r, 50);
|
|
363
|
+
if (typeof t.unref === 'function') t.unref();
|
|
364
|
+
})
|
|
365
|
+
]);
|
|
366
|
+
}
|
|
367
|
+
} catch (err) {
|
|
368
|
+
this._log('error', 'Error in shutdown hook:', err);
|
|
369
|
+
}
|
|
370
|
+
continue;
|
|
281
371
|
}
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
372
|
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
373
|
+
const perHookTimeout = Math.min(
|
|
374
|
+
remainingMs,
|
|
375
|
+
Math.max(100, Math.floor(remainingMs / (remainingHooks + 1)))
|
|
376
|
+
);
|
|
377
|
+
|
|
378
|
+
let timer = null;
|
|
379
|
+
const timeoutPromise = new Promise((resolve) => {
|
|
380
|
+
timer = setTimeout(() => {
|
|
381
|
+
this._log('warn', `Shutdown hook timed out after ${perHookTimeout}ms`);
|
|
382
|
+
resolve();
|
|
383
|
+
}, perHookTimeout);
|
|
384
|
+
if (typeof timer.unref === 'function') timer.unref();
|
|
385
|
+
});
|
|
386
|
+
|
|
291
387
|
try {
|
|
292
|
-
await
|
|
388
|
+
await Promise.race([
|
|
389
|
+
Promise.resolve().then(() => hook()),
|
|
390
|
+
timeoutPromise
|
|
391
|
+
]);
|
|
293
392
|
} catch (err) {
|
|
294
|
-
this._log('error',
|
|
393
|
+
this._log('error', 'Error in shutdown hook:', err);
|
|
394
|
+
} finally {
|
|
395
|
+
if (timer) clearTimeout(timer);
|
|
295
396
|
}
|
|
296
397
|
}
|
|
297
398
|
}
|