-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.rs
209 lines (180 loc) · 6.37 KB
/
main.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
use std::net::SocketAddr;
use std::time::UNIX_EPOCH;
use twirp::async_trait::async_trait;
use twirp::axum::body::Body;
use twirp::axum::http;
use twirp::axum::middleware::{self, Next};
use twirp::axum::routing::get;
use twirp::{invalid_argument, Context, Router, TwirpErrorResponse};
pub mod service {
pub mod haberdash {
pub mod v1 {
include!(concat!(env!("OUT_DIR"), "/service.haberdash.v1.rs"));
}
}
}
use service::haberdash::v1::{self as haberdash, MakeHatRequest, MakeHatResponse};
async fn ping() -> &'static str {
"Pong\n"
}
#[tokio::main]
pub async fn main() {
let api_impl = HaberdasherApiServer {};
let middleware = twirp::tower::builder::ServiceBuilder::new()
.layer(middleware::from_fn(request_id_middleware));
let twirp_routes = Router::new()
.nest(haberdash::SERVICE_FQN, haberdash::router(api_impl))
.layer(middleware);
let app = Router::new()
.nest("/twirp", twirp_routes)
.route("/_ping", get(ping))
.fallback(twirp::server::not_found_handler);
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let tcp_listener = tokio::net::TcpListener::bind(addr)
.await
.expect("failed to bind");
println!("Listening on {addr}");
if let Err(e) = twirp::axum::serve(tcp_listener, app).await {
eprintln!("server error: {}", e);
}
}
// Note: If your server type can't be Clone, consider wrapping it in `std::sync::Arc`.
#[derive(Clone)]
struct HaberdasherApiServer;
#[async_trait]
impl haberdash::HaberdasherApi for HaberdasherApiServer {
async fn make_hat(
&self,
ctx: Context,
req: MakeHatRequest,
) -> Result<MakeHatResponse, TwirpErrorResponse> {
if req.inches == 0 {
return Err(invalid_argument("inches"));
}
if let Some(id) = ctx.get::<RequestId>() {
println!("{id:?}");
};
println!("got {req:?}");
ctx.insert::<ResponseInfo>(ResponseInfo(42));
let ts = std::time::SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default();
Ok(MakeHatResponse {
color: "black".to_string(),
name: "top hat".to_string(),
size: req.inches,
timestamp: Some(prost_wkt_types::Timestamp {
seconds: ts.as_secs() as i64,
nanos: 0,
}),
})
}
}
// Demonstrate sending back custom extensions from the handlers.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Default)]
struct ResponseInfo(u16);
/// Demonstrate pulling the request id out of an http header and sharing it with the rpc handlers.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug, Default)]
struct RequestId(String);
async fn request_id_middleware(
mut request: http::Request<Body>,
next: Next,
) -> http::Response<Body> {
let rid = request
.headers()
.get("x-request-id")
.and_then(|v| v.to_str().ok())
.map(|x| RequestId(x.to_string()));
if let Some(rid) = rid {
request.extensions_mut().insert(rid);
}
let mut res = next.run(request).await;
let info = res
.extensions()
.get::<ResponseInfo>()
.expect("must include ResponseInfo")
.0;
res.headers_mut().insert("x-response-info", info.into());
res
}
#[cfg(test)]
mod test {
use service::haberdash::v1::HaberdasherApiClient;
use twirp::client::Client;
use twirp::url::Url;
use twirp::TwirpErrorCode;
use crate::service::haberdash::v1::HaberdasherApi;
use super::*;
#[tokio::test]
async fn success() {
let api = HaberdasherApiServer {};
let ctx = twirp::Context::default();
let res = api.make_hat(ctx, MakeHatRequest { inches: 1 }).await;
assert!(res.is_ok());
let res = res.unwrap();
assert_eq!(res.size, 1);
}
#[tokio::test]
async fn invalid_request() {
let api = HaberdasherApiServer {};
let ctx = twirp::Context::default();
let res = api.make_hat(ctx, MakeHatRequest { inches: 0 }).await;
assert!(res.is_err());
let err = res.unwrap_err();
assert_eq!(err.code, TwirpErrorCode::InvalidArgument);
}
/// A running network server task, bound to an arbitrary port on localhost, chosen by the OS
struct NetServer {
port: u16,
server_task: tokio::task::JoinHandle<()>,
shutdown_sender: tokio::sync::oneshot::Sender<()>,
}
impl NetServer {
async fn start(api_impl: HaberdasherApiServer) -> Self {
let twirp_routes =
Router::new().nest(haberdash::SERVICE_FQN, haberdash::router(api_impl));
let app = Router::new()
.nest("/twirp", twirp_routes)
.route("/_ping", get(ping))
.fallback(twirp::server::not_found_handler);
let tcp_listener = tokio::net::TcpListener::bind("localhost:0")
.await
.expect("failed to bind");
let addr = tcp_listener.local_addr().unwrap();
println!("Listening on {addr}");
let port = addr.port();
let (shutdown_sender, shutdown_receiver) = tokio::sync::oneshot::channel::<()>();
let server_task = tokio::spawn(async move {
let shutdown_receiver = async move {
shutdown_receiver.await.unwrap();
};
if let Err(e) = twirp::axum::serve(tcp_listener, app)
.with_graceful_shutdown(shutdown_receiver)
.await
{
eprintln!("server error: {}", e);
}
});
NetServer {
port,
server_task,
shutdown_sender,
}
}
async fn shutdown(self) {
self.shutdown_sender.send(()).unwrap();
self.server_task.await.unwrap();
}
}
#[tokio::test]
async fn test_net() {
let api_impl = HaberdasherApiServer {};
let server = NetServer::start(api_impl).await;
let url = Url::parse(&format!("http://localhost:{}/twirp/", server.port)).unwrap();
let client = Client::from_base_url(url).unwrap();
let resp = client.make_hat(MakeHatRequest { inches: 1 }).await;
println!("{:?}", resp);
assert_eq!(resp.unwrap().size, 1);
server.shutdown().await;
}
}