import { ClusterWorker } from 'poolifier'
import { type RawData, WebSocketServer } from 'ws'
+
import {
type DataPayload,
type MessagePayload,
MessageType,
type WorkerData,
- type WorkerResponse
+ type WorkerResponse,
} from './types.js'
-const factorial: (n: number) => number = n => {
- if (n === 0) {
- return 1
+class WebSocketServerWorker extends ClusterWorker<WorkerData, WorkerResponse> {
+ private static wss: WebSocketServer
+
+ private static readonly factorial = (n: number | bigint): bigint => {
+ if (n === 0 || n === 1) {
+ return 1n
+ } else {
+ n = BigInt(n)
+ let factorial = 1n
+ for (let i = 1n; i <= n; i++) {
+ factorial *= i
+ }
+ return factorial
+ }
}
- return factorial(n - 1) * n
-}
-const startWebSocketServer = (workerData?: WorkerData): WorkerResponse => {
- try {
- const wss = new WebSocketServer({ port: workerData?.port }, () => {
+ private static readonly startWebSocketServer = (
+ workerData?: WorkerData
+ ): WorkerResponse => {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ const { port } = workerData!
+
+ WebSocketServerWorker.wss = new WebSocketServer({ port }, () => {
console.info(
- `⚡️[ws server]: WebSocket server is started on worker at ws://localhost:${
- workerData?.port as number
- }/`
+ `⚡️[ws server]: WebSocket server is started in cluster worker at ws://localhost:${port.toString()}/`
)
})
- wss.on('connection', ws => {
+ WebSocketServerWorker.wss.on('connection', ws => {
ws.on('error', console.error)
ws.on('message', (message: RawData) => {
const { type, data } = JSON.parse(
ws.send(
JSON.stringify({
type: MessageType.echo,
- data
+ data,
})
)
break
case MessageType.factorial:
ws.send(
- JSON.stringify({
- type: MessageType.factorial,
- data: { number: factorial(data.number as number) }
- })
+ JSON.stringify(
+ {
+ type: MessageType.factorial,
+ data: {
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+ number: WebSocketServerWorker.factorial(data.number!),
+ },
+ },
+ (_, v: unknown) => (typeof v === 'bigint' ? v.toString() : v)
+ )
)
break
}
})
return {
status: true,
- port: wss.options.port
- }
- } catch (err) {
- return {
- status: false,
- error: err as Error
+ port: WebSocketServerWorker.wss.options.port,
}
}
-}
-class WebSocketServerWorker extends ClusterWorker<WorkerData, WorkerResponse> {
public constructor () {
- super(startWebSocketServer)
+ super(WebSocketServerWorker.startWebSocketServer, {
+ killHandler: () => {
+ WebSocketServerWorker.wss.close()
+ },
+ })
}
}