rap_client/
callback_server.rs1use http_body_util::{BodyExt, Full};
3use hyper::body::{Bytes, Incoming};
4use hyper::server::conn::http1;
5use hyper::{Request, Response, StatusCode};
6use hyper_util::rt::TokioIo;
7use rap_protocol::RapCallback;
8use std::convert::Infallible;
9use std::future::Future;
10use std::sync::Arc;
11use tokio::net::TcpListener;
12use tokio::sync::mpsc;
13
14pub async fn bind_callback_listener()
17-> Result<(TcpListener, String), Box<dyn std::error::Error + Send + Sync>> {
18 let listener = TcpListener::bind("127.0.0.1:0").await?;
19 let base_url = format!("http://127.0.0.1:{}", listener.local_addr()?.port());
20 Ok((listener, base_url))
21}
22
23pub fn start_callback_server_on<F, Fut>(
26 listener: TcpListener,
27 handler: F,
28) -> tokio::task::JoinHandle<()>
29where
30 F: Fn(RapCallback) -> Fut + Send + Sync + 'static,
31 Fut: Future<Output = ()> + Send + 'static,
32{
33 let handler = Arc::new(handler);
34 tracing::info!(
35 "RAP callback server listening on {:?}",
36 listener.local_addr()
37 );
38 tokio::spawn(rap_protocol::log_panic(
39 "callback_accept_loop",
40 async move {
41 loop {
42 let (stream, _) = match listener.accept().await {
43 Ok(c) => c,
44 Err(e) => {
45 tracing::warn!("Callback accept error: {}", e);
46 continue;
47 }
48 };
49 let handler = handler.clone();
50 tokio::spawn(rap_protocol::log_panic("callback_connection", async move {
51 let svc = hyper::service::service_fn(move |req: Request<Incoming>| {
52 let handler = handler.clone();
53 async move { Ok::<_, Infallible>(handle(req, handler).await) }
54 });
55 if let Err(e) = http1::Builder::new()
56 .serve_connection(TokioIo::new(stream), svc)
57 .await
58 {
59 tracing::warn!("Callback connection error: {}", e);
60 }
61 }));
62 }
63 },
64 ))
65}
66
67pub async fn start_callback_server<F, Fut>(
70 handler: F,
71) -> Result<String, Box<dyn std::error::Error + Send + Sync>>
72where
73 F: Fn(RapCallback) -> Fut + Send + Sync + 'static,
74 Fut: Future<Output = ()> + Send + 'static,
75{
76 let (listener, base_url) = bind_callback_listener().await?;
77 start_callback_server_on(listener, handler);
78 Ok(base_url)
79}
80
81pub async fn start_callback_channel()
84-> Result<(String, mpsc::UnboundedReceiver<RapCallback>), Box<dyn std::error::Error + Send + Sync>>
85{
86 let (tx, rx) = mpsc::unbounded_channel();
87 let base_url = start_callback_server(move |cb| {
88 let tx = tx.clone();
89 async move {
90 let _ = tx.send(cb);
91 }
92 })
93 .await?;
94 Ok((base_url, rx))
95}
96
97fn ok_response(status: StatusCode, body: &str) -> Response<Full<Bytes>> {
98 Response::builder()
99 .status(status)
100 .body(Full::new(Bytes::from(body.to_owned())))
101 .expect("bug: failed to build HTTP response")
102}
103
104async fn handle<F, Fut>(req: Request<Incoming>, handler: Arc<F>) -> Response<Full<Bytes>>
105where
106 F: Fn(RapCallback) -> Fut + Send + Sync,
107 Fut: Future<Output = ()> + Send,
108{
109 if req.method() != hyper::Method::POST {
110 return ok_response(StatusCode::METHOD_NOT_ALLOWED, "POST only");
111 }
112
113 let body = match req.into_body().collect().await {
114 Ok(b) => b.to_bytes(),
115 Err(e) => {
116 tracing::warn!("Failed to read callback body: {}", e);
117 return ok_response(StatusCode::BAD_REQUEST, "Failed to read body");
118 }
119 };
120
121 let cb: RapCallback = match serde_json::from_slice(&body) {
122 Ok(c) => c,
123 Err(e) => {
124 let raw = String::from_utf8_lossy(&body);
125 tracing::error!("Invalid callback payload: {e}\nRaw body: {raw}");
126 return ok_response(StatusCode::BAD_REQUEST, &format!("Bad request: {}", e));
127 }
128 };
129
130 handler(cb).await;
131 ok_response(StatusCode::OK, "OK")
132}