Skip to content

Commit d713dd4

Browse files
authored
Merge pull request #283 from Tim-Zhang/update-examples
Update examples
2 parents e5264e0 + 725f0f1 commit d713dd4

File tree

8 files changed

+193
-160
lines changed

8 files changed

+193
-160
lines changed

example/async-client.rs

Lines changed: 36 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,25 @@ async fn main() {
3535
"health.check()",
3636
now.elapsed(),
3737
);
38+
39+
let resp = thc
40+
.check(
41+
context::with_duration(core::time::Duration::from_millis(20)),
42+
&req,
43+
)
44+
.await;
45+
46+
assert_eq!(
47+
resp,
48+
Err(ttrpc::Error::Others(
49+
"Receive packet timeout Elapsed(())".into()
50+
))
51+
);
52+
3853
println!(
3954
"Green Thread 1 - {} -> {:?} ended: {:?}",
4055
"health.check()",
41-
thc.check(context::with_duration(core::time::Duration::from_millis(20)), &req)
42-
.await,
56+
resp,
4357
now.elapsed(),
4458
);
4559
});
@@ -51,18 +65,16 @@ async fn main() {
5165
now.elapsed(),
5266
);
5367

54-
let show = match tac
68+
let resp = tac
5569
.list_interfaces(default_ctx(), &agent::ListInterfacesRequest::new())
56-
.await
57-
{
58-
Err(e) => format!("{:?}", e),
59-
Ok(s) => format!("{:?}", s),
60-
};
70+
.await;
71+
let expected_resp = utils::resp::asynchronous::agent_list_interfaces();
72+
assert_eq!(resp, expected_resp);
6173

6274
println!(
63-
"Green Thread 2 - {} -> {} ended: {:?}",
75+
"Green Thread 2 - {} -> {:?} ended: {:?}",
6476
"agent.list_interfaces()",
65-
show,
77+
resp,
6678
now.elapsed(),
6779
);
6880
});
@@ -74,17 +86,16 @@ async fn main() {
7486
now.elapsed()
7587
);
7688

77-
let show = match ac
89+
let resp = ac
7890
.online_cpu_mem(default_ctx(), &agent::OnlineCPUMemRequest::new())
79-
.await
80-
{
81-
Err(e) => format!("{:?}", e),
82-
Ok(s) => format!("{:?}", s),
83-
};
91+
.await;
92+
let expected_resp = utils::resp::online_cpu_mem_not_impl();
93+
assert_eq!(resp, Err(expected_resp));
94+
8495
println!(
85-
"Green Thread 3 - {} -> {} ended: {:?}",
96+
"Green Thread 3 - {} -> {:?} ended: {:?}",
8697
"agent.online_cpu_mem()",
87-
show,
98+
resp,
8899
now.elapsed()
89100
);
90101

@@ -102,7 +113,13 @@ async fn main() {
102113
);
103114
});
104115

105-
let _ = tokio::join!(t1, t2, t3);
116+
let (r1, r2, r3) = tokio::join!(t1, t2, t3);
117+
assert!(
118+
r1.is_ok() && r2.is_ok() && r3.is_ok(),
119+
"async test is failed because some error occurred"
120+
);
121+
122+
println!("***** Asycn test is OK! *****");
106123
}
107124

108125
fn default_ctx() -> Context {

example/async-server.rs

Lines changed: 10 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -6,19 +6,14 @@
66
mod protocols;
77
mod utils;
88

9-
#[macro_use]
10-
extern crate log;
11-
129
use std::sync::Arc;
1310

1411
use log::LevelFilter;
1512

1613
#[cfg(unix)]
17-
use protocols::asynchronous::{agent, agent_ttrpc, health, health_ttrpc, types};
14+
use protocols::asynchronous::{agent, agent_ttrpc, health, health_ttrpc};
1815
#[cfg(unix)]
1916
use ttrpc::asynchronous::Server;
20-
use ttrpc::error::{Error, Result};
21-
use ttrpc::proto::{Code, Status};
2217

2318
#[cfg(unix)]
2419
use async_trait::async_trait;
@@ -35,30 +30,18 @@ impl health_ttrpc::Health for HealthService {
3530
&self,
3631
_ctx: &::ttrpc::r#async::TtrpcContext,
3732
_req: health::CheckRequest,
38-
) -> Result<health::HealthCheckResponse> {
39-
let mut status = Status::new();
40-
41-
status.set_code(Code::NOT_FOUND);
42-
status.set_message("Just for fun".to_string());
43-
44-
sleep(std::time::Duration::from_secs(10)).await;
45-
46-
Err(Error::RpcStatus(status))
33+
) -> ttrpc::Result<health::HealthCheckResponse> {
34+
// Mock timeout
35+
sleep(std::time::Duration::from_secs(1)).await;
36+
unreachable!();
4737
}
4838

4939
async fn version(
5040
&self,
51-
ctx: &::ttrpc::r#async::TtrpcContext,
52-
req: health::CheckRequest,
53-
) -> Result<health::VersionCheckResponse> {
54-
info!("version {:?}", req);
55-
info!("ctx {:?}", ctx);
56-
let mut rep = health::VersionCheckResponse::new();
57-
rep.agent_version = "mock.0.1".to_string();
58-
rep.grpc_version = "0.0.1".to_string();
59-
let mut status = Status::new();
60-
status.set_code(Code::NOT_FOUND);
61-
Ok(rep)
41+
_ctx: &::ttrpc::r#async::TtrpcContext,
42+
_req: health::CheckRequest,
43+
) -> ttrpc::Result<health::VersionCheckResponse> {
44+
utils::resp::asynchronous::health_version()
6245
}
6346
}
6447

@@ -71,19 +54,7 @@ impl agent_ttrpc::AgentService for AgentService {
7154
_ctx: &::ttrpc::r#async::TtrpcContext,
7255
_req: agent::ListInterfacesRequest,
7356
) -> ::ttrpc::Result<agent::Interfaces> {
74-
let mut rp = Vec::new();
75-
76-
let mut i = types::Interface::new();
77-
i.name = "first".to_string();
78-
rp.push(i);
79-
let mut i = types::Interface::new();
80-
i.name = "second".to_string();
81-
rp.push(i);
82-
83-
let mut i = agent::Interfaces::new();
84-
i.Interfaces = rp;
85-
86-
Ok(i)
57+
utils::resp::asynchronous::agent_list_interfaces()
8758
}
8859
}
8960

example/async-stream-client.rs

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,21 @@ async fn main() {
4949

5050
let t8 = tokio::spawn(server_send_stream(sc));
5151

52-
let _ = tokio::join!(t1, t2, t3, t4, t5, t6, t7, t8);
52+
let (r1, r2, r3, r4, r5, r6, r7, r8) = tokio::join!(t1, t2, t3, t4, t5, t6, t7, t8);
53+
54+
assert!(
55+
r1.is_ok()
56+
&& r2.is_ok()
57+
&& r3.is_ok()
58+
&& r4.is_ok()
59+
&& r5.is_ok()
60+
&& r6.is_ok()
61+
&& r7.is_ok()
62+
&& r8.is_ok(),
63+
"async-stream test is failed because some error occurred"
64+
);
65+
66+
println!("***** Async Stream test is OK! *****");
5367
}
5468

5569
fn default_ctx() -> Context {

example/build.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ fn replace_text_in_file(file_name: &str, from: &str, to: &str) -> Result<(), std
8080
let new_contents = contents.replace(from, to);
8181

8282
let mut dst = File::create(file_name)?;
83-
dst.write(new_contents.as_bytes())?;
83+
dst.write_all(new_contents.as_bytes())?;
8484

8585
Ok(())
8686
}

example/client.rs

Lines changed: 30 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,6 @@ use protocols::sync::{agent, agent_ttrpc, health, health_ttrpc};
2020
use std::thread;
2121
use std::time::Duration;
2222
use ttrpc::context::{self, Context};
23-
use ttrpc::error::Error;
24-
use ttrpc::proto::Code;
2523
use ttrpc::Client;
2624

2725
#[cfg(not(target_os = "linux"))]
@@ -45,6 +43,8 @@ fn main() {
4543
thread::sleep(Duration::from_secs(1));
4644
let current_fd_count = get_fd_count();
4745
assert_eq!(current_fd_count, expected_fd_count, "check fd count");
46+
47+
println!("***** Sync test is OK! *****");
4848
}
4949

5050
fn connect_once() {
@@ -67,26 +67,22 @@ fn connect_once() {
6767
now.elapsed(),
6868
);
6969

70-
let rsp = thc.check(default_ctx(), &req);
71-
match rsp.as_ref() {
72-
Err(Error::RpcStatus(s)) => {
73-
assert_eq!(Code::NOT_FOUND, s.code());
74-
assert_eq!("Just for fun".to_string(), s.message())
75-
}
76-
Err(e) => {
77-
panic!("not expecting an error from the example server: {:?}", e)
78-
}
79-
Ok(x) => {
80-
panic!(
81-
"not expecting a OK response from the example server: {:?}",
82-
x
83-
)
84-
}
85-
}
70+
let resp = thc.check(
71+
context::with_duration(core::time::Duration::from_millis(20)),
72+
&req,
73+
);
74+
75+
assert_eq!(
76+
resp,
77+
Err(ttrpc::Error::Others(
78+
"Receive packet from Receiver timeout: timed out waiting on channel".into()
79+
))
80+
);
81+
8682
println!(
8783
"OS Thread {:?} - health.check() -> {:?} ended: {:?}",
8884
std::thread::current().id(),
89-
rsp,
85+
resp,
9086
now.elapsed(),
9187
);
9288
});
@@ -98,21 +94,14 @@ fn connect_once() {
9894
now.elapsed(),
9995
);
10096

101-
let show = match tac.list_interfaces(default_ctx(), &agent::ListInterfacesRequest::new()) {
102-
Err(e) => {
103-
panic!("not expecting an error from the example server: {:?}", e)
104-
}
105-
Ok(s) => {
106-
assert_eq!("first".to_string(), s.Interfaces[0].name);
107-
assert_eq!("second".to_string(), s.Interfaces[1].name);
108-
format!("{s:?}")
109-
}
110-
};
97+
let resp = tac.list_interfaces(default_ctx(), &agent::ListInterfacesRequest::new());
98+
let expected_resp = utils::resp::sync::agent_list_interfaces();
99+
assert_eq!(resp, expected_resp);
111100

112101
println!(
113102
"OS Thread {:?} - agent.list_interfaces() -> {} ended: {:?}",
114103
std::thread::current().id(),
115-
show,
104+
"{resp:?}",
116105
now.elapsed(),
117106
);
118107
});
@@ -121,34 +110,22 @@ fn connect_once() {
121110
"Main OS Thread - agent.online_cpu_mem() started: {:?}",
122111
now.elapsed()
123112
);
124-
let show = match ac.online_cpu_mem(default_ctx(), &agent::OnlineCPUMemRequest::new()) {
125-
Err(Error::RpcStatus(s)) => {
126-
assert_eq!(Code::NOT_FOUND, s.code());
127-
assert_eq!(
128-
"/grpc.AgentService/OnlineCPUMem is not supported".to_string(),
129-
s.message()
130-
);
131-
format!("{s:?}")
132-
}
133-
Err(e) => {
134-
panic!("not expecting an error from the example server: {:?}", e)
135-
}
136-
Ok(s) => {
137-
panic!(
138-
"not expecting a OK response from the example server: {:?}",
139-
s
140-
)
141-
}
142-
};
113+
let resp = ac
114+
.online_cpu_mem(default_ctx(), &agent::OnlineCPUMemRequest::new())
115+
.expect_err("not the expecting error from the example server");
116+
let expected_resp = utils::resp::online_cpu_mem_not_impl();
117+
assert_eq!(resp, expected_resp);
118+
143119
println!(
144-
"Main OS Thread - agent.online_cpu_mem() -> {} ended: {:?}",
145-
show,
120+
"Main OS Thread - agent.online_cpu_mem() -> {:?} ended: {:?}",
121+
resp,
146122
now.elapsed()
147123
);
148124

149125
let version = hc.version(default_ctx(), &health::CheckRequest::new());
150-
assert_eq!("mock.0.1", version.as_ref().unwrap().agent_version.as_str());
151-
assert_eq!("0.0.1", version.as_ref().unwrap().grpc_version.as_str());
126+
let expected_version_resp = utils::resp::sync::health_version();
127+
assert_eq!(version, expected_version_resp);
128+
152129
println!(
153130
"Main OS Thread - health.version() started: {:?}",
154131
now.elapsed()

0 commit comments

Comments
 (0)