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 | { | |
20 | onlineHandler: () => { | |
21 | pool | |
22 | .execute({ | |
23 | port: 8080, | |
24 | maxWorkers: | |
25 | Math.round(availableParallelism() / 4) < 1 | |
26 | ? 1 | |
27 | : Math.round(availableParallelism() / 4), | |
28 | workerFile: requestHandlerWorkerFile, | |
29 | enableTasksQueue: true, | |
30 | tasksQueueOptions: { | |
31 | concurrency: 8 | |
32 | }, | |
33 | errorHandler: (e: Error) => { | |
34 | console.error('Thread worker error:', e) | |
35 | } | |
36 | }) | |
041dc05b | 37 | .then(response => { |
d0ed34c9 JB |
38 | if (response.status) { |
39 | console.info( | |
40 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions | |
41 | `Express is listening in cluster worker on port ${response?.port}` | |
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 | ) |