Skip to content

Conversation

@mrdlm
Copy link
Owner

@mrdlm mrdlm commented May 3, 2025

Summary by CodeRabbit

  • New Features
    • Introduced a new server application for managing a cluster of Mango servers, supporting PRIMARY, SECONDARY, and STANDALONE roles.
    • Added support for registering servers and handling heartbeat commands to monitor server status.
    • Enhanced command handling to route operations and enforce a single PRIMARY server registration.
    • Added asynchronous replication of write requests from PRIMARY to SECONDARY servers.
    • Introduced client support to query secondary server addresses dynamically.
    • Enabled server startup configuration with role and port parameters.
  • Improvements
    • Improved error messages and usage instructions for new commands.
    • Added color-coded responses for success and error messages in client interactions.
    • Enhanced command processing with replication awareness based on server role.
    • Updated default server port configuration.

@coderabbitai
Copy link

coderabbitai bot commented May 3, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

The changes introduce a new server application, MangoTree, which manages a cluster of Mango servers with roles PRIMARY, SECONDARY, and STANDALONE. It supports new commands including REGISTER, HEARTBEAT, and SECONDARIES for server registration, health checks, and querying secondary servers. The command parsing system is extended to handle these commands with parameter validation and error messaging. The MangoTree server maintains a registry of servers, routes client commands based on server roles, and manages communication with registered servers. Additionally, replication management is introduced for primary servers to asynchronously replicate writes to secondaries. Server roles are integrated into MangoServer and CommandProcessor for role-aware behavior.

Changes

File(s) Change Summary
src/main/java/commands/CommandParser.java Added support for SECONDARIES command; enhanced REGISTER command argument validation; added handler for SECONDARIES.
src/main/java/commands/CommandType.java Added HEARTBEAT, REGISTER, and SECONDARIES enum constants with parameter counts and usage error messages.
src/main/java/tree/MangoTree.java New MangoTree server application managing server cluster roles, registration, command routing, and client handling. Includes enums for server status and role, and server registry management.
src/main/java/MangoApp.java Modified main method to instantiate MangoServer with role and port if two arguments are provided.
src/main/java/client/MangoClient.java Changed field visibility from private to protected; added getId() method returning "host:port" string.
src/main/java/client/MangoTreeClient.java New class extending MangoClient; added method to fetch secondary server addresses by sending SECONDARIES command.
src/main/java/client/ServerAddress.java Added new record ServerAddress to encapsulate host and port information.
src/main/java/replication/ReplicationManager.java New class managing asynchronous replication of write requests to secondary servers, with client refresh and retry logic.
src/main/java/server/CommandProcessor.java Added server role awareness; integrated replication manager; replicate writes asynchronously if role is PRIMARY.
src/main/java/server/MangoServer.java Added constructor accepting role and port; initializes CommandProcessor with server role; logs role on start.
src/main/java/tree/ServerRole.java Added new enum ServerRole with values PRIMARY, SECONDARY, and STANDALONE.
src/main/resources/config.properties Changed default port from 8080 to 8082.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant MangoTree
    participant CommandParser
    participant ServerRegistry
    participant MangoClient
    participant ReplicationManager

    Client->>MangoTree: Connects and sends command
    MangoTree->>CommandParser: Parses command
    CommandParser-->>MangoTree: Returns Command object

    alt REGISTER command
        MangoTree->>ServerRegistry: Register server with role, host, port
        ServerRegistry-->>MangoTree: Update registry
        MangoTree-->>Client: Respond with registration status
    else HEARTBEAT command
        MangoTree->>ServerRegistry: Update server heartbeat
        ServerRegistry-->>MangoTree: Update status
        MangoTree-->>Client: Respond with heartbeat acknowledgement
    else SECONDARIES command
        MangoTree->>ServerRegistry: Get list of secondaries
        ServerRegistry-->>MangoTree: List of secondary servers
        MangoTree-->>Client: Return secondary server addresses
    else PUT command
        MangoTree->>MangoClient (PRIMARY): Forward PUT command
        MangoClient-->>MangoTree: Return response
        MangoTree->>ReplicationManager: asyncReplicate(key, value)
        MangoTree-->>Client: Return response
    else GET command
        MangoTree->>MangoClient (random SECONDARY): Forward GET command
        MangoClient-->>MangoTree: Return response
        MangoTree-->>Client: Return response
    else DELETE command
        MangoTree->>MangoClient (PRIMARY): Forward DELETE command
        MangoClient-->>MangoTree: Return response
        MangoTree-->>Client: Return response
    end
Loading

Possibly related PRs

  • #21: simple mango client #22: Initial implementation of the MangoClient class, which is extended and modified in this PR by changing field visibility and adding getId().

Poem

🐇 In Mango groves where servers play,
New commands bloom in bright array.
REGISTER, HEARTBEAT, SECONDARIES too,
Keep the cluster strong and true.
Writes replicate with gentle care,
Roles assigned with flair to share.
🍃🥭 Let's hop along, the future's fair!


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between d8b8f75 and 238165b.

📒 Files selected for processing (12)
  • src/main/java/MangoApp.java (1 hunks)
  • src/main/java/client/MangoClient.java (1 hunks)
  • src/main/java/client/MangoTreeClient.java (1 hunks)
  • src/main/java/client/ServerAddress.java (1 hunks)
  • src/main/java/commands/CommandParser.java (2 hunks)
  • src/main/java/commands/CommandType.java (1 hunks)
  • src/main/java/replication/ReplicationManager.java (1 hunks)
  • src/main/java/server/CommandProcessor.java (3 hunks)
  • src/main/java/server/MangoServer.java (3 hunks)
  • src/main/java/tree/MangoTree.java (1 hunks)
  • src/main/java/tree/ServerRole.java (1 hunks)
  • src/main/resources/config.properties (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 6

🧹 Nitpick comments (2)
src/main/java/commands/CommandParser.java (1)

59-67: Simplify arity check & avoid duplicated conditions

if (args.length < REGISTER.getParameterCount() || args.length > REGISTER.getParameterCount()) is equivalent to !=. Using != communicates intent better and avoids 2 comparisons.

-if (args.length < REGISTER.getParameterCount() || args.length > REGISTER.getParameterCount()) {
+if (args.length != REGISTER.getParameterCount()) {
src/main/java/tree/MangoTree.java (1)

101-109: Socket is served in clear-text – consider TLS

Static analysis flagged the use of java.net.ServerSocket without encryption. If any sensitive data or credentials travel through this channel, switch to SSLServerSocket or wrap the stream in TLS (e.g., with Netty/SSLEngine) to prevent MITM attacks.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 566ff03 and d8b8f75.

📒 Files selected for processing (3)
  • src/main/java/commands/CommandParser.java (2 hunks)
  • src/main/java/commands/CommandType.java (1 hunks)
  • src/main/java/tree/MangoTree.java (1 hunks)
🧰 Additional context used
🪛 ast-grep (0.31.1)
src/main/java/tree/MangoTree.java

[info] 100-100: "Detected use of a Java socket that is not encrypted. As a result, the
traffic could be read by an attacker intercepting the network traffic. Use
an SSLSocket created by 'SSLSocketFactory' or 'SSLServerSocketFactory'
instead."
Context: new ServerSocket(port)
Note: [CWE-319] Cleartext Transmission of Sensitive Information [REFERENCES]
- https://owasp.org/Top10/A02_2021-Cryptographic_Failures

(unencrypted-socket-java)

Comment on lines 10 to 12
HELP(0, "HELP expects no parameters"),
HEARTBEAT(2, "ERROR: Usage: HEARTBEAT <HOST> <PORT>"),
REGISTER(3, "ERROR: Usage: REGISTER <PRIMARY|SECONDARY> <HOST> <PORT>");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Verification agent

🧩 Analysis chain

HEARTBEAT parameter count conflicts with its actual parser handling

HEARTBEAT is declared with parameterCount = 2, yet CommandParser.handleHeartbeat() accepts zero arguments and does not validate the incoming argsString. This mismatch means:

  • A syntactically-correct HEARTBEAT <HOST> <PORT> command will be parsed as invalid (args discarded), whilst
  • A bare HEARTBEAT (no args) will happily pass, breaking the public contract advertised by the error message.

Update either the enum or the parser so they agree on the same arity; otherwise every client/server pairing will eventually drift into inconsistent behaviour.

-    HEARTBEAT(2, "ERROR: Usage: HEARTBEAT <HOST> <PORT>"),
+    HEARTBEAT(0, "HEARTBEAT expects no parameters"),

#!/bin/bash
# Show CommandType enum around HEARTBEAT
rg -n -C2 "HEARTBEAT" src/main/java/commands/CommandType.java

# Inspect handleHeartbeat in CommandParser
rg -n -C10 "handleHeartbeat" src/main/java/commands/CommandParser.java

# Search where parameterCount is used in CommandParser
rg -n -C3 "parameterCount" src/main/java/commands/CommandParser.java

#!/bin/bash
# Inspect the HEARTBEAT enum entry
rg -n -C2 "HEARTBEAT" src/main/java/commands/CommandType.java

# Inspect handleHeartbeat method in CommandParser
rg -n -C5 "handleHeartbeat" src/main/java/commands/CommandParser.java

# Find where parameterCount from CommandType is enforced or checked
rg -n -C5 "parameterCount" src/main/java/commands/CommandParser.java

🏁 Script executed:

#!/bin/bash
# Show the HEARTBEAT entry in CommandType
rg -n -C2 "HEARTBEAT" src/main/java/commands/CommandType.java

# Show the handleHeartbeat implementation in CommandParser
rg -n -C5 "handleHeartbeat" src/main/java/commands/CommandParser.java

# Show where CommandType.parameterCount is enforced in CommandParser
rg -n -C5 "parameterCount" src/main/java/commands/CommandParser.java

Length of output: 1258


Align HEARTBEAT’s declared arity with its parser

The enum entry for HEARTBEAT declares parameterCount = 2 with a usage message for <HOST> <PORT>, but CommandParser.handleHeartbeat() ignores argsString entirely and always returns a zero-arg command. This mismatch will:

  • Reject valid HEARTBEAT <HOST> <PORT> invocations (args dropped)
  • Accept a bare HEARTBEAT without error

Choose one consistent approach:

  • Parse two parameters in handleHeartbeat(...), validate argsString.split(" ") length == 2, and pass host/port into the new Command(HEARTBEAT, args)
  • Or change the enum to parameterCount = 0 and update the message to "HEARTBEAT expects no parameters"

Locations to update:

  • src/main/java/commands/CommandType.java (line 11)
  • src/main/java/commands/CommandParser.java (handleHeartbeat at lines 69–71)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
HELP(0, "HELP expects no parameters"),
HEARTBEAT(2, "ERROR: Usage: HEARTBEAT <HOST> <PORT>"),
REGISTER(3, "ERROR: Usage: REGISTER <PRIMARY|SECONDARY> <HOST> <PORT>");
HELP(0, "HELP expects no parameters"),
HEARTBEAT(0, "HEARTBEAT expects no parameters"),
REGISTER(3, "ERROR: Usage: REGISTER <PRIMARY|SECONDARY> <HOST> <PORT>");

Comment on lines 55 to 71
case REGISTER -> handleRegister(argsString);
};
}

private static Command handleRegister(final String argsString) {
String[] args = argsString.strip().split(SPACE_DELIMITER);

if (args.length < REGISTER.getParameterCount() || args.length > REGISTER.getParameterCount()) {
throw new InvalidParametersException(REGISTER.getErrorMessage());
}

return new Command(REGISTER, args);
}

private static Command handleHeartbeat(final String argsString) {
return new Command(HEARTBEAT, null);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Inconsistent HEARTBEAT handling & missing validation

handleHeartbeat() discards argsString entirely. If the enum is kept at 2 params, this method should validate arity exactly as the other handlers do; if the enum is changed to 0, the error message inside the enum should be updated accordingly (see previous comment).

-private static Command handleHeartbeat(final String argsString) {
-    return new Command(HEARTBEAT, null);
+private static Command handleHeartbeat(final String argsString) {
+    if (!argsString.isEmpty()) {
+        throw new InvalidParametersException(HEARTBEAT.getErrorMessage());
+    }
+    return new Command(HEARTBEAT, null);
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
case REGISTER -> handleRegister(argsString);
};
}
private static Command handleRegister(final String argsString) {
String[] args = argsString.strip().split(SPACE_DELIMITER);
if (args.length < REGISTER.getParameterCount() || args.length > REGISTER.getParameterCount()) {
throw new InvalidParametersException(REGISTER.getErrorMessage());
}
return new Command(REGISTER, args);
}
private static Command handleHeartbeat(final String argsString) {
return new Command(HEARTBEAT, null);
}
private static Command handleHeartbeat(final String argsString) {
if (!argsString.isEmpty()) {
throw new InvalidParametersException(HEARTBEAT.getErrorMessage());
}
return new Command(HEARTBEAT, null);
}

Comment on lines +206 to +210
if (role == ServerRole.PRIMARY) {
if (primaryServerId != null && primaryServerId != serverId) {
throw new RuntimeException("There's already a primary server registered");
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

String comparison uses != instead of .equals

primaryServerId != serverId compares references, not content. Use !primaryServerId.equals(serverId) to avoid false positives/negatives.

-if (primaryServerId != null && primaryServerId != serverId) {
+if (primaryServerId != null && !primaryServerId.equals(serverId)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (role == ServerRole.PRIMARY) {
if (primaryServerId != null && primaryServerId != serverId) {
throw new RuntimeException("There's already a primary server registered");
}
}
if (role == ServerRole.PRIMARY) {
if (primaryServerId != null && !primaryServerId.equals(serverId)) {
throw new RuntimeException("There's already a primary server registered");
}
}

Comment on lines 74 to 76
private HashMap<String, ServerInfo> registeredServers;
private String primaryServerId;

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

HashMap is not thread-safe for concurrent connection threads

registeredServers is accessed and mutated from every connectionExecutor thread. A plain HashMap will race, leading to visibility issues or ConcurrentModificationException. Replace with a concurrent collection or introduce proper synchronisation.

-private HashMap<String, ServerInfo> registeredServers;
+private final ConcurrentMap<String, ServerInfo> registeredServers = new ConcurrentHashMap<>();
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
private HashMap<String, ServerInfo> registeredServers;
private String primaryServerId;
private final ConcurrentMap<String, ServerInfo> registeredServers = new ConcurrentHashMap<>();
private String primaryServerId;

Comment on lines 163 to 177
if (command.type().equals(CommandType.REGISTER)) {
System.out.println("Registering command: " + command);
String role = command.args()[0];
Integer port = Integer.valueOf(command.args()[1]);
String host = command.args()[2];

try {
handleRegistration(role, port, host);
} catch (final Exception e) {
System.err.println("Error registering command: " + e.getMessage());
return String.format(WRAP_RED, "ERROR REGISTERING: " + e.getMessage());
}
}

return String.format(WRAP_GREEN, "SUCCESSFULLY REGISTERED");
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Argument order for REGISTER is reversed – will throw NumberFormatException

Specification: REGISTER <PRIMARY|SECONDARY> <HOST> <PORT>
Code: role = args[0]; port = Integer.valueOf(args[1]); host = args[2];

args[1] is <HOST> (e.g. "127.0.0.1") – parsing it as an Integer will explode the first time a client registers. Swap the indices or change the spec.

-String role = command.args()[0];
-Integer port = Integer.valueOf(command.args()[1]);
-String host = command.args()[2];
+String role = command.args()[0];
+String host = command.args()[1];
+Integer port = Integer.valueOf(command.args()[2]);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (command.type().equals(CommandType.REGISTER)) {
System.out.println("Registering command: " + command);
String role = command.args()[0];
Integer port = Integer.valueOf(command.args()[1]);
String host = command.args()[2];
try {
handleRegistration(role, port, host);
} catch (final Exception e) {
System.err.println("Error registering command: " + e.getMessage());
return String.format(WRAP_RED, "ERROR REGISTERING: " + e.getMessage());
}
}
return String.format(WRAP_GREEN, "SUCCESSFULLY REGISTERED");
if (command.type().equals(CommandType.REGISTER)) {
System.out.println("Registering command: " + command);
- String role = command.args()[0];
- Integer port = Integer.valueOf(command.args()[1]);
- String host = command.args()[2];
+ String role = command.args()[0];
+ String host = command.args()[1];
+ Integer port = Integer.valueOf(command.args()[2]);
try {
handleRegistration(role, port, host);
} catch (final Exception e) {
System.err.println("Error registering command: " + e.getMessage());
return String.format(WRAP_RED, "ERROR REGISTERING: " + e.getMessage());
}
}
return String.format(WRAP_GREEN, "SUCCESSFULLY REGISTERED");

Comment on lines +226 to +229
public void stop() {
// stop health check executor
// stop connection executor
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

stop() is empty – resources are never released

start() calls stop() in the finally block, but stop() does nothing. At minimum, shut down executors and close all client sockets to avoid thread leaks on server restart/shutdown.

public void stop() {
-    // stop health check executor
-    // stop connection executor
+    connectionExecutor.shutdownNow();
+    healthCheckExecutor.shutdownNow();
+    registeredServers.values().forEach(s -> {
+        try { s.getClient().close(); } catch (IOException ignored) {}
+    });
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
public void stop() {
// stop health check executor
// stop connection executor
}
public void stop() {
connectionExecutor.shutdownNow();
healthCheckExecutor.shutdownNow();
registeredServers.values().forEach(s -> {
try {
s.getClient().close();
} catch (IOException ignored) {
}
});
}

@mrdlm mrdlm merged commit d9b0007 into main May 3, 2025
2 of 3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants