Injecting Remote Context via Options
UPDATE 2016-12-22 We ended up implementing a different solution as described in https://github.com/strongloop/loopback/pull/3023.
Tasks
- [x] Make the change in the
masterbranch - see https://github.com/strongloop/loopback/pull/3023 (released in[email protected]) - [x] Back-port to
2.x- see https://github.com/strongloop/loopback/issues/3048 (released in[email protected]) - [x] Update the documentation - see https://github.com/strongloop/loopback.io/pull/227
- [x] Close other context-related issues and point users to this new solution.
Original description for posterity
The example below allows you to inject the remote context object (from strong remoting) into all methods that accept an options argument.
function inject(ctx, next) {
var options = hasOptions(ctx.method.accepts) && (ctx.args.options || {});
if(options) {
options.remoteCtx = ctx;
ctx.args.options = options;
}
next();
}
app.remotes().before('*.*', inject);
app.remotes().before('*.prototype.*', function(ctx, instance, next) {
inject(ctx, next);
});
// unfortunately this requires us to add the options object
// to the remote method definition
app.remotes().methods().forEach(function(method) {
if(!hasOptions(method.accepts)) {
method.accepts.push({
arg: 'options',
type: 'object',
injectCtx: true
});
}
});
function hasOptions(accepts) {
for (var i = 0; i < accepts.length; i++) {
var argDesc = accepts[i];
if (argDesc.arg === 'options' && argDesc.injectCtx) {
return true;
}
}
}
Why? So you can use the remote context in remote methods, operation hooks, connector implementation, etc.
MyModel.observe('before save', function(ctx, next) {
console.log(ctx.options.remoteCtx.accessToken.userId); // current user
});
This approach is specifically designed to allow you to do what is possible with loopback.getCurrentContext() but without the dependency on cls. The injection approach is much simpler and should be quite a bit faster since cls adds some significant overhead.
@bajtos @fabien @raymondfeng
@ritch - the initial chunk of code sits in server/server.js correct?
A boot script works fine... The goal is to add this to core
The mechanism of passing the context object via the options argument looks ok, it's consistent with what we already do for transactions.
However, I dislike the fact that we want to expose the full remoting context to all model methods.
IMO, model methods should be as much transport (remoting-context) agnostic as possible. In my mind, here is the basic promise of LoopBack and strong-remoting: write your model methods once, then invoke them using whatever transport is most appropriate (REST RPC, JSON-RPC, WebSocket, MQTT, etc.). Once users start coupling their method implementation with remoting context details, it will be difficult to switch to a different transport. For example, I believe the websocket transport does not have the concept of req and res objects as provided by express.
We already had a similar discussion when implementing loopback.context() middleware, see https://github.com/strongloop/loopback/pull/337#issuecomment-59007194 and the following comments. The agreement was to implement a flag (disabled by default) which turns on this new behavior.
I am proposing to do the same here, for example:
// usage - code-first
app.enableRemotingContextInjection();
// usage via loopback-boot
// server/config.json
{
port: 3000,
enableRemotingContextInjection: true,
// etc.
}
// implementation - provided by LoopBack
app.enableRemotingContextInjection = function() {
app.remotes().before('*.*', inject);
app.remotes().before('*.prototype.*', function(ctx, instance, next) {
inject(ctx, next);
});
// etc.
};
Thoughts?
I think we should leave users the choice, either this or use the cls approach. Sometimes you need access to the context, possibly even outside of the methods covered above.
@ritch how would one set the accessToken or a user object?
eg. When I create a middleware after loopback.token() to set things up, how would I get access to ctx.options.remoteCtx to set things?
nvm, I understand that ctx.options.remoteCtx is an object with req and res etc.
I'm finding that using the above sample code does not inject the remoteCtx when calling a models methods directly.
Eg. I have a contractor model that hasMany contracts. The Contract.before('access', function () { }) hook is breaking when I try to access a contractor (ctx.options is undefined) but works fine when accessing the contract directly
Example: In contractor.js
Contractor.afterRemote('**', function (ctx, next) {
var Contract = Contractor.app.models.Contract
Contract.find(function (contracts) {
console.log(contracts)
})
})
Blows up with a 500 error when accessing contractor via explorer with the message:
TypeError: Cannot read property 'req' of undefined which comes from the Contract.before('access') when trying to access ctx.options.remoteCtx.req which works fine when accessing Contract directly
Just to summarize the error I'm seeing...
Anytime I access a related model, whether it's using includes in the url or just running a MyRelatedModel.find, the before access hooks in the myRelatedModel instance context.options does not contain remoteCtx.
Anytime I access a related model, whether it's using includes in the url or just running a MyRelatedModel.find, the before access hooks in the myRelatedModel instance context.options does not contain remoteCtx.
This is a know issue of remoting hooks, see https://github.com/strongloop/loopback/issues/737. If you are accessing your Contract model via Contractor model, then you need to configure context-injecting hook for Contractor too.
You need to pass the options.remoteCtx yourself in the example you mentioned above.
Contractor.afterRemote('**', function (ctx, next) {
var Contract = Contractor.app.models.Contract
var filter = {};
var options = {remoteCtx: ctx};
// the example above was also missing the `err` argument
Contract.find(filter, options, function (err, contracts) {
console.log(contracts);
});
});
This highlights a downside of this approach: you must pass the remoteCtx around yourself. The advantage is you get to control when the remoteCtx is set. It is also much less magic (and error prone) than using the cls approach.
This approach breaks User.login for us. The 3rd argument here: https://github.com/strongloop/loopback/blob/master/common/models/user.js#L169 is now the options arg (containing the remoteCtx object), which results in an error here: https://github.com/strongloop/loopback/blob/master/common/models/user.js#L228
Thanks @ritch most helpful info. I think i'm almost there. Small problem though:
Via explorer: GET /contracts
Contract.observe('access', function (ctx, next) {
//ctx has no access to remoting context
next();
});
I believe this is just the same issue you describe a fix for above except that I'm not sure (since I'm not directly calling Contract.find) how I can inject the remote context via the options object you describe above. My understanding is that if I could directly call:
Contract.find(filter, { remoteCtx: ctx }, function (err, contracts) {
})
then in:
Contract.observe('access', function (ctx, next) {
//ctx.options.remoteCtx will be set
});
@digitalsadhu you need to inject the remoting context into options argument via a remoting hook. See the code in the issue description.
function inject(ctx, next) {
var options = hasOptions(ctx.method.accepts) && (ctx.args.options || {});
if(options) {
options.remoteCtx = ctx;
ctx.args.options = options;
}
next();
}
app.remotes().before('*.*', inject);
app.remotes().before('*.prototype.*', function(ctx, instance, next) {
inject(ctx, next);
});
This code will inject remoting context to all models and all methods. If you prefer to inject the context only for Contract methods, then you can change the hook spec:
app.remotes().before('Contract.*', inject);
app.remotes().before('Contract.prototype.*', function(ctx, instance, next) {
inject(ctx, next);
});
Thanks @bajtos I am doing that in a context.js boot script. Thats working fine in most cases. There are a couple places where its not working:
Contract.observe('access') doesn't get ctx.options.remoteCtx where as Contract.observe('after save') does.
I should also say, I've logged out the injection and it does happen before the access hook is called and all looks well, it just never makes it onto the access hook ctx object
This works:
Contract.observe('after save', function createHistory(ctx, next) {
var History = Contract.app.models.History;
var contract = ctx.instance;
History.create({
contractId: contract.id,
createdBy: ctx.options.remoteCtx.req.user.name,
snapshot: JSON.stringify(contract)
}, next);
});
This doesn't work:
Contract.observe('access', function limitContractStaff(ctx, next) {
var user = ctx.options.remoteCtx.req.user;
//ctx.options === {}
if (user.group === roles.MANAGER)
ctx.query.where = merge(ctx.query.where || {}, { createdBy: user.name });
next();
});
NVM, pretty sure its just an overly complicated model with side effects I wasn't aware of. Sorry for the spam ;)
@digitalsadhu OK :) OTOH, it is possible that your model method doesn't have options argument and therefore the remoting hook does not inject remoteCtx.
Nope. I've tracked down the last of my issues and now have a working solution. Every case was just me not explicitly passing {remoteCtx:ctx} to model methods such as find or findById etc. once I had tracked down all of those everything worked.
@bajtos @ritch
FWIW The reason I've jumped through hoops to get rid of getCurrentContext with this approach is that I've repeatedly run into issues with getCurrentContext returning null with various connectors or platforms. Eg. windows with mssql connector
The latest I've discovered (and should file a bug) is that if you use the memory connector and give a file to add persistence. The use of async.queue to save changes to the json file seems to be the culprit (I did some investigation and removed the use of async.queue and the issue went away).
I have a feeling you guys are already pretty aware of these types of issues and I suspect its mostly related to cls right?
Anyway, my comment being, I think it be really great to see a simpler approach such as the one provided in this issue used.
Thanks for all the help!
The use of async.queue to save changes to the json file seems to be the culprit (I did some investigation and removed the use of async.queue and the issue went away).
Thanks for digging in this far...
I have a feeling you guys are already pretty aware of these types of issues and I suspect its mostly related to cls right?
Yes - cls is not a dependency I am comfortable with. The only reason we ever considered it was the simplicity in using getCurrentContext()... Your experience with it not reliably returning the context is what I have feared for a while. I would recommend moving away from getCurrentContext() and using my prescribed method. You have to be diligent about passing the remoteCtx around, which as you've seen is a bit tricky... but this is much easier than trying to figure out if getCurrentContext is broken or not every time you see it returning null.