From 70750888483bd184275f3a1c17a2c38fa5b03047 Mon Sep 17 00:00:00 2001 From: Feross Aboukhadijeh Date: Thu, 2 Feb 2017 17:43:16 -0800 Subject: [PATCH] Close websockets when peers are evicted from LRU cache MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Possibly fixes: https://github.com/feross/bittorrent-tracker/issues/196 Close websockets when peers are evicted from LRU cache, otherwise it's possible for a peer object to be evicted from the LRU cache without the socket being cleaned up. That will leak memory until the websocket is closed by the remote client. It also messes up the stats. --- lib/server/swarm.js | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/lib/server/swarm.js b/lib/server/swarm.js index 738005f..0b39918 100644 --- a/lib/server/swarm.js +++ b/lib/server/swarm.js @@ -7,12 +7,24 @@ var randomIterate = require('random-iterate') // Regard this as the default implementation of an interface that you // need to support when overriding Server.createSwarm() and Server.getSwarm() function Swarm (infoHash, server) { + this.complete = 0 + this.incomplete = 0 this.peers = new LRU({ max: server.peersCacheLength || 1000, maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes }) - this.complete = 0 - this.incomplete = 0 + + // When a peer is evicted from the LRU cache, if it's a websocket peer, + // close the websocket. + this.peers.on('evict', function (data) { + var peer = data.value + if (peer.socket) { + try { + peer.socket.close() + peer.socket = null + } catch (err) {} + } + }) } Swarm.prototype.announce = function (params, cb) {