taler-rust

GNU Taler code in Rust. Largely core banking integrations.
Log | Files | Refs | Submodules | README | LICENSE

serve.rs (4782B)


      1 /*
      2   This file is part of TALER
      3   Copyright (C) 2025, 2026 Taler Systems SA
      4 
      5   TALER is free software; you can redistribute it and/or modify it under the
      6   terms of the GNU Affero General Public License as published by the Free Software
      7   Foundation; either version 3, or (at your option) any later version.
      8 
      9   TALER is distributed in the hope that it will be useful, but WITHOUT ANY
     10   WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11   A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
     12 
     13   You should have received a copy of the GNU Affero General Public License along with
     14   TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 */
     16 
     17 use std::{cell::Cell, pin::pin, time::Duration};
     18 
     19 use axum::{Router, serve::Listener};
     20 use hyper::service::{Service as _, service_fn};
     21 use hyper_util::{
     22     rt::{TokioExecutor, TokioIo},
     23     server::conn::auto::Builder,
     24     service::TowerToHyperService,
     25 };
     26 use tokio::{
     27     io::{AsyncRead, AsyncWrite},
     28     sync::{Notify, watch},
     29     time::{Instant, timeout_at},
     30 };
     31 
     32 const FIRST_REQUEST_GRACE: Duration = Duration::from_secs(10);
     33 
     34 pub(super) async fn run(
     35     mut listener: impl Listener,
     36     router: Router,
     37     shutdown: impl Future<Output = ()>,
     38 ) {
     39     let mut shutdown = pin!(shutdown);
     40     let (drain, _) = watch::channel(Instant::now());
     41     let router: Router = router.with_state(());
     42     loop {
     43         tokio::select! {
     44             biased;
     45             _ = &mut shutdown => break,
     46             (io, _) = listener.accept() => {
     47                 tokio::spawn(serve_connection(io, router.clone(), drain.subscribe()));
     48             }
     49         }
     50     }
     51     drop(listener);
     52     drain.send_replace(Instant::now() + FIRST_REQUEST_GRACE);
     53     // Each connection holds its receiver until Hyper finishes serving it.
     54     drain.closed().await;
     55 }
     56 
     57 async fn serve_connection(
     58     io: impl AsyncRead + AsyncWrite + Unpin + Send + 'static,
     59     router: Router,
     60     mut drain: watch::Receiver<Instant>,
     61 ) {
     62     let first_request = Notify::new();
     63     let started = Cell::new(Some(&first_request));
     64     let router = TowerToHyperService::new(router);
     65     let service = service_fn(move |request| {
     66         if let Some(started) = started.take() {
     67             started.notify_one();
     68         }
     69         router.call(request)
     70     });
     71 
     72     let builder = Builder::new(TokioExecutor::new());
     73     let mut conn = pin!(builder.serve_connection_with_upgrades(TokioIo::new(io), service));
     74     let result = tokio::select! {
     75         result = &mut conn => result,
     76         _ = async {
     77             let _ = drain.changed().await;
     78             let deadline = *drain.borrow();
     79             // Calling graceful_shutdown before the first dispatch can lose the request.
     80             let _ = timeout_at(deadline, first_request.notified()).await;
     81         } => {
     82             conn.as_mut().graceful_shutdown();
     83             conn.await
     84         }
     85     };
     86     if let Err(err) = result {
     87         tracing::trace!(target: "api", "failed to serve connection: {err}");
     88     }
     89 }
     90 
     91 #[cfg(test)]
     92 mod tests {
     93     use std::time::Duration;
     94 
     95     use axum::{routing::get, serve::ListenerExt};
     96     use tokio::{
     97         io::{AsyncReadExt, AsyncWriteExt},
     98         net::{TcpListener, TcpStream},
     99         sync::{mpsc, oneshot},
    100         time::timeout,
    101     };
    102 
    103     use super::*;
    104 
    105     #[tokio::test]
    106     async fn answer_first_request_after_shutdown() {
    107         timeout(Duration::from_secs(5), async {
    108             let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
    109             let addr = listener.local_addr().unwrap();
    110             let (accepted, mut events) = mpsc::unbounded_channel();
    111             let listener = listener.tap_io(move |_| accepted.send(()).unwrap());
    112             let (shutdown, signal) = oneshot::channel();
    113             let router = Router::new().route("/", get(async || "answered"));
    114             let server = tokio::spawn(run(listener, router, async { signal.await.unwrap() }));
    115 
    116             let mut client = TcpStream::connect(addr).await.unwrap();
    117             assert_eq!(events.recv().await, Some(()));
    118             shutdown.send(()).unwrap();
    119             // The listener has been dropped, so the request arrives during draining.
    120             assert_eq!(events.recv().await, None);
    121             client
    122                 .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
    123                 .await
    124                 .unwrap();
    125             let mut response = String::new();
    126             client.read_to_string(&mut response).await.unwrap();
    127             assert!(response.starts_with("HTTP/1.1 200 OK"), "{response:?}");
    128             assert!(response.ends_with("answered"), "{response:?}");
    129             server.await.unwrap();
    130         })
    131         .await
    132         .expect("server did not finish draining the connection");
    133     }
    134 }