Jeff-Lewis / cls-hooked

cls-hooked : CLS using AsynWrap or async_hooks instead of async-listener for node 4.7+
BSD 2-Clause "Simplified" License
764 stars 89 forks source link

context is lost in async waterfall in hapi #47

Open elgreatly opened 5 years ago

elgreatly commented 5 years ago

i'm creating a package and use cls-hooked to keep the request in the context in hapi.js

1- i created the function to start context

let createNamespace = require('cls-hooked').createNamespace;
const ns = createNamespace('test');

bindCurrentNamespace(req, reply) {
    ns.bindEmitter(req);

    ns.run(() => {
        reply()
    });
}

2- another functions to set and get value

 setCurrentContext(req, reply) {
    ns.set('test', 'test');
    reply();
}

 getCurrentContext() {
    return ns.get('test');
 }

when i'm using these functions in async waterfall i lost the context in the second callback

async.waterfall(
    [
      function(cb) {
        getCurrentContext(); // return 'test'
        getTest(cb);
      },
      function(testData, cb1) {
       getCurrentContext(); // return undefined
       getTest2(testData, (err, data) => {
          callback(err, data);
        });
      }
    ],
    callback
  );

i tried to console the namespace to check if it keep the same namespace or not i checked it like that

let ns = getNamespace();
async.waterfall(
    [
      function(cb) {
        console.log(ns);
        getCurrentContext(); // return 'test'
        getTest(cb);
      },
      function(testData, cb1) {
       console.log(ns);
       getCurrentContext(); // return undefined
       getTest2(testData, (err, data) => {
          callback(err, data);
        });
      }
    ],
    callback
  );

what i found is:

  1. first log i got the ns like that
    Namespace {
    name: 'request',
    active: { _ns_name: 'request', id: 1096, 'test': 'test' },
    _set: [ null ],
    id: -1,
    _contexts:
    Map {
     1120 => { _ns_name: 'request', id: 1096, 'test': 'test' },
     1121 => { _ns_name: 'request', id: 1096, 'test': 'test' }
    }
    }
  2. second log i get the ns like that
    Namespace {
    name: 'request',
    active: null,
    _set: [],
    id: -1,
    _contexts: Map {},
    _indent: 0 
    }

    i found namespace.exit(context); in line 412 in context.js file this line exit the context before the callback Done

but when i removed it all requests overwrite each other

anyone have idea how to fix this issue?

elgreatly commented 5 years ago

@Jeff-Lewis do you have idea why this issue happen?