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
754 stars 89 forks source link

How to integrate with SocketIO #53

Open averri opened 4 years ago

averri commented 4 years ago

I'm trying to integrate the cls_hooked with SocketIO, using the Feathersjs framework:

const socketio = require('@feathersjs/socketio')
const tracer = require('../tracer')
const sync = require('feathers-sync')

module.exports = app => {
  // 'socket.feathers' is the same object as the connection
  // in a channel. 'socket.request' and 'socket.handshake' contains information
  // the HTTP request that initiated the connection.
  app.configure(socketio(io => {

    // https://docs.feathersjs.com/api/socketio.html#params
    io.use( (socket, next) => {
      tracer.run(() => {
        tracer.set('ip', socket.conn.remoteAddress)
        next()
      })
    })

  }))
}

The tracer.js:

const cls = require('cls-hooked')
const tracer = cls.createNamespace('app')
module.exports = tracer

... but the context is lost, it's not possible to get the 'ip' property from service functions.

ppatel890 commented 4 years ago

@averri Any luck figuring out how to setup with feathers?

averri commented 4 years ago

Hi @ppatel890, unfortunately I have abandoned the use of cls-hooked, I have re-engineered the application code to do not rely on cls-hooked.

ppatel890 commented 4 years ago

@averri - checking back in, any guidance on how you can have a requestId present throughout the entire socket 'request'?

averri commented 4 years ago

Hi @ppatel890, Nodejs 13 has a solution for this problem: https://nodejs.org/docs/latest-v13.x/api/async_hooks.html#async_hooks_class_asynclocalstorage

In order to have a variable associated with the context of the current request it needs the support of AsyncLocalStorage in the SocketIO middleware.

The AsycLocalStorage has similar features of this library, so it's recommended to move to AsyncLocalStorage.

malixsys commented 1 year ago

Hi @ppatel890, Nodejs 13 has a solution for this problem: https://nodejs.org/docs/latest-v13.x/api/async_hooks.html#async_hooks_class_asynclocalstorage

In order to have a variable associated with the context of the current request it needs the support of AsyncLocalStorage in the SocketIO middleware.

The AsycLocalStorage has similar features of this library, so it's recommended to move to AsyncLocalStorage.

@averri This library already uses async_hooks on Node 8+