Desktop foundation / core (ubuntu-latest) (push) Failing after 28s
Desktop foundation / core (macos-latest) (push) Canceled after 0s
Desktop foundation / core (windows-latest) (push) Canceled after 0s
Linux / verify (push) Canceled after 0s
Linux / keyless-cuda (push) Canceled after 0s
Linux / static-cuda-package (push) Canceled after 0s
Linux / hosted-cuda-package (push) Canceled after 0s
Linux / linux-static-cli (push) Canceled after 0s
Linux / linux-cli-container (push) Canceled after 0s
Linux / release-cli (push) Canceled after 0s
445 lines
16 KiB
Rust
445 lines
16 KiB
Rust
//! GET-only deployment readiness: exact identity and one network wait deadline.
|
|
use std::{collections::BTreeMap, net::IpAddr, path::Path, time::Duration};
|
|
|
|
use reqwest::{Client, Url, header::HeaderValue};
|
|
use serde_json::{Value, json};
|
|
|
|
const USAGE: &str = "usage: strata-next wait-ready --url LOOPBACK_ORIGIN --model ID [--key-file FILE] [--timeout-s N]";
|
|
const MAX_BODY: usize = 64 * 1024;
|
|
|
|
struct Options {
|
|
url: Url,
|
|
model: String,
|
|
key_file: Option<String>,
|
|
timeout: Duration,
|
|
}
|
|
|
|
fn parse(args: &[String]) -> Result<Options, String> {
|
|
let mut values = BTreeMap::new();
|
|
let mut args = args.iter();
|
|
while let Some(flag) = args.next() {
|
|
if !matches!(
|
|
flag.as_str(),
|
|
"--url" | "--model" | "--key-file" | "--timeout-s"
|
|
) {
|
|
return Err(USAGE.into());
|
|
}
|
|
let value = args.next().ok_or(USAGE)?;
|
|
if values.insert(flag.as_str(), value).is_some() {
|
|
return Err(USAGE.into());
|
|
}
|
|
}
|
|
let mut url =
|
|
Url::parse(values.get("--url").ok_or(USAGE)?).map_err(|_| "invalid readiness URL")?;
|
|
let loopback = url
|
|
.host_str()
|
|
.and_then(|host| {
|
|
host.trim_start_matches('[')
|
|
.trim_end_matches(']')
|
|
.parse::<IpAddr>()
|
|
.ok()
|
|
})
|
|
.is_some_and(|ip| ip.is_loopback());
|
|
if url.scheme() != "http"
|
|
|| !loopback
|
|
|| !url.username().is_empty()
|
|
|| url.password().is_some()
|
|
|| url.path() != "/"
|
|
|| url.query().is_some()
|
|
|| url.fragment().is_some()
|
|
|| url.port_or_known_default().is_none_or(|port| port == 0)
|
|
{
|
|
return Err("readiness URL must be an HTTP literal loopback origin without credentials, path, query or fragment; use an SSH tunnel for remote nodes".into());
|
|
}
|
|
url.set_path("/status");
|
|
let model = values.get("--model").ok_or(USAGE)?.to_string();
|
|
if model.trim().is_empty() || model.len() > 4096 || model.chars().any(char::is_control) {
|
|
return Err("model ID must contain 1..4096 bytes without control characters".into());
|
|
}
|
|
let seconds = match values.get("--timeout-s") {
|
|
Some(value) => value
|
|
.parse::<u64>()
|
|
.map_err(|_| "timeout-s must be 1..3600")?,
|
|
None => 300,
|
|
};
|
|
if !(1..=3600).contains(&seconds) {
|
|
return Err("timeout-s must be 1..3600".into());
|
|
}
|
|
Ok(Options {
|
|
url,
|
|
model,
|
|
timeout: Duration::from_secs(seconds),
|
|
key_file: values.get("--key-file").map(|s| s.to_string()),
|
|
})
|
|
}
|
|
|
|
pub(crate) fn validate(args: &[String]) -> Result<(), String> {
|
|
parse(args).map(|_| ())
|
|
}
|
|
|
|
async fn probe(
|
|
client: &Client,
|
|
url: &Url,
|
|
key: Option<&HeaderValue>,
|
|
model: &str,
|
|
expected_pid: Option<u32>,
|
|
) -> Result<bool, String> {
|
|
let mut request = client.get(url.clone());
|
|
if let Some(key) = key {
|
|
request = request.header(reqwest::header::AUTHORIZATION, key.clone());
|
|
}
|
|
// Do not return reqwest errors: their URLs or peer text are not diagnostics.
|
|
let mut response = match request.send().await {
|
|
Ok(response) => response,
|
|
Err(_) => return Ok(false),
|
|
};
|
|
let status = response.status();
|
|
if status == 401 || status == 403 {
|
|
return Err("readiness authentication rejected; check --key-file".into());
|
|
}
|
|
if status.is_redirection() {
|
|
return Err("readiness redirects are not allowed".into());
|
|
}
|
|
if status.is_server_error() || status == 429 {
|
|
return Ok(false);
|
|
}
|
|
if status != 200 {
|
|
return Err(format!(
|
|
"unexpected readiness HTTP status {}",
|
|
status.as_u16()
|
|
));
|
|
}
|
|
if response
|
|
.content_length()
|
|
.is_some_and(|n| n > MAX_BODY as u64)
|
|
{
|
|
return Err("readiness response exceeds 64 KiB".into());
|
|
}
|
|
let mut bytes = Vec::new();
|
|
loop {
|
|
let chunk = match response.chunk().await {
|
|
Ok(Some(chunk)) => chunk,
|
|
Ok(None) => break,
|
|
Err(_) => return Ok(false),
|
|
};
|
|
if chunk.len() > MAX_BODY - bytes.len() {
|
|
return Err("readiness response exceeds 64 KiB".into());
|
|
}
|
|
bytes.extend_from_slice(&chunk);
|
|
}
|
|
let value: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid readiness JSON")?;
|
|
if value.get("service").and_then(Value::as_str) != Some("strata-control")
|
|
|| value.get("model").and_then(Value::as_str) != Some(model)
|
|
{
|
|
return Err("readiness service or model does not match the requested deployment".into());
|
|
}
|
|
if expected_pid
|
|
.is_some_and(|pid| value.get("server_pid").and_then(Value::as_u64) != Some(u64::from(pid)))
|
|
{
|
|
return Err("readiness endpoint does not match the managed server PID".into());
|
|
}
|
|
let ready = value
|
|
.get("ready")
|
|
.and_then(Value::as_bool)
|
|
.ok_or("invalid readiness flag")?;
|
|
let worker = value
|
|
.get("worker")
|
|
.and_then(Value::as_str)
|
|
.ok_or("invalid readiness worker state")?;
|
|
if !matches!(
|
|
worker,
|
|
"unconfigured" | "starting" | "ready" | "restarting" | "failed" | "stopping" | "stopped"
|
|
) {
|
|
return Err("invalid readiness worker state".into());
|
|
}
|
|
if ready && worker != "ready" {
|
|
return Err("inconsistent readiness worker state".into());
|
|
}
|
|
Ok(ready)
|
|
}
|
|
|
|
pub(crate) struct Waiter {
|
|
options: Options,
|
|
key: Option<HeaderValue>,
|
|
client: Client,
|
|
}
|
|
|
|
impl Waiter {
|
|
pub(crate) fn new(args: &[String]) -> Result<Self, String> {
|
|
let options = parse(args)?;
|
|
let key = options
|
|
.key_file
|
|
.as_ref()
|
|
.map(|file| {
|
|
let token = crate::auth::read_token(Path::new(file))
|
|
.map_err(|_| "unable to read a valid private API key file")?;
|
|
let mut header = HeaderValue::from_str(&format!("Bearer {token}"))
|
|
.map_err(|_| "invalid API key")?;
|
|
header.set_sensitive(true);
|
|
Ok::<_, String>(header)
|
|
})
|
|
.transpose()?;
|
|
let client = Client::builder()
|
|
.no_proxy()
|
|
.redirect(reqwest::redirect::Policy::none())
|
|
.connect_timeout(Duration::from_secs(3))
|
|
.timeout(Duration::from_secs(3))
|
|
.build()
|
|
.map_err(|_| "unable to initialize readiness HTTP client")?;
|
|
Ok(Self {
|
|
options,
|
|
key,
|
|
client,
|
|
})
|
|
}
|
|
|
|
async fn lifecycle_request(
|
|
&self,
|
|
path: &str,
|
|
mutation_pid: Option<u32>,
|
|
) -> Result<Value, String> {
|
|
let mut url = self.options.url.clone();
|
|
url.set_path(path);
|
|
let mut request = if let Some(pid) = mutation_pid {
|
|
self.client
|
|
.post(url)
|
|
.header("x-strata-expected-pid", pid.to_string())
|
|
} else {
|
|
self.client.get(url)
|
|
};
|
|
if let Some(key) = &self.key {
|
|
request = request.header(reqwest::header::AUTHORIZATION, key.clone());
|
|
}
|
|
let mut response = request
|
|
.send()
|
|
.await
|
|
.map_err(|_| "lifecycle HTTP request failed; mutation outcome may be unknown")?;
|
|
if response.status() != 200 {
|
|
return Err(format!(
|
|
"lifecycle HTTP status {}; no request replayed",
|
|
response.status().as_u16()
|
|
));
|
|
}
|
|
if response
|
|
.content_length()
|
|
.is_some_and(|n| n > MAX_BODY as u64)
|
|
{
|
|
return Err("lifecycle response exceeds 64 KiB".into());
|
|
}
|
|
let mut bytes = Vec::new();
|
|
while let Some(chunk) = response
|
|
.chunk()
|
|
.await
|
|
.map_err(|_| "lifecycle response interrupted; mutation outcome may be unknown")?
|
|
{
|
|
if chunk.len() > MAX_BODY - bytes.len() {
|
|
return Err("lifecycle response exceeds 64 KiB".into());
|
|
}
|
|
bytes.extend_from_slice(&chunk);
|
|
}
|
|
serde_json::from_slice(&bytes).map_err(|_| "invalid lifecycle JSON".into())
|
|
}
|
|
|
|
fn lifecycle_identity(&self, value: &Value, pid: u32) -> Result<(), String> {
|
|
if value["service"] != "strata-control"
|
|
|| value["model"] != self.options.model
|
|
|| value["server_pid"].as_u64() != Some(u64::from(pid))
|
|
{
|
|
return Err("lifecycle endpoint does not match managed service, model and PID".into());
|
|
}
|
|
if value["shutting_down"] != false {
|
|
return Err("managed lifecycle is shutting down or invalid".into());
|
|
}
|
|
if !value["draining"].is_boolean()
|
|
|| !value["drained"].is_boolean()
|
|
|| value["requests_in_flight"].as_u64().is_none()
|
|
|| value["generation_jobs"].as_u64().is_none()
|
|
{
|
|
return Err("invalid lifecycle state".into());
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
pub(crate) async fn admission(self, pid: u32, drain: bool) -> Result<Value, String> {
|
|
tokio::time::timeout(self.options.timeout, async {
|
|
let before = self.lifecycle_request("/admin/lifecycle", None).await?;
|
|
self.lifecycle_identity(&before, pid)?;
|
|
// Never replay a mutation after a lost response. The operator can
|
|
// explicitly reconcile or resume admission using the same PID check.
|
|
let path = if drain {
|
|
"/admin/drain"
|
|
} else {
|
|
"/admin/resume"
|
|
};
|
|
let mut state = self.lifecycle_request(path, Some(pid)).await?;
|
|
loop {
|
|
self.lifecycle_identity(&state, pid)?;
|
|
if state["draining"] != drain {
|
|
return Err("admission state does not match requested action".into());
|
|
}
|
|
if !drain {
|
|
return Ok(state);
|
|
}
|
|
if state["drained"] == true {
|
|
if state["requests_in_flight"] != 0
|
|
|| state["generation_jobs"] != 0
|
|
|| !matches!(state["worker"].as_str(), Some("ready" | "unconfigured"))
|
|
{
|
|
return Err("inconsistent drained lifecycle state".into());
|
|
}
|
|
return Ok(state);
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(100)).await;
|
|
state = self.lifecycle_request("/admin/lifecycle", None).await?;
|
|
}
|
|
})
|
|
.await
|
|
.map_err(|_| "admission deadline expired; inspect lifecycle before retrying or resuming")?
|
|
}
|
|
|
|
pub(crate) async fn wait(self, expected_pid: Option<u32>) -> Result<Value, String> {
|
|
let Self {
|
|
options,
|
|
key,
|
|
client,
|
|
} = self;
|
|
// Includes connect, headers, every body chunk, and all retry sleeps. A peer
|
|
// sending bytes more often than a socket timeout cannot prolong this budget.
|
|
tokio::time::timeout(options.timeout, async {
|
|
let mut attempts = 0u64;
|
|
loop {
|
|
attempts += 1;
|
|
if probe(&client, &options.url, key.as_ref(), &options.model, expected_pid).await? {
|
|
let mut result = json!({"ready":true, "service":"strata-control", "model":options.model, "attempts":attempts});
|
|
if let Some(pid) = expected_pid { result["server_pid"] = json!(pid); }
|
|
return Ok(result);
|
|
}
|
|
tokio::time::sleep(Duration::from_millis(250)).await;
|
|
}
|
|
}).await.map_err(|_| "readiness deadline expired; model did not become ready within timeout-s")?
|
|
}
|
|
}
|
|
|
|
pub async fn run(args: &[String]) -> Result<Value, String> {
|
|
Waiter::new(args)?.wait(None).await
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
fn args(url: &str) -> Vec<String> {
|
|
["--url", url, "--model", "fixture"]
|
|
.map(str::to_owned)
|
|
.to_vec()
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn managed_readiness_requires_exact_numeric_pid_but_plain_wait_is_compatible() {
|
|
for reported in [
|
|
None,
|
|
Some(json!(123)),
|
|
Some(json!(124)),
|
|
Some(json!("123")),
|
|
Some(json!(0)),
|
|
] {
|
|
let mut body = json!({"service":"strata-control", "model":"fixture", "ready":true, "worker":"ready"});
|
|
if let Some(value) = reported.clone() {
|
|
body["server_pid"] = value;
|
|
}
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let url = format!("http://{}", listener.local_addr().unwrap());
|
|
let router = axum::Router::new().route(
|
|
"/status",
|
|
axum::routing::get(move || async move { axum::Json(body) }),
|
|
);
|
|
let server = tokio::spawn(async move {
|
|
axum::serve(listener, router).await.unwrap();
|
|
});
|
|
let managed = Waiter::new(&args(&url)).unwrap().wait(Some(123)).await;
|
|
assert_eq!(managed.is_ok(), reported == Some(json!(123)));
|
|
if let Ok(value) = managed {
|
|
assert_eq!(value["server_pid"], 123);
|
|
}
|
|
let plain = run(&args(&url)).await.unwrap();
|
|
assert_eq!(plain["ready"], true);
|
|
assert!(plain.get("server_pid").is_none());
|
|
server.abort();
|
|
let _ = server.await;
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
async fn admission_refuses_wrong_endpoint_and_never_replays_failed_post() {
|
|
use std::sync::{
|
|
Arc,
|
|
atomic::{AtomicUsize, Ordering},
|
|
};
|
|
for reported_pid in [124, 123] {
|
|
let calls = Arc::new(AtomicUsize::new(0));
|
|
let observed = calls.clone();
|
|
let value = json!({"service":"strata-control","model":"fixture","server_pid":reported_pid,
|
|
"shutting_down":false,"draining":false,"drained":false,"requests_in_flight":0,"generation_jobs":0,"worker":"ready"});
|
|
let app = axum::Router::new()
|
|
.route(
|
|
"/admin/lifecycle",
|
|
axum::routing::get(move || async move { axum::Json(value) }),
|
|
)
|
|
.route(
|
|
"/admin/drain",
|
|
axum::routing::post(move |headers: axum::http::HeaderMap| async move {
|
|
assert_eq!(headers["x-strata-expected-pid"], "123");
|
|
observed.fetch_add(1, Ordering::SeqCst);
|
|
axum::http::StatusCode::INTERNAL_SERVER_ERROR
|
|
}),
|
|
);
|
|
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let url = format!("http://{}", listener.local_addr().unwrap());
|
|
let server = tokio::spawn(async move {
|
|
axum::serve(listener, app).await.unwrap();
|
|
});
|
|
assert!(
|
|
Waiter::new(&args(&url))
|
|
.unwrap()
|
|
.admission(123, true)
|
|
.await
|
|
.is_err()
|
|
);
|
|
assert_eq!(
|
|
calls.load(Ordering::SeqCst),
|
|
usize::from(reported_pid == 123)
|
|
);
|
|
server.abort();
|
|
let _ = server.await;
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn validates_origin_and_budgets_before_network_or_credentials() {
|
|
for url in ["http://127.0.0.1:18082", "http://[::1]:18082/"] {
|
|
let options = parse(&args(url)).unwrap();
|
|
assert_eq!(options.url.path(), "/status");
|
|
}
|
|
for url in [
|
|
"https://127.0.0.1",
|
|
"http://localhost",
|
|
"http://192.0.2.1",
|
|
"http://key@127.0.0.1",
|
|
"http://127.0.0.1/status",
|
|
"http://127.0.0.1?key=x",
|
|
"http://127.0.0.1#x",
|
|
"http://127.0.0.1:0",
|
|
] {
|
|
assert!(parse(&args(url)).is_err());
|
|
}
|
|
for budget in ["0", "3601", "-1", "nan"] {
|
|
let mut args = args("http://127.0.0.1");
|
|
args.extend(["--timeout-s".into(), budget.into()]);
|
|
assert!(parse(&args).is_err());
|
|
}
|
|
let mut repeated = args("http://127.0.0.1");
|
|
repeated.extend(["--model".into(), "other".into()]);
|
|
assert!(parse(&repeated).is_err());
|
|
}
|
|
}
|