GITv

Finish requests in progress when gitv-web is stopped

Browse files

SIGTERM (systemctl stop or restart) killed the server outright, cutting off clones and downloads mid-transfer. It now stops accepting connections and exits once the requests in progress have finished, or when systemd's stop timeout runs out, logging both steps. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 16:17
Commit
f5068ab01c31
Parent
0eac27b

4 files changed +60−3

@@ -26,7 +26,7 @@ shlex = "2.0.1"
subtle = "2.6.1"
syntect = { version = "5.3.0", default-features = false, features = ["default-syntaxes", "html", "regex-onig"] }
thiserror = "2.0.21"
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync", "io-util", "process", "time"] }
tokio = { version = "1.54.1", features = ["rt-multi-thread", "macros", "net", "sync", "io-util", "process", "time", "signal"] }
[profile.release]
lto = "thin"
@@ -277,10 +277,34 @@ fn serve(port: u16) -> Result<(), String> {
);
// Connection details let sign-in throttle each client separately.
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
axum::serve(listener, app).await.map_err(|e| e.to_string())
axum::serve(listener, app).with_graceful_shutdown(shutdown_requested()).await.map_err(|e| e.to_string())?;
eprintln!("gitv-web: stopped");
Ok(())
})
}
/// Resolves when systemd (SIGTERM) or a terminal (Ctrl-C) asks the server to stop. From then
/// on it takes no new connections, and stops once the requests in progress (clones and
/// downloads included) have finished, or systemd's stop timeout runs out.
async fn shutdown_requested() {
let terminate = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut signal) => {
signal.recv().await;
}
Err(error) => {
eprintln!("gitv-web: can't watch for SIGTERM, so it will stop at once: {error}");
std::future::pending::<()>().await;
}
}
};
tokio::select! {
() = terminate => {}
_ = tokio::signal::ctrl_c() => {}
}
eprintln!("gitv-web: stopping; finishing requests in progress");
}
#[cfg(test)]
mod tests {
use super::*;
@@ -185,7 +185,7 @@ fn account_dir() -> PathBuf {
/// A running `gitv-web`, stopped when dropped. Unless started signed out, it has its own
/// account and a signed-in session, which [`Server::get`] uses.
pub struct Server {
child: Child,
pub child: Child,
pub port: u16,
pub account: Account,
pub cookie: Option<String>,
@@ -904,3 +904,36 @@ fn byte_named_refs_and_paged_trees_keep_the_selected_revision() {
assert!(server.get("/ada/bytes/log").text().contains("ref=odd-%FE"));
assert_eq!(server.get("/ada/bytes/tree?page=2").status, 404);
}
#[test]
fn sigterm_lets_a_download_in_progress_finish() {
use std::io::{Read, Write};
let host = Host::new("web-shutdown");
let work = common::scratch("web-shutdown-work");
git(&work, &["init", "-qb", "main"]);
// Large enough that the response is still streaming when the signal arrives.
fs::write(work.join("big.bin"), vec![b'x'; 8 << 20]).unwrap();
git(&work, &["add", "."]);
git(&work, &["commit", "-qm", "Big"]);
assert!(host.git(&work, &["push", "-q", "ada@test:ada/big.git", "main"]).status.success());
assert!(host.ssh("ada", "visibility big public").status.success());
let mut server = Server::start_signed_out(&host.repos);
let mut stream = std::net::TcpStream::connect(("127.0.0.1", server.port)).unwrap();
write!(stream, "GET /ada/big/raw?path=big.bin HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n").unwrap();
let mut first = [0u8; 1024];
let mut got = stream.read(&mut first).unwrap();
assert!(got > 0, "the download started");
// SAFETY: kill only sends a signal to the server this test started.
assert_eq!(unsafe { nix::libc::kill(server.child.id() as i32, nix::libc::SIGTERM) }, 0);
let mut rest = Vec::new();
stream.read_to_end(&mut rest).unwrap();
got += rest.len();
let head_end = first.windows(4).position(|w| w == b"\r\n\r\n").unwrap() + 4;
assert_eq!(got - head_end, 8 << 20, "the whole file arrived after the signal");
let status = server.child.wait().unwrap();
assert!(status.success(), "{status:?}");
assert!(server.logged().contains("stopping; finishing requests in progress"), "{}", server.logged());
assert!(std::net::TcpStream::connect(("127.0.0.1", server.port)).is_err(), "no new connections");
}