Skip to content

Commit 8387aa0

Browse files
authored
fix(client): Fix a bug where it causes Node process to crash when calling emit(), disconnect() and connect() in quick succession (#34)
Signed-off-by: Ray Tung <ray@kasada.io>
1 parent 0db64b5 commit 8387aa0

File tree

2 files changed

+31
-2
lines changed

2 files changed

+31
-2
lines changed

src/socket.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@ import {
1010
} from "./error";
1111
import * as protocol from "./protocol";
1212
import {PassThrough, Duplex} from "stream";
13-
import {awaitNextTick} from "./util";
1413

1514
/**
1615
* Reconnection settings for the socket
@@ -345,7 +344,9 @@ export class FluentSocket extends EventEmitter {
345344
) {
346345
if (this.state === SocketState.DISCONNECTING) {
347346
// Try again once the socket has fully closed
348-
await awaitNextTick();
347+
await new Promise(resolve =>
348+
this.once(FluentSocketEvent.CLOSE, resolve)
349+
);
349350
return await this.connect();
350351
} else {
351352
// noop, we're connected

test/test.client.ts

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import {
1616
} from "../src/error";
1717
import {awaitNextTick, awaitTimeout} from "../src/util";
1818
import {FluentSocketEvent} from "../src/socket";
19+
import {FluentServer} from "../src";
1920

2021
chai.use(chaiAsPromised);
2122
const expect = chai.expect;
@@ -518,6 +519,33 @@ describe("FluentClient", () => {
518519
sinon.assert.calledTwice(spy);
519520
});
520521

522+
it("should allow multiple connects and disconnects in succession", async () => {
523+
const server = new FluentServer();
524+
await server.listen();
525+
526+
try {
527+
const client = new FluentClient("abc", {
528+
socket: {
529+
port: server.port,
530+
},
531+
disableAutoconnect: true,
532+
});
533+
534+
await client.connect();
535+
try {
536+
const firstEvent = client.emit("a", {event: "foo bar"});
537+
538+
await client.disconnect();
539+
await client.connect();
540+
await expect(firstEvent).to.eventually.be.fulfilled;
541+
} finally {
542+
await client.shutdown();
543+
}
544+
} finally {
545+
await server.close();
546+
}
547+
});
548+
521549
it("should reject pending events after shutdown", async () => {
522550
const {client, socket} = createFluentClient("test");
523551
socket.isWritable = false;

0 commit comments

Comments
 (0)