Skip to content

Commit 8fb9f97

Browse files
committed
fix(cluster): prefer master when there're two same node for a slot
1 parent 6b67c3f commit 8fb9f97

File tree

3 files changed

+37
-3
lines changed

3 files changed

+37
-3
lines changed

lib/cluster/ConnectionPool.ts

+7-1
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,13 @@ export default class ConnectionPool extends EventEmitter {
123123
debug("Reset with %O", nodes);
124124
const newNodes = {};
125125
nodes.forEach(node => {
126-
newNodes[getNodeKey(node)] = node;
126+
const key = getNodeKey(node);
127+
128+
// Don't override the existing (master) node
129+
// when the current one is slave.
130+
if (!(node.readOnly && newNodes[key])) {
131+
newNodes[key] = node;
132+
}
127133
});
128134

129135
Object.keys(this.nodes.all).forEach(key => {

test/unit/clusters/ConnectionPool.ts

+28
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import * as sinon from "sinon";
2+
import { expect } from "chai";
3+
import ConnectionPool from "../../../lib/cluster/ConnectionPool";
4+
5+
describe("ConnectionPool", () => {
6+
describe("#reset", () => {
7+
it("prefers to master if there are two same node for a slot", () => {
8+
const pool = new ConnectionPool({});
9+
const stub = sinon.stub(pool, "findOrCreate");
10+
11+
pool.reset([
12+
{ host: "127.0.0.1", port: 30001, readOnly: true },
13+
{ host: "127.0.0.1", port: 30001, readOnly: false }
14+
]);
15+
16+
expect(stub.callCount).to.eql(1);
17+
expect(stub.firstCall.args[1]).to.eql(false);
18+
19+
pool.reset([
20+
{ host: "127.0.0.1", port: 30001, readOnly: false },
21+
{ host: "127.0.0.1", port: 30001, readOnly: true }
22+
]);
23+
24+
expect(stub.callCount).to.eql(2);
25+
expect(stub.firstCall.args[1]).to.eql(false);
26+
});
27+
});
28+
});

test/unit/cluster.ts test/unit/clusters/index.ts

+2-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
import { nodeKeyToRedisOptions } from "../../lib/cluster/util";
2-
import { Cluster } from "../../lib";
1+
import { nodeKeyToRedisOptions } from "../../../lib/cluster/util";
2+
import { Cluster } from "../../../lib";
33
import * as sinon from "sinon";
44
import { expect } from "chai";
55

0 commit comments

Comments
 (0)