I consider myself a beginner with TCP connections, but I wanted to learn more about it so I started a project called the “Build Your Own Redis Challenge” from codecrafters.io. I am trying to implement the WAIT Redis command. I have set up a master server that connects to its replicas as well as a client. Basically, how the tester works is that it creates replicas that connect to my server, then switches to a client that sends REDIS commands (SET, PING, etc.) to my server and expects responses from the server (“+OKrn”, etc.). For example, when a client sends a “SET” command, it expects a”+OKrn” simple string response back from the server and for that server to propagate that SET command to its replicas. I have noticed that after the tester switches to the client and sends a SET command, the server sends the “+OKrn” response to both the client and to one of its replicas, even though it is only supposed to send the response to just the client. Here is the code for my server:
const server = net.createServer((connection) => {
// Handle connection
connection.type = 'client';
connection.on('data', async (data) => {
const command = await readData(data);
let commands = command.slice(3).split('rn'); // parses Redis response into an array
commands.pop(); // removes empty element at the end
console.log("Commands", commands);
if (commands.includes("SET")){
// only the client enters here
// server handles the SET command then writes an OK simple string response
connection.write("+OKrn");
propagateToReplicas(command); // sends client command to master's replicas
} else if (commands.includes("PSYNC")){
// replicas enter here
// replicas complete handshake with server here
// replica connection is then added to replicas array
connection.type = 'replica'; // Set type as replica
replicas.push(connection);
numOfReplicas += 1;
}
})
}
const propagateToReplicas = (command) => {
if (replicas.length == 0){
return
}
replicas.forEach((replica) => {
console.log("Command to be Propagated", command);
replica.write(command);
})
}
Here are the logs that I am receiving. Notice that one of the replicas receives the “+OKrn” response instead of the propagated command.
Logs of responses
I suspected the issue might have been that the socket connection between the client and the replicas might be shared, so I tried to tag each socket connection with an attribute (connection.type = “client” and connection.type = “replica” for example) to make a distinction, but that hasn’t worked either.
jonathan nwokeji is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.