Deprecate getCurrentContext()
Well its been fun. And by fun I mean: not so fun. We've tried to create a simple method for getting at contextual information no matter where your code is executing. We did this by depending on a sophisticated module called continuation-local-storage .
Continuation-local storage works like thread-local storage in threaded programming, but is based on chains of Node-style callbacks instead of threads.
Someday there will be a more reliable mechanism than the userland cls module, and we can re-add first class support for getCurrentContext(). But until then I am proposing we deprecate this method with the standard warning message.
What does this mean for users of getCurrentContext()? You will get an annoying message (configurable) every time you use the method. We will still support it, and we won't break semver. But we strongly encourage you to refactor.
For an immediate work around, take a look at https://github.com/strongloop/loopback/issues/1495. A more sustainable workaround will be added as a feature to the framework.
/cc @bajtos @raymondfeng @superkhau @piscisaureus
I'm concerned about this, as I have been using getCurrentContext extensively. And without any issues thusfar. I'm on mobile right now, so I don't have access to the whole discussion(s) - IIRC mainly regarding unreliable availability on different platforms - but what's the reasoning here?
Can we have a flag to silence the deprecation warning? ;-)
I abandoned getCurrentContext pretty quickly since it led to unpredictable behavior. Notably, retrieving the Access Token using something like getCurrentContext().get('accessToken') seemed to work at random, if at all, so we worked around it by getting the accessToken from the request instead. Apart from that, we have not needed it anywhere.
I was thinking about the problems of getCurrentContext we are experiencing. It seems to me that most of the issues are caused by the fact that any connector using connection pool must be CLS aware and include few lines of code to switch to the right CLS context. I am wondering we can add this small piece into loopback-datasource-juggler, so that we don't depend on connector implementation anymore?
An example to illustrate my point:
DAO.create = function(data, options, cb) {
// setup instance, call hooks, etc.
clsCtx = // save current CLS context;
connector.create(/*args*/, function(err, result) {
// restore CLS context from clsCtx
// continue as before
});
};
If that's not a viable approach, then I support @fabien's request for a feature flag. This flag can have three states:
undefined- print a warning (default)true- getCurrentContext is enabled (no warning is printed)false- getCurrentContext is disabled (no warning is printed)
Thoughts?
@bajtos Can you or somebody to do a quick PoC to verify your theory?
I'm willing to advocate explicit context passing as the preferred way as it is the only reliable/performant way. It's fine with me to keep the getCurrentContext() if @bajtos's idea works.
I don't think fixing the connector boundary and lack of CLS support in the connectors is the only issue. I've seen issues from our usage of async (which were eventually fixed).
I'm OK with a flag too. Opt-in and with a bit of warning in the documentation. As far as regular API - I still think we should deprecate it.
This flag can have three states:
The states LGTM.
+1 for flag, please
loopback.getCurrentContext() has given lot of hard time while developing unit test cases so far. We had to setup dummy context before executing tests.
However today we faced one major issue where loopback.getCurrentContext () is returned as null when a async callback function gets called.
We are making an external HTTP call from within loopback API in async manner. loopback.getCurrnetContext () is consistently coming as null in the callback made by that http request. The loopback api call is returned by that time.
Is there any way to completely avoid loopback.getCurrentContext() and still make context information available everywhere without explicitly passing it around?
Don't think so. You can get the context everywhere except in Model.observes callbacks. Our preference has been to avoid doing anything that needs context in Model.observes callbacks and get by without getCurrentContext or passing context around. We have found that we can usually get by in this way, sometimes using beforeRemote/afterRemote as a substitute.
On Wed, 23 Dec 2015 at 17:42, Sachin Mane [email protected] wrote:
loopback.getCurrentContext() has given lot of hard time while developing unit test cases so far. We had to setup dummy context before executing tests.
However today we faced one major issue where loopback.getCurrentContext () is returned as null when a async callback function gets called.
We are making an external HTTP call from within loopback API in async manner. loopback.getCurrnetContext () is consistently coming as null in the callback made by that http request. The loopback api call is returned by that time.
Is there any way to completely avoid loopback.getCurrentContext() and still make context information available everywhere without explicitly passing it around?
— Reply to this email directly or view it on GitHub https://github.com/strongloop/loopback/issues/1676#issuecomment-166940426 .
Any progress about cls?
Another bug in node-continuation-local-storage:
It looks like setImmediate breaks cls, therefore any modules using setImmediate are going to break current-context feature. An example: express-session, see https://github.com/strongloop/loopback-context/issues/6
@bajtos I was just yesterday reading through the CLS Issues on github (like this: https://github.com/othiym23/node-continuation-local-storage/issues/59) to get a feel for what the current status is on solving problems like these. It seems like the "solution" is to continue monkey patching libraries that mess up CLS and hope for something native to Javascript which enables this sort of functionality. The only native work is still in early draft (Zones: https://github.com/domenic/zones). I left feeling like CLS cannot be relied upon.
With that in mind, what's Loopback's plan here? This seems like a major pain point for the framework. The Loopback Context is currently dangerously unreliable, and moving away from CLS would be a huge undertaking. However, not having a good way to pass state becomes a huge problem at times. We can explicitly pass things via options in a lot of cases, but it's not universal and it doesn't cover built-ins.
What's the plan?
@doublemarked @pulkitsinghal @diadara
Cross-posting https://github.com/strongloop/loopback/pull/2604#issuecomment-241663799:
Backwards compatibility. We are in a difficult situation - at one hand, we know that continuation-local-storage (and thus loopback-context too) is broken and cannot be reliably fixed in general. At the same time, there may be many users that are depending on loopback-context and for whom it may work, perhaps because their use case does not trigger any of the bugs.
My vision is to make it easy for users that wish to continue using loopback-context to do so, while also making it clear that using loopback-context is not recommended, to prevent new users from using this dangerous concept. Eventually, I would like to stop supporting loopback-context completely, but I am afraid we are not there yet.
What's the plan?
We have deprecated current-context in 2.x and removed it in 3.0 in favor of a standalone loopback-context module.
For short to medium term, I would like us to improve strong-remoting to make it easy to pass context explicitly via options, even though I do realise explicit context passing is far from perfect.
For long term, it would be great to have something similar to thread-local/continuation-local storage. I am afraid this is a problem of the platform (Node.js and/or JavaScript) that cannot be fixed in LoopBack :(
@bajtos TYVM for the reply on this. I think the plan is reasonable and that it feels like you're moving things in the right direction.
I would like to ask more about the following,
For short to medium term, I would like us to improve strong-remoting to make it easy to pass context explicitly via options, even though I do realise explicit context passing is far from perfect.
Glad to hear. Sure, it's maybe inconvenient but having the ability to maintain continuity in some way would be invaluable. This seems to me like the most important stopgap for the time being. Has this work been started? Is there an Git Issue where I could monitor / join the discussion?
Is there an Git Issue where I could monitor / join the discussion?
Sure, see https://github.com/strongloop/loopback/issues/1495.
(The link is in this issue's description too.)
Has this work been started?
Not yet :(
For short to medium term, I would like us to improve strong-remoting to make it easy to pass context explicitly via options, even though I do realise explicit context passing is far from perfect.
From what I found in strongloop/strong-remoting#328 was that the options are lost in the SharedMethod.prototype.invoke method; Thus making the workaround of passing the context per #1495 as an option to not work if you use strong-remoting :(
When trying to simply create a new entry in database using loopback create method,following error pops up: loopback deprecated loopback#context middleware is deprecated.
Another interesting POV with examples showing what breaks CLS propagation: https://github.com/LewisJEllis/async-context-examples/blob/3ff52a73b410183f934b37a69f1df540ede1657e/README.md
I read 2 particularly interesting points in that article.
- the async module is called out for losing context
- CLS correctly maintains context when promises are used
When I did a deep dive into our issues a while back I specifically found the problem to be the use of async inside the database connector.
Is there therefore reason to hope that replacing the async module with promises could fix the issue?
I think it's fair to say that the introduction of CLS-based context propagation within Loopback (sometime mid 2014) turned out extremely painful for many of us (https://github.com/strongloop/loopback/milestone/62).
Before any real issues surfaced, I failed to recognize the risks it introduced, and therefor it continued to permeate throughout my codebase for a long time. Since it had been working fine for such a long time - in my particular setup - I was a bit shocked to hear about its deprecation, initially.
However, over the last few weeks I finally decided to bite the bullet, once I was indeed affected by the lost context issues so many had been reporting before. It wasn't pretty. Nor fun ...
In a testsuite of around 3600 tests (and almost 10.000 assertions, most integration tested), there were easily around 5000(!) calls that would look up the current context. Which now was null - needless to say, there were a huge number of failures, and a daunting task ahead.
I finally finished this afternoon, and here's what I found:
The workaround suggested at #1495 is a good start, but considering that I had so many custom methods (implemented as part of mixins, mostly), it was definitely not solvable by this suggestion alone.
In the end I was able to fix this in 99% of all use-cases, the 1% being cases where you are absolutely unable to pass on the context yourself (things like: app.getCurrentUser() had to be fixed differently, or dropped all together).
Unfortunately, there were a lot of issues along the way:
- just as CLS itself sometimes 'drops the ball' and loses context, it's very easy to do the same. You have to be very careful, as you have to do it explicitly every single time. In a way, its much more error prone than CLS ever was ...
- all exposed custom methods needed their method signature updated with an optional
optionsargument. This was especially true when methods followed the naming conventions of core methods (find, delete, etc.), because they did not always follow the newer convention of havingoptionsand failed to receive thecallbackfunction, causing a time-out. - before,
optionswas considered private/not exposed to remoting. I found a number of uses foroptionsthat you would not want to simply expose, yet the proposed workaround forces you. In short, you have to be careful, and by default user/remoting suppliedoptionsshould be ignored. - Swagger/Explorer signatures are polluted with a useless
optionsargument.
There were many related/newly-induced issues that popped up during the fixing process; no surprises there, if you take into account how this feature was applicable in so many cases.
I've posted my own implementation of the workaround here:
https://gist.github.com/fabien/98fcdf031286d4b67b25331253e47b63
You can specify your custom methods as follows:
MyModel.settings.injectContextMethods = MyModel.settings.injectContextMethods || [];
MyModel.settings.injectContextMethods.push('myCustomMethod'); // static
MyModel.settings.injectContextMethods.push('prototype.myCustomMethod'); // proto
// Or in your my-model.json
{
"injectContextMethods": [
"myCustomMethod",
"prototype.myCustomMethod"
]
}
Unless you already specified options as part of your actual accepts arguments, the user supplied options will be discarded. If it is already part of accepts it will merge them, with the actual context overwriting any user supplied values to prevent tampering.
You could also implement the optional extractRemotingOptions method or use the inject context hook notification to further filter or enhance the options being passed.
In short: it should have never been promoted as a Loopback feature, but most importantly, it should have been fixed a long long time ago. Either using an alternative (which we appear to have with newer Node versions), or with a solution integrated into Loopback and strong-remoting itself as follows:
Model.remoteMethod('import', {
injectContext: true,
isStatic: true,
http: { verb: 'post', path: '/import' },
accepts: { arg: 'data', type: 'object', http: { source: 'body' } },
returns: { arg: 'result', type: [Model.modelName], root: true }
});
With the injectContext annotation above, strong-remoting should not add options permanently to the remote method signature (accepts) but only inject it at runtime. Unless of course, it is actually part of accepts already - causing it to be merged instead.
I hope we can prevent similar deprecations of (once) core features of the framework, and find a stable solution to this concept after all.
It's a valid feature to have (for an example from the Rails world, where Thread.current has a similar reputation as CLS: https://github.com/steveklabnik/request_store).
And finally, I hope my gist helps to solve someone's issues as well.