/**
 * Create request domain for node cluster server.
 * @function serverside.middleware.defineClusterDomainMiddleware
 * @param {object} context - Server context object.
 * @param {number} context.SERVER_CRASH_DELAY - Milliseconds to wait before killing the process when error occur.
 * @author Taka Okunishi
 *
 */

var domain = require('domain');
module.exports = function (context) {
    context.assertKeys(['SERVER_CRASH_DELAY']);
    var delay = context.SERVER_CRASH_DELAY;
    return function (req, res, next) {
        var workingDomain = domain.create();
        workingDomain.on('error', function (err) {
            process.clusterDomainError && process.clusterDomainError(err);
            var killTimer = setTimeout(function () {
                process.exit(1);
            }, delay);
            killTimer.unref();
            next(err);
        });
        workingDomain.add(req);
        workingDomain.add(res);
        workingDomain.add(next);
        workingDomain.run(function () {
            next();
        });
    };
};