Skip to content

Commit 7075088

Browse files
committed
Close websockets when peers are evicted from LRU cache
Possibly fixes: webtorrent#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.
1 parent 8f33b95 commit 7075088

File tree

1 file changed

+14
-2
lines changed

1 file changed

+14
-2
lines changed

lib/server/swarm.js

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,12 +7,24 @@ var randomIterate = require('random-iterate')
77
// Regard this as the default implementation of an interface that you
88
// need to support when overriding Server.createSwarm() and Server.getSwarm()
99
function Swarm (infoHash, server) {
10+
this.complete = 0
11+
this.incomplete = 0
1012
this.peers = new LRU({
1113
max: server.peersCacheLength || 1000,
1214
maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes
1315
})
14-
this.complete = 0
15-
this.incomplete = 0
16+
17+
// When a peer is evicted from the LRU cache, if it's a websocket peer,
18+
// close the websocket.
19+
this.peers.on('evict', function (data) {
20+
var peer = data.value
21+
if (peer.socket) {
22+
try {
23+
peer.socket.close()
24+
peer.socket = null
25+
} catch (err) {}
26+
}
27+
})
1628
}
1729

1830
Swarm.prototype.announce = function (params, cb) {

0 commit comments

Comments
 (0)