refactor: null -> undefined where appropriate
[poolifier.git] / examples / typescript / websocket-server-pool / ws-hybrid / src / main.ts
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 webSocketServerWorkerFile = join(
7 dirname(fileURLToPath(import.meta.url)),
8 `websocket-server-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 Math.round(availableParallelism() / 2),
18 webSocketServerWorkerFile,
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 })
37 .then(response => {
38 if (response.status) {
39 console.info(
40 // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
41 `WebSocket server is listening in cluster worker on port ${response.port}`
42 )
43 }
44 return undefined
45 })
46 .catch(error => {
47 console.error(
48 'WebSocket server failed to start in cluster worker:',
49 error
50 )
51 })
52 },
53 errorHandler: (e: Error) => {
54 console.error('Cluster worker error', e)
55 }
56 }
57 )