Skip to content

Commit 689870f

Browse files
authored
Fix EventEmitter leak (#21)
Signed-off-by: James Elias Sigurdarson <jamiees2@gmail.com>
1 parent 39c416f commit 689870f

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/socket.ts

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -453,9 +453,18 @@ export class FluentSocket extends EventEmitter {
453453
this.processMessages(protocol.decodeServerStream(this.passThroughStream));
454454

455455
return new Promise<void>((resolve, reject) => {
456-
// This may call both resolve and reject, but the ES standard says this is OK
457-
this.once(FluentSocketEvent.CONNECTED, () => resolve());
458-
this.once(FluentSocketEvent.ERROR, err => reject(err));
456+
const onConnected = () => {
457+
resolve();
458+
// Avoid a memory leak and remove the other listener
459+
this.removeListener(FluentSocketEvent.ERROR, onError);
460+
};
461+
const onError = (err: Error) => {
462+
reject(err);
463+
// Avoid a memory leak and remove the other listener
464+
this.removeListener(FluentSocketEvent.CONNECTED, onConnected);
465+
};
466+
this.once(FluentSocketEvent.CONNECTED, onConnected);
467+
this.once(FluentSocketEvent.ERROR, onError);
459468
});
460469
}
461470

@@ -483,7 +492,7 @@ export class FluentSocket extends EventEmitter {
483492
this.onMessage(message);
484493
}
485494
} catch (e) {
486-
this.close(CloseState.RECONNECT, e);
495+
this.close(CloseState.RECONNECT, e as Error);
487496
}
488497
}
489498

test/test.socket.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,19 @@ describe("FluentSocket", () => {
6060
sinon.assert.calledOnce(connectStub);
6161
});
6262

63+
it("should not preserve error handlers after connect", done => {
64+
const {socket, connectStub} = createFluentSocket({disableReconnect: true});
65+
66+
socket.on(FluentSocketEvent.WRITABLE, () => {
67+
expect(socket.listenerCount(FluentSocketEvent.ERROR)).to.equal(0);
68+
done();
69+
});
70+
71+
socket.connect();
72+
73+
sinon.assert.calledOnce(connectStub);
74+
});
75+
6376
it("should not block for draining on write by default", done => {
6477
const {socket, stream, connectStub} = createFluentSocket({
6578
disableReconnect: true,

0 commit comments

Comments
 (0)