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:
1 parent
597ac432e1
commit
5bafd000c8
13 files changed
+651
-51
No files matched your search
+66
-5
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user