Skip to content

Commit ef236fa

Browse files
committed
Handle case of emitting both 'end' and 'close'. Closes #282
1 parent 186e2ab commit ef236fa

File tree

2 files changed

+21
-10
lines changed

2 files changed

+21
-10
lines changed

lib/agent.js

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -56,8 +56,15 @@ Agent.prototype.close = function(err) {
5656
};
5757

5858
Agent.prototype._cleanup = function() {
59+
60+
// Only clean up once if the stream emits both 'end' and 'close'.
61+
if (this.closed) return;
62+
5963
this.closed = true;
6064

65+
this.backend.agentsCount--;
66+
if (!this.stream.isServer) this.backend.remoteAgentsCount--;
67+
6168
// Clean up doc subscription streams
6269
for (var collection in this.subscribedDocs) {
6370
var docs = this.subscribedDocs[collection];
@@ -259,12 +266,7 @@ Agent.prototype._open = function() {
259266
});
260267
});
261268

262-
function cleanup() {
263-
agent.backend.agentsCount--;
264-
if (!agent.stream.isServer) agent.backend.remoteAgentsCount--;
265-
agent._cleanup();
266-
}
267-
269+
var cleanup = agent._cleanup.bind(agent);
268270
this.stream.on('end', cleanup);
269271
this.stream.on('close', cleanup);
270272
};

test/client/connection.js

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -106,10 +106,19 @@ describe('client connection', function() {
106106
var connection = backend.connect();
107107
connection.on('connected', function() {
108108
connection.socket.stream.emit('close')
109-
setTimeout(function() {
110-
expect(backend.agentsCount).equal(0);
111-
done();
112-
}, 10);
109+
expect(backend.agentsCount).equal(0);
110+
done();
111+
});
112+
});
113+
114+
it('updates correctly after stream emits both "end" and "close"', function(done) {
115+
var backend = this.backend;
116+
var connection = backend.connect();
117+
connection.on('connected', function() {
118+
connection.socket.stream.emit('end')
119+
connection.socket.stream.emit('close')
120+
expect(backend.agentsCount).equal(0);
121+
done();
113122
});
114123
});
115124

0 commit comments

Comments
 (0)