node-continuation-local-storage
node-continuation-local-storage copied to clipboard
Value persists in cls namespace even when http request has ended
Hi! I'm using the usual method to have CLS contexts per http request:
// express middleware
function runInNamespace(req, res, next) {
var namespace = cls.getNamespace('horus-dashboard-ns');
// wrap the events from request and response
namespace.bindEmitter(req);
namespace.bindEmitter(res);
// run following middleware in the scope of
// the namespace we created
namespace.run(function() {
namespace.set('login', 'anonymous');
namespace.set('reqMethod', req.method);
namespace.set('reqUrl', req.url);
next();
});
}
I'm using the Sequelize Bluebird shim to have CLS play nicely with Promises.
On a certain request, I pre-populate a cache and store it in the namespace:
var cache = exports.clsNamespace.get('allConfigs');
if ( cache != null ) return Promise.resolve(cache);
// populates some data
exports.clsNamespace.set('allConfigs', data);
The thing is, I thought that allConfigs
property would disappear when the HTTP request ended (that cache is intended to be used by several pieces of business logic, but on the same request). What I'm seeing is, that once the first request populates the cache, other requests detect it and I end up always using stale data.
Is this the correct behaviour? Should I manually clear the namespace before every request?
I'm having exactly the same issue.
Hi @stnever.
Can you post the complete code? i.e. in what context you're running the var cache = exports.clsNamespace.get('allConfigs');
etc code?
It sounds like the cache code is being run out of context i.e. is writing the cache to the "root" CLS context, rather than within the context of the request. Hence why it then persists across different requests.
Combining CLS with promises gets complicated. (see #64 if you want to nerd out about it!)
@stnever Did you fix it?
By the way, I'd recommend using cls-bluebird if you're using CLS with Bluebird promises. I did a big rewrite of it and it's more reliable than the Sequelize shim. cls-bluebird has got 100,000 tests for god's sake!
Concerning this issue, I don't think the OP ever gave enough detail to understand where the problem is coming from. If you're also having this problem @stnever maybe post a more complete example?
Oops, sorry for the delay!
I'm afraid the portion of code where this was happening was refactored a while ago, and I didn't get around to building a completely reproducible example. At any rate, I'm no longer seeing this problem.
I'll check cls-bluebird, thanks!
OK if you're also having this problem @mariodu maybe post a more complete example?