Skip to content

Commit

Permalink
Fix EventEmitter leak
Browse files Browse the repository at this point in the history
Signed-off-by: James Elias Sigurdarson <jamiees2@gmail.com>
  • Loading branch information
jamiees2 committed Oct 7, 2021
1 parent cb44be4 commit bbb5658
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
17 changes: 13 additions & 4 deletions src/socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -453,9 +453,18 @@ export class FluentSocket extends EventEmitter {
this.processMessages(protocol.decodeServerStream(this.passThroughStream));

return new Promise<void>((resolve, reject) => {
// This may call both resolve and reject, but the ES standard says this is OK
this.once(FluentSocketEvent.CONNECTED, () => resolve());
this.once(FluentSocketEvent.ERROR, err => reject(err));
const onConnected = () => {
resolve();
// Avoid a memory leak and remove the other listener
this.removeListener(FluentSocketEvent.ERROR, onError);
};
const onError = (err: Error) => {
reject(err);
// Avoid a memory leak and remove the other listener
this.removeListener(FluentSocketEvent.CONNECTED, onConnected);
};
this.once(FluentSocketEvent.CONNECTED, onConnected);
this.once(FluentSocketEvent.ERROR, onError);
});
}

Expand Down Expand Up @@ -483,7 +492,7 @@ export class FluentSocket extends EventEmitter {
this.onMessage(message);
}
} catch (e) {
this.close(CloseState.RECONNECT, e);
this.close(CloseState.RECONNECT, e as Error);
}
}

Expand Down
13 changes: 13 additions & 0 deletions test/test.socket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,19 @@ describe("FluentSocket", () => {
sinon.assert.calledOnce(connectStub);
});

it("should not preserve error handlers after connect", done => {
const {socket, connectStub} = createFluentSocket({disableReconnect: true});

socket.on(FluentSocketEvent.WRITABLE, () => {
expect(socket.listenerCount(FluentSocketEvent.ERROR)).to.equal(0);
done();
});

socket.connect();

sinon.assert.calledOnce(connectStub);
});

it("should not block for draining on write by default", done => {
const {socket, stream, connectStub} = createFluentSocket({
disableReconnect: true,
Expand Down

0 comments on commit bbb5658

Please sign in to comment.