@morojs/moro 1.8.9 → 1.8.10
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/dist/core/cluster/thread-cluster.d.ts +178 -0
- package/dist/core/cluster/thread-cluster.js +389 -0
- package/dist/core/cluster/thread-cluster.js.map +1 -0
- package/dist/core/framework.js.map +1 -1
- package/dist/core/http/moro-engine-server.d.ts +28 -1
- package/dist/core/http/moro-engine-server.js +274 -36
- package/dist/core/http/moro-engine-server.js.map +1 -1
- package/dist/core/http/utils/compression.js +12 -6
- package/dist/core/http/utils/compression.js.map +1 -1
- package/dist/core/http/utils/uws-worker-clustering.js +10 -6
- package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
- package/dist/core/http/uws-http-server.js +3 -2
- package/dist/core/http/uws-http-server.js.map +1 -1
- package/dist/core/jobs/leader-election.js +16 -5
- package/dist/core/jobs/leader-election.js.map +1 -1
- package/dist/core/networking/websocket-manager.js +4 -2
- package/dist/core/networking/websocket-manager.js.map +1 -1
- package/dist/core/runtime/node-adapter.d.ts +1 -1
- package/dist/core/runtime/node-adapter.js.map +1 -1
- package/dist/core/utilities/builtin.d.ts +1 -0
- package/dist/core/utilities/builtin.js +25 -0
- package/dist/core/utilities/builtin.js.map +1 -0
- package/dist/core/utilities/package-utils.d.ts +28 -3
- package/dist/core/utilities/package-utils.js +24 -12
- package/dist/core/utilities/package-utils.js.map +1 -1
- package/dist/core/workers/worker-manager.js +4 -3
- package/dist/core/workers/worker-manager.js.map +1 -1
- package/dist/moro.d.ts +5 -0
- package/dist/moro.js +364 -204
- package/dist/moro.js.map +1 -1
- package/dist/types/http.d.ts +1 -1
- package/dist/types/http.js.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"package-utils.js","sourceRoot":"","sources":["../../../src/core/utilities/package-utils.ts"],"names":[],"mappings":"AAAA,0CAA0C;AAC1C,2EAA2E;AAE3E,OAAO,EAAE,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AAC;QACtC,OAAO,CAAC,aAAa,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC;IACjD,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,yBAAyB;IACvC,OAAO,gBAAgB,CAAC;AAC1B,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,iCAAiC;IAC/C,YAAY,GAAG,SAAS,CAAC;IACzB,gBAAgB,GAAG,EAAE,CAAC;AACxB,CAAC;AAED;;;;;;;;;;;GAWG;AACH,MAAM,UAAU,mBAAmB,CAAC,QAAgB;IAClD,IAAI,CAAC,QAAQ,EAAE,CAAC;QACd,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,0EAA0E;IAC1E,IACE,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;QAC9B,QAAQ,CAAC,UAAU,CAAC,SAAS,CAAC;QAC9B,QAAQ,CAAC,UAAU,CAAC,UAAU,CAAC,EAC/B,CAAC;QACD,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,qDAAqD;IACrD,MAAM,wBAAwB,GAAG,kBAAkB,CAAC;IACpD,MAAM,iBAAiB,GAAG,wBAAwB,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;IAElE,qDAAqD;IACrD,MAAM,cAAc,GAAG,QAAQ,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { selfRequire } from './self-require.js';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.2.0). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (engine >= 1.4.0). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate (engine >= 1.5.0). */\n wsDeflate: boolean;\n}\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = {\n limits: false,\n tls: false,\n http2: false,\n wsDeflate: false,\n};\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n caps = {\n limits: c.limits === true,\n tls: c.tls === true,\n http2: c.http2 === true,\n wsDeflate: c.wsDeflate === true,\n };\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n // Primary: anchor to moro's OWN compiled location, so moro's `@morojs/engine`\n // dependency resolves relative to where moro is installed regardless of\n // `process.cwd()` (Docker WORKDIR, supervisord, pm2, a subdirectory, …). The\n // cwd-based walk below is a defensive fallback for exotic layouts.\n if (selfRequire) return selfRequire;\n\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"package-utils.js","sourceRoot":"","sources":["../../../src/core/utilities/package-utils.ts"],"names":[],"mappings":"AAAA,0CAA0C;AA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,CAAC,CAAC;IAEhD,oDAAoD;IACpD,MAAM,YAAY,GAAG,QAAQ,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC;IAEjD,sCAAsC;IACtC,IAAI,iBAAiB,IAAI,cAAc,IAAI,YAAY,EAAE,CAAC;QACxD,OAAO,aAAa,CAAC,QAAQ,CAAC,CAAC,IAAI,CAAC;IACtC,CAAC;IAED,2DAA2D;IAC3D,OAAO,QAAQ,CAAC;AAClB,CAAC","sourcesContent":["// Package and Module Resolution Utilities\n// ESM-compatible helpers for detecting and resolving optional dependencies\n\nimport { createRequire } from 'module';\nimport { dirname, join } from 'path';\nimport { existsSync, realpathSync } from 'fs';\nimport { pathToFileURL } from 'url';\nimport { selfRequire } from './self-require.js';\n\n/**\n * Check if a package is available in the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to check (e.g., 'socket.io', 'zod')\n * @returns true if the package is installed, false otherwise\n *\n * @example\n * if (isPackageAvailable('socket.io')) {\n * // socket.io is installed, safe to import\n * const { Server } = await import('socket.io');\n * }\n */\nexport function isPackageAvailable(packageName: string): boolean {\n try {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n userRequire.resolve(packageName);\n return true;\n } catch {\n return false;\n }\n}\n\n/**\n * Resolve a package path from the user's node_modules\n * Uses ESM-compatible module resolution from the user's working directory\n *\n * @param packageName - The name of the package to resolve\n * @returns The resolved package path\n * @throws Error if the package is not found\n *\n * @example\n * const socketIOPath = resolveUserPackage('socket.io');\n * const { Server } = await import(socketIOPath);\n */\nexport function resolveUserPackage(packageName: string): string {\n const userRequire = createRequire(join(process.cwd(), 'package.json'));\n return userRequire.resolve(packageName);\n}\n\n/**\n * Create a require function for the user's working directory\n * Useful for resolving packages installed by the user, not in Moro's dependencies\n *\n * @returns A require function scoped to the user's working directory\n *\n * @example\n * const userRequire = createUserRequire();\n * const packagePath = userRequire.resolve('some-package');\n */\nexport function createUserRequire() {\n return createRequire(join(process.cwd(), 'package.json'));\n}\n\n// ---------------------------------------------------------------------------\n// Native HTTP engine loading\n// ---------------------------------------------------------------------------\n\n/**\n * Package names probed for the native HTTP engine, in priority order.\n * '@morojs/engine' is Moro's own engine (installed as an optionalDependency of\n * the framework); 'uWebSockets.js' is honored as a legacy user-installed peer.\n */\nexport const NATIVE_ENGINE_PACKAGES = ['@morojs/engine', 'uWebSockets.js'] as const;\n\nconst FRAMEWORK_PACKAGE_NAME = '@morojs/moro';\n\n/** Feature flags the framework gates option-passing on, so it never hands a\n * serve() option to an engine build that predates it. Everything defaults\n * false, so an older engine behaves exactly as it did before these existed. */\nexport interface EngineCapabilities {\n /** The full serve() limit surface is parsed (engine >= 1.1.0). */\n limits: boolean;\n /** In-process TLS termination via options.ssl (engine >= 1.1.x). */\n tls: boolean;\n /** ALPN HTTP/2 via options.http2 (reserved). */\n http2: boolean;\n /** WebSocket permessage-deflate via options.wsDeflate. */\n wsDeflate: boolean;\n /** responseTimeoutMs / responseBackpressureLimit / maxUriSize are parsed. */\n responseLimits: boolean;\n /** ssl.ciphers / ssl.ciphersuites / ssl.ecdhCurve are parsed. */\n tlsPolicy: boolean;\n /** setStaticRoute()/clearStaticRoutes() exist (not used by the framework:\n * a static route bypasses middleware and hooks, so exposing it is an API\n * decision, not an adapter one). */\n staticRoutes: boolean;\n /** prepareResponse()/respondPrepared()/respondPreparedEmpty()/endWith()\n * exist (engine >= 1.1.6): the adapter replays prepared header blocks for\n * the responses it emits itself. */\n responseTemplates: boolean;\n /** onAborted/onWritable are delivered on a later loop turn, never from\n * inside respond()/write()/end() (engine >= 1.1.6). */\n asyncNotify: boolean;\n /** A server left open at environment teardown is closed by the engine's\n * cleanup hook, so the engine may run inside worker threads that can be\n * terminate()d (engine >= 1.1.6). Gates thread-based clustering. */\n workerThreads: boolean;\n /** V8 fast API calls are installed on the hot entry points (informational). */\n fastCalls: boolean;\n /** Batched pipelined dispatch (onRequestBatch / getBatchBuffers / getPath). */\n batchDispatch: boolean;\n /** I/O transport in use ('uv', 'uring'), when the engine reports it. */\n transport?: string;\n}\n\n// One place to name every boolean flag: getEngineCapabilities coerces each\n// with `=== true`, and NO_CAPABILITIES is derived from the same list, so a\n// flag added here can never be read on one path and forgotten on the other.\nconst CAP_KEYS = [\n 'limits',\n 'tls',\n 'http2',\n 'wsDeflate',\n 'responseLimits',\n 'tlsPolicy',\n 'staticRoutes',\n 'responseTemplates',\n 'asyncNotify',\n 'workerThreads',\n 'fastCalls',\n 'batchDispatch',\n] as const;\n\nexport interface NativeEngineLoadResult {\n /** The loaded engine module (CJS namespace: App, SSLApp, ...) */\n module: any;\n /** Which package satisfied the load */\n source: string;\n /** The engine package's version, when its package.json is resolvable */\n version?: string;\n /** Feature flags (Moro-shaped engine only; all-false for uWS or an\n * engine too old to advertise them). */\n capabilities?: EngineCapabilities;\n}\n\nconst NO_CAPABILITIES: EngineCapabilities = Object.freeze(\n Object.fromEntries(CAP_KEYS.map(k => [k, false]))\n) as unknown as EngineCapabilities;\n\nconst capabilitiesCache = new WeakMap<object, EngineCapabilities>();\n\n/**\n * Feature-detect a loaded engine module. Reads probe().capabilities when the\n * engine exposes it (>= 1.1.0); otherwise everything is false so the framework\n * passes only the options an older engine understood. uWS-style modules (no\n * probe/serve) report all-false — their SSL/limits go through the uWS-specific\n * paths, not these flags.\n */\nexport function getEngineCapabilities(module: any): EngineCapabilities {\n const surface = module?.default || module;\n if (!surface || typeof surface !== 'object') return NO_CAPABILITIES;\n const cached = capabilitiesCache.get(surface);\n if (cached) return cached;\n\n let caps: EngineCapabilities = NO_CAPABILITIES;\n try {\n if (typeof surface.probe === 'function') {\n const probe = surface.probe();\n const c = probe?.capabilities;\n if (c && typeof c === 'object') {\n const next: Record<string, boolean | string> = {};\n for (const key of CAP_KEYS) next[key] = c[key] === true;\n if (typeof probe.transport === 'string') next.transport = probe.transport;\n caps = next as unknown as EngineCapabilities;\n }\n }\n } catch {\n caps = NO_CAPABILITIES;\n }\n capabilitiesCache.set(surface, caps);\n return caps;\n}\n\n// undefined = never attempted, null = attempted and failed\nlet cachedEngine: NativeEngineLoadResult | null | undefined;\nlet engineLoadErrors: string[] = [];\n\n/**\n * Locate the installed framework package directory so the engine (a dependency\n * of moro, not of the user's app) resolves under strict layouts like pnpm's.\n * Walks up from cwd looking for node_modules/@morojs/moro, resolving symlinks\n * so pnpm's store-linked layout anchors requires next to moro's own deps.\n * Inside the framework repo itself (tests, examples) cwd is the framework dir.\n */\nfunction findFrameworkAnchor(): ReturnType<typeof createRequire> | null {\n // Primary: anchor to moro's OWN compiled location, so moro's `@morojs/engine`\n // dependency resolves relative to where moro is installed regardless of\n // `process.cwd()` (Docker WORKDIR, supervisord, pm2, a subdirectory, …). The\n // cwd-based walk below is a defensive fallback for exotic layouts.\n if (selfRequire) return selfRequire;\n\n try {\n const cwdPackageJson = join(process.cwd(), 'package.json');\n if (existsSync(cwdPackageJson)) {\n const require = createRequire(cwdPackageJson);\n const name = require(cwdPackageJson)?.name;\n if (name === FRAMEWORK_PACKAGE_NAME) {\n return require;\n }\n }\n } catch {\n // fall through to the node_modules walk\n }\n\n let dir = process.cwd();\n for (;;) {\n const packageJson = join(dir, 'node_modules', '@morojs', 'moro', 'package.json');\n try {\n if (existsSync(packageJson)) {\n return createRequire(join(realpathSync(dirname(packageJson)), 'package.json'));\n }\n } catch {\n // unreadable/broken link - keep walking up\n }\n const parent = dirname(dir);\n if (parent === dir) return null;\n dir = parent;\n }\n}\n\n/**\n * Synchronously load the native HTTP engine, trying '@morojs/engine' first and\n * falling back to a user-installed 'uWebSockets.js'. Loading is require-based\n * (both packages are CJS at their core - .node addon loading is require-based),\n * so the instance is shared with any later import() via the CJS module cache.\n *\n * The default call is memoized: the engine either loads once per process or it\n * doesn't. Failure details are retained for logging via\n * getNativeEngineLoadErrors().\n *\n * @param options.candidates - Override the probed package names (testing).\n * When provided, the call bypasses the cache.\n * @returns The loaded engine and its source package, or null if none loads\n */\nexport function loadNativeEngine(options?: {\n candidates?: readonly string[];\n /** When provided, every per-attempt failure message is appended here, so a\n * candidate-override caller (which bypasses the memoized diagnostics) can\n * still report exactly WHY the engine didn't load — not just \"not installed\". */\n collectErrors?: string[];\n}): NativeEngineLoadResult | null {\n const useCache = !options?.candidates;\n if (useCache && cachedEngine !== undefined) {\n if (options?.collectErrors && !cachedEngine) {\n options.collectErrors.push(...engineLoadErrors);\n }\n return cachedEngine;\n }\n\n const candidates = options?.candidates ?? NATIVE_ENGINE_PACKAGES;\n const errors: string[] = [];\n let result: NativeEngineLoadResult | null = null;\n\n const frameworkRequire = findFrameworkAnchor();\n const userRequire = createUserRequire();\n\n for (const candidate of candidates) {\n // Moro's own engine lives in moro's dependencies (framework anchor first);\n // the legacy uWS peer dep lives in the user's node_modules (cwd first).\n const anchors =\n candidate === 'uWebSockets.js'\n ? [userRequire, frameworkRequire]\n : [frameworkRequire, userRequire];\n\n for (const anchor of anchors) {\n if (!anchor) continue;\n try {\n const module = anchor(candidate);\n // Capability check: the HTTP server needs either a uWS-style App()\n // factory or the Moro-shaped engine surface (serve()/respond()).\n // A package that loads but can't serve (e.g. a pre-M1 @morojs/engine\n // that only exposes probe()) must not shadow a usable alternative.\n const surface = module?.default || module;\n const uwsStyle = typeof surface?.App === 'function';\n const moroStyle =\n !uwsStyle &&\n typeof surface?.serve === 'function' &&\n typeof surface?.respond === 'function';\n if (!uwsStyle && !moroStyle) {\n errors.push(\n `${candidate}: loaded but provides neither App() nor serve()/respond() - not a usable HTTP engine`\n );\n continue;\n }\n let version: string | undefined;\n try {\n // May be blocked by the package's exports map - version is optional\n version = anchor(`${candidate}/package.json`)?.version;\n } catch {\n version = undefined;\n }\n result = {\n module,\n source: candidate,\n ...(version !== undefined ? { version } : {}),\n capabilities: moroStyle ? getEngineCapabilities(module) : NO_CAPABILITIES,\n };\n break;\n } catch (error) {\n const message = error instanceof Error ? error.message.split('\\n')[0] : String(error);\n errors.push(`${candidate}: ${message}`);\n }\n }\n if (result) break;\n }\n\n // Candidate-override probes (e.g. the clustering worker's uWS-only check)\n // must not clobber the diagnostics of the real default load, which\n // framework startup logging reads via getNativeEngineLoadErrors().\n if (useCache) {\n engineLoadErrors = result ? [] : [...new Set(errors)];\n cachedEngine = result;\n }\n // Hand this specific call's failure detail back to a caller that asked for it,\n // regardless of caching (so 'moro'/'uws' fallback reasons are precise).\n if (options?.collectErrors && !result) {\n options.collectErrors.push(...new Set(errors));\n }\n return result;\n}\n\n/**\n * Failure details from the most recent unsuccessful loadNativeEngine() call,\n * one entry per package/anchor attempt. Empty after a successful load.\n */\nexport function getNativeEngineLoadErrors(): readonly string[] {\n return engineLoadErrors;\n}\n\n/**\n * Clear the memoized engine load result. Testing only.\n */\nexport function resetNativeEngineLoaderForTesting(): void {\n cachedEngine = undefined;\n engineLoadErrors = [];\n}\n\n/**\n * Convert a file path to a file URL for ESM dynamic imports\n * This is required on Windows where absolute paths like C:\\path\\to\\module\n * need to be converted to file:/// URLs for dynamic import() to work\n *\n * @param filePath - The file path to convert (absolute or relative)\n * @returns A proper URL string for ESM import() that works cross-platform\n *\n * @example\n * const modulePath = 'C:\\\\Users\\\\project\\\\module.js';\n * const module = await import(filePathToImportURL(modulePath));\n */\nexport function filePathToImportURL(filePath: string): string {\n if (!filePath) {\n return filePath;\n }\n\n // If it's already a URL (starts with file:// or http(s)://), return as-is\n if (\n filePath.startsWith('file://') ||\n filePath.startsWith('http://') ||\n filePath.startsWith('https://')\n ) {\n return filePath;\n }\n\n // Check if it's a Windows absolute path (C:\\ or C:/)\n const windowsAbsolutePathRegex = /^[A-Za-z]:[\\\\//]/;\n const isWindowsAbsolute = windowsAbsolutePathRegex.test(filePath);\n\n // Check if it's a Unix absolute path (starts with /)\n const isUnixAbsolute = filePath.startsWith('/');\n\n // Check if it's a Windows UNC path (\\\\server\\share)\n const isWindowsUNC = filePath.startsWith('\\\\\\\\');\n\n // Convert absolute paths to file URLs\n if (isWindowsAbsolute || isUnixAbsolute || isWindowsUNC) {\n return pathToFileURL(filePath).href;\n }\n\n // For relative paths, return as-is (they work in import())\n return filePath;\n}\n"]}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import { requireBuiltin } from '../utilities/builtin.js';
|
|
2
|
+
// worker_threads on first use (core/utilities/builtin.ts).
|
|
3
|
+
const wt = () => requireBuiltin('worker_threads');
|
|
3
4
|
import { createFrameworkLogger } from '../logger/index.js';
|
|
4
5
|
import { cpus } from 'os';
|
|
5
6
|
import { isPackageAvailable } from '../utilities/package-utils.js';
|
|
@@ -77,7 +78,7 @@ export class WorkerManager {
|
|
|
77
78
|
}
|
|
78
79
|
let worker;
|
|
79
80
|
try {
|
|
80
|
-
worker = new Worker(WORKER_ENTRY, {
|
|
81
|
+
worker = new (wt().Worker)(WORKER_ENTRY, {
|
|
81
82
|
workerData: { type: 'worker' },
|
|
82
83
|
});
|
|
83
84
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"worker-manager.js","sourceRoot":"","sources":["../../../src/core/workers/worker-manager.ts"],"names":[],"mappings":"AAAA,2DAA2D;AAC3D,OAAO,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AACxC,OAAO,EAAE,qBAAqB,EAAE,MAAM,oBAAoB,CAAC;AAC3D,OAAO,EAAE,IAAI,EAAE,MAAM,IAAI,CAAC;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,+BAA+B,CAAC;AACnE,+EAA+E;AAC/E,gFAAgF;AAChF,gFAAgF;AAChF,+EAA+E;AAC/E,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAC;AAEjD,sBAAsB;AACtB,MAAM,YAAY,GAAG,kBAAkB,CAAC,cAAc,CAAC,CAAC;AAExD,MAAM,MAAM,GAAG,qBAAqB,CAAC,eAAe,CAAC,CAAC;AAEtD,iDAAiD;AACjD,MAAM,sBAAsB,GAAG,IAAI,CAAC;AAEpC,oFAAoF;AACpF,MAAM,cAAc,GAA2B,EAAE,IAAI,EAAE,CAAC,EAAE,MAAM,EAAE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EAAE;YACnD,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["// Worker Thread Manager - Offload CPU-intensive operations\nimport { Worker } from 'worker_threads';\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { cpus } from 'os';\nimport { isPackageAvailable } from '../utilities/package-utils.js';\n// WORKER_ENTRY resolves to worker.js, this file's compiled sibling in dist/**,\n// via import.meta in ./worker-entry.js. That ESM-only syntax is isolated in its\n// own module (mapped to a stub in jest.config) so importing WorkerManager under\n// ts-jest's CommonJS transform never hits a load-time import.meta SyntaxError.\nimport { WORKER_ENTRY } from './worker-entry.js';\n\n// Optional JWT import\nconst jwtAvailable = isPackageAvailable('jsonwebtoken');\n\nconst logger = createFrameworkLogger('WorkerManager');\n\n// Upper bound on the exponential restart backoff\nconst MAX_RESTART_BACKOFF_MS = 5000;\n\n// Hoisted constants — avoids object allocation inside sort comparator on every call\nconst PRIORITY_ORDER: Record<string, number> = { high: 3, normal: 2, low: 1 };\n\n// Simple counter for task IDs — avoids expensive crypto.randomBytes for non-security IDs\nlet taskIdCounter = 0;\n\n/**\n * Worker task definitions\n */\nexport interface WorkerTask {\n id: string;\n type: string;\n data: any;\n priority?: 'low' | 'normal' | 'high';\n timeout?: number;\n}\n\n/**\n * Worker result\n */\nexport interface WorkerResult {\n taskId: string;\n success: boolean;\n data?: any;\n error?: string;\n executionTime: number;\n}\n\n/**\n * Active task tracking\n */\ninterface ActiveTask {\n resolve: CallableFunction;\n reject: CallableFunction;\n timeout: NodeJS.Timeout | null;\n // The worker a task was dispatched to (set once it leaves the queue). Used so a\n // crashed worker only rejects its own in-flight tasks, not everyone else's.\n assignedWorker?: Worker;\n}\n\n/**\n * Built-in worker tasks\n */\nexport const WORKER_TASKS = {\n JWT_VERIFY: 'jwt:verify',\n JWT_SIGN: 'jwt:sign',\n CRYPTO_HASH: 'crypto:hash',\n CRYPTO_ENCRYPT: 'crypto:encrypt',\n CRYPTO_DECRYPT: 'crypto:decrypt',\n DATA_COMPRESS: 'data:compress',\n DATA_DECOMPRESS: 'data:decompress',\n IMAGE_PROCESS: 'image:process',\n HEAVY_COMPUTATION: 'computation:heavy',\n JSON_TRANSFORM: 'json:transform',\n} as const;\n\n/**\n * Worker Thread Manager\n * Manages a pool of worker threads for CPU-intensive operations\n */\nexport class WorkerManager {\n private workers: Map<number, Worker> = new Map();\n private taskQueue: WorkerTask[] = [];\n private activeTasks: Map<string, ActiveTask> = new Map();\n private workerCount: number;\n private maxQueueSize: number;\n private isShuttingDown = false;\n private maxRestartAttempts: number;\n private restartBackoffMs: number;\n private restartAttempts = 0;\n private restartTimers = new Set<NodeJS.Timeout>();\n private handledFailures = new WeakSet<Worker>();\n private poolFailed = false;\n\n constructor(\n options: {\n workerCount?: number;\n maxQueueSize?: number;\n maxRestartAttempts?: number;\n restartBackoffMs?: number;\n } = {}\n ) {\n this.workerCount = options.workerCount || Math.max(1, cpus().length - 1); // Leave 1 core for main thread\n this.maxQueueSize = options.maxQueueSize || 1000;\n this.maxRestartAttempts = options.maxRestartAttempts ?? 10;\n this.restartBackoffMs = options.restartBackoffMs ?? 100;\n\n this.initializeWorkers();\n }\n\n /**\n * Initialize worker threads\n */\n private initializeWorkers(): void {\n for (let i = 0; i < this.workerCount; i++) {\n this.createWorker();\n }\n\n logger.info(`Initialized ${this.workerCount} worker threads`, 'WorkerInit', {\n totalWorkers: this.workerCount,\n maxQueueSize: this.maxQueueSize,\n });\n }\n\n /**\n * Create a single worker thread\n */\n private createWorker(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n let worker: Worker;\n try {\n worker = new Worker(WORKER_ENTRY, {\n workerData: { type: 'worker' },\n });\n } catch (error) {\n // Spawning can fail synchronously (e.g. a missing entry file). Treat it the\n // same as a runtime failure so we back off instead of throwing.\n logger.error('Failed to spawn worker thread', 'WorkerSpawn', {\n error: error instanceof Error ? error.message : String(error),\n });\n this.scheduleRestart();\n return;\n }\n\n worker.on('message', (result: WorkerResult) => {\n // A successful message proves the pool is healthy; reset the restart budget.\n this.restartAttempts = 0;\n this.handleWorkerResult(result);\n });\n\n worker.on('error', error => {\n logger.error('Worker thread error', 'WorkerError', { error: error.message });\n this.handleWorkerFailure(worker);\n });\n\n worker.on('exit', code => {\n if (code !== 0 && !this.isShuttingDown) {\n logger.warn(`Worker exited with code ${code}, restarting`, 'WorkerExit');\n this.handleWorkerFailure(worker);\n }\n });\n\n this.workers.set(worker.threadId, worker);\n logger.debug(`Created worker thread ${worker.threadId}`, 'WorkerCreate');\n }\n\n /**\n * Handle a crashed worker: reject only the tasks that were assigned to it and\n * schedule a backed-off restart. A failed worker emits both 'error' and 'exit',\n * so this is guarded to run at most once per worker.\n */\n private handleWorkerFailure(worker: Worker): void {\n if (this.handledFailures.has(worker)) {\n return;\n }\n this.handledFailures.add(worker);\n\n this.workers.delete(worker.threadId);\n\n if (this.isShuttingDown) {\n return;\n }\n\n // Reject only the tasks that were dispatched to this specific worker. Tasks\n // still queued (or running on other workers) are intentionally left alone.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.assignedWorker === worker) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker thread failed'));\n this.activeTasks.delete(taskId);\n }\n }\n\n this.scheduleRestart();\n }\n\n /**\n * Schedule a replacement worker with exponential backoff, capping the number of\n * consecutive restart attempts so a persistently broken worker entry can never\n * spin into an unbounded restart loop.\n */\n private scheduleRestart(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n this.restartAttempts++;\n\n if (this.restartAttempts > this.maxRestartAttempts) {\n this.failPool();\n return;\n }\n\n const delay = Math.min(\n this.restartBackoffMs * 2 ** (this.restartAttempts - 1),\n MAX_RESTART_BACKOFF_MS\n );\n\n logger.warn(\n `Scheduling worker restart in ${delay}ms (attempt ${this.restartAttempts}/${this.maxRestartAttempts})`,\n 'WorkerRestart'\n );\n\n const timer = setTimeout(() => {\n this.restartTimers.delete(timer);\n this.createWorker();\n }, delay);\n\n // Don't keep the process alive purely for a pending restart\n timer.unref();\n this.restartTimers.add(timer);\n }\n\n /**\n * Give up after too many failed restarts: fail every outstanding task cleanly\n * (rejecting their promises) instead of looping forever.\n */\n private failPool(): void {\n if (this.poolFailed) {\n return;\n }\n this.poolFailed = true;\n\n logger.error(\n `Worker pool failed to recover after ${this.maxRestartAttempts} restart attempts`,\n 'WorkerPoolFailed'\n );\n\n const error = new Error(\n `Worker pool is unavailable after ${this.maxRestartAttempts} failed restart attempts`\n );\n\n // Every queued task also has an activeTasks entry, so this rejects both\n // in-flight and queued work.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(error);\n this.activeTasks.delete(taskId);\n }\n\n this.taskQueue.length = 0;\n }\n\n /**\n * Execute a task on a worker thread\n */\n async executeTask<T = any>(task: WorkerTask): Promise<T> {\n if (this.isShuttingDown) {\n throw new Error('Worker manager is shutting down');\n }\n\n if (this.poolFailed) {\n throw new Error('Worker pool is unavailable (too many worker failures)');\n }\n\n return new Promise<T>((resolve, reject) => {\n // Check queue size limit\n if (this.taskQueue.length >= this.maxQueueSize) {\n reject(new Error('Worker queue is full'));\n return;\n }\n\n // Add to queue\n this.taskQueue.push(task);\n\n // Set up promise handlers\n const timeout = task.timeout\n ? setTimeout(() => {\n this.activeTasks.delete(task.id);\n reject(new Error(`Task ${task.id} timed out`));\n }, task.timeout)\n : null;\n\n // Don't keep process alive for worker timeouts\n if (timeout) {\n timeout.unref();\n }\n\n this.activeTasks.set(task.id, { resolve, reject, timeout });\n\n // Try to assign task to available worker\n this.processQueue();\n });\n }\n\n /**\n * Process the task queue\n */\n private processQueue(): void {\n // Sort queue by priority (high first)\n this.taskQueue.sort(\n (a, b) =>\n (PRIORITY_ORDER[b.priority || 'normal'] ?? 0) -\n (PRIORITY_ORDER[a.priority || 'normal'] ?? 0)\n );\n\n // Assign tasks to available workers\n for (const [threadId, worker] of this.workers.entries()) {\n if (this.taskQueue.length === 0) break;\n\n // Check if worker is available (not currently processing)\n // For simplicity, we'll send tasks and let workers handle queuing\n const task = this.taskQueue.shift();\n if (task) {\n // Record the assignment so a crashed worker only rejects its own tasks.\n const taskInfo = this.activeTasks.get(task.id);\n if (taskInfo) {\n taskInfo.assignedWorker = worker;\n }\n worker.postMessage(task);\n logger.debug(`Assigned task ${task.id} to worker ${threadId}`, 'TaskAssigned');\n }\n }\n }\n\n /**\n * Handle result from worker thread\n */\n private handleWorkerResult(result: WorkerResult): void {\n const taskInfo = this.activeTasks.get(result.taskId);\n if (!taskInfo) {\n logger.warn(`Received result for unknown task ${result.taskId}`, 'UnknownTaskResult');\n return;\n }\n\n // Clear timeout\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n\n // Remove from active tasks\n this.activeTasks.delete(result.taskId);\n\n // Handle result\n if (result.success) {\n logger.debug(`Task ${result.taskId} completed in ${result.executionTime}ms`, 'TaskCompleted');\n taskInfo.resolve(result.data);\n } else {\n logger.error(`Task ${result.taskId} failed: ${result.error}`, 'TaskFailed');\n taskInfo.reject(new Error(result.error || 'Task failed'));\n }\n\n // Process next task in queue\n this.processQueue();\n }\n\n /**\n * Shutdown all workers\n */\n async shutdown(): Promise<void> {\n this.isShuttingDown = true;\n\n // Cancel any pending worker restarts\n for (const timer of this.restartTimers) {\n clearTimeout(timer);\n }\n this.restartTimers.clear();\n\n // Reject all pending tasks\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker manager shutting down'));\n }\n\n // Terminate all workers\n const shutdownPromises = Array.from(this.workers.values()).map(\n worker =>\n new Promise<void>(resolve => {\n worker.once('exit', () => resolve());\n void worker.terminate();\n })\n );\n\n await Promise.all(shutdownPromises);\n this.workers.clear();\n this.activeTasks.clear();\n this.taskQueue.length = 0;\n\n logger.info('Worker manager shutdown complete', 'WorkerShutdown');\n }\n\n /**\n * Get worker statistics\n */\n getStats() {\n return {\n workerCount: this.workers.size,\n activeTasks: this.activeTasks.size,\n queuedTasks: this.taskQueue.length,\n isShuttingDown: this.isShuttingDown,\n };\n }\n}\n\n// Singleton instance\nlet workerManagerInstance: WorkerManager | null = null;\n\n/**\n * Get or create the worker manager instance\n */\nexport function getWorkerManager(options?: {\n workerCount?: number;\n maxQueueSize?: number;\n}): WorkerManager {\n if (!workerManagerInstance) {\n workerManagerInstance = new WorkerManager(options);\n }\n return workerManagerInstance;\n}\n\n/**\n * Execute task on worker thread (convenience function)\n */\nexport async function executeOnWorker<T = any>(task: WorkerTask): Promise<T> {\n const manager = getWorkerManager();\n return manager.executeTask<T>(task);\n}\n\n/**\n * Built-in task helpers\n */\nexport const workerTasks = {\n /**\n * JWT verification (CPU-intensive)\n */\n async verifyJWT(token: string, secret: string, options?: any): Promise<any> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT verification requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-verify-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_VERIFY,\n data: { token, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * JWT signing (CPU-intensive)\n */\n async signJWT(payload: any, secret: string, options?: any): Promise<string> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT signing requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-sign-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_SIGN,\n data: { payload, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * Crypto hash (CPU-intensive)\n */\n async hash(data: string, algorithm = 'sha256'): Promise<string> {\n return executeOnWorker({\n id: `crypto-hash-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.CRYPTO_HASH,\n data: { data, algorithm },\n priority: 'normal',\n timeout: 10000,\n });\n },\n\n /**\n * Data compression (CPU-intensive for large payloads)\n */\n async compress(\n data: string | Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-compress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_COMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n // Buffers cross the thread boundary as plain Uint8Array\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Data decompression (CPU-intensive for large payloads)\n */\n async decompress(\n data: Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-decompress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_DECOMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Heavy computation example\n */\n async heavyComputation(data: any): Promise<any> {\n return executeOnWorker({\n id: `computation-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.HEAVY_COMPUTATION,\n data,\n priority: 'normal',\n timeout: 30000,\n });\n },\n\n /**\n * JSON transformation (can be CPU-intensive for large objects)\n */\n async transformJSON(data: any, transformer: (data: any) => any): Promise<any> {\n return executeOnWorker({\n id: `json-transform-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JSON_TRANSFORM,\n data: { data, transformer: transformer.toString() },\n priority: 'normal',\n timeout: 15000,\n });\n },\n};\n"]}
|
|
1
|
+
{"version":3,"file":"worker-manager.js","sourceRoot":"","sources":["../../../src/core/workers/worker-manager.ts"],"names":[],"mappings":"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ACf,CAAC,CAAC;QACH,OAAO,MAAM,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;IAChE,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,gBAAgB,CAAC,IAAS;QAC9B,OAAO,eAAe,CAAC;YACrB,EAAE,EAAE,eAAe,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,aAAa,EAAE;YAClD,IAAI,EAAE,YAAY,CAAC,iBAAiB;YACpC,IAAI;YACJ,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC;IAED;;OAEG;IACH,KAAK,CAAC,aAAa,CAAC,IAAS,EAAE,WAA+B;QAC5D,OAAO,eAAe,CAAC;YACrB,EAAE,EAAE,kBAAkB,IAAI,CAAC,GAAG,EAAE,IAAI,EAAE,aAAa,EAAE;YACrD,IAAI,EAAE,YAAY,CAAC,cAAc;YACjC,IAAI,EAAE,EAAE,IAAI,EAAE,WAAW,EAAE,WAAW,CAAC,QAAQ,EAAE,EAAE;YACnD,QAAQ,EAAE,QAAQ;YAClB,OAAO,EAAE,KAAK;SACf,CAAC,CAAC;IACL,CAAC;CACF,CAAC","sourcesContent":["// Worker Thread Manager - Offload CPU-intensive operations\nimport type { Worker } from 'worker_threads';\nimport { requireBuiltin } from '../utilities/builtin.js';\n\n// worker_threads on first use (core/utilities/builtin.ts).\nconst wt = () => requireBuiltin<typeof import('worker_threads')>('worker_threads');\nimport { createFrameworkLogger } from '../logger/index.js';\nimport { cpus } from 'os';\nimport { isPackageAvailable } from '../utilities/package-utils.js';\n// WORKER_ENTRY resolves to worker.js, this file's compiled sibling in dist/**,\n// via import.meta in ./worker-entry.js. That ESM-only syntax is isolated in its\n// own module (mapped to a stub in jest.config) so importing WorkerManager under\n// ts-jest's CommonJS transform never hits a load-time import.meta SyntaxError.\nimport { WORKER_ENTRY } from './worker-entry.js';\n\n// Optional JWT import\nconst jwtAvailable = isPackageAvailable('jsonwebtoken');\n\nconst logger = createFrameworkLogger('WorkerManager');\n\n// Upper bound on the exponential restart backoff\nconst MAX_RESTART_BACKOFF_MS = 5000;\n\n// Hoisted constants — avoids object allocation inside sort comparator on every call\nconst PRIORITY_ORDER: Record<string, number> = { high: 3, normal: 2, low: 1 };\n\n// Simple counter for task IDs — avoids expensive crypto.randomBytes for non-security IDs\nlet taskIdCounter = 0;\n\n/**\n * Worker task definitions\n */\nexport interface WorkerTask {\n id: string;\n type: string;\n data: any;\n priority?: 'low' | 'normal' | 'high';\n timeout?: number;\n}\n\n/**\n * Worker result\n */\nexport interface WorkerResult {\n taskId: string;\n success: boolean;\n data?: any;\n error?: string;\n executionTime: number;\n}\n\n/**\n * Active task tracking\n */\ninterface ActiveTask {\n resolve: CallableFunction;\n reject: CallableFunction;\n timeout: NodeJS.Timeout | null;\n // The worker a task was dispatched to (set once it leaves the queue). Used so a\n // crashed worker only rejects its own in-flight tasks, not everyone else's.\n assignedWorker?: Worker;\n}\n\n/**\n * Built-in worker tasks\n */\nexport const WORKER_TASKS = {\n JWT_VERIFY: 'jwt:verify',\n JWT_SIGN: 'jwt:sign',\n CRYPTO_HASH: 'crypto:hash',\n CRYPTO_ENCRYPT: 'crypto:encrypt',\n CRYPTO_DECRYPT: 'crypto:decrypt',\n DATA_COMPRESS: 'data:compress',\n DATA_DECOMPRESS: 'data:decompress',\n IMAGE_PROCESS: 'image:process',\n HEAVY_COMPUTATION: 'computation:heavy',\n JSON_TRANSFORM: 'json:transform',\n} as const;\n\n/**\n * Worker Thread Manager\n * Manages a pool of worker threads for CPU-intensive operations\n */\nexport class WorkerManager {\n private workers: Map<number, Worker> = new Map();\n private taskQueue: WorkerTask[] = [];\n private activeTasks: Map<string, ActiveTask> = new Map();\n private workerCount: number;\n private maxQueueSize: number;\n private isShuttingDown = false;\n private maxRestartAttempts: number;\n private restartBackoffMs: number;\n private restartAttempts = 0;\n private restartTimers = new Set<NodeJS.Timeout>();\n private handledFailures = new WeakSet<Worker>();\n private poolFailed = false;\n\n constructor(\n options: {\n workerCount?: number;\n maxQueueSize?: number;\n maxRestartAttempts?: number;\n restartBackoffMs?: number;\n } = {}\n ) {\n this.workerCount = options.workerCount || Math.max(1, cpus().length - 1); // Leave 1 core for main thread\n this.maxQueueSize = options.maxQueueSize || 1000;\n this.maxRestartAttempts = options.maxRestartAttempts ?? 10;\n this.restartBackoffMs = options.restartBackoffMs ?? 100;\n\n this.initializeWorkers();\n }\n\n /**\n * Initialize worker threads\n */\n private initializeWorkers(): void {\n for (let i = 0; i < this.workerCount; i++) {\n this.createWorker();\n }\n\n logger.info(`Initialized ${this.workerCount} worker threads`, 'WorkerInit', {\n totalWorkers: this.workerCount,\n maxQueueSize: this.maxQueueSize,\n });\n }\n\n /**\n * Create a single worker thread\n */\n private createWorker(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n let worker: Worker;\n try {\n worker = new (wt().Worker)(WORKER_ENTRY, {\n workerData: { type: 'worker' },\n });\n } catch (error) {\n // Spawning can fail synchronously (e.g. a missing entry file). Treat it the\n // same as a runtime failure so we back off instead of throwing.\n logger.error('Failed to spawn worker thread', 'WorkerSpawn', {\n error: error instanceof Error ? error.message : String(error),\n });\n this.scheduleRestart();\n return;\n }\n\n worker.on('message', (result: WorkerResult) => {\n // A successful message proves the pool is healthy; reset the restart budget.\n this.restartAttempts = 0;\n this.handleWorkerResult(result);\n });\n\n worker.on('error', error => {\n logger.error('Worker thread error', 'WorkerError', { error: error.message });\n this.handleWorkerFailure(worker);\n });\n\n worker.on('exit', code => {\n if (code !== 0 && !this.isShuttingDown) {\n logger.warn(`Worker exited with code ${code}, restarting`, 'WorkerExit');\n this.handleWorkerFailure(worker);\n }\n });\n\n this.workers.set(worker.threadId, worker);\n logger.debug(`Created worker thread ${worker.threadId}`, 'WorkerCreate');\n }\n\n /**\n * Handle a crashed worker: reject only the tasks that were assigned to it and\n * schedule a backed-off restart. A failed worker emits both 'error' and 'exit',\n * so this is guarded to run at most once per worker.\n */\n private handleWorkerFailure(worker: Worker): void {\n if (this.handledFailures.has(worker)) {\n return;\n }\n this.handledFailures.add(worker);\n\n this.workers.delete(worker.threadId);\n\n if (this.isShuttingDown) {\n return;\n }\n\n // Reject only the tasks that were dispatched to this specific worker. Tasks\n // still queued (or running on other workers) are intentionally left alone.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.assignedWorker === worker) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker thread failed'));\n this.activeTasks.delete(taskId);\n }\n }\n\n this.scheduleRestart();\n }\n\n /**\n * Schedule a replacement worker with exponential backoff, capping the number of\n * consecutive restart attempts so a persistently broken worker entry can never\n * spin into an unbounded restart loop.\n */\n private scheduleRestart(): void {\n if (this.isShuttingDown || this.poolFailed) {\n return;\n }\n\n this.restartAttempts++;\n\n if (this.restartAttempts > this.maxRestartAttempts) {\n this.failPool();\n return;\n }\n\n const delay = Math.min(\n this.restartBackoffMs * 2 ** (this.restartAttempts - 1),\n MAX_RESTART_BACKOFF_MS\n );\n\n logger.warn(\n `Scheduling worker restart in ${delay}ms (attempt ${this.restartAttempts}/${this.maxRestartAttempts})`,\n 'WorkerRestart'\n );\n\n const timer = setTimeout(() => {\n this.restartTimers.delete(timer);\n this.createWorker();\n }, delay);\n\n // Don't keep the process alive purely for a pending restart\n timer.unref();\n this.restartTimers.add(timer);\n }\n\n /**\n * Give up after too many failed restarts: fail every outstanding task cleanly\n * (rejecting their promises) instead of looping forever.\n */\n private failPool(): void {\n if (this.poolFailed) {\n return;\n }\n this.poolFailed = true;\n\n logger.error(\n `Worker pool failed to recover after ${this.maxRestartAttempts} restart attempts`,\n 'WorkerPoolFailed'\n );\n\n const error = new Error(\n `Worker pool is unavailable after ${this.maxRestartAttempts} failed restart attempts`\n );\n\n // Every queued task also has an activeTasks entry, so this rejects both\n // in-flight and queued work.\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(error);\n this.activeTasks.delete(taskId);\n }\n\n this.taskQueue.length = 0;\n }\n\n /**\n * Execute a task on a worker thread\n */\n async executeTask<T = any>(task: WorkerTask): Promise<T> {\n if (this.isShuttingDown) {\n throw new Error('Worker manager is shutting down');\n }\n\n if (this.poolFailed) {\n throw new Error('Worker pool is unavailable (too many worker failures)');\n }\n\n return new Promise<T>((resolve, reject) => {\n // Check queue size limit\n if (this.taskQueue.length >= this.maxQueueSize) {\n reject(new Error('Worker queue is full'));\n return;\n }\n\n // Add to queue\n this.taskQueue.push(task);\n\n // Set up promise handlers\n const timeout = task.timeout\n ? setTimeout(() => {\n this.activeTasks.delete(task.id);\n reject(new Error(`Task ${task.id} timed out`));\n }, task.timeout)\n : null;\n\n // Don't keep process alive for worker timeouts\n if (timeout) {\n timeout.unref();\n }\n\n this.activeTasks.set(task.id, { resolve, reject, timeout });\n\n // Try to assign task to available worker\n this.processQueue();\n });\n }\n\n /**\n * Process the task queue\n */\n private processQueue(): void {\n // Sort queue by priority (high first)\n this.taskQueue.sort(\n (a, b) =>\n (PRIORITY_ORDER[b.priority || 'normal'] ?? 0) -\n (PRIORITY_ORDER[a.priority || 'normal'] ?? 0)\n );\n\n // Assign tasks to available workers\n for (const [threadId, worker] of this.workers.entries()) {\n if (this.taskQueue.length === 0) break;\n\n // Check if worker is available (not currently processing)\n // For simplicity, we'll send tasks and let workers handle queuing\n const task = this.taskQueue.shift();\n if (task) {\n // Record the assignment so a crashed worker only rejects its own tasks.\n const taskInfo = this.activeTasks.get(task.id);\n if (taskInfo) {\n taskInfo.assignedWorker = worker;\n }\n worker.postMessage(task);\n logger.debug(`Assigned task ${task.id} to worker ${threadId}`, 'TaskAssigned');\n }\n }\n }\n\n /**\n * Handle result from worker thread\n */\n private handleWorkerResult(result: WorkerResult): void {\n const taskInfo = this.activeTasks.get(result.taskId);\n if (!taskInfo) {\n logger.warn(`Received result for unknown task ${result.taskId}`, 'UnknownTaskResult');\n return;\n }\n\n // Clear timeout\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n\n // Remove from active tasks\n this.activeTasks.delete(result.taskId);\n\n // Handle result\n if (result.success) {\n logger.debug(`Task ${result.taskId} completed in ${result.executionTime}ms`, 'TaskCompleted');\n taskInfo.resolve(result.data);\n } else {\n logger.error(`Task ${result.taskId} failed: ${result.error}`, 'TaskFailed');\n taskInfo.reject(new Error(result.error || 'Task failed'));\n }\n\n // Process next task in queue\n this.processQueue();\n }\n\n /**\n * Shutdown all workers\n */\n async shutdown(): Promise<void> {\n this.isShuttingDown = true;\n\n // Cancel any pending worker restarts\n for (const timer of this.restartTimers) {\n clearTimeout(timer);\n }\n this.restartTimers.clear();\n\n // Reject all pending tasks\n // eslint-disable-next-line @typescript-eslint/no-unused-vars\n for (const [taskId, taskInfo] of this.activeTasks.entries()) {\n if (taskInfo.timeout) {\n clearTimeout(taskInfo.timeout);\n }\n taskInfo.reject(new Error('Worker manager shutting down'));\n }\n\n // Terminate all workers\n const shutdownPromises = Array.from(this.workers.values()).map(\n worker =>\n new Promise<void>(resolve => {\n worker.once('exit', () => resolve());\n void worker.terminate();\n })\n );\n\n await Promise.all(shutdownPromises);\n this.workers.clear();\n this.activeTasks.clear();\n this.taskQueue.length = 0;\n\n logger.info('Worker manager shutdown complete', 'WorkerShutdown');\n }\n\n /**\n * Get worker statistics\n */\n getStats() {\n return {\n workerCount: this.workers.size,\n activeTasks: this.activeTasks.size,\n queuedTasks: this.taskQueue.length,\n isShuttingDown: this.isShuttingDown,\n };\n }\n}\n\n// Singleton instance\nlet workerManagerInstance: WorkerManager | null = null;\n\n/**\n * Get or create the worker manager instance\n */\nexport function getWorkerManager(options?: {\n workerCount?: number;\n maxQueueSize?: number;\n}): WorkerManager {\n if (!workerManagerInstance) {\n workerManagerInstance = new WorkerManager(options);\n }\n return workerManagerInstance;\n}\n\n/**\n * Execute task on worker thread (convenience function)\n */\nexport async function executeOnWorker<T = any>(task: WorkerTask): Promise<T> {\n const manager = getWorkerManager();\n return manager.executeTask<T>(task);\n}\n\n/**\n * Built-in task helpers\n */\nexport const workerTasks = {\n /**\n * JWT verification (CPU-intensive)\n */\n async verifyJWT(token: string, secret: string, options?: any): Promise<any> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT verification requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-verify-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_VERIFY,\n data: { token, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * JWT signing (CPU-intensive)\n */\n async signJWT(payload: any, secret: string, options?: any): Promise<string> {\n if (!jwtAvailable) {\n throw new Error(\n 'JWT signing requires the \"jsonwebtoken\" package. Please install it with: npm install jsonwebtoken @types/jsonwebtoken'\n );\n }\n return executeOnWorker({\n id: `jwt-sign-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JWT_SIGN,\n data: { payload, secret, options },\n priority: 'high',\n timeout: 5000,\n });\n },\n\n /**\n * Crypto hash (CPU-intensive)\n */\n async hash(data: string, algorithm = 'sha256'): Promise<string> {\n return executeOnWorker({\n id: `crypto-hash-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.CRYPTO_HASH,\n data: { data, algorithm },\n priority: 'normal',\n timeout: 10000,\n });\n },\n\n /**\n * Data compression (CPU-intensive for large payloads)\n */\n async compress(\n data: string | Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-compress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_COMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n // Buffers cross the thread boundary as plain Uint8Array\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Data decompression (CPU-intensive for large payloads)\n */\n async decompress(\n data: Buffer | Uint8Array,\n options?: { format?: 'gzip' | 'deflate' | 'brotli' }\n ): Promise<Buffer> {\n const result = await executeOnWorker<Uint8Array>({\n id: `data-decompress-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.DATA_DECOMPRESS,\n data: { input: data, format: options?.format ?? 'gzip' },\n priority: 'normal',\n timeout: 30000,\n });\n return Buffer.isBuffer(result) ? result : Buffer.from(result);\n },\n\n /**\n * Heavy computation example\n */\n async heavyComputation(data: any): Promise<any> {\n return executeOnWorker({\n id: `computation-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.HEAVY_COMPUTATION,\n data,\n priority: 'normal',\n timeout: 30000,\n });\n },\n\n /**\n * JSON transformation (can be CPU-intensive for large objects)\n */\n async transformJSON(data: any, transformer: (data: any) => any): Promise<any> {\n return executeOnWorker({\n id: `json-transform-${Date.now()}-${++taskIdCounter}`,\n type: WORKER_TASKS.JSON_TRANSFORM,\n data: { data, transformer: transformer.toString() },\n priority: 'normal',\n timeout: 15000,\n });\n },\n};\n"]}
|
package/dist/moro.d.ts
CHANGED
|
@@ -253,7 +253,12 @@ export declare class Moro extends EventEmitter {
|
|
|
253
253
|
* - BetterStack Node.js Clustering: https://betterstack.com/community/guides/scaling-nodejs/node-clustering/
|
|
254
254
|
*/
|
|
255
255
|
private clusterWorkers;
|
|
256
|
+
private threadCluster;
|
|
256
257
|
private startWithClustering;
|
|
258
|
+
private startPrimaryServices;
|
|
259
|
+
private startThreadPrimary;
|
|
260
|
+
private startProcessPrimary;
|
|
261
|
+
private startClusterWorker;
|
|
257
262
|
private handleWorkerMessage;
|
|
258
263
|
/**
|
|
259
264
|
* Gracefully close the application and clean up resources
|