skonves / express-http-context

Get and set request-scoped context anywhere
MIT License
299 stars 26 forks source link

Context lost after making the first call to odbc #18

Open ranjithchev opened 6 years ago

ranjithchev commented 6 years ago
const app = require('express')();
const httpContext = require('express-http-context');
var db = require('odbc')();
const cn = "DRIVER={ODBC Driver 13 for SQL Server};SERVER=SOMESERVER,SOMEPORT;DATABASE=somedb;Trusted_Connection=Yes"

app.use(httpContext.middleware);

app.get('/', (req, res) => {
    httpContext.set('foo', 'bar');

    console.log(httpContext.get('foo'));      // prints 'bar'

    db.open(cn, (err) => {
        if (err) throw err;

        console.log(httpContext.get('foo'));  // prints undefined!
        ...
    });
});
...

My environment is

RedHat Enterprise Linux 7.2 (maipo) Node: 6.9.1 npm: 5.6.0 express-http-context: 1.0.4 (have tried 1.0.0 as well)

skonves commented 6 years ago

Thanks for the detailed info! 😃

As I have been looking into these types of issues (context being lost in certain scenarios) I have been looking at the issues in both cls-hooked (on which express-http-context depends) and NodeJS itself. Jeff Lewis, the maintainer of cls-hooked, has some good commentary in https://github.com/Jeff-Lewis/cls-hooked/issues/23 as well as in https://github.com/nodejs/diagnostics/blob/master/tracing/AsyncHooks/problematic-modules.md. (In fact, most of Jeff's contributions are worth reading.)

It looks like many of the consumers of async_hooks and it's dependencies are seeing issues with loss of context and we're doing what we can to try to get it working for everyone. Information like you have provided really helps, so again, thank you!

ranjithchev commented 6 years ago

Hi @skonves . Can you help us with an example as requested https://github.com/wankdanker/node-odbc/issues/37#issuecomment-411878915

edevil commented 6 years ago

@skonves shouldn’t odbc and mysql be added to that list of modules that break the async hooks?

real-artswan commented 5 years ago

Is there any news/workarounds on making it work with mongoose?

webdevian commented 5 years ago

Still having the same issue with mongoose

ayyappayalamati commented 5 years ago

same issue when playing with redis as well, context turned undefined after making the call to redis

rohitsud commented 5 years ago

Short of implementing these modules with support for CLS, there is no way to ensure request tracking will work once these modules have been called.

zhujun24 commented 4 years ago

I have write a tidy npm package http-request-context to do this, using async_hooks, u can try it.