question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

context is lost on 'end' event of http request stream

See original GitHub issue

Here is a sample snippet:

const http = require('http');
var createNamespace = require('cls-hooked').createNamespace;
var session = createNamespace('session-ns');


const server = http.createServer(function (request, response) {
    session.run(function (ctx) {
        session.set('key', 1)
        read(request, response, function (req, res) {
            process._rawDebug(`DONE - key: ${session.get('key')}`)
            res.end(`key: ${session.get('key')}\r\n`)
        })
    })
})

server.listen(8080)

function read(req, res, done) {
    let body = [];
    req
        .on('data', function (chunk) {
            body.push(chunk)
        })
        .on('end', function () {
            body = Buffer.concat(body).toString()
            process._rawDebug(`End - key: ${session.get('key')}`)
            done(req, res)
        });
}

As you can see I have created a http server and read the body by a stream. run the snippet then use curl. curl http://localhost:8080
console output:

End - key: 1  
DONE - key: 1

for simple GET requests the context is correct, but when you send data in the body the context is lost. curl http://localhost:8080 -X POST -d aaaaaaaaaa console output:

End - key: undefined   
DONE - key: undefined

This issues is also related to this skonves/express-http-context#4. The problem is not the body-parser package, I have tracked it down and found that it is caused by the same issue as here, the callback of ‘end’ event looses context.

Node runtime: reproducible on all v8.14.0, v10.4.0, v10.3.0, and v10.14.1
OS: Ubuntu 18.04
cls-hooked: 4.2.2

Issue Analytics

  • State:open
  • Created 5 years ago
  • Reactions:4
  • Comments:25 (6 by maintainers)

github_iconTop GitHub Comments

5reactions
kjavaherpourcommented, Mar 20, 2020

Hi @Jeff-Lewis, any progress on this?

5reactions
Aidiiincommented, Feb 6, 2019

@Strate @PoslavskySV I decided to use my own naive implementation.

const asyncHooks = require('async_hooks')

let contexts = {}

asyncHooks.createHook({
  init (asyncId, type, triggerAsyncId, resource) {
    if (contexts[triggerAsyncId] !== undefined) {
      contexts[asyncId] = contexts[triggerAsyncId]
    } else {
      contexts[asyncId] = {}
    }
  },

  destroy (asyncId) {
    delete contexts[asyncId]
  }
}).enable()


function run (callback) {
  let eid = asyncHooks.executionAsyncId()
  contexts[eid] = {}
  callback()
}

function set (k, v) {
  let eid = asyncHooks.executionAsyncId()
  let ctx = contexts[eid]
  if (ctx !== undefined) {
    ctx[k] = v
  }
}

function get (k) {
  let eid = asyncHooks.executionAsyncId()
  let ctx = contexts[eid]
  return ctx !== undefined ? ctx[k] : undefined
}

module.exports = {get, set, run, contexts}

It doesn’t have the above issue, and I use it with async/await on node 8.14 without any problems. Also, I use these packages on my project: express, body-parse, Sequelize, oauth2-server, cookie-parser, and request-promise-native. Though I had some issues with nested Promises at first but when I rewrote them with async/await it worked fine.

Read more comments on GitHub >

github_iconTop Results From Across the Web

c# - Can http context get lost with async await? - Stack Overflow
Call will have no HttpContext to start with, so it is not where failure can happen (even when the calls run past end...
Read more >
Understanding and Handling Connection Lifetime Events in ...
Raised when the disconnect timeout period expires while the SignalR client code is trying to reconnect after losing the transport connection.
Read more >
Stream | Node.js v19.3.0 Documentation
A Writable stream will always emit the 'close' event if it is created with the emitClose option. Event: 'drain' #. Added in: v0.9.4....
Read more >
Using AWS Lambda with Amazon DynamoDB
Example eventPolling and batching streamsExecution role permissionsConfiguring a stream as an event sourceEvent source mapping APIsError handlingAmazon ...
Read more >
HTTP Request Connector - MuleSoft Documentation
If you complete the RAML Location field first, all other fields ... each request (evaluating all the MEL expressions in the context of...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found