Respond to code review: sampling defaults, abort race, hardening + README

Bug fixes (from review/README.md):
- Apply config sampling defaults field-by-field, so an absent temperature no
  longer means greedy; expose top_k/min_p/repetition_penalty on ChatRequest;
  top_k=0 is "disabled" (-> 64), not greedy.
- Fix cross-request abort race: Engine::request_stop() sets the cancel flag only;
  the owning generate loop does STOP+drain itself, instead of a spawned abort()
  that could hit a later request holding the lock.
- Initialize tracing-subscriber (RUST_LOG, default info); events were dropped.
- TempFilesGuard removes materialized images on every exit path (error/panic/drop);
  build_prompt runs in spawn_blocking off the async worker; ureq image fetch gets a
  15s timeout, a 32MB cap and a basic SSRF guard (literal loopback/private hosts).
- Non-blocking shutdown (STOP+QUIT without taking the request lock first) and a
  bounded drain_to_done that marks the engine dead on timeout.

Operational hardening:
- Graceful shutdown on SIGTERM as well as SIGINT.
- Warn when binding a non-loopback address (no auth, allowed_hosts not enforced).
- Configurable startup/silence timeouts (optional config keys, default 600s).

Docs:
- Add README.md (English): what strata-ctl is, why Rust for stable server use,
  architecture, usage, honest status, and credits to Strata / Niko1221.

76 tests green + 2 real-file ignored; clippy clean; cargo fmt applied.
Deferred (heavy): automatic engine restart after a crash.
This commit is contained in:
adm committed 2026-11-24 18:42:56 +01:00
1 parent 597ac432e1
commit 5bafd000c8
13 files changed
+651 -51

No files matched your search

+64 -19
View File
@@ -16,7 +16,7 @@ use tokio_stream::wrappers::UnboundedReceiverStream;
use crate::engine::{Engine, EngineLine, Outcome};
use super::formatter::{self, Formatter, Piece};
use super::formatter::{self, Formatter, Piece, Prompt};
use super::stop::StopFilter;
use super::types::{
completion_id, now_unix, tool_call_id, ApiErrorEnvelope, ChatChunk, ChatMessage, ChatRequest,
@@ -41,18 +41,15 @@ impl ChatService {
/// One-shot completion.
pub async fn complete(&self, req: &ChatRequest) -> Result<ChatResponse, ApiErrorEnvelope> {
let prompt = self.fmt.build_prompt(req)?;
let mut prompt = self.build_prompt_blocking(req).await?;
// temp files are removed on any exit path (engine error/panic included)
let _temp = TempFilesGuard(std::mem::take(&mut prompt.temp_files));
let outcome = self
.engine
.generate(prompt.max_new, &prompt.sampling, &prompt.ids, |_| {})
.await
.map_err(formatter_error)?;
// drop per-request temp files (materialized images) now generation is done
for p in &prompt.temp_files {
let _ = std::fs::remove_file(p);
}
let mut dec = self.fmt.decoder();
let reason = outcome.done.as_ref().map(|d| d.finish.as_str());
let decoded =
@@ -115,7 +112,7 @@ impl ChatService {
&self,
req: &ChatRequest,
) -> Result<impl Stream<Item = Event> + Send + 'static, ApiErrorEnvelope> {
let prompt = self.fmt.build_prompt(req)?;
let prompt = self.build_prompt_blocking(req).await?;
let id = completion_id();
let created = now_unix();
@@ -135,6 +132,8 @@ impl ChatService {
);
let p_stops = req.stop.clone().map(|s| s.into_vec()).unwrap_or_default();
tokio::spawn(async move {
// temp files removed on any exit path (error/panic/drop included)
let _temp = TempFilesGuard(p_temp);
// Open the stream the way OpenAI clients expect: role first.
send(
&tx,
@@ -205,11 +204,6 @@ impl ChatService {
);
}
// drop per-request temp files (materialized images)
for p in &p_temp {
let _ = std::fs::remove_file(p);
}
let finish = if st.had_tools {
FinishReason::ToolCalls
} else if st.stop_hit {
@@ -230,6 +224,23 @@ impl ChatService {
Ok(UnboundedReceiverStream::new(rx))
}
/// Run `build_prompt` off the async worker: image materialization does
/// blocking network/disk I/O (ureq fetch, image decode, fs write) that would
/// otherwise stall the Tokio event loop and every other HTTP request.
async fn build_prompt_blocking(&self, req: &ChatRequest) -> Result<Prompt, ApiErrorEnvelope> {
let fmt = self.fmt.clone();
let req = req.clone();
tokio::task::spawn_blocking(move || fmt.build_prompt(&req))
.await
.map_err(|e| {
ApiErrorEnvelope::new(
format!("prompt build task failed: {e}"),
"engine_error",
None,
)
})?
}
}
/// Mutable per-request emit state for the streaming path (kept in one struct so
@@ -241,6 +252,18 @@ struct EmitState {
stop_hit: bool,
}
/// Removes per-request temp files (materialized images) on ANY exit path:
/// normal return, engine error, panic, or a dropped stream future.
struct TempFilesGuard(Vec<std::path::PathBuf>);
impl Drop for TempFilesGuard {
fn drop(&mut self) {
for p in &self.0 {
let _ = std::fs::remove_file(p);
}
}
}
fn send_piece(
tx: &UnboundedSender<Event>,
id: &str,
@@ -248,7 +271,7 @@ fn send_piece(
model: &str,
piece: &Piece,
st: &mut EmitState,
abort_engine: &Arc<Engine>,
engine: &Arc<Engine>,
) {
let delta = match piece {
Piece::Content(s) => {
@@ -256,11 +279,10 @@ fn send_piece(
let emit = st.stops.feed(s);
if st.stops.hit && !st.stop_hit {
st.stop_hit = true;
// stop reached: abort the engine so we don't keep generating
let e = abort_engine.clone();
tokio::spawn(async move {
let _ = e.abort().await;
});
// stop reached: signal the owning generate loop to STOP+drain.
// No spawn/abort(): that could race a later request on the lock
// and abort the wrong one.
engine.request_stop();
}
if emit.is_empty() {
return;
@@ -344,3 +366,26 @@ fn usage_of(outcome: &Outcome, prompt_len: u32, completion: u32) -> Usage {
fn formatter_error(err: crate::engine::EngineError) -> ApiErrorEnvelope {
formatter::engine_error(err).1
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn temp_files_guard_removes_on_drop() {
let p = std::env::temp_dir().join(format!(
"strata-ctl-guard-{}-{}.tmp",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
std::fs::write(&p, b"x").unwrap();
assert!(p.exists());
{
let _g = TempFilesGuard(vec![p.clone()]);
}
assert!(!p.exists(), "guard must remove the file on drop");
}
}
+8
View File
@@ -119,6 +119,14 @@ pub struct ChatRequest {
pub presence_penalty: Option<f64>,
#[serde(default)]
pub seed: Option<u64>,
/// Engine sampling extensions many OpenAI-compatible clients send
/// (OpenWebUI, llama.cpp, ...). `top_k = 0` means "disabled".
#[serde(default)]
pub top_k: Option<u32>,
#[serde(default)]
pub min_p: Option<f64>,
#[serde(default)]
pub repetition_penalty: Option<f64>,
#[serde(default)]
pub stop: Option<Stop>,
/// Tool definitions. Parsed but not yet acted on: kept so the request
+32
View File
@@ -14,6 +14,7 @@
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use std::time::Duration;
use serde::Deserialize;
@@ -79,6 +80,13 @@ pub struct Config {
#[serde(default)]
pub sampling: SamplingDefaults,
/// Startup (wait for `READY`) and silence-watchdog timeouts, in seconds.
/// Optional: both default to 600s when absent.
#[serde(default)]
pub startup_timeout_secs: Option<u64>,
#[serde(default)]
pub silence_timeout_secs: Option<u64>,
/// Keys we understand but don't act on yet are NOT listed above, so they
/// arrive here untouched — the "ignore what isn't ours" guarantee.
#[serde(flatten)]
@@ -165,6 +173,16 @@ impl Config {
cli.or(self.port).unwrap_or(8095)
}
/// Timeout waiting for the engine's `READY` line (default 600s).
pub fn startup_timeout(&self) -> Duration {
Duration::from_secs(self.startup_timeout_secs.unwrap_or(600))
}
/// Silence watchdog: max gap between engine output lines (default 600s).
pub fn silence_timeout(&self) -> Duration {
Duration::from_secs(self.silence_timeout_secs.unwrap_or(600))
}
/// The top-level keys present in the file that we are not acting on —
/// reported by `--check` so the shared-file contract stays visible.
pub fn ignored_keys(&self) -> Vec<&str> {
@@ -281,4 +299,18 @@ mod tests {
let keys = s.keys();
assert_eq!(keys, " temperature=1.0");
}
#[test]
fn timeouts_default_and_override() {
let cfg = Config::parse(REAL, "test").unwrap();
assert_eq!(cfg.startup_timeout(), Duration::from_secs(600));
assert_eq!(cfg.silence_timeout(), Duration::from_secs(600));
let cfg2 = Config::parse(
r#"{"exe":"/x/e","startup_timeout_secs":30,"silence_timeout_secs":120}"#,
"test",
)
.unwrap();
assert_eq!(cfg2.startup_timeout(), Duration::from_secs(30));
assert_eq!(cfg2.silence_timeout(), Duration::from_secs(120));
}
}
+16 -2
View File
@@ -184,8 +184,11 @@ impl Sampling {
key("top_p", fmt_float(tp));
}
if let Some(tk) = self.top_k {
// the engine's sampled path keeps at most 64 candidates
key("top_k", (tk.clamp(1, 64)).to_string());
// `top_k = 0` means "disabled" in OpenAI-compatible clients: map it
// to the engine's widest sampled path (64) instead of clamping to 1,
// which would silently make sampling greedy.
let k = if tk == 0 { 64 } else { tk.clamp(1, 64) };
key("top_k", k.to_string());
}
if let Some(mp) = self.min_p.filter(|mp| *mp > 0.0 && *mp <= 1.0) {
key("min_p", fmt_float(mp));
@@ -346,6 +349,17 @@ mod tests {
assert_eq!(s.keys(), " temperature=1.0 top_p=0.9 top_k=64 seed=42");
}
#[test]
fn top_k_zero_means_disabled_not_greedy() {
// 0 is "disabled" for OpenAI-compatible clients: it must NOT become 1
// (greedy); we map it to the engine's widest sampled path.
let s = Sampling {
top_k: Some(0),
..Default::default()
};
assert_eq!(s.keys(), " top_k=64");
}
#[test]
fn penalties_drag_the_window() {
let s = Sampling {
+47 -7
View File
@@ -167,6 +167,14 @@ impl Engine {
})
}
/// Override the silence watchdog (max gap between engine output lines).
/// Builder-style so callers can tune it from config without a new `start`
/// parameter.
pub fn with_silence(mut self, silence: Duration) -> Self {
self.silence = silence;
self
}
pub fn ready(&self) -> Ready {
self.ready
}
@@ -211,7 +219,10 @@ impl Engine {
// here, inside the request that owns the wires.
if self.ctl.flag.load(std::sync::atomic::Ordering::Relaxed) {
self.send("STOP\n").await?;
drain_to_done(&mut g.stdout).await?;
if let Err(e) = drain_to_done(&mut g.stdout, self.silence).await {
g.dead = true;
return Err(e);
}
return Err(EngineError::Refused("aborted".into()));
}
let raw = match tokio::time::timeout(self.silence, read_line(&mut g.stdout)).await {
@@ -220,7 +231,9 @@ impl Engine {
// and report, like Python's silence watchdog. The DONE we
// trigger is drained here, so the wires stay usable.
let _ = self.send("STOP\n").await;
let _ = drain_to_done(&mut g.stdout).await;
if drain_to_done(&mut g.stdout, self.silence).await.is_err() {
g.dead = true;
}
return Err(EngineError::Silent(self.silence));
}
Ok(Err(e)) => {
@@ -283,13 +296,31 @@ impl Engine {
self.pipes.try_lock().is_ok()
}
/// `QUIT` and reap the child.
/// Signals the request that owns the wires to stop, WITHOUT taking the lock
/// or sending STOP from outside: the owning `generate` loop sees the flag and
/// does STOP+drain itself. For the synchronous token callback (stop-sequence
/// hit), where spawning `abort()` could race a later request that already
/// took the lock and abort the wrong one.
pub fn request_stop(&self) {
self.ctl
.flag
.store(true, std::sync::atomic::Ordering::Relaxed);
}
/// `QUIT` and reap the child. Signals first without waiting on the request
/// lock: STOP finishes the in-flight request (DONE) and QUIT makes the engine
/// exit, so the owning `generate` releases the wires. Taking `pipes.lock()`
/// first would block Ctrl-C for up to the silence timeout mid-generation.
pub async fn shutdown(&self) -> Result<(), EngineError> {
let mut g = self.pipes.lock().await;
let _ = self.send("STOP\n").await;
let _ = self.send("QUIT\n").await;
let mut g = match tokio::time::timeout(Duration::from_secs(5), self.pipes.lock()).await {
Ok(g) => g,
Err(_) => return Ok(()), // engine already signalled; do not hang
};
if g.dead {
return Ok(());
}
let _ = self.send("QUIT\n").await;
let _ = tokio::time::timeout(Duration::from_secs(5), g.child.wait()).await;
let _ = g.child.start_kill();
g.dead = true;
@@ -297,9 +328,18 @@ impl Engine {
}
}
async fn drain_to_done(stdout: &mut BufReader<ChildStdout>) -> Result<(), EngineError> {
async fn drain_to_done(
stdout: &mut BufReader<ChildStdout>,
timeout: Duration,
) -> Result<(), EngineError> {
loop {
match EngineLine::parse(&read_line(stdout).await?).into_kind() {
// Bounded: an engine that never answers STOP must not hold the wires
// forever (the caller marks itself dead on timeout).
let raw = match tokio::time::timeout(timeout, read_line(stdout)).await {
Err(_) => return Err(EngineError::Silent(timeout)),
Ok(r) => r?,
};
match EngineLine::parse(&raw).into_kind() {
LineKind::Done | LineKind::Err => return Ok(()),
_ => continue,
}
+17 -6
View File
@@ -22,6 +22,9 @@ pub struct InklingFormatter {
model: String,
effort: Option<String>,
max_new_default: u32,
/// Config-level sampling defaults, applied field-by-field when the request
/// omits a knob (otherwise the engine would fall back to greedy).
default_sampling: Sampling,
}
impl InklingFormatter {
@@ -30,6 +33,7 @@ impl InklingFormatter {
template: ChatTemplate,
model: String,
effort: Option<String>,
default_sampling: Sampling,
) -> Self {
Self {
tok,
@@ -37,6 +41,7 @@ impl InklingFormatter {
model,
effort,
max_new_default: 2048,
default_sampling,
}
}
@@ -100,14 +105,20 @@ impl Formatter for InklingFormatter {
.map(|p| super::images::encode_path(&p.to_string_lossy()))
.collect();
// Per-request knobs win; anything the client omits falls back to the
// config defaults (so an absent temperature does not mean greedy).
let d = &self.default_sampling;
let sampling = Sampling {
temperature: req.temperature,
top_p: req.top_p,
frequency_penalty: req.frequency_penalty,
presence_penalty: req.presence_penalty,
seed: req.seed,
temperature: req.temperature.or(d.temperature),
top_p: req.top_p.or(d.top_p),
top_k: req.top_k.or(d.top_k),
min_p: req.min_p.or(d.min_p),
repetition_penalty: req.repetition_penalty.or(d.repetition_penalty),
frequency_penalty: req.frequency_penalty.or(d.frequency_penalty),
presence_penalty: req.presence_penalty.or(d.presence_penalty),
penalty_last_n: d.penalty_last_n,
seed: req.seed.or(d.seed),
images,
..Default::default()
};
Ok(Prompt {
ids,
+102 -12
View File
@@ -6,12 +6,20 @@
//! Unsupported formats (WebP/TIFF/AVIF, which agents like omp send) are
//! normalized to PNG; JPEG/PNG/BMP/GIF pass through untouched.
use std::io::Read;
use std::path::PathBuf;
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use base64::Engine;
use serde_json::Value as Json;
/// Cap on a fetched image body: a hostile/slow URL must not exhaust memory.
const MAX_IMAGE_BYTES: u64 = 32 * 1024 * 1024;
/// Global timeout for an image fetch (connect + read), so a slow URL cannot
/// stall the request indefinitely.
const FETCH_TIMEOUT: Duration = Duration::from_secs(15);
#[derive(Debug, thiserror::Error)]
pub enum ImageError {
#[error("unsupported image source: {0}")]
@@ -101,11 +109,23 @@ pub fn materialize(sources: &[String]) -> Result<Vec<PathBuf>, ImageError> {
);
let mut out = Vec::new();
for (idx, src) in sources.iter().enumerate() {
let raw = load_bytes(src)?;
let (data, ext) = normalize(raw)?;
let p = base.join(format!("{nonce}-{idx}{ext}"));
std::fs::write(&p, &data).map_err(|e| ImageError::Io(e.to_string()))?;
out.push(p);
let written = (|| -> Result<PathBuf, ImageError> {
let raw = load_bytes(src)?;
let (data, ext) = normalize(raw)?;
let p = base.join(format!("{nonce}-{idx}{ext}"));
std::fs::write(&p, &data).map_err(|e| ImageError::Io(e.to_string()))?;
Ok(p)
})();
match written {
Ok(p) => out.push(p),
Err(e) => {
// a later image failed: do not leak the ones already written
for p in &out {
let _ = std::fs::remove_file(p);
}
return Err(e);
}
}
}
Ok(out)
}
@@ -126,18 +146,64 @@ fn load_bytes(src: &str) -> Result<Vec<u8>, ImageError> {
.map_err(|e| ImageError::Decode(e.to_string()));
}
if src.starts_with("http://") || src.starts_with("https://") {
let mut resp = ureq::get(src)
.call()
.map_err(|e| ImageError::Fetch(e.to_string()))?;
return resp
.body_mut()
.read_to_vec()
.map_err(|e| ImageError::Fetch(e.to_string()));
return fetch_http(src);
}
let path = src.strip_prefix("file://").unwrap_or(src);
std::fs::read(path).map_err(|e| ImageError::Io(format!("{path}: {e}")))
}
/// Fetch an http(s) image with a timeout and a size cap. Blocks literal
/// loopback/private hosts (basic SSRF guard); a hostname that *resolves* to an
/// internal address (DNS rebinding) is not covered here.
fn fetch_http(src: &str) -> Result<Vec<u8>, ImageError> {
if is_blocked_host(src) {
return Err(ImageError::Fetch(
"refusing to fetch an internal/loopback address".into(),
));
}
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(FETCH_TIMEOUT))
.build()
.new_agent();
let mut resp = agent
.get(src)
.call()
.map_err(|e| ImageError::Fetch(e.to_string()))?;
let mut buf = Vec::new();
resp.body_mut()
.as_reader()
.take(MAX_IMAGE_BYTES)
.read_to_end(&mut buf)
.map_err(|e| ImageError::Fetch(e.to_string()))?;
Ok(buf)
}
/// True for localhost / `.local` / `.internal` names and literal loopback,
/// private, link-local or unspecified IPs.
fn is_blocked_host(url: &str) -> bool {
let rest = url.split_once("://").map(|(_, r)| r).unwrap_or(url);
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
let host = authority
.rsplit_once('@')
.map(|(_, h)| h)
.unwrap_or(authority);
let host = match host.strip_prefix('[') {
Some(v6) => v6.split(']').next().unwrap_or(v6), // [::1]:port
None => host.split(':').next().unwrap_or(host), // host:port
};
let host = host.to_ascii_lowercase();
if host == "localhost" || host.ends_with(".local") || host.ends_with(".internal") {
return true;
}
match host.parse::<std::net::IpAddr>() {
Ok(std::net::IpAddr::V4(v4)) => {
v4.is_loopback() || v4.is_private() || v4.is_link_local() || v4.is_unspecified()
}
Ok(std::net::IpAddr::V6(v6)) => v6.is_loopback() || v6.is_unspecified(),
Err(_) => false,
}
}
/// Keep JPEG/PNG/BMP/GIF as-is; convert anything else to PNG via the image crate.
fn normalize(data: Vec<u8>) -> Result<(Vec<u8>, &'static str), ImageError> {
if let Some(ext) = sniff(&data) {
@@ -164,3 +230,27 @@ fn sniff(data: &[u8]) -> Option<&'static str> {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ssrf_guard_blocks_internal_hosts() {
for url in [
"http://localhost/x.png",
"http://127.0.0.1/x.png",
"http://10.0.0.5/x.png",
"http://192.168.1.1/x.png",
"http://169.254.1.1/x.png",
"http://[::1]/x.png",
"http://user@127.0.0.1/x.png",
"http://foo.local/x.png",
] {
assert!(is_blocked_host(url), "{url} should be blocked");
}
for url in ["https://example.com/x.png", "https://8.8.8.8/x.png"] {
assert!(!is_blocked_host(url), "{url} should be allowed");
}
}
}
+66 -5
View File
@@ -7,7 +7,6 @@
use std::path::Path;
use std::process::ExitCode;
use std::sync::Arc;
use std::time::Duration;
use strata_ctl::api::{router, ChatService};
use strata_ctl::config::{Config, ConfigError};
@@ -74,6 +73,14 @@ fn parse_args<I: Iterator<Item = String>>(mut it: I) -> Result<Args, String> {
#[tokio::main]
async fn main() -> ExitCode {
// Without a subscriber every tracing event (engine INFO, stream errors)
// would be silently dropped. RUST_LOG overrides the default `info` level.
tracing_subscriber::fmt()
.with_env_filter(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info")),
)
.init();
let args = match parse_args(std::env::args().skip(1)) {
Ok(a) => a,
Err(e) => {
@@ -140,17 +147,18 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
template,
cfg.model_name().to_string(),
cfg.reasoning_effort.clone(),
cfg.sampling.to_sampling(),
));
let engine = match Engine::start(
&cfg.exe,
&cfg.engine_argv(),
cfg.cwd.as_deref(),
Duration::from_secs(600),
cfg.startup_timeout(),
)
.await
{
Ok(e) => Arc::new(e),
Ok(e) => Arc::new(e.with_silence(cfg.silence_timeout())),
Err(e) => {
eprintln!("error: the engine failed to start: {e}");
return ExitCode::FAILURE;
@@ -164,7 +172,16 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
let svc = ChatService::new(engine.clone(), fmt);
let app = router(svc);
let addr = format!("{}:{}", cfg.bind_host(cli_host), cfg.bind_port(cli_port));
let host = cfg.bind_host(cli_host);
let port = cfg.bind_port(cli_port);
if !is_loopback_host(&host) {
tracing::warn!(
host = %host,
"binding a non-loopback address: the API has NO authentication and \
`allowed_hosts` is not enforced — anyone on the network can use it"
);
}
let addr = format!("{host}:{port}");
let listener = match tokio::net::TcpListener::bind(&addr).await {
Ok(l) => l,
Err(e) => {
@@ -177,7 +194,7 @@ async fn serve(cfg: &Config, cli_host: Option<&str>, cli_port: Option<u16>) -> E
let shutdown_engine = engine.clone();
let result = axum::serve(listener, app)
.with_graceful_shutdown(async move {
let _ = tokio::signal::ctrl_c().await;
wait_for_shutdown_signal().await;
println!("\nshutting down");
let _ = shutdown_engine.shutdown().await;
})
@@ -228,3 +245,47 @@ fn report_config_error(path: &std::path::Path, err: ConfigError) -> ExitCode {
}
ExitCode::FAILURE
}
/// Resolve on Ctrl-C (SIGINT) or SIGTERM (systemd's default stop signal).
async fn wait_for_shutdown_signal() {
let ctrl_c = tokio::signal::ctrl_c();
let mut sigterm = match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
{
Ok(s) => s,
Err(e) => {
tracing::warn!(error = %e, "cannot install SIGTERM handler; SIGINT only");
let _ = ctrl_c.await;
return;
}
};
tokio::select! {
_ = ctrl_c => {},
_ = sigterm.recv() => {},
}
}
/// True for `localhost` and literal loopback IPs (127.0.0.1, ::1). Wildcard
/// binds (0.0.0.0, ::) and LAN addresses are NOT loopback.
fn is_loopback_host(host: &str) -> bool {
if host.eq_ignore_ascii_case("localhost") {
return true;
}
host.parse::<std::net::IpAddr>()
.map(|ip| ip.is_loopback())
.unwrap_or(false)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn loopback_detection() {
for h in ["127.0.0.1", "::1", "localhost", "LOCALHOST"] {
assert!(is_loopback_host(h), "{h} should be loopback");
}
for h in ["0.0.0.0", "::", "192.168.1.10", "10.0.0.5"] {
assert!(!is_loopback_host(h), "{h} should NOT be loopback");
}
}
}