Commit | Line | Data |
---|---|---|
d0ed34c9 JB |
1 | import { dirname, extname, join } from 'node:path' |
2 | import { fileURLToPath } from 'node:url' | |
3 | import { FixedClusterPool, availableParallelism } from 'poolifier' | |
4 | import type { ClusterWorkerData, ClusterWorkerResponse } from './types.js' | |
5 | ||
6 | const expressWorkerFile = join( | |
7 | dirname(fileURLToPath(import.meta.url)), | |
8 | `express-worker${extname(fileURLToPath(import.meta.url))}` | |
9 | ) | |
10 | ||
11 | const requestHandlerWorkerFile = join( | |
12 | dirname(fileURLToPath(import.meta.url)), | |
13 | `request-handler-worker${extname(fileURLToPath(import.meta.url))}` | |
14 | ) | |
15 | ||
16 | const pool = new FixedClusterPool<ClusterWorkerData, ClusterWorkerResponse>( | |
17 | availableParallelism(), | |
18 | expressWorkerFile, | |
19 | { | |
c5033c2d | 20 | enableEvents: false, |
d0ed34c9 JB |
21 | onlineHandler: () => { |
22 | pool | |
23 | .execute({ | |
24 | port: 8080, | |
25 | maxWorkers: | |
26 | Math.round(availableParallelism() / 4) < 1 | |
27 | ? 1 | |
28 | : Math.round(availableParallelism() / 4), | |
29 | workerFile: requestHandlerWorkerFile, | |
30 | enableTasksQueue: true, | |
31 | tasksQueueOptions: { | |
32 | concurrency: 8 | |
33 | }, | |
34 | errorHandler: (e: Error) => { | |
35 | console.error('Thread worker error:', e) | |
36 | } | |
37 | }) | |
041dc05b | 38 | .then(response => { |
d0ed34c9 JB |
39 | if (response.status) { |
40 | console.info( | |
c63a35a0 | 41 | `Express is listening in cluster worker on port ${response.port}` |
d0ed34c9 JB |
42 | ) |
43 | } | |
fefd3cef | 44 | return undefined |
d0ed34c9 | 45 | }) |
041dc05b | 46 | .catch(error => { |
d0ed34c9 JB |
47 | console.error('Express failed to start in cluster worker:', error) |
48 | }) | |
49 | }, | |
50 | errorHandler: (e: Error) => { | |
51 | console.error('Cluster worker error:', e) | |
52 | } | |
53 | } | |
54 | ) |