Skip to content

Instantly share code, notes, and snippets.

@ryanto
Last active April 15, 2018 13:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ryanto/bffb505c5de82c6c8438acd328362ef5 to your computer and use it in GitHub Desktop.
Save ryanto/bffb505c5de82c6c8438acd328362ef5 to your computer and use it in GitHub Desktop.

Worker killer

An express middleware to restart the fastboot process after N requets. Code from https://github.com/outdoorsy/fastboot-graceful-server.

The middleware

// worker-killer.js

/* eslint-env node */

module.exports = function(options) {
  options.minRequests = options.minRequests || 100;
  options.maxRequests = options.maxRequests || 200;

  let server = options.server;
  let ui = server.ui;
  let requestCount = 0;

  let flexRoom = options.maxRequests - options.minRequests;
  let killRequestCount = options.minRequests + Math.floor(Math.random() * flexRoom);

  return function(req, res, next) {
    requestCount++;

    ui.writeLine(`Request ${requestCount}/${killRequestCount}: ${req.headers['user-agent']}`);

    if (requestCount === killRequestCount) {
      res.on('finish', () => {
        ui.writeLine('reached max request count, shutting down');

        req.connection.server.close(() => {
          ui.writeLine('server closed');
          process.exit();
        });

        // kill after 30s just in case processes don't finish in time
        setTimeout(function() {
          console.error("Could not close connections in time, forcefully shutting down");
          process.exit()
        }, 30 * 1000);
      });
    }

    next();
  }
};

The server

// index.js

/* eslint-env node */

const FastBootAppServer = require('fastboot-app-server');
const workerKiller = require('./worker-killer');


let server = new FastBootAppServer({
  distPath: 'path/to/fastboot-dist',

  beforeMiddleware: function(app) {
    app.use(workerKiller({
      minRequests: 1,
      maxRequests: 1,
      server: this,
    }))
  }
});

server.start();

Running fastboot

$ node index.js
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment