node-apn icon indicating copy to clipboard operation
node-apn copied to clipboard

Resource leak when calling shutdown before finish writing

Open rluvaton opened this issue 2 years ago • 1 comments

This code causes resource leak and don't close the TLS socket

const apn = require('../');

let i = 0;

const pushToken = ''

function send(provider, token) {

  const note = new apn.Notification();
  note.alert = `Hey hello, I just sent my first Push Notification`;

  // The topic is usually the bundle identifier of your application.
  note.topic = '<my-topic>';

  console.log(`Sending: ${note.compile()} to`);

  return provider.send(note, [token]).then(result => {
    console.log('sent:', result.sent.length);
    console.log('failed:', result.failed.length);
    console.log(result.failed);
  });
}

async function run() {
  const users = [
    { name: 'Wendy', devices: [pushToken] },
  ];
  const service = new apn.Provider({
    // ...
  });

  Promise.all(
    users.map(user => {
      try {
        return send(service, pushToken);
      } finally {
        return service.shutdown();
      }
    }),
  )
    .finally(() => {
      printActiveHandles();

      if (i++ < 10) {
        run();
      } else {
        setInterval(() => {
          printActiveHandles()
        }, 1000)
      }
    });
}


function printActiveHandles() {
  const data = process._getActiveHandles();

  const formatted = data.map(item => item.constructor.name);

  console.log(`Got ${formatted.length} active handles`, formatted);
}

run();

this will log in the end:

Got 13 active handles [
  'WriteStream', 'WriteStream',
  'TLSSocket',   'TLSSocket',
  'TLSSocket',   'TLSSocket',
  'TLSSocket',   'TLSSocket',
  'TLSSocket',   'TLSSocket',
  'TLSSocket',   'TLSSocket',
  'TLSSocket'
]

rluvaton avatar Feb 16 '23 21:02 rluvaton

Thanks for opening this issue!

  • ❌ Please edit your post and use the provided template when creating a new issue. This helps everyone to understand your post better and asks for essential information to quicker review the issue.