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
//! Service bootstrap: a bind configuration and, with feature `rest`, an
//! axum server loop that shuts down gracefully on SIGINT or SIGTERM.
use anyhow::Result;
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
#[cfg(feature = "rest")]
use anyhow::Context as _;
#[cfg(feature = "rest")]
use std::net::SocketAddr;
/// A service that can be started. Nothing in `krab_core` calls it; it is a
/// shape for applications to implement.
#[async_trait]
pub trait ApiService: Send + Sync {
/// Runs the service, typically until shutdown. `Err` if it fails to start
/// or exits abnormally.
async fn start(&self) -> Result<()>;
}
/// Where a service listens, and under what name.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServiceConfig {
/// Service name, used in log events and error messages (default
/// `unknown`).
pub name: String,
/// Address to bind (default `127.0.0.1`). Must be an IP literal:
/// `serve_with_graceful_shutdown` parses `host:port` as a socket address
/// and does not resolve host names.
pub host: String,
/// Port to bind (default 8080).
pub port: u16,
/// Protocol configuration. `None` keeps legacy single-protocol behavior.
#[serde(default)]
pub protocol: Option<crate::protocol::ProtocolConfig>,
}
impl Default for ServiceConfig {
fn default() -> Self {
Self {
name: "unknown".to_string(),
host: "127.0.0.1".to_string(),
port: 8080,
protocol: None,
}
}
}
/// Binds `config.host:config.port` and serves `app` until SIGINT (Ctrl+C) or,
/// on Unix, SIGTERM, then drains in-flight requests before returning.
///
/// Serves with connection info, so handlers and the client-IP extraction see
/// the peer address. Errors when the address does not parse, the bind fails,
/// or the server exits with an error. Logs `service_listening`,
/// `service_shutdown_signal_received` and `service_shutdown_complete`.
#[cfg(feature = "rest")]
pub async fn serve_with_graceful_shutdown(app: axum::Router, config: &ServiceConfig) -> Result<()> {
let addr = format!("{}:{}", config.host, config.port)
.parse::<SocketAddr>()
.with_context(|| format!("invalid {} service bind address", config.name))?;
let service_name_for_signal = config.name.clone();
tracing::info!(
service = %config.name,
host = %config.host,
port = config.port,
%addr,
"service_listening"
);
let listener = tokio::net::TcpListener::bind(addr)
.await
.with_context(|| format!("failed to bind {} service listener", config.name))?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async move {
wait_for_shutdown_signal().await;
tracing::info!(service = %service_name_for_signal, "service_shutdown_signal_received");
})
.await
.with_context(|| format!("{} service server exited with error", config.name))?;
tracing::info!(service = %config.name, "service_shutdown_complete");
Ok(())
}
/// Resolve on SIGINT (Ctrl+C) — and, on Unix, also SIGTERM.
///
/// Kubernetes and Docker stop containers with SIGTERM; listening only for
/// Ctrl+C meant the process never drained in-flight requests and was
/// SIGKILLed at the grace-period deadline.
#[cfg(feature = "rest")]
async fn wait_for_shutdown_signal() {
#[cfg(unix)]
{
let mut sigterm =
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(stream) => stream,
Err(error) => {
// Registration failing is exceptional; fall back to
// Ctrl+C alone rather than refusing to serve.
tracing::warn!(error = %error, "sigterm_handler_registration_failed");
let _ = tokio::signal::ctrl_c().await;
return;
}
};
tokio::select! {
_ = tokio::signal::ctrl_c() => {}
_ = sigterm.recv() => {}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
}
}