@morojs/moro 1.8.8 → 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.
Files changed (36) hide show
  1. package/dist/core/cluster/thread-cluster.d.ts +178 -0
  2. package/dist/core/cluster/thread-cluster.js +389 -0
  3. package/dist/core/cluster/thread-cluster.js.map +1 -0
  4. package/dist/core/framework.js.map +1 -1
  5. package/dist/core/http/moro-engine-server.d.ts +29 -1
  6. package/dist/core/http/moro-engine-server.js +375 -68
  7. package/dist/core/http/moro-engine-server.js.map +1 -1
  8. package/dist/core/http/utils/compression.js +12 -6
  9. package/dist/core/http/utils/compression.js.map +1 -1
  10. package/dist/core/http/utils/uws-worker-clustering.js +10 -6
  11. package/dist/core/http/utils/uws-worker-clustering.js.map +1 -1
  12. package/dist/core/http/uws-http-server.d.ts +1 -0
  13. package/dist/core/http/uws-http-server.js +105 -22
  14. package/dist/core/http/uws-http-server.js.map +1 -1
  15. package/dist/core/jobs/leader-election.js +16 -5
  16. package/dist/core/jobs/leader-election.js.map +1 -1
  17. package/dist/core/networking/websocket-manager.js +4 -2
  18. package/dist/core/networking/websocket-manager.js.map +1 -1
  19. package/dist/core/routing/unified-router.js +60 -29
  20. package/dist/core/routing/unified-router.js.map +1 -1
  21. package/dist/core/runtime/node-adapter.d.ts +1 -1
  22. package/dist/core/runtime/node-adapter.js.map +1 -1
  23. package/dist/core/utilities/builtin.d.ts +1 -0
  24. package/dist/core/utilities/builtin.js +25 -0
  25. package/dist/core/utilities/builtin.js.map +1 -0
  26. package/dist/core/utilities/package-utils.d.ts +28 -3
  27. package/dist/core/utilities/package-utils.js +24 -12
  28. package/dist/core/utilities/package-utils.js.map +1 -1
  29. package/dist/core/workers/worker-manager.js +4 -3
  30. package/dist/core/workers/worker-manager.js.map +1 -1
  31. package/dist/moro.d.ts +5 -0
  32. package/dist/moro.js +364 -204
  33. package/dist/moro.js.map +1 -1
  34. package/dist/types/http.d.ts +1 -1
  35. package/dist/types/http.js.map +1 -1
  36. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
- // Worker Thread Manager - Offload CPU-intensive operations
2
- import { Worker } from 'worker_threads';
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,CAAC,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC;AAE9E,yFAAyF;AACzF,IAAI,aAAa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L,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":"AAEA,OAAO,EAAE,cAAc,EAAE,MAAM,yBAAyB,CAAC;AAEzD,2DAA2D;AAC3D,MAAM,EAA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AAM,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