Skip to content

Commit ebe3c21

Browse files
committed
Only close websocket when it's not participating in any more swarms
1 parent f64e569 commit ebe3c21

File tree

2 files changed

+25
-5
lines changed

2 files changed

+25
-5
lines changed

lib/server/swarm.js

Lines changed: 24 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,19 +7,29 @@ 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.infoHash = infoHash
1011
this.complete = 0
1112
this.incomplete = 0
13+
1214
this.peers = new LRU({
1315
max: server.peersCacheLength || 1000,
1416
maxAge: server.peersCacheTtl || 20 * 60 * 1000 // 20 minutes
1517
})
1618

17-
// When a websocket peer is evicted from the LRU cache, close the websocket
18-
// after a short timeout period. We wait 1s so the server has a chance to send
19-
// a response to 'stopped' events, which remove the peer and cause an eviction.
19+
// When a peer is evicted from the LRU store, send a synthetic 'stopped' event
20+
// so the stats get updated correctly.
2021
this.peers.on('evict', function (data) {
2122
var peer = data.value
22-
if (peer.socket) {
23+
this.announce({
24+
type: peer.type,
25+
event: 'stopped',
26+
numwant: 0,
27+
peer_id: peer.peerId
28+
}, noop)
29+
30+
// When a websocket peer is evicted, and it's not in any other swarms, close
31+
// the websocket to conserve server resources.
32+
if (peer.socket && peer.socket.infoHashes.length === 0) {
2333
try {
2434
peer.socket.close()
2535
peer.socket = null
@@ -86,6 +96,14 @@ Swarm.prototype._onAnnounceStopped = function (params, peer, id) {
8696

8797
if (peer.complete) this.complete -= 1
8898
else this.incomplete -= 1
99+
100+
// If it's a websocket, remove this swarm's infohash from the list of active
101+
// swarms that this peer is participating in.
102+
if (peer.socket) {
103+
var index = peer.socket.infoHashes.indexOf(this.infoHash)
104+
peer.socket.infoHashes.splice(index, 1)
105+
}
106+
89107
this.peers.remove(id)
90108
}
91109

@@ -133,3 +151,5 @@ Swarm.prototype._getPeers = function (numwant, ownPeerId, isWebRTC) {
133151
}
134152
return peers
135153
}
154+
155+
function noop () {}

server.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -585,7 +585,7 @@ Server.prototype._onWebSocketClose = function (socket) {
585585
debug('websocket close %s', socket.peerId)
586586

587587
if (socket.peerId) {
588-
socket.infoHashes.forEach(function (infoHash) {
588+
socket.infoHashes.slice(0).forEach(function (infoHash) {
589589
var swarm = self.torrents[infoHash]
590590
if (swarm) {
591591
swarm.announce({

0 commit comments

Comments
 (0)