Skip to content

Commit

Permalink
example: memstore: add timeout to client
Browse files Browse the repository at this point in the history
  • Loading branch information
drmingdrmer committed Dec 9, 2022
1 parent 85f0289 commit 627248f
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 7 deletions.
29 changes: 22 additions & 7 deletions examples/raft-kv-memstore/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use std::collections::BTreeSet;
use std::sync::Arc;
use std::sync::Mutex;
use std::time::Duration;

use openraft::error::AddLearnerError;
use openraft::error::CheckIsLeaderError;
Expand All @@ -16,9 +17,13 @@ use openraft::raft::ClientWriteResponse;
use openraft::BasicNode;
use openraft::RaftMetrics;
use reqwest::Client;
use reqwest::Error;
use reqwest::Response;
use serde::de::DeserializeOwned;
use serde::Deserialize;
use serde::Serialize;
use tokio::time::error::Elapsed;
use tokio::time::timeout;

use crate::ExampleNodeId;
use crate::ExampleRequest;
Expand Down Expand Up @@ -155,23 +160,33 @@ impl ExampleClient {
(t.0, format!("http://{}/{}", target_addr, uri))
};

let resp = if let Some(r) = req {
println!(
let fu = if let Some(r) = req {
tracing::debug!(
">>> client send request to {}: {}",
url,
serde_json::to_string_pretty(&r).unwrap()
);
self.inner.post(url.clone()).json(r)
} else {
println!(">>> client send request to {}", url,);
tracing::debug!(">>> client send request to {}", url,);
self.inner.get(url.clone())
}
.send()
.await
.map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
.send();

let res = timeout(Duration::from_millis(500), fu).await;
let resp = match res {
Ok(x) => {
let resp = x.map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
resp
}
Err(timeout_err) => {
tracing::error!("timeout {} to url: {}", timeout_err, url);
return Err(RPCError::Network(NetworkError::new(&timeout_err)));
}
};

let res: Result<Resp, Err> = resp.json().await.map_err(|e| RPCError::Network(NetworkError::new(&e)))?;
println!(
tracing::debug!(
"<<< client recv reply from {}: {}",
url,
serde_json::to_string_pretty(&res).unwrap()
Expand Down
5 changes: 5 additions & 0 deletions examples/raft-kv-memstore/src/network/raft_network_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -38,10 +38,15 @@ impl ExampleNetwork {
let addr = &target_node.addr;

let url = format!("http://{}/{}", addr, uri);
tracing::debug!("send_rpc to url: {}", url);
let client = reqwest::Client::new();

tracing::debug!("client is created for: {}", url);

let resp = client.post(url).json(&req).send().await.map_err(|e| RPCError::Network(NetworkError::new(&e)))?;

tracing::debug!("client.post() is sent");

let res: Result<Resp, Err> = resp.json().await.map_err(|e| RPCError::Network(NetworkError::new(&e)))?;

res.map_err(|e| RPCError::RemoteError(RemoteError::new(target, e)))
Expand Down

0 comments on commit 627248f

Please sign in to comment.