Skip to content

Commit

Permalink
fix: reconnected should also be fired before retrying the command (#…
Browse files Browse the repository at this point in the history
  • Loading branch information
uki00a authored Dec 10, 2024
1 parent d9210ea commit ad96f2c
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 3 deletions.
7 changes: 5 additions & 2 deletions connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -360,15 +360,18 @@ export class RedisConnection
return command.reject(error);
}

let backoff = 0;
for (let i = 0; i < this.maxRetryCount; i++) {
// Try to reconnect to the server and retry the command
this.#close(true);
try {
this.#dispatchEvent("reconnecting", { delay: backoff });
await this.connect();
const reply = await command.execute();
return command.resolve(reply);
} catch { // TODO: use `AggregateError`?
const backoff = this.backoff(i);
} catch (error) {
this.#dispatchEvent("error", { error }); // TODO: use `AggregateError`?
backoff = this.backoff(i);
await delay(backoff);
}
}
Expand Down
8 changes: 7 additions & 1 deletion tests/reconnect_test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { assertEquals } from "../deps/std/assert.ts";
import { assertEquals, assertInstanceOf } from "../deps/std/assert.ts";
import { beforeAll, describe, it } from "../deps/std/testing.ts";
import { newClient, nextPort, startRedis, stopRedis } from "./test_util.ts";

Expand All @@ -13,10 +13,16 @@ describe("reconnect", () => {
const client = await newClient({ hostname: "127.0.0.1", port });
assertEquals(await client.ping(), "PONG");
await stopRedis(server);
let reconnectingFired = 0;
client.addEventListener("reconnecting", (e) => {
reconnectingFired++;
assertInstanceOf(e, CustomEvent);
});
server = await startRedis({ port });
assertEquals(await client.ping(), "PONG");
client.close();
await stopRedis(server);
assertEquals(reconnectingFired, 1);
});

it("auto reconnect, with db spec", async () => {
Expand Down

0 comments on commit ad96f2c

Please sign in to comment.