Skip to content

Commit

Permalink
Merge pull request #9 from bossmodex/feat-cluster-mode
Browse files Browse the repository at this point in the history
feat: bun cluster mode (multithreading)
  • Loading branch information
NuroDev authored Dec 22, 2024
2 parents e2a789e + 31adcea commit f666a00
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 22 deletions.
57 changes: 35 additions & 22 deletions package/src/server/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
/// <reference types="astro/client" />

import { App } from 'astro/app';
import cluster from 'node:cluster';
import os from 'node:os';

import { extractHostname, serveStaticFile } from '~/server/utils.ts';

Expand All @@ -24,33 +26,44 @@ export function createExports(manifest: SSRManifest, options: Options): CreateEx

let _server: Server | null = null;
export function start(manifest: SSRManifest, options: Options) {
const app = new App(manifest);
const logger = app.getAdapterLogger();

const hostname = process.env.HOST ?? extractHostname(options.host);
const port = process.env.PORT ? Number.parseInt(process.env.PORT) : options.port;

_server = Bun.serve({
development: import.meta.env.DEV,
error: (error) =>
new Response(`<pre>${error}\n${error.stack}</pre>`, {
headers: { 'Content-Type': 'text/html' },
}),
fetch: handler(manifest, options),
hostname,
port,
});

function exit() {
if (_server) _server.stop();
process.exit();
}
if (cluster.isPrimary && options.cluster) {
const numCPUs = os.cpus().length;
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`Worker ${worker.process.pid} died`);
cluster.fork();
});
} else {
const app = new App(manifest);
const logger = app.getAdapterLogger();

_server = Bun.serve({
development: import.meta.env.DEV,
error: (error) =>
new Response(`<pre>${error}\n${error.stack}</pre>`, {
headers: { 'Content-Type': 'text/html' },
}),
fetch: handler(manifest, options),
hostname,
port,
});

function exit() {
if (_server) _server.stop();
process.exit();
}

process.on('SIGINT', exit);
process.on('SIGTERM', exit);
process.on('exit', exit);
process.on('SIGINT', exit);
process.on('SIGTERM', exit);
process.on('exit', exit);

logger.info(`Server listening on ${_server.url.href}`);
logger.info(`Server listening on ${_server.url.href}`);
}
}

function handler(
Expand Down
6 changes: 6 additions & 0 deletions package/src/validators.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,11 @@ export const OptionsSchema = z
port: z.coerce.number().default(4321),
/** TODO(@nurodev): Undocumented */
server: z.string(),
/**
* Enable clustering for the server. (Only linux!)
*
* @default false
*/
cluster: z.boolean().default(false),
})
.partial();

0 comments on commit f666a00

Please sign in to comment.