@morojs/moro 1.8.12 → 1.8.13
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/README.md +4 -2
- package/dist/core/cluster/thread-cluster.d.ts +25 -0
- package/dist/core/cluster/thread-cluster.js +95 -3
- package/dist/core/cluster/thread-cluster.js.map +1 -1
- package/dist/core/config/config-validator.js +15 -0
- package/dist/core/config/config-validator.js.map +1 -1
- package/dist/core/config/index.js +19 -2
- package/dist/core/config/index.js.map +1 -1
- package/dist/core/framework.d.ts +26 -0
- package/dist/core/framework.js +195 -6
- package/dist/core/framework.js.map +1 -1
- package/dist/core/http/http-server.d.ts +17 -0
- package/dist/core/http/http-server.js +21 -1
- package/dist/core/http/http-server.js.map +1 -1
- package/dist/core/http/http2-server.d.ts +13 -0
- package/dist/core/http/http2-server.js +11 -0
- package/dist/core/http/http2-server.js.map +1 -1
- package/dist/core/http/moro-engine-server.d.ts +28 -0
- package/dist/core/http/moro-engine-server.js +115 -11
- package/dist/core/http/moro-engine-server.js.map +1 -1
- package/dist/core/http/utils/body-type.d.ts +12 -0
- package/dist/core/http/utils/body-type.js +70 -0
- package/dist/core/http/utils/body-type.js.map +1 -0
- package/dist/core/http/utils/ssl-config.d.ts +11 -0
- package/dist/core/http/utils/ssl-config.js +3 -0
- package/dist/core/http/utils/ssl-config.js.map +1 -1
- package/dist/core/http/utils/uws-worker-clustering.js +5 -4
- package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
- package/dist/core/http/uws-http-server.d.ts +3 -0
- package/dist/core/http/uws-http-server.js +22 -1
- package/dist/core/http/uws-http-server.js.map +1 -1
- package/dist/core/middleware/built-in/body-parsers/index.d.ts +18 -0
- package/dist/core/middleware/built-in/body-parsers/index.js +41 -0
- package/dist/core/middleware/built-in/body-parsers/index.js.map +1 -1
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.d.ts +32 -8
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js +117 -25
- package/dist/core/middleware/built-in/cache/adapters/cache/redis.js.map +1 -1
- package/dist/core/middleware/built-in/compression/core.js +5 -0
- package/dist/core/middleware/built-in/compression/core.js.map +1 -1
- package/dist/core/middleware/built-in/session/core.d.ts +1 -0
- package/dist/core/middleware/built-in/session/core.js.map +1 -1
- package/dist/core/middleware/built-in/static/core.d.ts +18 -0
- package/dist/core/middleware/built-in/static/core.js +128 -7
- package/dist/core/middleware/built-in/static/core.js.map +1 -1
- package/dist/core/networking/adapters/engine-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/engine-adapter.js +40 -1
- package/dist/core/networking/adapters/engine-adapter.js.map +1 -1
- package/dist/core/networking/adapters/socketio-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/socketio-adapter.js +10 -1
- package/dist/core/networking/adapters/socketio-adapter.js.map +1 -1
- package/dist/core/networking/adapters/uws-adapter.d.ts +2 -2
- package/dist/core/networking/adapters/uws-adapter.js +54 -3
- package/dist/core/networking/adapters/uws-adapter.js.map +1 -1
- package/dist/core/networking/adapters/ws-adapter.d.ts +9 -2
- package/dist/core/networking/adapters/ws-adapter.js +97 -12
- package/dist/core/networking/adapters/ws-adapter.js.map +1 -1
- package/dist/core/networking/websocket-adapter.d.ts +19 -1
- package/dist/core/networking/websocket-adapter.js.map +1 -1
- package/dist/core/routing/index.d.ts +12 -8
- package/dist/core/routing/index.js +7 -2
- package/dist/core/routing/index.js.map +1 -1
- package/dist/core/routing/unified-router.d.ts +46 -8
- package/dist/core/routing/unified-router.js +108 -32
- package/dist/core/routing/unified-router.js.map +1 -1
- package/dist/core/utilities/package-utils.d.ts +7 -0
- package/dist/core/utilities/package-utils.js +2 -0
- package/dist/core/utilities/package-utils.js.map +1 -1
- package/dist/core/workers/worker-manager.js +2 -2
- package/dist/core/workers/worker-manager.js.map +1 -1
- package/dist/index.d.ts +4 -3
- package/dist/index.js +2 -1
- package/dist/index.js.map +1 -1
- package/dist/moro.d.ts +12 -1
- package/dist/moro.js +63 -7
- package/dist/moro.js.map +1 -1
- package/dist/types/cache.d.ts +2 -0
- package/dist/types/cache.js.map +1 -1
- package/dist/types/config.d.ts +9 -0
- package/dist/types/config.js.map +1 -1
- package/dist/types/http.d.ts +6 -0
- package/dist/types/http.js.map +1 -1
- package/dist/types/session.d.ts +1 -0
- package/dist/types/session.js.map +1 -1
- package/package.json +1 -1
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* True when a request body with this Content-Type decodes to a string,
|
|
3
|
+
* false when it must stay a Buffer.
|
|
4
|
+
*
|
|
5
|
+
* Rule: a missing Content-Type keeps the historical string behaviour;
|
|
6
|
+
* `text/*` and anything declaring a `charset` are text; `application/*` is
|
|
7
|
+
* text for the JSON/XML/JS/YAML family (including `+json`-style suffixes);
|
|
8
|
+
* every other type (`application/octet-stream`, `image/*`, `audio/*`,
|
|
9
|
+
* `video/*`, `font/*`, `application/pdf`, `application/zip`, protobuf,
|
|
10
|
+
* msgpack, ...) is binary.
|
|
11
|
+
*/
|
|
12
|
+
export declare function bodyIsText(contentType: string | undefined): boolean;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// Request-body text/binary classification, shared by the Node, uWS and native
|
|
2
|
+
// engine servers so `req.body` has the same shape on every backend.
|
|
3
|
+
//
|
|
4
|
+
// JSON, urlencoded and multipart bodies are parsed into objects upstream of
|
|
5
|
+
// this. For everything else the question is whether decoding the bytes as
|
|
6
|
+
// UTF-8 is lossless: a text body arriving as a Buffer is one toString() away
|
|
7
|
+
// from what the handler wanted, but a binary body decoded to a string is
|
|
8
|
+
// corrupted for good (every invalid sequence becomes U+FFFD), and there is no
|
|
9
|
+
// other way to reach the bytes. So the default for an unknown type is Buffer.
|
|
10
|
+
/** application/* subtypes that are text on the wire */
|
|
11
|
+
const TEXT_APPLICATION_SUBTYPES = new Set([
|
|
12
|
+
'json',
|
|
13
|
+
'xml',
|
|
14
|
+
'javascript',
|
|
15
|
+
'ecmascript',
|
|
16
|
+
'x-javascript',
|
|
17
|
+
'x-www-form-urlencoded',
|
|
18
|
+
'graphql',
|
|
19
|
+
'sql',
|
|
20
|
+
'yaml',
|
|
21
|
+
'x-yaml',
|
|
22
|
+
'toml',
|
|
23
|
+
'csv',
|
|
24
|
+
'ndjson',
|
|
25
|
+
'x-ndjson',
|
|
26
|
+
'jsonl',
|
|
27
|
+
'x-sh',
|
|
28
|
+
'xhtml',
|
|
29
|
+
'ld+json',
|
|
30
|
+
'problem+json',
|
|
31
|
+
'soap+xml',
|
|
32
|
+
]);
|
|
33
|
+
/** Structured-syntax suffixes (RFC 6838) that are always text */
|
|
34
|
+
const TEXT_SUFFIXES = ['+json', '+xml', '+yaml', '+toml'];
|
|
35
|
+
/**
|
|
36
|
+
* True when a request body with this Content-Type decodes to a string,
|
|
37
|
+
* false when it must stay a Buffer.
|
|
38
|
+
*
|
|
39
|
+
* Rule: a missing Content-Type keeps the historical string behaviour;
|
|
40
|
+
* `text/*` and anything declaring a `charset` are text; `application/*` is
|
|
41
|
+
* text for the JSON/XML/JS/YAML family (including `+json`-style suffixes);
|
|
42
|
+
* every other type (`application/octet-stream`, `image/*`, `audio/*`,
|
|
43
|
+
* `video/*`, `font/*`, `application/pdf`, `application/zip`, protobuf,
|
|
44
|
+
* msgpack, ...) is binary.
|
|
45
|
+
*/
|
|
46
|
+
export function bodyIsText(contentType) {
|
|
47
|
+
if (!contentType)
|
|
48
|
+
return true;
|
|
49
|
+
const semi = contentType.indexOf(';');
|
|
50
|
+
const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();
|
|
51
|
+
if (mime === '')
|
|
52
|
+
return true;
|
|
53
|
+
if (mime.startsWith('text/'))
|
|
54
|
+
return true;
|
|
55
|
+
if (semi !== -1 && /;\s*charset=/i.test(contentType))
|
|
56
|
+
return true;
|
|
57
|
+
if (mime.startsWith('application/')) {
|
|
58
|
+
const subtype = mime.slice('application/'.length);
|
|
59
|
+
if (TEXT_APPLICATION_SUBTYPES.has(subtype))
|
|
60
|
+
return true;
|
|
61
|
+
for (const suffix of TEXT_SUFFIXES) {
|
|
62
|
+
if (subtype.endsWith(suffix))
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
// message/*, model/*, image/*, audio/*, video/*, font/*, ...
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
//# sourceMappingURL=body-type.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"body-type.js","sourceRoot":"","sources":["../../../../src/core/http/utils/body-type.ts"],"names":[],"mappings":"AAAA,8EAA8E;AAC9E,oEAAoE;AACpE,EAAE;AACF,4EAA4E;AAC5E,0EAA0E;AAC1E,6EAA6E;AAC7E,yEAAyE;AACzE,8EAA8E;AAC9E,8EAA8E;AAE9E,uDAAuD;AACvD,MAAM,yBAAyB,GAAG,IAAI,GAAG,CAAC;IACxC,MAAM;IACN,KAAK;IACL,YAAY;IACZ,YAAY;IACZ,cAAc;IACd,uBAAuB;IACvB,SAAS;IACT,KAAK;IACL,MAAM;IACN,QAAQ;IACR,MAAM;IACN,KAAK;IACL,QAAQ;IACR,UAAU;IACV,OAAO;IACP,MAAM;IACN,OAAO;IACP,SAAS;IACT,cAAc;IACd,UAAU;CACX,CAAC,CAAC;AAEH,iEAAiE;AACjE,MAAM,aAAa,GAAG,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,CAAC,CAAC;AAE1D;;;;;;;;;;GAUG;AACH,MAAM,UAAU,UAAU,CAAC,WAA+B;IACxD,IAAI,CAAC,WAAW;QAAE,OAAO,IAAI,CAAC;IAC9B,MAAM,IAAI,GAAG,WAAW,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC;IACtC,MAAM,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,WAAW,CAAC,CAAC,CAAC,WAAW,CAAC,KAAK,CAAC,CAAC,EAAE,IAAI,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,WAAW,EAAE,CAAC;IAC3F,IAAI,IAAI,KAAK,EAAE;QAAE,OAAO,IAAI,CAAC;IAC7B,IAAI,IAAI,CAAC,UAAU,CAAC,OAAO,CAAC;QAAE,OAAO,IAAI,CAAC;IAC1C,IAAI,IAAI,KAAK,CAAC,CAAC,IAAI,eAAe,CAAC,IAAI,CAAC,WAAW,CAAC;QAAE,OAAO,IAAI,CAAC;IAClE,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,EAAE,CAAC;QACpC,MAAM,OAAO,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;QAClD,IAAI,yBAAyB,CAAC,GAAG,CAAC,OAAO,CAAC;YAAE,OAAO,IAAI,CAAC;QACxD,KAAK,MAAM,MAAM,IAAI,aAAa,EAAE,CAAC;YACnC,IAAI,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAC;gBAAE,OAAO,IAAI,CAAC;QAC5C,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IACD,6DAA6D;IAC7D,OAAO,KAAK,CAAC;AACf,CAAC","sourcesContent":["// Request-body text/binary classification, shared by the Node, uWS and native\n// engine servers so `req.body` has the same shape on every backend.\n//\n// JSON, urlencoded and multipart bodies are parsed into objects upstream of\n// this. For everything else the question is whether decoding the bytes as\n// UTF-8 is lossless: a text body arriving as a Buffer is one toString() away\n// from what the handler wanted, but a binary body decoded to a string is\n// corrupted for good (every invalid sequence becomes U+FFFD), and there is no\n// other way to reach the bytes. So the default for an unknown type is Buffer.\n\n/** application/* subtypes that are text on the wire */\nconst TEXT_APPLICATION_SUBTYPES = new Set([\n 'json',\n 'xml',\n 'javascript',\n 'ecmascript',\n 'x-javascript',\n 'x-www-form-urlencoded',\n 'graphql',\n 'sql',\n 'yaml',\n 'x-yaml',\n 'toml',\n 'csv',\n 'ndjson',\n 'x-ndjson',\n 'jsonl',\n 'x-sh',\n 'xhtml',\n 'ld+json',\n 'problem+json',\n 'soap+xml',\n]);\n\n/** Structured-syntax suffixes (RFC 6838) that are always text */\nconst TEXT_SUFFIXES = ['+json', '+xml', '+yaml', '+toml'];\n\n/**\n * True when a request body with this Content-Type decodes to a string,\n * false when it must stay a Buffer.\n *\n * Rule: a missing Content-Type keeps the historical string behaviour;\n * `text/*` and anything declaring a `charset` are text; `application/*` is\n * text for the JSON/XML/JS/YAML family (including `+json`-style suffixes);\n * every other type (`application/octet-stream`, `image/*`, `audio/*`,\n * `video/*`, `font/*`, `application/pdf`, `application/zip`, protobuf,\n * msgpack, ...) is binary.\n */\nexport function bodyIsText(contentType: string | undefined): boolean {\n if (!contentType) return true;\n const semi = contentType.indexOf(';');\n const mime = (semi === -1 ? contentType : contentType.slice(0, semi)).trim().toLowerCase();\n if (mime === '') return true;\n if (mime.startsWith('text/')) return true;\n if (semi !== -1 && /;\\s*charset=/i.test(contentType)) return true;\n if (mime.startsWith('application/')) {\n const subtype = mime.slice('application/'.length);\n if (TEXT_APPLICATION_SUBTYPES.has(subtype)) return true;\n for (const suffix of TEXT_SUFFIXES) {\n if (subtype.endsWith(suffix)) return true;\n }\n return false;\n }\n // message/*, model/*, image/*, audio/*, video/*, font/*, ...\n return false;\n}\n"]}
|
|
@@ -14,6 +14,14 @@ export interface SSLConfigInput {
|
|
|
14
14
|
minVersion?: 'TLSv1.2' | 'TLSv1.3';
|
|
15
15
|
requestCert?: boolean;
|
|
16
16
|
rejectUnauthorized?: boolean;
|
|
17
|
+
/**
|
|
18
|
+
* Watch the key/cert (and CA) files and reload the certificate when they
|
|
19
|
+
* change (`app.reloadTLS()` under the hood), the way an ACME client rotates
|
|
20
|
+
* them. File-path shape only. `true` = 1000 ms debounce.
|
|
21
|
+
*/
|
|
22
|
+
watch?: boolean | {
|
|
23
|
+
debounceMs?: number;
|
|
24
|
+
};
|
|
17
25
|
}
|
|
18
26
|
/** Canonical internal SSL config after normalization. */
|
|
19
27
|
export interface NormalizedSSLConfig {
|
|
@@ -65,5 +73,8 @@ export declare function sslForUws(ssl: NormalizedSSLConfig): {
|
|
|
65
73
|
* Project for the native @morojs/engine serve() options.ssl, which accepts
|
|
66
74
|
* BOTH shapes (file paths and inline PEM) and prefers inline. Pass everything
|
|
67
75
|
* through; the engine decides.
|
|
76
|
+
*
|
|
77
|
+
* The engine takes ONE CA per slot (`ca_file_name` / `ca`), so only the first
|
|
78
|
+
* CA of a list reaches it; the Node projection keeps the full list.
|
|
68
79
|
*/
|
|
69
80
|
export declare function sslForEngine(ssl: NormalizedSSLConfig): Record<string, unknown>;
|
|
@@ -88,6 +88,9 @@ export function sslForUws(ssl) {
|
|
|
88
88
|
* Project for the native @morojs/engine serve() options.ssl, which accepts
|
|
89
89
|
* BOTH shapes (file paths and inline PEM) and prefers inline. Pass everything
|
|
90
90
|
* through; the engine decides.
|
|
91
|
+
*
|
|
92
|
+
* The engine takes ONE CA per slot (`ca_file_name` / `ca`), so only the first
|
|
93
|
+
* CA of a list reaches it; the Node projection keeps the full list.
|
|
91
94
|
*/
|
|
92
95
|
export function sslForEngine(ssl) {
|
|
93
96
|
const out = {};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ssl-config.js","sourceRoot":"","sources":["../../../../src/core/http/utils/ssl-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AAoClC,MAAM,OAAO,GAAG,CAAI,CAAsB,EAAmB,EAAE,CAC7D,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAE3D;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAAiC,EACjC,YAAoC,EACpC,MAAmB;IAEnB,IAAI,SAAS,IAAI,YAAY,EAAE,CAAC;QAC9B,MAAM,EAAE,IAAI,CAAC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AAI,GAAG,CAAC,UAAU;QAAE,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IACpD,IAAI,GAAG,CAAC,WAAW,KAAK,SAAS;QAAE,GAAG,CAAC,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IACrE,IAAI,GAAG,CAAC,kBAAkB,KAAK,SAAS;QAAE,GAAG,CAAC,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;IAC1F,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Unified SSL/TLS configuration.\n *\n * MoroJS historically carried TWO incompatible SSL shapes:\n * - `config.server.ssl` = uWS-style file paths { key_file_name, cert_file_name, passphrase }\n * - `options.https` = node-style buffers { key, cert, ca }\n * and each reached only one runtime (uWS / http2 respectively). This module\n * normalizes both into ONE internal shape and projects it back out for each\n * of the four servers (Node https, uWS SSLApp, HTTP/2, the native engine), so\n * a single `server.ssl` config flows everywhere.\n */\nimport { readFileSync } from 'fs';\nimport type { MoroLogger } from '../../logger/index.js';\n\n/** Raw, un-normalized SSL config as a user may supply it (either shape). */\nexport interface SSLConfigInput {\n // File-path shape (uWS-style; also accepted node-style keyFile/certFile)\n key_file_name?: string;\n cert_file_name?: string;\n ca_file_name?: string | string[];\n keyFile?: string;\n certFile?: string;\n caFile?: string | string[];\n // Inline shape (node-style)\n key?: string | Buffer;\n cert?: string | Buffer;\n ca?: string | Buffer | Array<string | Buffer>;\n passphrase?: string;\n minVersion?: 'TLSv1.2' | 'TLSv1.3';\n requestCert?: boolean;\n rejectUnauthorized?: boolean;\n}\n\n/** Canonical internal SSL config after normalization. */\nexport interface NormalizedSSLConfig {\n keyFile?: string | undefined;\n certFile?: string | undefined;\n caFile?: string[] | undefined;\n key?: string | Buffer | undefined;\n cert?: string | Buffer | undefined;\n ca?: Array<string | Buffer> | undefined;\n passphrase?: string | undefined;\n minVersion?: 'TLSv1.2' | 'TLSv1.3' | undefined;\n requestCert?: boolean | undefined;\n rejectUnauthorized?: boolean | undefined;\n}\n\nconst toArray = <T>(v: T | T[] | undefined): T[] | undefined =>\n v === undefined ? undefined : Array.isArray(v) ? v : [v];\n\n/**\n * Normalize the two historical SSL shapes into one. `serverSsl`\n * (config.server.ssl) wins over `optionsHttps` (options.https) when both are\n * present, matching the pre-existing precedence in framework.ts. Returns null\n * when neither carries any key/cert material (TLS simply off).\n */\nexport function normalizeSSLConfig(\n serverSsl?: SSLConfigInput | null,\n optionsHttps?: SSLConfigInput | null,\n logger?: MoroLogger\n): NormalizedSSLConfig | null {\n if (serverSsl && optionsHttps) {\n logger?.warn('Both server.ssl and options.https are set; server.ssl takes precedence', 'SSL');\n }\n const src = serverSsl ?? optionsHttps;\n if (!src) return null;\n\n const out: NormalizedSSLConfig = {\n keyFile: src.keyFile ?? src.key_file_name,\n certFile: src.certFile ?? src.cert_file_name,\n caFile: toArray(src.caFile ?? src.ca_file_name),\n key: src.key,\n cert: src.cert,\n ca: toArray(src.ca),\n passphrase: src.passphrase,\n minVersion: src.minVersion,\n requestCert: src.requestCert,\n rejectUnauthorized: src.rejectUnauthorized,\n };\n\n const hasKey = Boolean(out.key || out.keyFile);\n const hasCert = Boolean(out.cert || out.certFile);\n if (!hasKey && !hasCert) return null; // nothing usable -> TLS off\n return out;\n}\n\n/** True when the config actually carries a key+cert (complete TLS material). */\nexport function sslIsComplete(ssl: NormalizedSSLConfig): boolean {\n return Boolean((ssl.key || ssl.keyFile) && (ssl.cert || ssl.certFile));\n}\n\n/**\n * Project for the Node http/https and HTTP/2 servers: node's tls API wants\n * key/cert/ca as strings or Buffers, so any file paths are read here.\n */\nexport function sslForNode(ssl: NormalizedSSLConfig): {\n key: string | Buffer;\n cert: string | Buffer;\n ca?: Array<string | Buffer>;\n passphrase?: string;\n minVersion?: string;\n requestCert?: boolean;\n rejectUnauthorized?: boolean;\n} {\n const key = ssl.key ?? (ssl.keyFile ? readFileSync(ssl.keyFile) : undefined);\n const cert = ssl.cert ?? (ssl.certFile ? readFileSync(ssl.certFile) : undefined);\n const ca = ssl.ca ?? (ssl.caFile ? ssl.caFile.map(p => readFileSync(p)) : undefined);\n if (!key || !cert) {\n throw new Error('sslForNode requires both a key and a certificate');\n }\n return {\n key,\n cert,\n ...(ca && { ca }),\n ...(ssl.passphrase && { passphrase: ssl.passphrase }),\n ...(ssl.minVersion && { minVersion: ssl.minVersion }),\n ...(ssl.requestCert !== undefined && { requestCert: ssl.requestCert }),\n ...(ssl.rejectUnauthorized !== undefined && {\n rejectUnauthorized: ssl.rejectUnauthorized,\n }),\n };\n}\n\n/**\n * Project for uWebSockets.js SSLApp, which requires FILE PATHS (it has no\n * inline-PEM option). Returns null when only inline PEM is available so the\n * caller can log a clear error instead of silently booting plain HTTP.\n */\nexport function sslForUws(ssl: NormalizedSSLConfig): {\n key_file_name: string;\n cert_file_name: string;\n ca_file_name?: string;\n passphrase?: string;\n} | null {\n if (!ssl.keyFile || !ssl.certFile) return null;\n return {\n key_file_name: ssl.keyFile,\n cert_file_name: ssl.certFile,\n ...(ssl.caFile && ssl.caFile[0] && { ca_file_name: ssl.caFile[0] }),\n ...(ssl.passphrase && { passphrase: ssl.passphrase }),\n };\n}\n\n/**\n * Project for the native @morojs/engine serve() options.ssl, which accepts\n * BOTH shapes (file paths and inline PEM) and prefers inline. Pass everything\n * through; the engine decides.\n */\nexport function sslForEngine(ssl: NormalizedSSLConfig): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (ssl.keyFile) out.key_file_name = ssl.keyFile;\n if (ssl.certFile) out.cert_file_name = ssl.certFile;\n if (ssl.caFile && ssl.caFile[0]) out.ca_file_name = ssl.caFile[0];\n if (ssl.key) out.key = ssl.key;\n if (ssl.cert) out.cert = ssl.cert;\n if (ssl.ca && ssl.ca[0]) out.ca = ssl.ca[0];\n if (ssl.passphrase) out.passphrase = ssl.passphrase;\n if (ssl.minVersion) out.minVersion = ssl.minVersion;\n if (ssl.requestCert !== undefined) out.requestCert = ssl.requestCert;\n if (ssl.rejectUnauthorized !== undefined) out.rejectUnauthorized = ssl.rejectUnauthorized;\n return out;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"ssl-config.js","sourceRoot":"","sources":["../../../../src/core/http/utils/ssl-config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,IAAI,CAAC;AA0ClC,MAAM,OAAO,GAAG,CAAI,CAAsB,EAAmB,EAAE,CAC7D,CAAC,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;AAE3D;;;;;GAKG;AACH,MAAM,UAAU,kBAAkB,CAChC,SAAiC,EACjC,YAAoC,EACpC,MAAmB;IAEnB,IAAI,SAAS,IAAI,YAAY,EAAE,CAAC;QAC9B,MAAM,EAAE,IAAI,CAAC,wEAAwE,EAAE,KAAK,CAAC,CAAC;IAChG,CAAC;IACD,MAAM,GAAG,GAAG,SAAS,IAAI,YAAY,CAAC;IACtC,IAAI,CAAC,GAAG;QAAE,OAAO,IAAI,CAAC;IAEtB,MAAM,GAAG,GAAwB;QAC/B,OAAO,EAAE,GAAG,CAAC,OAAO,IAAI,GAAG,CAAC,aAAa;QACzC,QAAQ,EAAE,GAAG,CAAC,QAAQ,IAAI,GAAG,CAAC,cAAc;QAC5C,MAAM,EAAE,OAAO,CAAC,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,YAAY,CAAC;QAC/C,GAAG,EAAE,GAAG,CAAC,GAAG;QACZ,IAAI,EAAE,GAAG,CAAC,IAAI;QACd,EAAE,EAAE,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC;QACnB,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,UAAU,EAAE,GAAG,CAAC,UAAU;QAC1B,WAAW,EAAE,GAAG,CAAC,WAAW;QAC5B,kBAAkB,EAAE,GAAG,CAAC,kB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AC,cAAc,GAAG,GAAG,CAAC,QAAQ,CAAC;IACpD,IAAI,GAAG,CAAC,MAAM,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC,YAAY,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IAClE,IAAI,GAAG,CAAC,GAAG;QAAE,GAAG,CAAC,GAAG,GAAG,GAAG,CAAC,GAAG,CAAC;IAC/B,IAAI,GAAG,CAAC,IAAI;QAAE,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC;IAClC,IAAI,GAAG,CAAC,EAAE,IAAI,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC;QAAE,GAAG,CAAC,EAAE,GAAG,GAAG,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IAC5C,IAAI,GAAG,CAAC,UAAU;QAAE,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IACpD,IAAI,GAAG,CAAC,UAAU;QAAE,GAAG,CAAC,UAAU,GAAG,GAAG,CAAC,UAAU,CAAC;IACpD,IAAI,GAAG,CAAC,WAAW,KAAK,SAAS;QAAE,GAAG,CAAC,WAAW,GAAG,GAAG,CAAC,WAAW,CAAC;IACrE,IAAI,GAAG,CAAC,kBAAkB,KAAK,SAAS;QAAE,GAAG,CAAC,kBAAkB,GAAG,GAAG,CAAC,kBAAkB,CAAC;IAC1F,OAAO,GAAG,CAAC;AACb,CAAC","sourcesContent":["/**\n * Unified SSL/TLS configuration.\n *\n * MoroJS historically carried TWO incompatible SSL shapes:\n * - `config.server.ssl` = uWS-style file paths { key_file_name, cert_file_name, passphrase }\n * - `options.https` = node-style buffers { key, cert, ca }\n * and each reached only one runtime (uWS / http2 respectively). This module\n * normalizes both into ONE internal shape and projects it back out for each\n * of the four servers (Node https, uWS SSLApp, HTTP/2, the native engine), so\n * a single `server.ssl` config flows everywhere.\n */\nimport { readFileSync } from 'fs';\nimport type { MoroLogger } from '../../logger/index.js';\n\n/** Raw, un-normalized SSL config as a user may supply it (either shape). */\nexport interface SSLConfigInput {\n // File-path shape (uWS-style; also accepted node-style keyFile/certFile)\n key_file_name?: string;\n cert_file_name?: string;\n ca_file_name?: string | string[];\n keyFile?: string;\n certFile?: string;\n caFile?: string | string[];\n // Inline shape (node-style)\n key?: string | Buffer;\n cert?: string | Buffer;\n ca?: string | Buffer | Array<string | Buffer>;\n passphrase?: string;\n minVersion?: 'TLSv1.2' | 'TLSv1.3';\n requestCert?: boolean;\n rejectUnauthorized?: boolean;\n /**\n * Watch the key/cert (and CA) files and reload the certificate when they\n * change (`app.reloadTLS()` under the hood), the way an ACME client rotates\n * them. File-path shape only. `true` = 1000 ms debounce.\n */\n watch?: boolean | { debounceMs?: number };\n}\n\n/** Canonical internal SSL config after normalization. */\nexport interface NormalizedSSLConfig {\n keyFile?: string | undefined;\n certFile?: string | undefined;\n caFile?: string[] | undefined;\n key?: string | Buffer | undefined;\n cert?: string | Buffer | undefined;\n ca?: Array<string | Buffer> | undefined;\n passphrase?: string | undefined;\n minVersion?: 'TLSv1.2' | 'TLSv1.3' | undefined;\n requestCert?: boolean | undefined;\n rejectUnauthorized?: boolean | undefined;\n}\n\nconst toArray = <T>(v: T | T[] | undefined): T[] | undefined =>\n v === undefined ? undefined : Array.isArray(v) ? v : [v];\n\n/**\n * Normalize the two historical SSL shapes into one. `serverSsl`\n * (config.server.ssl) wins over `optionsHttps` (options.https) when both are\n * present, matching the pre-existing precedence in framework.ts. Returns null\n * when neither carries any key/cert material (TLS simply off).\n */\nexport function normalizeSSLConfig(\n serverSsl?: SSLConfigInput | null,\n optionsHttps?: SSLConfigInput | null,\n logger?: MoroLogger\n): NormalizedSSLConfig | null {\n if (serverSsl && optionsHttps) {\n logger?.warn('Both server.ssl and options.https are set; server.ssl takes precedence', 'SSL');\n }\n const src = serverSsl ?? optionsHttps;\n if (!src) return null;\n\n const out: NormalizedSSLConfig = {\n keyFile: src.keyFile ?? src.key_file_name,\n certFile: src.certFile ?? src.cert_file_name,\n caFile: toArray(src.caFile ?? src.ca_file_name),\n key: src.key,\n cert: src.cert,\n ca: toArray(src.ca),\n passphrase: src.passphrase,\n minVersion: src.minVersion,\n requestCert: src.requestCert,\n rejectUnauthorized: src.rejectUnauthorized,\n };\n\n const hasKey = Boolean(out.key || out.keyFile);\n const hasCert = Boolean(out.cert || out.certFile);\n if (!hasKey && !hasCert) return null; // nothing usable -> TLS off\n return out;\n}\n\n/** True when the config actually carries a key+cert (complete TLS material). */\nexport function sslIsComplete(ssl: NormalizedSSLConfig): boolean {\n return Boolean((ssl.key || ssl.keyFile) && (ssl.cert || ssl.certFile));\n}\n\n/**\n * Project for the Node http/https and HTTP/2 servers: node's tls API wants\n * key/cert/ca as strings or Buffers, so any file paths are read here.\n */\nexport function sslForNode(ssl: NormalizedSSLConfig): {\n key: string | Buffer;\n cert: string | Buffer;\n ca?: Array<string | Buffer>;\n passphrase?: string;\n minVersion?: string;\n requestCert?: boolean;\n rejectUnauthorized?: boolean;\n} {\n const key = ssl.key ?? (ssl.keyFile ? readFileSync(ssl.keyFile) : undefined);\n const cert = ssl.cert ?? (ssl.certFile ? readFileSync(ssl.certFile) : undefined);\n const ca = ssl.ca ?? (ssl.caFile ? ssl.caFile.map(p => readFileSync(p)) : undefined);\n if (!key || !cert) {\n throw new Error('sslForNode requires both a key and a certificate');\n }\n return {\n key,\n cert,\n ...(ca && { ca }),\n ...(ssl.passphrase && { passphrase: ssl.passphrase }),\n ...(ssl.minVersion && { minVersion: ssl.minVersion }),\n ...(ssl.requestCert !== undefined && { requestCert: ssl.requestCert }),\n ...(ssl.rejectUnauthorized !== undefined && {\n rejectUnauthorized: ssl.rejectUnauthorized,\n }),\n };\n}\n\n/**\n * Project for uWebSockets.js SSLApp, which requires FILE PATHS (it has no\n * inline-PEM option). Returns null when only inline PEM is available so the\n * caller can log a clear error instead of silently booting plain HTTP.\n */\nexport function sslForUws(ssl: NormalizedSSLConfig): {\n key_file_name: string;\n cert_file_name: string;\n ca_file_name?: string;\n passphrase?: string;\n} | null {\n if (!ssl.keyFile || !ssl.certFile) return null;\n return {\n key_file_name: ssl.keyFile,\n cert_file_name: ssl.certFile,\n ...(ssl.caFile && ssl.caFile[0] && { ca_file_name: ssl.caFile[0] }),\n ...(ssl.passphrase && { passphrase: ssl.passphrase }),\n };\n}\n\n/**\n * Project for the native @morojs/engine serve() options.ssl, which accepts\n * BOTH shapes (file paths and inline PEM) and prefers inline. Pass everything\n * through; the engine decides.\n *\n * The engine takes ONE CA per slot (`ca_file_name` / `ca`), so only the first\n * CA of a list reaches it; the Node projection keeps the full list.\n */\nexport function sslForEngine(ssl: NormalizedSSLConfig): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n if (ssl.keyFile) out.key_file_name = ssl.keyFile;\n if (ssl.certFile) out.cert_file_name = ssl.certFile;\n if (ssl.caFile && ssl.caFile[0]) out.ca_file_name = ssl.caFile[0];\n if (ssl.key) out.key = ssl.key;\n if (ssl.cert) out.cert = ssl.cert;\n if (ssl.ca && ssl.ca[0]) out.ca = ssl.ca[0];\n if (ssl.passphrase) out.passphrase = ssl.passphrase;\n if (ssl.minVersion) out.minVersion = ssl.minVersion;\n if (ssl.requestCert !== undefined) out.requestCert = ssl.requestCert;\n if (ssl.rejectUnauthorized !== undefined) out.rejectUnauthorized = ssl.rejectUnauthorized;\n return out;\n}\n"]}
|
|
@@ -10,7 +10,7 @@
|
|
|
10
10
|
import { requireBuiltin } from '../../utilities/builtin.js';
|
|
11
11
|
// worker_threads is loaded on first use (core/utilities/builtin.ts).
|
|
12
12
|
const wt = () => requireBuiltin('worker_threads');
|
|
13
|
-
import
|
|
13
|
+
import { usableCpuCount, usableMemoryBytes } from '../../cluster/thread-cluster.js';
|
|
14
14
|
import { createFrameworkLogger } from '../../logger/index.js';
|
|
15
15
|
import { loadNativeEngine } from '../../utilities/package-utils.js';
|
|
16
16
|
const logger = createFrameworkLogger('UWSClustering');
|
|
@@ -27,10 +27,11 @@ export class UWSWorkerClusterManager {
|
|
|
27
27
|
this.workerCount = this.calculateWorkerCount();
|
|
28
28
|
}
|
|
29
29
|
calculateWorkerCount() {
|
|
30
|
-
|
|
30
|
+
// Container-aware counts (cgroup quota / affinity mask), not the host's
|
|
31
|
+
let workerCount = this.config.workers || usableCpuCount();
|
|
31
32
|
if (workerCount === 'auto') {
|
|
32
|
-
const cpuCount =
|
|
33
|
-
const totalMemoryGB =
|
|
33
|
+
const cpuCount = usableCpuCount();
|
|
34
|
+
const totalMemoryGB = usableMemoryBytes() / (1024 * 1024 * 1024);
|
|
34
35
|
let memoryPerWorkerGB = this.config.memoryPerWorkerGB;
|
|
35
36
|
if (!memoryPerWorkerGB) {
|
|
36
37
|
const headroomGB = 4;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"uws-worker-clustering.js","sourceRoot":"","sources":["../../../../src/core/http/utils/uws-worker-clustering.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,oEAAoE;AACpE,EAAE;AACF,2FAA2F;AAC3F,0FAA0F;AAC1F,wFAAwF;AACxF,8FAA8F;AAC9F,yEAAyE;AACzE,2CAA2C;AAG3C,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D,qEAAqE;AACrE,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,cAAc,CAAkC,gBAAgB,CAAC,CAAC;AACnF,OAAO,EAAE,MAAM,IAAI,CAAC;AACpB,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM,MAAM,GAAG,qBAAqB,CAAC,eAAe,CAAC,CAAC;AActD,MAAM,OAAO,uBAAuB;IAC1B,OAAO,GAAa,EAAE,CAAC;IACvB,WAAW,GAAQ,IAAI,CAAC;IACxB,oBAAoB,GAAQ,IAAI,CAAC;IACjC,GAAG,GAAQ,IAAI,CAAC;IAChB,MAAM,CAAmB;IACzB,WAAW,C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,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,EAAE,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// uWebSockets.js Worker Thread Clustering Implementation\n// Uses worker threads with acceptor pattern for maximum performance\n//\n// NOTE: When terminating, you may see \"uv_loop_close() while having open handles\" warnings\n// from Node.js. This is a known limitation when using uWebSockets.js with worker threads.\n// The uWS C++ addon maintains internal libuv poll handles that cannot be cleanly closed\n// through JavaScript APIs. These warnings are harmless - the process will still exit cleanly.\n// To suppress these warnings, you can run Node.js with: --no-warnings or\n// NODE_NO_WARNINGS=1 environment variable.\n\nimport type { Worker } from 'worker_threads';\nimport { requireBuiltin } from '../../utilities/builtin.js';\n\n// worker_threads is loaded on first use (core/utilities/builtin.ts).\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport os from 'os';\nimport { createFrameworkLogger } from '../../logger/index.js';\nimport { loadNativeEngine } from '../../utilities/package-utils.js';\n\nconst logger = createFrameworkLogger('UWSClustering');\n\nexport interface UWSClusterConfig {\n workers?: number | 'auto';\n memoryPerWorkerGB?: number;\n port: number;\n host?: string;\n ssl?: {\n key_file_name?: string;\n cert_file_name?: string;\n passphrase?: string;\n };\n}\n\nexport class UWSWorkerClusterManager {\n private workers: Worker[] = [];\n private acceptorApp: any = null;\n private acceptorListenSocket: any = null;\n private uws: any = null;\n private config: UWSClusterConfig;\n private workerCount: number;\n private isShuttingDown = false;\n\n constructor(config: UWSClusterConfig) {\n this.config = config;\n this.workerCount = this.calculateWorkerCount();\n }\n\n private calculateWorkerCount(): number {\n let workerCount = this.config.workers || os.cpus().length;\n\n if (workerCount === 'auto') {\n const cpuCount = os.cpus().length;\n const totalMemoryGB = os.totalmem() / (1024 * 1024 * 1024);\n\n let memoryPerWorkerGB = this.config.memoryPerWorkerGB;\n\n if (!memoryPerWorkerGB) {\n const headroomGB = 4;\n memoryPerWorkerGB = Math.max(0.5, Math.floor((totalMemoryGB - headroomGB) / cpuCount));\n }\n\n workerCount = Math.min(cpuCount, Math.floor(totalMemoryGB / memoryPerWorkerGB));\n\n logger.info(\n `Auto-calculated worker count: ${workerCount} (CPU: ${cpuCount}, RAM: ${totalMemoryGB.toFixed(1)}GB, ${memoryPerWorkerGB}GB per worker)`,\n 'WorkerCalculation'\n );\n } else if (typeof workerCount === 'number') {\n logger.info(`Using specified worker count: ${workerCount}`, 'WorkerCalculation');\n }\n\n return workerCount;\n }\n\n async startAcceptorAndWorkers(_appFactory: () => any): Promise<void> {\n if (!wt().isMainThread) {\n throw new Error('startAcceptorAndWorkers can only be called from main thread');\n }\n\n try {\n // Worker clustering uses the uWS-shaped App/SSLApp + SO_REUSEPORT API,\n // so it needs uWebSockets.js specifically (not @morojs/engine).\n const engine = loadNativeEngine({ candidates: ['uWebSockets.js'] });\n if (!engine) {\n throw new Error('uWebSockets.js is not available for uWS worker clustering');\n }\n const uwsModule = engine.module;\n this.uws = uwsModule.default || uwsModule;\n\n // Create acceptor app - must match SSL config of worker apps\n const ssl = this.config.ssl;\n if (ssl && ssl.key_file_name && ssl.cert_file_name) {\n this.acceptorApp = this.uws.SSLApp({\n key_file_name: ssl.key_file_name,\n cert_file_name: ssl.cert_file_name,\n passphrase: ssl.passphrase,\n });\n logger.info('uWebSockets SSL acceptor app created', 'Acceptor');\n } else {\n this.acceptorApp = this.uws.App();\n logger.info('uWebSockets acceptor app created', 'Acceptor');\n }\n\n // Start listening on acceptor\n const port = this.config.port;\n this.acceptorApp.listen(port, (token: any) => {\n if (token) {\n this.acceptorListenSocket = token;\n logger.info(\n `Acceptor listening on port ${port} from thread ${wt().threadId}`,\n 'Acceptor'\n );\n } else {\n throw new Error(`Failed to listen on port ${port} from thread ${wt().threadId}`);\n }\n });\n\n // Spawn workers\n logger.info(`Starting ${this.workerCount} worker threads`, 'Workers');\n\n for (let i = 0; i < this.workerCount; i++) {\n await this.spawnWorker(i);\n }\n\n // Setup graceful shutdown\n this.setupGracefulShutdown();\n } catch (error) {\n logger.error('Failed to start acceptor and workers', 'Startup', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n private async spawnWorker(index: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const scriptPath = process.argv[1];\n if (scriptPath === undefined) {\n reject(new Error('Cannot spawn worker: process.argv[1] (entry script) is unavailable'));\n return;\n }\n const worker = new (wt().Worker)(scriptPath, {\n workerData: {\n isUWSWorker: true,\n workerIndex: index,\n config: this.config,\n },\n argv: process.argv.slice(2),\n env: {\n ...process.env,\n UWS_WORKER_MODE: 'true',\n UWS_WORKER_INDEX: String(index),\n },\n });\n\n let descriptorReceived = false;\n\n worker.on('message', (message: any) => {\n if (message.type === 'descriptor' && message.descriptor) {\n if (!this.acceptorApp) {\n logger.error('Acceptor app not initialized', 'WorkerSpawn');\n reject(new Error('Acceptor app not initialized'));\n return;\n }\n\n try {\n this.acceptorApp.addChildAppDescriptor(message.descriptor);\n descriptorReceived = true;\n logger.info(\n `Worker ${index} (thread ${message.threadId}) registered with acceptor`,\n 'WorkerSpawn'\n );\n resolve();\n } catch (error) {\n logger.error('Failed to add child app descriptor', 'WorkerSpawn', {\n error: error instanceof Error ? error.message : String(error),\n });\n reject(error);\n }\n } else if (message.type === 'error') {\n logger.error(`Worker ${index} initialization error: ${message.error}`, 'WorkerSpawn');\n reject(new Error(message.error));\n }\n });\n\n worker.on('error', (error: Error) => {\n logger.error(`Worker ${index} error`, 'Worker', {\n error: error.message,\n });\n if (!descriptorReceived) {\n reject(error);\n }\n });\n\n worker.on('exit', (code: number) => {\n // Worker threads don't have exitedAfterDisconnect like cluster workers\n // Restart on any non-zero exit code\n if (code !== 0) {\n logger.warn(`Worker ${index} died unexpectedly (code: ${code}). Restarting...`, 'Worker');\n\n // Remove from workers array\n const workerIdx = this.workers.indexOf(worker);\n if (workerIdx > -1) {\n this.workers.splice(workerIdx, 1);\n }\n\n // Restart worker\n this.spawnWorker(index).catch(error => {\n logger.error('Failed to restart worker', 'Worker', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n });\n\n this.workers.push(worker);\n\n // Timeout for descriptor reception\n setTimeout(() => {\n if (!descriptorReceived) {\n logger.error(`Worker ${index} failed to send descriptor within timeout`, 'WorkerSpawn');\n void worker.terminate();\n reject(new Error(`Worker ${index} initialization timeout`));\n }\n }, 10000); // 10 second timeout\n });\n }\n\n private setupGracefulShutdown(): void {\n const gracefulShutdown = async () => {\n if (this.isShuttingDown) return;\n this.isShuttingDown = true;\n\n logger.info('Gracefully shutting down worker cluster...', 'Shutdown');\n\n // Close acceptor listen socket first\n if (this.acceptorListenSocket && this.uws) {\n try {\n this.uws.us_listen_socket_close(this.acceptorListenSocket);\n this.acceptorListenSocket = null;\n logger.info('Acceptor listen socket closed', 'Shutdown');\n } catch (error) {\n logger.error('Error closing acceptor socket', 'Shutdown', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Send shutdown message to all workers and wait for them to close\n const shutdownPromises = this.workers.map((worker, index) => {\n return new Promise<void>(resolve => {\n let workerExited = false;\n\n const timeout = setTimeout(() => {\n if (!workerExited) {\n logger.info(\n `Worker ${index} taking too long to exit, terminating forcefully`,\n 'Shutdown'\n );\n try {\n // Terminate is the last resort for stuck workers\n void worker.terminate();\n } catch {\n logger.error(`Error terminating worker ${index}`, 'Shutdown');\n }\n }\n resolve();\n }, 2000); // Give 2 seconds for graceful exit\n\n worker.once('exit', code => {\n workerExited = true;\n clearTimeout(timeout);\n if (code === 0) {\n logger.info(`Worker ${index} exited cleanly`, 'Shutdown');\n } else if (code === 1) {\n logger.info(`Worker ${index} terminated (exit code ${code})`, 'Shutdown');\n } else {\n logger.warn(`Worker ${index} exited with unexpected code ${code}`, 'Shutdown');\n }\n resolve();\n });\n\n // Send shutdown message\n try {\n worker.postMessage({ type: 'shutdown' });\n } catch {\n logger.error(`Failed to send shutdown message to worker ${index}`, 'Shutdown');\n clearTimeout(timeout);\n try {\n void worker.terminate();\n } catch {\n // Ignore termination errors\n }\n resolve();\n }\n });\n });\n\n await Promise.all(shutdownPromises);\n logger.info('All workers shut down', 'Shutdown');\n\n // Clear acceptor app reference to allow uWebSockets to cleanup\n if (this.acceptorApp) {\n this.acceptorApp = null;\n }\n\n // Give uWebSockets event loop time to fully cleanup before exiting\n await new Promise(resolve => setTimeout(resolve, 200));\n\n logger.info('Shutdown complete', 'Shutdown');\n process.exit(0);\n };\n\n process.on('SIGINT', () => void gracefulShutdown());\n process.on('SIGTERM', () => void gracefulShutdown());\n }\n\n static isUWSWorker(): boolean {\n return !wt().isMainThread && process.env.UWS_WORKER_MODE === 'true';\n }\n\n static async sendDescriptorToAcceptor(app: any): Promise<void> {\n const { isMainThread, parentPort, threadId } = wt();\n if (isMainThread || !parentPort) {\n throw new Error('sendDescriptorToAcceptor can only be called from worker thread');\n }\n\n try {\n const descriptor = app.getDescriptor();\n\n parentPort.postMessage({\n type: 'descriptor',\n descriptor,\n threadId,\n });\n\n logger.info(`Worker thread ${threadId} sent descriptor to acceptor`, 'Worker');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('Failed to send descriptor to acceptor', 'Worker', { error: errorMessage });\n\n if (parentPort) {\n parentPort.postMessage({\n type: 'error',\n error: errorMessage,\n });\n }\n\n throw error;\n }\n }\n\n static setupWorkerShutdownHandler(closeCallback: () => void | Promise<void>): void {\n const { parentPort, threadId } = wt();\n if (!parentPort) {\n return;\n }\n\n parentPort.on('message', (message: any) => {\n void (async () => {\n if (message.type === 'shutdown') {\n logger.info(`Worker thread ${threadId} shutting down...`, 'Worker');\n\n try {\n // Call the close callback and wait if it's async\n const result = closeCallback();\n if (result && typeof result.then === 'function') {\n await result;\n }\n\n // Give uWebSockets event loop time to fully cleanup\n await new Promise(resolve => setTimeout(resolve, 150));\n\n // Close parent port to signal we're ready to exit\n if (parentPort) {\n parentPort.close();\n }\n\n logger.info(`Worker thread ${threadId} cleanup complete`, 'Worker');\n\n // DON'T call process.exit() - let Node.js exit naturally\n // This allows the event loop to properly drain all uWebSockets handles\n // The worker will exit on its own once all handles are closed\n } catch (error) {\n logger.error('Error during worker shutdown', 'Worker', {\n error: error instanceof Error ? error.message : String(error),\n });\n // Still don't force exit - let it drain naturally\n }\n }\n })();\n });\n }\n}\n"]}
|
|
1
|
+
{"version":3,"file":"uws-worker-clustering.js","sourceRoot":"","sources":["../../../../src/core/http/utils/uws-worker-clustering.ts"],"names":[],"mappings":"AAAA,yDAAyD;AACzD,oEAAoE;AACpE,EAAE;AACF,2FAA2F;AAC3F,0FAA0F;AAC1F,wFAAwF;AACxF,8FAA8F;AAC9F,yEAAyE;AACzE,2CAA2C;AAG3C,OAAO,EAAE,cAAc,EAAE,MAAM,4BAA4B,CAAC;AAE5D,qEAAqE;AACrE,MAAM,EAAE,GAAG,GAAG,EAAE,CAAC,cAAc,CAAkC,gBAAgB,CAAC,CAAC;AACnF,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,iCAAiC,CAAC;AACpF,OAAO,EAAE,qBAAqB,EAAE,MAAM,uBAAuB,CAAC;AAC9D,OAAO,EAAE,gBAAgB,EAAE,MAAM,kCAAkC,CAAC;AAEpE,MAAM,MAAM,GAAG,qBAAqB,CAAC,eAAe,CAAC,CAAC;AActD,MAAM,OAAO,uBAAuB;IAC1B,OAAO,GAAa,EAAE,CAAC;IACvB,WAAW,GAAQ,IAAI,CAAC;IACxB,oBAAoB,GAAQ,IAAI,CAAC;IACjC,GAAG,GAAQ,IAAI,CAAC;IAChB,MAAM,CAAmB;IACzB,WAAW,CAAS;IACpB,cAAc,GAAG,KAAK,CAAC;IAE/B,YAAY,MAAwB;QAClC,IAAI,CAAC,MAAM,GAAG,MAAM,CAAC;QACrB,IAAI,CAAC,WAAW,GAAG,IAAI,CAAC,oBAAoB,EAAE,CAAC;IACjD,CAAC;IAEO,oBAAoB;QAC1B,wEAAwE;QACxE,IAAI,WAAW,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,IAAI,cAAc,EAAE,CAAC;QAE1D,IAAI,W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K,UAAU,EAAE,CAAC;oBAChC,MAAM,CAAC,IAAI,CAAC,iBAAiB,QAAQ,mBAAmB,EAAE,QAAQ,CAAC,CAAC;oBAEpE,IAAI,CAAC;wBACH,iDAAiD;wBACjD,MAAM,MAAM,GAAG,aAAa,EAAE,CAAC;wBAC/B,IAAI,MAAM,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;4BAChD,MAAM,MAAM,CAAC;wBACf,CAAC;wBAED,oDAAoD;wBACpD,MAAM,IAAI,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC,UAAU,CAAC,OAAO,EAAE,GAAG,CAAC,CAAC,CAAC;wBAEvD,kDAAkD;wBAClD,IAAI,UAAU,EAAE,CAAC;4BACf,UAAU,CAAC,KAAK,EAAE,CAAC;wBACrB,CAAC;wBAED,MAAM,CAAC,IAAI,CAAC,iBAAiB,QAAQ,mBAAmB,EAAE,QAAQ,CAAC,CAAC;wBAEpE,yDAAyD;wBACzD,uEAAuE;wBACvE,8DAA8D;oBAChE,CAAC;oBAAC,OAAO,KAAK,EAAE,CAAC;wBACf,MAAM,CAAC,KAAK,CAAC,8BAA8B,EAAE,QAAQ,EAAE;4BACrD,KAAK,EAAE,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,CAAC;yBAC9D,CAAC,CAAC;wBACH,kDAAkD;oBACpD,CAAC;gBACH,CAAC;YACH,CAAC,CAAC,EAAE,CAAC;QACP,CAAC,CAAC,CAAC;IACL,CAAC;CACF","sourcesContent":["// uWebSockets.js Worker Thread Clustering Implementation\n// Uses worker threads with acceptor pattern for maximum performance\n//\n// NOTE: When terminating, you may see \"uv_loop_close() while having open handles\" warnings\n// from Node.js. This is a known limitation when using uWebSockets.js with worker threads.\n// The uWS C++ addon maintains internal libuv poll handles that cannot be cleanly closed\n// through JavaScript APIs. These warnings are harmless - the process will still exit cleanly.\n// To suppress these warnings, you can run Node.js with: --no-warnings or\n// NODE_NO_WARNINGS=1 environment variable.\n\nimport type { Worker } from 'worker_threads';\nimport { requireBuiltin } from '../../utilities/builtin.js';\n\n// worker_threads is loaded on first use (core/utilities/builtin.ts).\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport { usableCpuCount, usableMemoryBytes } from '../../cluster/thread-cluster.js';\nimport { createFrameworkLogger } from '../../logger/index.js';\nimport { loadNativeEngine } from '../../utilities/package-utils.js';\n\nconst logger = createFrameworkLogger('UWSClustering');\n\nexport interface UWSClusterConfig {\n workers?: number | 'auto';\n memoryPerWorkerGB?: number;\n port: number;\n host?: string;\n ssl?: {\n key_file_name?: string;\n cert_file_name?: string;\n passphrase?: string;\n };\n}\n\nexport class UWSWorkerClusterManager {\n private workers: Worker[] = [];\n private acceptorApp: any = null;\n private acceptorListenSocket: any = null;\n private uws: any = null;\n private config: UWSClusterConfig;\n private workerCount: number;\n private isShuttingDown = false;\n\n constructor(config: UWSClusterConfig) {\n this.config = config;\n this.workerCount = this.calculateWorkerCount();\n }\n\n private calculateWorkerCount(): number {\n // Container-aware counts (cgroup quota / affinity mask), not the host's\n let workerCount = this.config.workers || usableCpuCount();\n\n if (workerCount === 'auto') {\n const cpuCount = usableCpuCount();\n const totalMemoryGB = usableMemoryBytes() / (1024 * 1024 * 1024);\n\n let memoryPerWorkerGB = this.config.memoryPerWorkerGB;\n\n if (!memoryPerWorkerGB) {\n const headroomGB = 4;\n memoryPerWorkerGB = Math.max(0.5, Math.floor((totalMemoryGB - headroomGB) / cpuCount));\n }\n\n workerCount = Math.min(cpuCount, Math.floor(totalMemoryGB / memoryPerWorkerGB));\n\n logger.info(\n `Auto-calculated worker count: ${workerCount} (CPU: ${cpuCount}, RAM: ${totalMemoryGB.toFixed(1)}GB, ${memoryPerWorkerGB}GB per worker)`,\n 'WorkerCalculation'\n );\n } else if (typeof workerCount === 'number') {\n logger.info(`Using specified worker count: ${workerCount}`, 'WorkerCalculation');\n }\n\n return workerCount;\n }\n\n async startAcceptorAndWorkers(_appFactory: () => any): Promise<void> {\n if (!wt().isMainThread) {\n throw new Error('startAcceptorAndWorkers can only be called from main thread');\n }\n\n try {\n // Worker clustering uses the uWS-shaped App/SSLApp + SO_REUSEPORT API,\n // so it needs uWebSockets.js specifically (not @morojs/engine).\n const engine = loadNativeEngine({ candidates: ['uWebSockets.js'] });\n if (!engine) {\n throw new Error('uWebSockets.js is not available for uWS worker clustering');\n }\n const uwsModule = engine.module;\n this.uws = uwsModule.default || uwsModule;\n\n // Create acceptor app - must match SSL config of worker apps\n const ssl = this.config.ssl;\n if (ssl && ssl.key_file_name && ssl.cert_file_name) {\n this.acceptorApp = this.uws.SSLApp({\n key_file_name: ssl.key_file_name,\n cert_file_name: ssl.cert_file_name,\n passphrase: ssl.passphrase,\n });\n logger.info('uWebSockets SSL acceptor app created', 'Acceptor');\n } else {\n this.acceptorApp = this.uws.App();\n logger.info('uWebSockets acceptor app created', 'Acceptor');\n }\n\n // Start listening on acceptor\n const port = this.config.port;\n this.acceptorApp.listen(port, (token: any) => {\n if (token) {\n this.acceptorListenSocket = token;\n logger.info(\n `Acceptor listening on port ${port} from thread ${wt().threadId}`,\n 'Acceptor'\n );\n } else {\n throw new Error(`Failed to listen on port ${port} from thread ${wt().threadId}`);\n }\n });\n\n // Spawn workers\n logger.info(`Starting ${this.workerCount} worker threads`, 'Workers');\n\n for (let i = 0; i < this.workerCount; i++) {\n await this.spawnWorker(i);\n }\n\n // Setup graceful shutdown\n this.setupGracefulShutdown();\n } catch (error) {\n logger.error('Failed to start acceptor and workers', 'Startup', {\n error: error instanceof Error ? error.message : String(error),\n });\n throw error;\n }\n }\n\n private async spawnWorker(index: number): Promise<void> {\n return new Promise((resolve, reject) => {\n const scriptPath = process.argv[1];\n if (scriptPath === undefined) {\n reject(new Error('Cannot spawn worker: process.argv[1] (entry script) is unavailable'));\n return;\n }\n const worker = new (wt().Worker)(scriptPath, {\n workerData: {\n isUWSWorker: true,\n workerIndex: index,\n config: this.config,\n },\n argv: process.argv.slice(2),\n env: {\n ...process.env,\n UWS_WORKER_MODE: 'true',\n UWS_WORKER_INDEX: String(index),\n },\n });\n\n let descriptorReceived = false;\n\n worker.on('message', (message: any) => {\n if (message.type === 'descriptor' && message.descriptor) {\n if (!this.acceptorApp) {\n logger.error('Acceptor app not initialized', 'WorkerSpawn');\n reject(new Error('Acceptor app not initialized'));\n return;\n }\n\n try {\n this.acceptorApp.addChildAppDescriptor(message.descriptor);\n descriptorReceived = true;\n logger.info(\n `Worker ${index} (thread ${message.threadId}) registered with acceptor`,\n 'WorkerSpawn'\n );\n resolve();\n } catch (error) {\n logger.error('Failed to add child app descriptor', 'WorkerSpawn', {\n error: error instanceof Error ? error.message : String(error),\n });\n reject(error);\n }\n } else if (message.type === 'error') {\n logger.error(`Worker ${index} initialization error: ${message.error}`, 'WorkerSpawn');\n reject(new Error(message.error));\n }\n });\n\n worker.on('error', (error: Error) => {\n logger.error(`Worker ${index} error`, 'Worker', {\n error: error.message,\n });\n if (!descriptorReceived) {\n reject(error);\n }\n });\n\n worker.on('exit', (code: number) => {\n // Worker threads don't have exitedAfterDisconnect like cluster workers\n // Restart on any non-zero exit code\n if (code !== 0) {\n logger.warn(`Worker ${index} died unexpectedly (code: ${code}). Restarting...`, 'Worker');\n\n // Remove from workers array\n const workerIdx = this.workers.indexOf(worker);\n if (workerIdx > -1) {\n this.workers.splice(workerIdx, 1);\n }\n\n // Restart worker\n this.spawnWorker(index).catch(error => {\n logger.error('Failed to restart worker', 'Worker', {\n error: error instanceof Error ? error.message : String(error),\n });\n });\n }\n });\n\n this.workers.push(worker);\n\n // Timeout for descriptor reception\n setTimeout(() => {\n if (!descriptorReceived) {\n logger.error(`Worker ${index} failed to send descriptor within timeout`, 'WorkerSpawn');\n void worker.terminate();\n reject(new Error(`Worker ${index} initialization timeout`));\n }\n }, 10000); // 10 second timeout\n });\n }\n\n private setupGracefulShutdown(): void {\n const gracefulShutdown = async () => {\n if (this.isShuttingDown) return;\n this.isShuttingDown = true;\n\n logger.info('Gracefully shutting down worker cluster...', 'Shutdown');\n\n // Close acceptor listen socket first\n if (this.acceptorListenSocket && this.uws) {\n try {\n this.uws.us_listen_socket_close(this.acceptorListenSocket);\n this.acceptorListenSocket = null;\n logger.info('Acceptor listen socket closed', 'Shutdown');\n } catch (error) {\n logger.error('Error closing acceptor socket', 'Shutdown', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n // Send shutdown message to all workers and wait for them to close\n const shutdownPromises = this.workers.map((worker, index) => {\n return new Promise<void>(resolve => {\n let workerExited = false;\n\n const timeout = setTimeout(() => {\n if (!workerExited) {\n logger.info(\n `Worker ${index} taking too long to exit, terminating forcefully`,\n 'Shutdown'\n );\n try {\n // Terminate is the last resort for stuck workers\n void worker.terminate();\n } catch {\n logger.error(`Error terminating worker ${index}`, 'Shutdown');\n }\n }\n resolve();\n }, 2000); // Give 2 seconds for graceful exit\n\n worker.once('exit', code => {\n workerExited = true;\n clearTimeout(timeout);\n if (code === 0) {\n logger.info(`Worker ${index} exited cleanly`, 'Shutdown');\n } else if (code === 1) {\n logger.info(`Worker ${index} terminated (exit code ${code})`, 'Shutdown');\n } else {\n logger.warn(`Worker ${index} exited with unexpected code ${code}`, 'Shutdown');\n }\n resolve();\n });\n\n // Send shutdown message\n try {\n worker.postMessage({ type: 'shutdown' });\n } catch {\n logger.error(`Failed to send shutdown message to worker ${index}`, 'Shutdown');\n clearTimeout(timeout);\n try {\n void worker.terminate();\n } catch {\n // Ignore termination errors\n }\n resolve();\n }\n });\n });\n\n await Promise.all(shutdownPromises);\n logger.info('All workers shut down', 'Shutdown');\n\n // Clear acceptor app reference to allow uWebSockets to cleanup\n if (this.acceptorApp) {\n this.acceptorApp = null;\n }\n\n // Give uWebSockets event loop time to fully cleanup before exiting\n await new Promise(resolve => setTimeout(resolve, 200));\n\n logger.info('Shutdown complete', 'Shutdown');\n process.exit(0);\n };\n\n process.on('SIGINT', () => void gracefulShutdown());\n process.on('SIGTERM', () => void gracefulShutdown());\n }\n\n static isUWSWorker(): boolean {\n return !wt().isMainThread && process.env.UWS_WORKER_MODE === 'true';\n }\n\n static async sendDescriptorToAcceptor(app: any): Promise<void> {\n const { isMainThread, parentPort, threadId } = wt();\n if (isMainThread || !parentPort) {\n throw new Error('sendDescriptorToAcceptor can only be called from worker thread');\n }\n\n try {\n const descriptor = app.getDescriptor();\n\n parentPort.postMessage({\n type: 'descriptor',\n descriptor,\n threadId,\n });\n\n logger.info(`Worker thread ${threadId} sent descriptor to acceptor`, 'Worker');\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n logger.error('Failed to send descriptor to acceptor', 'Worker', { error: errorMessage });\n\n if (parentPort) {\n parentPort.postMessage({\n type: 'error',\n error: errorMessage,\n });\n }\n\n throw error;\n }\n }\n\n static setupWorkerShutdownHandler(closeCallback: () => void | Promise<void>): void {\n const { parentPort, threadId } = wt();\n if (!parentPort) {\n return;\n }\n\n parentPort.on('message', (message: any) => {\n void (async () => {\n if (message.type === 'shutdown') {\n logger.info(`Worker thread ${threadId} shutting down...`, 'Worker');\n\n try {\n // Call the close callback and wait if it's async\n const result = closeCallback();\n if (result && typeof result.then === 'function') {\n await result;\n }\n\n // Give uWebSockets event loop time to fully cleanup\n await new Promise(resolve => setTimeout(resolve, 150));\n\n // Close parent port to signal we're ready to exit\n if (parentPort) {\n parentPort.close();\n }\n\n logger.info(`Worker thread ${threadId} cleanup complete`, 'Worker');\n\n // DON'T call process.exit() - let Node.js exit naturally\n // This allows the event loop to properly drain all uWebSockets handles\n // The worker will exit on its own once all handles are closed\n } catch (error) {\n logger.error('Error during worker shutdown', 'Worker', {\n error: error instanceof Error ? error.message : String(error),\n });\n // Still don't force exit - let it drain naturally\n }\n }\n })();\n });\n }\n}\n"]}
|
|
@@ -18,6 +18,9 @@ export declare class UwsRequest extends LazyEventEmitter {
|
|
|
18
18
|
params: Record<string, string>;
|
|
19
19
|
body: any;
|
|
20
20
|
ip: string;
|
|
21
|
+
_rawBody: Buffer | undefined;
|
|
22
|
+
/** The request body exactly as received, before any parsing; null when empty. */
|
|
23
|
+
get rawBody(): Buffer | null;
|
|
21
24
|
_server: UWebSocketsHttpServer;
|
|
22
25
|
_uwsReq: any;
|
|
23
26
|
_queryString: string | null;
|
|
@@ -7,6 +7,7 @@ import { parseMultipart as parseMultipartBuffer, } from './utils/multipart-parse
|
|
|
7
7
|
import { LazyEventEmitter } from './utils/lazy-event-emitter.js';
|
|
8
8
|
import { parseRawQueryString } from './utils/query-parser.js';
|
|
9
9
|
import { resolveCompressionSettings, compressBuffer, isCompressible, negotiateEncoding, } from './utils/compression.js';
|
|
10
|
+
import { bodyIsText } from './utils/body-type.js';
|
|
10
11
|
// Back-compat alias (this parser is now the transport-neutral one in utils/)
|
|
11
12
|
const parseUwsQueryString = parseRawQueryString;
|
|
12
13
|
/**
|
|
@@ -25,6 +26,11 @@ export class UwsRequest extends LazyEventEmitter {
|
|
|
25
26
|
params = {};
|
|
26
27
|
body = null;
|
|
27
28
|
ip = '';
|
|
29
|
+
_rawBody = undefined;
|
|
30
|
+
/** The request body exactly as received, before any parsing; null when empty. */
|
|
31
|
+
get rawBody() {
|
|
32
|
+
return this._rawBody ?? null;
|
|
33
|
+
}
|
|
28
34
|
_server;
|
|
29
35
|
_uwsReq; // valid ONLY synchronously inside the uWS route callback
|
|
30
36
|
_queryString;
|
|
@@ -1557,9 +1563,24 @@ export class UWebSocketsHttpServer {
|
|
|
1557
1563
|
const stable = buffer === view ? Buffer.from(buffer) : buffer;
|
|
1558
1564
|
httpReq.body = parseMultipartBuffer(stable, contentType, this.multipartLimits);
|
|
1559
1565
|
}
|
|
1560
|
-
else {
|
|
1566
|
+
else if (bodyIsText(contentType)) {
|
|
1561
1567
|
httpReq.body = buffer.toString('utf-8');
|
|
1562
1568
|
}
|
|
1569
|
+
else {
|
|
1570
|
+
// Binary stays a Buffer. The single-chunk fast path aliases
|
|
1571
|
+
// uWS-owned memory that is recycled after this callback, so a
|
|
1572
|
+
// Buffer that outlives it must be a copy.
|
|
1573
|
+
httpReq.body = buffer === view ? Buffer.from(buffer) : buffer;
|
|
1574
|
+
}
|
|
1575
|
+
// Raw bytes for signature checks: reuse the stable binary copy when
|
|
1576
|
+
// one was made, otherwise copy out of uWS-owned memory now.
|
|
1577
|
+
if (totalLength > 0) {
|
|
1578
|
+
httpReq._rawBody = Buffer.isBuffer(httpReq.body)
|
|
1579
|
+
? httpReq.body
|
|
1580
|
+
: buffer === view
|
|
1581
|
+
? Buffer.from(buffer)
|
|
1582
|
+
: buffer;
|
|
1583
|
+
}
|
|
1563
1584
|
finish(resolve);
|
|
1564
1585
|
}
|
|
1565
1586
|
catch (parseError) {
|