Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

When are ctx ws references marked and swept by node's GC? #13

Open
NelsonFrancisco opened this issue Dec 3, 2020 · 0 comments
Open

Comments

@NelsonFrancisco
Copy link

Hello

I'll take your documentation example and tweak it a little for demonstration purposes

const Koa = require('koa')
const websocket = require('koa-easy-ws')

const app = new Koa()

app.use(websocket())
app.use(async (ctx, next) => {
  if (ctx.ws) {
    const ws = await ctx.ws() // retrieve socket

    // here I hydrate ctx with some stuff
    ctx.websocket = ws
    ctx.client = authenticatedClient()
    ctx.websocketSendJson = fantasticFunctionThatStringifiesAJsonAndSendsIt

    ctx.websocket.on('message',()=>{ctx.websocketSendJson(amazingJson)})   
    ctx.websocket.on('close',()=>{doSomething()})   
    // hydration end
  }
  ctx.body = 'general kenobi'
})

As you can see, some of my application's middlewares hydrate ctx with some helpful stuff for authentication purposes for example.

The thing is that my application has some memory leaks, and I am suspicious about these ctx hydrators.

I am handling some stuff in the 'close' event of the websocket, for example, to close a connection that I opened to a third party message broker.

The thing is that I am not deleting or doing anything about these objects that I place in ctx. Should I?

As you can see in the example above, after the ws request is handled by registering all of those callbacks (on.close, on.message) and then the middleware returns. Later ctx stuff is still needed. So, when will it be freed? When the websocket closes? If so, why? Isn't it just another callback just like on.message and on.pong?

Please help me making this right. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant