Jeff-Lewis / cls-hooked

cls-hooked : CLS using AsynWrap or async_hooks instead of async-listener for node 4.7+

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to integrate with SocketIO

averri opened this issue · comments

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.

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

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.

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

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.

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+