Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

new: hot reload functionallity #14

Merged
merged 6 commits into from May 23, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .travis.yml
@@ -1,8 +1,8 @@
language: node_js
sudo: required
node_js:
- "4"
- "6"
- "8"
before_script: npm install -g yarn
script: make all
after_success:
Expand Down
11 changes: 9 additions & 2 deletions README.md
Expand Up @@ -68,14 +68,21 @@ when done.
* `opts`: The options object containing
* `opts.server` The restify server to install the routes on to.
* `[opts.config]` The POJO of the enroute config.
* `[opts.basePath]` Used with `[opts.config]`. The POJO requires a
`basePath` to correctly resolve the route source file(s).
* `[opts.basePath]` Used with `[opts.config]`. The POJO requires a
`basePath` to correctly resolve the route source file(s).
* `[opts.configPath]` The path to the enroute config on disk.
* `[opts.hotReload]` Indicate whether you want the server to reload the
route from disk each time a request is served,
defaults to false
* `cb` The callback. Returns `Error` if there's an error installing the routes.

Note only one of `opts.config` or `opts.configPath` is needed. The module will
either read in the file from disk, or use a pre-populated POJO.

`opts.hotReload` allows the restify server to reload the route from disk each
time the request is processed. This is extremely slow and should only be used
in non-production instances.

### Example
```javascript
const enroute = require('restify-enroute');
Expand Down
4 changes: 3 additions & 1 deletion lib/index.js
Expand Up @@ -18,6 +18,7 @@ module.exports = {
* validate.
* @param {string} [opts.configPath] The path to the data on disk to
* validate.
* @param {boolean} [opts.hotReload] Whether to hot reload the routes
* @param {string} opts.server The restify server to install the routes
* onto.
* @param {function} cb The callback f(err, result)
Expand All @@ -39,7 +40,8 @@ module.exports = {
install({
enroute: ctx.config,
server: opts.server,
basePath: ctx.basePath
basePath: ctx.basePath,
hotReload: opts.hotReload
}, function (err) {
return _cb(err);
});
Expand Down
105 changes: 103 additions & 2 deletions lib/install.js
Expand Up @@ -6,22 +6,44 @@ var _ = require('lodash');
var assert = require('assert-plus');
var vasync = require('vasync');
var verror = require('verror');
var compose = require('restify').helpers.compose;
var bunyan = require('bunyan');

// local globals
var LOG;


/**
* Install the enroute routes into the restify server.
*
* @param {object} opts Options object.
* @param {object} opts.enroute The parsed enroute configuration.
* @param {object} opts.log an optional logger
* @param {boolean} [opts.hotReload] Whether to hot reload the routes
* @param {object} opts.server The restify server.
* @param {string} opts.basePath The basepath to resolve source files.
* @param {function} cb The callback.
* @returns {undefined}
*/
function install(opts, cb) {
assert.object(opts, 'opts');
assert.optionalObject(opts.log, 'opts.log');
assert.object(opts.enroute, 'opts.enroute');
assert.object(opts.server, 'opts.server');
assert.string(opts.basePath, 'opts.basePath');
assert.optionalBool(opts.hotReload, 'opts.hotReload');

var log;

if (opts.log) {
log = opts.log.child({ component : 'enroute' });
} else {
// only create default logger if one wasn't passed in.
if (!LOG) {
LOG = bunyan.createLogger({ name: 'enroute' });
}
log = LOG;
}

vasync.pipeline({arg: {}, funcs: [
// Read the routes from disk and parse them as functions
Expand All @@ -32,6 +54,11 @@ function install(opts, cb) {
return cb1();
});

if (opts.hotReload) {
log.info({ basePath: opts.basePath },
'hot reloading of routes is enabled for base dir');
}

// go through each of the route names
_.forEach(opts.enroute.routes, function (methods, routeName) {
// go through each of the HTTP methods
Expand All @@ -42,20 +69,34 @@ function install(opts, cb) {
var route;

try {
var func = (opts.hotReload) ?
// restify middleware wrapper for hot reload
function enrouteHotReloadProxy(req, res, next) {
return reloadProxy({
basePath: opts.basePath,
method: method,
req: req,
res: res,
routeName: routeName,
sourceFile: sourceFile
}, next);
} : require(sourceFile);

route = {
name: routeName,
method: method,
func: require(sourceFile)
func: func
};
} catch (e) {
return cb1(new verror.VError({
name: 'EnrouteRequireError',
cause: e,
info: {
file: sourceFile,
route: routeName,
method: method
}
}, 'route function is invalid'));
}, 'failed to require file, possible syntax error'));
}
// if HTTP method is 'delete', since restify uses 'del'
// instead of 'delete', change it to 'del'
Expand Down Expand Up @@ -89,4 +130,64 @@ function install(opts, cb) {
});
}


/**
* using the restify handler composer, create a middleware on the fly that
* re-requires the file on every load executes it.
* @private
* @function reloadProxy
* @param {Object} opts an options object
* @param {String} opts.basePath The basepath to resolve source files.
* @param {String} opts.method http verb
* @param {Object} opts.log the enroute logger
* @param {Object} opts.req the request object
* @param {Object} opts.res the response object
* @param {String} opts.routeName the name of the restify route
* @param {String} opts.sourceFile the response object
* @param {Function} cb callback fn
* @returns {undefined}
*/
function reloadProxy(opts, cb) {
assert.object(opts, 'opts');
assert.string(opts.basePath, 'opts.basePath');
assert.string(opts.method, 'opts.method');
assert.object(opts.req, 'opts.req');
assert.object(opts.res, 'opts.res');
assert.string(opts.routeName, 'opts.routeName');
assert.string(opts.sourceFile, 'opts.sourceFile');
assert.func(cb, 'cb');

// clear require cache for code loaded from a specific base dir
Object.keys(require.cache).forEach(function (cacheKey) {
if (cacheKey.indexOf(opts.basePath) !== -1) {
delete require.cache[cacheKey];
}
});

var handlers;

try {
handlers = require(opts.sourceFile);
} catch (e) {
var err = new verror.VError({
name: 'EnrouteRequireError',
cause: e,
info: {
file: opts.sourceFile,
route: opts.routeName,
method: opts.method
}
}, 'failed to require file, possible syntax error');

// now that the chain has failed, send back the require error.
return cb(err);
}

// if no require error, execute the handler chain. any errors that occur at
// runtime should be a runtime exception.
var handlerChain = compose(handlers);
return handlerChain(opts.req, opts.res, cb);
}


module.exports = install;
3 changes: 3 additions & 0 deletions lib/schemas.js
Expand Up @@ -99,6 +99,9 @@ module.exports = {
},
schemaVersion: {
type: 'number'
},
hotReload: {
type: 'boolean'
}
},
additionalProperties: false,
Expand Down
5 changes: 4 additions & 1 deletion package.json
Expand Up @@ -33,18 +33,21 @@
"chai": "^3.5.0",
"coveralls": "^2.11.14",
"eslint": "^3.8.1",
"fs-extra": "^6.0.1",
"istanbul": "^0.4.5",
"jscs": "^3.0.7",
"mkdirp": "^0.5.1",
"mocha": "^3.1.2",
"nsp": "^2.6.2",
"restify": "^7.0.0",
"restify-clients": "^1.4.0",
"uuid": "^2.0.3"
},
"dependencies": {
"ajv": "^4.8.0",
"assert-plus": "^1.0.0",
"bunyan": "^1.8.12",
"lodash": "^4.16.4",
"restify": "^7.2.0",
"vasync": "^1.6.4",
"verror": "^1.6.0"
}
Expand Down
9 changes: 9 additions & 0 deletions test/etc/fooHotReload.js
@@ -0,0 +1,9 @@
'use strict'

module.exports = function fooGet(req, res, next) {
res.header('name', 'foo');
res.header('method', 'get');
res.header('reload', 'yes');
res.send(200);
next();
};
108 changes: 108 additions & 0 deletions test/install.js
Expand Up @@ -4,15 +4,19 @@ var path = require('path');

var _ = require('lodash');
var assert = require('chai').assert;
var fsExtra = require('fs-extra');
var mkdirp = require('mkdirp');
var restify = require('restify');
var restifyClients = require('restify-clients');
var vasync = require('vasync');
var uuid = require('uuid');

var enroute = require('../lib/index');

var HOST = 'localhost' || process.env.HOST;
var PORT = 1337 || process.env.PORT;
var BASEPATH = path.join(__dirname, '..');
var HOT_RELOAD_TMP_DIR = '/tmp/' + uuid.v4();

var CONFIG = {
schemaVersion: 1,
Expand Down Expand Up @@ -71,6 +75,64 @@ var CONFIG = {
}
};

var HOT_RELOAD_CONFIG = {
schemaVersion: 1,
routes: {
foo: {
get: {
source: './fooGet.js'
},
post: {
source: './fooPost.js'
},
put: {
source: './fooPut.js'
},
delete: {
source: './fooDelete.js'
},
head: {
source: './fooHead.js'
},
patch: {
source: './fooPatch.js'
},
options: {
source: './fooOptions.js'
}
},
bar: {
get: {
source: './barGet.js'
},
post: {
source: './barPost.js'
},
put: {
source: './barPut.js'
},
delete: {
source: './barDelete.js'
},
head: {
source: './barHead.js'
},
patch: {
source: './barPatch.js'
},
options: {
source: './barOptions.js'
}
},
array: {
get: {
source: './arrayGet.js'
}
}
}
};


var SERVER;

describe('enroute-install', function () {
Expand Down Expand Up @@ -145,6 +207,52 @@ describe('enroute-install', function () {
});
});

describe('hot reload', function () {
before(function (done) {
SERVER = restify.createServer();
/* eslint-disable consistent-return */
mkdirp(HOT_RELOAD_TMP_DIR, function (err) {
if (err) {
return done(err);
}
// copy over the hot reloaded route
fsExtra.copy(BASEPATH + '/test/etc',
HOT_RELOAD_TMP_DIR, function (e2) {
return done(e2);
});
});
});

it('should hot reload routes', function (done) {
enroute.install({
config: HOT_RELOAD_CONFIG,
server: SERVER,
basePath: HOT_RELOAD_TMP_DIR,
hotReload: true
}, function (err) {
assert.ifError(err);
// assert the routes were installed correctly
assertServer({}, function (err2) {
assert.ifError(err2);
// now we change fooGet.js to return a 'reload' header
fsExtra.copy(HOT_RELOAD_TMP_DIR + '/fooHotReload.js',
HOT_RELOAD_TMP_DIR + '/fooGet.js', function (err3) {

assert.ifError(err3);
var client = restifyClients.createStringClient('http://'
+ HOST + ':' + PORT);
client.get('/foo', function (err4, req, res, obj) {
assert.ifError(err4);
assert.equal('yes', res.headers.reload);
return done();
});
});
});
});
});

});


/// Privates

Expand Down