Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test cases for server.rs #34

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/simple_run.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ async fn main() {
let cc = cluster_config.clone();
handles.push(tokio::spawn(async move {
let mut server = Server::new(id, config, cc).await;
server.start().await;
server.start(None).await;
}));
}

Expand Down
4 changes: 2 additions & 2 deletions examples/simulate_add_node.rs
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async fn main() {
let cc = cluster_config.clone();
handles.push(tokio::spawn(async move {
let mut server = Server::new(id, config, cc).await;
server.start().await;
server.start(None).await;
}));
}

Expand All @@ -65,7 +65,7 @@ async fn main() {
// Launching a new node
handles.push(tokio::spawn(async move {
let mut server = Server::new(new_node_id, new_node_conf, cluster_config).await;
server.start().await;
server.start(None).await;
}));

// Simulate sending a Raft Join request after a few seconds
Expand Down
4 changes: 2 additions & 2 deletions examples/simulate_node_failure.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ async fn main() {
let cc = cluster_config.clone();
let server_handle = tokio::spawn(async move {
let mut server = Server::new(id, config, cc).await;
server.start().await;
server.start(None).await;
});
server_handles.push(server_handle);
}
Expand Down Expand Up @@ -78,7 +78,7 @@ async fn main() {
let cc = cluster_config.clone();
let server_handle = tokio::spawn(async move {
let mut server = Server::new(server_to_stop.try_into().unwrap(), config, cc).await;
server.start().await;
server.start(None).await;
});
server_handles[server_to_stop - 1] = server_handle;
}
Expand Down
91 changes: 88 additions & 3 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ use std::net::SocketAddr;
use std::time::{Duration, Instant};
use tokio::io::AsyncReadExt;
use tokio::time::sleep;
use std::sync::mpsc;

#[derive(Debug, Clone, PartialEq)]
enum RaftState {
Expand All @@ -38,7 +39,7 @@ enum MessageType {
JoinResponse,
}

#[derive(Debug)]
#[derive(Debug, Clone)]
struct ServerState {
current_term: u32,
state: RaftState,
Expand Down Expand Up @@ -69,7 +70,7 @@ pub struct LogEntry {
pub data: u32,
}

#[derive(Debug)]
#[derive(Debug, Clone)]
pub struct ServerConfig {
pub election_timeout: Duration,
pub address: SocketAddr,
Expand All @@ -79,6 +80,7 @@ pub struct ServerConfig {
pub storage_location: Option<String>,
}

#[derive(Clone)]
pub struct Server {
pub id: u32,
state: ServerState,
Expand Down Expand Up @@ -135,7 +137,7 @@ impl Server {
}
}

pub async fn start(&mut self) {
pub async fn start(&mut self, rx: Option<mpsc::Receiver<()>>) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

I understand this PR is still in Draft, but why do you wanna introduce a channel over here ?

Copy link
Author

Choose a reason for hiding this comment

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

Hey 👋🏻
No worries, feel free to review anytime I'm completely fine with it.

This is added because if I don't pass some sort of signal, the test case will keep running forever because of the infinite loop. I couldn't think of any better approach than this that's why I consider it optional so actual implementation/usage won't have to pass any value. I'm planning to add it in other methods too where we have an infinite loop.

I'm happy to learn some new techniques/patterns if you can share them here.

Thanks!

if let Err(e) = self.network_manager.open().await {
error!(self.log, "Failed to open network manager: {}", e);
return;
Expand All @@ -159,6 +161,11 @@ impl Server {
RaftState::Candidate => self.candidate().await,
RaftState::Leader => self.leader().await,
}
if let Some(ref rx) = rx {
if rx.try_recv().is_ok() {
break;
}
}
}
}

Expand Down Expand Up @@ -964,3 +971,81 @@ impl Server {
self.peers().len()
}
}

#[cfg(test)]
mod tests {

use crate::cluster::{ClusterConfig, NodeMeta};
use crate::server::{Server, ServerConfig, RaftState};
use std::time::Duration;
use std::net::SocketAddr;
use std::str::FromStr;
use std::collections::HashMap;
use std::sync::mpsc;
use std::thread;

async fn server_util() -> Server {
let id: u32 = 3;
let peers = vec![
NodeMeta::from((1, SocketAddr::from_str("127.0.0.1:5001").unwrap())),
NodeMeta::from((2, SocketAddr::from_str("127.0.0.1:5002").unwrap())),
NodeMeta::from((3, SocketAddr::from_str("127.0.0.1:5003").unwrap())),
NodeMeta::from((4, SocketAddr::from_str("127.0.0.1:5004").unwrap())),
NodeMeta::from((5, SocketAddr::from_str("127.0.0.1:5005").unwrap())),
];
let addr: SocketAddr = peers[0].address;
let cluster_config = ClusterConfig::new(peers.clone());
let server_config = ServerConfig {
election_timeout: Duration::from_millis(10),
address: addr,
default_leader: Some(3u32),
leadership_preferences: HashMap::new(),
storage_location: Some("".to_string()),
};
Server::new(id, server_config, cluster_config).await
}

#[tokio::test]
async fn test_server() {
let server = server_util().await.clone();
assert_eq!(server.state.state, RaftState::Follower)
}

#[tokio::test]
async fn test_server_start() {
// will send signal over channel to start method to exit out of the loop
let (tx, rx) = mpsc::channel();
let t = thread::spawn(move || async {
let mut server = server_util().await.clone();
server.start(Some(rx)).await;
});

thread::sleep(Duration::from_millis(100));
tx.send(()).unwrap();
let _ = t.join().unwrap();
}

#[tokio::test]
async fn test_server_start_failed_quorum() {
let id: u32 = 2;
let peers = vec![
NodeMeta::from((1, SocketAddr::from_str("127.0.0.1:5001").unwrap())),
NodeMeta::from((2, SocketAddr::from_str("127.0.0.1:5002").unwrap())),
];
let addr: SocketAddr = peers[0].address;
let cluster_config = ClusterConfig::new(peers.clone());
let server_config = ServerConfig {
election_timeout: Duration::from_millis(10),
address: addr,
default_leader: Some(1u32),
leadership_preferences: HashMap::new(),
storage_location: Some("".to_string()),
};
let mut server = Server::new(id, server_config, cluster_config).await;
server.start(None).await;
assert_eq!(server.peer_count(), 1);
let votes = server.state.votes_received.len();
assert_eq!(server.is_quorum(votes.try_into().unwrap()), false);
}

}
Loading