Skip to content

Instantly share code, notes, and snippets.

@fponticelli
Last active April 29, 2016 15:51
Show Gist options
  • Save fponticelli/ca2a44839fe5ddb3df3be82343cfdc3c to your computer and use it in GitHub Desktop.
Save fponticelli/ca2a44839fe5ddb3df3be82343cfdc3c to your computer and use it in GitHub Desktop.
A multi-process webserver with abe and nodejs + cluster.
import abe.App;
import bl.server.*;
import js.Node.*;
import js.node.Cluster;
import js.node.Os;
import npm.Chalk.*;
class Server {
public static var defaultPort(default, null) = 8787;
public static var defaultHost(default, null) = "0.0.0.0";
public static var maxCpus = #if local 2 #else 128 #end;
public static function main() {
if(Cluster.instance.isMaster) {
var port = getPort(),
host = getHost();
abe.Ports.ifAvailable(port, host)
.success(startCluster)
.failure(function(err) {
console.error(red.apply(err.message));
process.exit(1);
});
} else {
startServer();
}
}
public static function startCluster(_) {
var cluster = Cluster.instance,
cpus = thx.Ints.min(maxCpus, Os.cpus().length);
console.info('Master process ${process.pid} will start $cpus sub-processes');
for(i in 0...cpus) {
var f = cluster.fork();
}
cluster.on('online', function(worker) {
console.log(green.apply('Worker ${worker.process.pid} is online'));
});
cluster.on('exit', function(worker, code, signal) {
console.error(red.apply('Worker ${worker.process.pid} died with code $code, and signal $signal'));
console.log('Starting a new worker');
cluster.fork();
});
}
public static function startServer() {
var app = new App(),
router = app.router;
router.use(mw.Compression.create());
router.use(mw.Morgan.create("common", { immediate : false }));
// router.use(mw.Cors.create());
router.use(mw.FavIcon.create("assets/icon.png"));
// REGISTER ROUTES
router.register(new Index());
// API
var api = router.mount("/api");
api.register(new Upcoming());
// STATIC FILES
var staticAssets = router.mount("/");
staticAssets.use(express.Express.serveStatic("www"));
// START SERVER
var port = getPort(),
host = getHost();
app.http(port, host);
console.info(green.apply('Process ${process.pid} is listening on port: $host:$port'));
}
static function getPort() {
if (process.argv[2] != null) {
return Std.parseInt(process.argv[2]);
} else {
return defaultPort;
}
}
static function getHost() {
if (process.argv[3] != null) {
return process.argv[3];
} else {
return defaultHost;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment