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

309 lines
11 KiB
Rust

//! Process-local admission drain. A request remains admitted until its body is
//! consumed/dropped; commands remain tracked through worker protocol cleanup.
use std::{
pin::Pin,
sync::{Arc, Mutex},
task::{Context, Poll},
};
use axum::{
Json,
body::{Body, Bytes},
extract::{Request, State},
http::{StatusCode, header::RETRY_AFTER},
middleware::Next,
response::{IntoResponse, Response},
};
use http_body::{Body as HttpBody, Frame, SizeHint};
use serde::Serialize;
use serde_json::json;
pub const DEFAULT_MAX_IN_FLIGHT_REQUESTS: usize = 17;
pub fn validate_capacity(value: usize) -> Result<(), &'static str> {
if (1..=256).contains(&value) { Ok(()) } else { Err("max_in_flight_requests must be between 1 and 256") }
}
#[derive(Clone)]
pub struct Lifecycle(Arc<Mutex<Snapshot>>);
impl Default for Lifecycle {
fn default() -> Self {
Self::new(DEFAULT_MAX_IN_FLIGHT_REQUESTS).expect("valid default capacity")
}
}
#[derive(Debug, PartialEq, Eq)]
enum AdmissionError {
Draining,
Overloaded,
}
#[derive(Clone, Copy, Default, Serialize)]
pub struct Snapshot {
pub max_in_flight_requests: usize,
pub draining: bool,
pub shutting_down: bool,
pub requests_in_flight: usize,
pub generation_jobs: usize,
}
pub struct Guard {
lifecycle: Lifecycle,
generation: bool,
}
impl Lifecycle {
pub fn new(max_in_flight_requests: usize) -> Result<Self, &'static str> {
validate_capacity(max_in_flight_requests)?;
Ok(Self(Arc::new(Mutex::new(Snapshot { max_in_flight_requests, ..Snapshot::default() }))))
}
pub fn snapshot(&self) -> Snapshot {
*self.0.lock().expect("admission mutex")
}
pub fn set_draining(&self, draining: bool) {
let mut state = self.0.lock().expect("admission mutex");
state.draining = draining || state.shutting_down;
}
/// Signal shutdown cannot be undone by an administrative resume.
pub fn begin_shutdown(&self) {
let mut state = self.0.lock().expect("admission mutex");
state.shutting_down = true;
state.draining = true;
}
/// Wait for admitted HTTP bodies and queued/active worker commands. This
/// bounds only the drain phase; process/connection cleanup happens later.
pub async fn wait_drained(&self, grace: std::time::Duration) -> bool {
tokio::time::timeout(grace, async {
loop {
let state = self.snapshot();
if state.requests_in_flight == 0 && state.generation_jobs == 0 {
return;
}
tokio::time::sleep(std::time::Duration::from_millis(25)).await;
}
})
.await
.is_ok()
}
fn admit(&self) -> Result<Guard, AdmissionError> {
let mut state = self.0.lock().expect("admission mutex");
if state.draining {
return Err(AdmissionError::Draining);
}
if state.requests_in_flight >= state.max_in_flight_requests {
return Err(AdmissionError::Overloaded);
}
state.requests_in_flight += 1;
Ok(Guard { lifecycle: self.clone(), generation: false })
}
// Called only for requests that already passed admission. Drain must not
// prevent those requests from entering the command queue later.
pub fn generation(&self) -> Guard {
self.0.lock().expect("admission mutex").generation_jobs += 1;
Guard { lifecycle: self.clone(), generation: true }
}
}
impl Drop for Guard {
fn drop(&mut self) {
let mut state = self.lifecycle.0.lock().expect("admission mutex");
if self.generation {
state.generation_jobs -= 1;
} else {
state.requests_in_flight -= 1;
}
}
}
/// The 503 of a draining runtime and the 429 of a full one.
fn refusal_response(refusal: AdmissionError) -> Response {
match refusal {
AdmissionError::Draining => (
StatusCode::SERVICE_UNAVAILABLE,
Json(json!({"error":{
"type":"server_error", "code":"runtime_draining",
"message":"Runtime is draining; new inference requests are not accepted"
}})),
)
.into_response(),
AdmissionError::Overloaded => (
StatusCode::TOO_MANY_REQUESTS,
[(RETRY_AFTER, "1")],
Json(json!({"error":{
"type":"server_error", "code":"runtime_overloaded",
"message":"Runtime request capacity is full; retry later"
}})),
)
.into_response(),
}
}
pub async fn admit(State(lifecycle): State<Lifecycle>, request: Request, next: Next) -> Response {
let guard = match lifecycle.admit() {
Ok(guard) => guard,
Err(refusal) => return refusal_response(refusal),
};
let response = next.run(request).await;
let (parts, body) = response.into_parts();
Response::from_parts(parts, Body::new(TrackedBody { body, guard: Some(guard) }))
}
struct TrackedBody {
body: Body,
guard: Option<Guard>,
}
impl HttpBody for TrackedBody {
type Data = Bytes;
type Error = axum::Error;
fn poll_frame(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Result<Frame<Bytes>, Self::Error>>> {
let frame = Pin::new(&mut self.body).poll_frame(cx);
if matches!(frame, Poll::Ready(None | Some(Err(_)))) {
self.guard.take();
}
frame
}
fn is_end_stream(&self) -> bool {
self.body.is_end_stream()
}
fn size_hint(&self) -> SizeHint {
self.body.size_hint()
}
}
#[cfg(test)]
mod tests {
use super::*;
use http_body_util::{BodyExt, StreamBody};
use std::{collections::VecDeque, convert::Infallible};
struct Frames(VecDeque<Frame<Bytes>>);
#[tokio::test]
async fn signal_drain_cannot_resume_and_waits_for_both_lifetimes() {
use std::time::Duration;
let lifecycle = Lifecycle::default();
let request = lifecycle.admit().unwrap();
lifecycle.begin_shutdown();
lifecycle.set_draining(false);
assert!(lifecycle.snapshot().shutting_down);
assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining)));
// An admitted request can still enqueue after signal arrival.
let command = lifecycle.generation();
assert!(!lifecycle.wait_drained(Duration::ZERO).await);
drop(request);
assert!(!lifecycle.wait_drained(Duration::from_millis(5)).await);
let cloned = lifecycle.clone();
let waiter = tokio::spawn(async move { cloned.wait_drained(Duration::from_secs(1)).await });
drop(command);
assert!(waiter.await.unwrap());
assert!(lifecycle.wait_drained(Duration::ZERO).await);
lifecycle.set_draining(false);
assert!(lifecycle.snapshot().draining);
}
#[test]
fn concurrent_admission_reserves_capacity_and_releases_on_drop() {
assert!(Lifecycle::new(0).is_err());
assert!(Lifecycle::new(257).is_err());
assert!(Lifecycle::new(256).is_ok());
let lifecycle = Lifecycle::new(3).unwrap();
assert_eq!(admit_from_32_threads(&lifecycle), 3);
assert_eq!(lifecycle.snapshot().requests_in_flight, 0);
let _request = lifecycle.admit().unwrap();
lifecycle.set_draining(true);
assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining)));
}
/// 32 threads admit at once; each holds its guard until every attempt is done and sees the full count.
/// Returns how many were admitted.
fn admit_from_32_threads(lifecycle: &Lifecycle) -> usize {
use std::{sync::Barrier, thread};
let start = Arc::new(Barrier::new(32));
let reserved = Arc::new(Barrier::new(32));
thread::scope(|scope| {
let handles: Vec<_> = (0..32)
.map(|_| {
let lifecycle = lifecycle.clone();
let start = start.clone();
let reserved = reserved.clone();
scope.spawn(move || {
start.wait();
let admission = lifecycle.admit();
reserved.wait(); // Keep every admitted guard until all attempts finish.
let count = lifecycle.snapshot().requests_in_flight;
reserved.wait();
assert_eq!(count, 3);
admission.is_ok()
})
})
.collect();
handles.into_iter().map(|h| h.join().unwrap()).filter(|ok| *ok).count()
})
}
impl futures_core::Stream for Frames {
type Item = Result<Frame<Bytes>, Infallible>;
fn poll_next(mut self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Poll::Ready(self.0.pop_front().map(Ok))
}
}
/// A body of one terminal data frame followed by the `x-fixture` trailer (also returned).
fn terminal_frame_and_trailers() -> (Frames, axum::http::HeaderMap) {
let mut trailers = axum::http::HeaderMap::new();
trailers.insert("x-fixture", "kept".parse().unwrap());
let frames = Frames(VecDeque::from([
Frame::data(Bytes::from_static(b"data: terminal\n\n")),
Frame::trailers(trailers.clone()),
]));
(frames, trailers)
}
/// Once the drain is lifted a request is admitted and released by dropping its body.
fn assert_admits_again_after_drain(lifecycle: &Lifecycle) {
lifecycle.set_draining(false);
let guard = lifecycle.admit().unwrap();
drop(TrackedBody { body: Body::empty(), guard: Some(guard) });
assert_eq!(lifecycle.snapshot().requests_in_flight, 0);
}
/// The data frame and the trailers pass through; the request is released when the body ends.
async fn assert_frames_then_release(lifecycle: &Lifecycle, mut body: TrackedBody, trailers: axum::http::HeaderMap) {
assert_eq!(
body.frame().await.unwrap().unwrap().into_data().unwrap(),
"data: terminal
"
);
assert_eq!(lifecycle.snapshot().requests_in_flight, 1);
assert_eq!(body.frame().await.unwrap().unwrap().into_trailers().unwrap(), trailers);
assert!(body.frame().await.is_none());
assert_eq!(lifecycle.snapshot().requests_in_flight, 0);
}
#[tokio::test]
async fn drain_tracks_body_frames_trailers_and_command_lifetimes_independently() {
let lifecycle = Lifecycle::default();
let request = lifecycle.admit().unwrap();
lifecycle.set_draining(true);
assert!(matches!(lifecycle.admit(), Err(AdmissionError::Draining)));
// Already admitted work can enqueue after drain was requested.
let command = lifecycle.generation();
let (frames, trailers) = terminal_frame_and_trailers();
let body = TrackedBody { body: Body::new(StreamBody::new(frames)), guard: Some(request) };
assert_frames_then_release(&lifecycle, body, trailers).await;
assert_eq!(lifecycle.snapshot().generation_jobs, 1);
drop(command);
assert_eq!(lifecycle.snapshot().generation_jobs, 0);
assert_admits_again_after_drain(&lifecycle);
}
}