diff --git a/src/config.ts b/src/config.ts index 6c4b38b..732f2a6 100644 --- a/src/config.ts +++ b/src/config.ts @@ -4,6 +4,7 @@ export const config: Config = { port: Number(process.env.PORT ?? 3000), host: process.env.HOST ?? '0.0.0.0', logger: Boolean(Number(process.env.LOGGER) ?? 0), + workers: Number(process.env.WORKERS ?? 1), png: { enabled: Boolean(Number(process.env.PNG ?? 1)), size: { diff --git a/src/server.ts b/src/server.ts index 67ce831..18785ba 100644 --- a/src/server.ts +++ b/src/server.ts @@ -1,7 +1,26 @@ +import cluster from "node:cluster"; import { config } from './config.js'; import { app } from './app.js'; -(async () => { +const useCluster = config.workers > 1; + +if (cluster.isPrimary && useCluster) { + for (let i = 0; i < config.workers; i++) { + cluster.fork(); + } + + cluster.on( + "exit", + (worker, code, signal) => { + console.log(`Worker ${worker.process.pid} died with code ${code} and signal ${signal}`); + + // Fork a new worker + cluster.fork(); + }, + ); +} else { + console.log(`Worker ${process.pid} started`); + const server = await app(); server.listen( @@ -18,4 +37,4 @@ import { app } from './app.js'; console.info(`Server listening at http://${config.host}:${config.port}`); } ); -})(); +} diff --git a/src/types.ts b/src/types.ts index cd042a5..20ed0fe 100644 --- a/src/types.ts +++ b/src/types.ts @@ -14,6 +14,7 @@ export type Config = { port: number; host: string; logger: boolean; + workers: number, versions: number[]; png: { enabled: boolean;