commit ed4278906bc774f4899a497a2ee97ea15d468781
parent db14f19173a8486a5035c733a484f3fb6ca7d2fb
Author: Antoine A <>
Date: Thu, 19 Nov 2026 12:56:09 +0100
taler-api: answer every accepted connection on a graceful shutdown
Diffstat:
4 files changed, 142 insertions(+), 11 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
@@ -2387,6 +2387,8 @@ dependencies = [
"criterion",
"dashmap",
"http-body-util",
+ "hyper",
+ "hyper-util",
"jiff",
"listenfd",
"prometheus-client",
diff --git a/common/taler-api/Cargo.toml b/common/taler-api/Cargo.toml
@@ -16,6 +16,8 @@ listenfd = "1.0.0"
socket2 = "0.6"
dashmap = "6.1"
http-body-util.workspace = true
+hyper.workspace = true
+hyper-util = { workspace = true, features = ["server-auto", "service", "tokio"] }
zlib-rs = "0.6.3"
tower-http = { version = "0.7", features = ["cors"] }
tokio = { workspace = true, features = ["signal"] }
diff --git a/common/taler-api/src/api.rs b/common/taler-api/src/api.rs
@@ -1,6 +1,6 @@
/*
This file is part of TALER
- Copyright (C) 2025, 2026 Taler Systems SA
+ Copyright (C) 2026 Taler Systems SA
TALER is free software; you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free Software
@@ -50,6 +50,7 @@ use crate::{
pub mod observability;
pub mod prepared;
pub mod revenue;
+mod serve;
pub mod wire;
pub use axum::Router;
@@ -148,16 +149,8 @@ impl TalerRouter for Router {
let router = self.finalize();
let signal = shutdown_signal(notify);
match listener {
- Listener::Tcp(tcp_listener) => {
- axum::serve(tcp_listener, router)
- .with_graceful_shutdown(signal)
- .await?;
- }
- Listener::Unix(unix_listener) => {
- axum::serve(unix_listener, router)
- .with_graceful_shutdown(signal)
- .await?;
- }
+ Listener::Tcp(listener) => serve::run(listener, router, signal).await,
+ Listener::Unix(listener) => serve::run(listener, router, signal).await,
}
info!(target: "api", "Server stopped");
diff --git a/common/taler-api/src/api/serve.rs b/common/taler-api/src/api/serve.rs
@@ -0,0 +1,134 @@
+/*
+ This file is part of TALER
+ Copyright (C) 2025, 2026 Taler Systems SA
+
+ TALER is free software; you can redistribute it and/or modify it under the
+ terms of the GNU Affero General Public License as published by the Free Software
+ Foundation; either version 3, or (at your option) any later version.
+
+ TALER is distributed in the hope that it will be useful, but WITHOUT ANY
+ WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
+ A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License along with
+ TALER; see the file COPYING. If not, see <http://www.gnu.org/licenses/>
+*/
+
+use std::{cell::Cell, pin::pin, time::Duration};
+
+use axum::{Router, serve::Listener};
+use hyper::service::{Service as _, service_fn};
+use hyper_util::{
+ rt::{TokioExecutor, TokioIo},
+ server::conn::auto::Builder,
+ service::TowerToHyperService,
+};
+use tokio::{
+ io::{AsyncRead, AsyncWrite},
+ sync::{Notify, watch},
+ time::{Instant, timeout_at},
+};
+
+const FIRST_REQUEST_GRACE: Duration = Duration::from_secs(10);
+
+pub(super) async fn run(
+ mut listener: impl Listener,
+ router: Router,
+ shutdown: impl Future<Output = ()>,
+) {
+ let mut shutdown = pin!(shutdown);
+ let (drain, _) = watch::channel(Instant::now());
+ let router: Router = router.with_state(());
+ loop {
+ tokio::select! {
+ biased;
+ _ = &mut shutdown => break,
+ (io, _) = listener.accept() => {
+ tokio::spawn(serve_connection(io, router.clone(), drain.subscribe()));
+ }
+ }
+ }
+ drop(listener);
+ drain.send_replace(Instant::now() + FIRST_REQUEST_GRACE);
+ // Each connection holds its receiver until Hyper finishes serving it.
+ drain.closed().await;
+}
+
+async fn serve_connection(
+ io: impl AsyncRead + AsyncWrite + Unpin + Send + 'static,
+ router: Router,
+ mut drain: watch::Receiver<Instant>,
+) {
+ let first_request = Notify::new();
+ let started = Cell::new(Some(&first_request));
+ let router = TowerToHyperService::new(router);
+ let service = service_fn(move |request| {
+ if let Some(started) = started.take() {
+ started.notify_one();
+ }
+ router.call(request)
+ });
+
+ let builder = Builder::new(TokioExecutor::new());
+ let mut conn = pin!(builder.serve_connection_with_upgrades(TokioIo::new(io), service));
+ let result = tokio::select! {
+ result = &mut conn => result,
+ _ = async {
+ let _ = drain.changed().await;
+ let deadline = *drain.borrow();
+ // Calling graceful_shutdown before the first dispatch can lose the request.
+ let _ = timeout_at(deadline, first_request.notified()).await;
+ } => {
+ conn.as_mut().graceful_shutdown();
+ conn.await
+ }
+ };
+ if let Err(err) = result {
+ tracing::trace!(target: "api", "failed to serve connection: {err}");
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use std::time::Duration;
+
+ use axum::{routing::get, serve::ListenerExt};
+ use tokio::{
+ io::{AsyncReadExt, AsyncWriteExt},
+ net::{TcpListener, TcpStream},
+ sync::{mpsc, oneshot},
+ time::timeout,
+ };
+
+ use super::*;
+
+ #[tokio::test]
+ async fn answer_first_request_after_shutdown() {
+ timeout(Duration::from_secs(5), async {
+ let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (accepted, mut events) = mpsc::unbounded_channel();
+ let listener = listener.tap_io(move |_| accepted.send(()).unwrap());
+ let (shutdown, signal) = oneshot::channel();
+ let router = Router::new().route("/", get(async || "answered"));
+ let server = tokio::spawn(run(listener, router, async { signal.await.unwrap() }));
+
+ let mut client = TcpStream::connect(addr).await.unwrap();
+ assert_eq!(events.recv().await, Some(()));
+ shutdown.send(()).unwrap();
+ // The listener has been dropped, so the request arrives during draining.
+ assert_eq!(events.recv().await, None);
+ client
+ .write_all(b"GET / HTTP/1.1\r\nHost: localhost\r\n\r\n")
+ .await
+ .unwrap();
+ let mut response = String::new();
+ client.read_to_string(&mut response).await.unwrap();
+ assert!(response.starts_with("HTTP/1.1 200 OK"), "{response:?}");
+ assert!(response.ends_with("answered"), "{response:?}");
+ server.await.unwrap();
+ })
+ .await
+ .expect("server did not finish draining the connection");
+ }
+}