Skip to content

Memory leak in subscribe #1087

@changesbyjames

Description

@changesbyjames

Hello!

I'm heavily using subscribe on a project I'm currently working on and I think there is a small memory leak in the cleanup logic of the subscribe function. This is the main subscribe function. Most of the cleanup is done fully but that additional listener stream && stream.on('error', onerror) at the bottom is never removed. After a while, this does have an impact.

async function subscribe(event, fn, onsubscribe = noop, onerror = noop) {
  event = parseEvent(event)

  if (!connection)
    connection = init(sql, slot, options.publications)

  const subscriber = { fn, onsubscribe }
  const fns = subscribers.has(event)
    ? subscribers.get(event).add(subscriber)
    : subscribers.set(event, new Set([subscriber])).get(event)

  const unsubscribe = () => {
    fns.delete(subscriber)
    fns.size === 0 && subscribers.delete(event)
+   stream && stream.removeListener('error', onerror)
  }

  return connection.then(x => {
    connected(x)
    onsubscribe()
    stream && stream.on('error', onerror)
    return { unsubscribe, state, sql }
  })
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions