Files
leleka/control-plane/src/wait_ready.rs
T

325 lines
11 KiB
Rust

//! GET-only deployment readiness: exact identity and one network wait deadline.
use std::{path::Path, time::Duration};
use reqwest::{Client, Url, header::HeaderValue};
use serde_json::{Value, json};
const MAX_BODY: usize = 64 * 1024;
mod options;
use options::{Options, parse};
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),
};
if let Some(retry) = classify_status(response.status())? {
return Ok(retry);
}
let Some(bytes) = read_probe_body(&mut response).await? else {
return Ok(false);
};
let value: Value = serde_json::from_slice(&bytes).map_err(|_| "invalid readiness JSON")?;
check_probe_identity(&value, model, expected_pid)?;
readiness_flag(&value)
}
/// `Ok(None)` means the status is 200 and the body is to be read; `Ok(Some(false))` means try again later.
fn classify_status(status: reqwest::StatusCode) -> Result<Option<bool>, String> {
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(Some(false));
}
if status != 200 {
return Err(format!(
"unexpected readiness HTTP status {}",
status.as_u16()
));
}
Ok(None)
}
/// The bounded body, or `None` when the connection broke mid-body (try again later).
async fn read_probe_body(response: &mut reqwest::Response) -> Result<Option<Vec<u8>>, String> {
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(None),
};
if chunk.len() > MAX_BODY - bytes.len() {
return Err("readiness response exceeds 64 KiB".into());
}
bytes.extend_from_slice(&chunk);
}
Ok(Some(bytes))
}
fn check_probe_identity(
value: &Value,
model: &str,
expected_pid: Option<u32>,
) -> Result<(), String> {
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());
}
Ok(())
}
fn readiness_flag(value: &Value) -> Result<bool, String> {
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,
})
}
fn lifecycle_builder(&self, path: &str, mutation_pid: Option<u32>) -> reqwest::RequestBuilder {
let mut url = self.options.url.clone();
url.set_path(path);
let request = if let Some(pid) = mutation_pid {
self.client
.post(url)
.header("x-strata-expected-pid", pid.to_string())
} else {
self.client.get(url)
};
match &self.key {
Some(key) => request.header(reqwest::header::AUTHORIZATION, key.clone()),
None => request,
}
}
async fn lifecycle_request(
&self,
path: &str,
mutation_pid: Option<u32>,
) -> Result<Value, String> {
let mut response = self
.lifecycle_builder(path, mutation_pid)
.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()
));
}
let bytes = read_lifecycle_body(&mut response).await?;
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, self.admit(pid, drain))
.await
.map_err(
|_| "admission deadline expired; inspect lifecycle before retrying or resuming",
)?
}
async fn admit(&self, pid: u32, drain: bool) -> Result<Value, String> {
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 admission_settled(&state, drain)? {
return Ok(state);
}
tokio::time::sleep(Duration::from_millis(100)).await;
state = self.lifecycle_request("/admin/lifecycle", None).await?;
}
}
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;
let (url, model) = (&options.url, &options.model);
if probe(&client, url, key.as_ref(), model, expected_pid).await? {
return Ok(ready_result(model, attempts, expected_pid));
}
tokio::time::sleep(Duration::from_millis(250)).await;
}
})
.await
.map_err(|_| "readiness deadline expired; model did not become ready within timeout-s")?
}
}
fn ready_result(model: &str, attempts: u64, expected_pid: Option<u32>) -> Value {
let mut result =
json!({"ready":true, "service":"strata-control", "model":model, "attempts":attempts});
if let Some(pid) = expected_pid {
result["server_pid"] = json!(pid);
}
result
}
/// An admission answer is settled when it shows the requested state (and, for a drain, no work left).
fn admission_settled(state: &Value, drain: bool) -> Result<bool, String> {
if state["draining"] != drain {
return Err("admission state does not match requested action".into());
}
if !drain {
return Ok(true);
}
if state["drained"] != true {
return Ok(false);
}
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());
}
Ok(true)
}
async fn read_lifecycle_body(response: &mut reqwest::Response) -> Result<Vec<u8>, String> {
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);
}
Ok(bytes)
}
pub async fn run(args: &[String]) -> Result<Value, String> {
Waiter::new(args)?.wait(None).await
}
#[cfg(test)]
mod tests;