| 1 | import { dirname, extname, join } from 'node:path' |
| 2 | import { fileURLToPath } from 'node:url' |
| 3 | |
| 4 | import { availableParallelism, FixedClusterPool } from 'poolifier' |
| 5 | |
| 6 | import type { WorkerData, WorkerResponse } from './types.js' |
| 7 | |
| 8 | const workerFile = join( |
| 9 | dirname(fileURLToPath(import.meta.url)), |
| 10 | `worker${extname(fileURLToPath(import.meta.url))}` |
| 11 | ) |
| 12 | |
| 13 | const pool = new FixedClusterPool<WorkerData, WorkerResponse>( |
| 14 | availableParallelism(), |
| 15 | workerFile, |
| 16 | { |
| 17 | enableEvents: false, |
| 18 | onlineHandler: () => { |
| 19 | pool |
| 20 | .execute({ port: 8080 }) |
| 21 | .then(response => { |
| 22 | if (response.status) { |
| 23 | console.info( |
| 24 | `WebSocket server is listening in cluster worker on port ${response.port}` |
| 25 | ) |
| 26 | } |
| 27 | return undefined |
| 28 | }) |
| 29 | .catch((error: unknown) => { |
| 30 | console.error( |
| 31 | 'WebSocket server failed to start in cluster worker:', |
| 32 | error |
| 33 | ) |
| 34 | }) |
| 35 | }, |
| 36 | errorHandler: (e: Error) => { |
| 37 | console.error('Cluster worker error', e) |
| 38 | } |
| 39 | } |
| 40 | ) |