Files
leleka/control-plane/tests/http_surface/harness.rs
T

202 lines
6.8 KiB
Rust

//! The harness of the HTTP surface scenarios: the real router and worker supervisor over the mock engine.
use std::{path::PathBuf, sync::Arc, time::Duration};
use leleka_serving_policy::{cors::Cors, shared::sampling_defaults_from_config};
use serde_json::Value;
use leleka_control_plane::{
app::{AppState, EngineLink, HttpPolicy, ModelView, Services, router},
lifecycle::Guard,
settings::Settings,
worker::{Control, GenerationCommand, WorkerConfig, WorkerState, WorkerStatus, run_supervised},
};
use tokio::sync::{RwLock, mpsc, watch};
pub(super) struct Harness {
pub(super) base: String,
pub(super) state: AppState,
stop: watch::Sender<bool>,
worker: tokio::task::JoinHandle<()>,
server: tokio::task::JoinHandle<()>,
dir: PathBuf,
_guards: Vec<Guard>,
}
fn worker_config(dir: &std::path::Path, context: u64, loaded: bool) -> WorkerConfig {
let engine = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/mock_engine.sh");
WorkerConfig {
executable: engine.into_os_string(),
args: vec![
"lifecycle".into(),
dir.to_string_lossy().into_owned(),
context.to_string(),
"--max-context".into(),
context.to_string(),
],
startup_timeout: Duration::from_secs(10),
lazy: !loaded,
..Default::default()
}
}
fn setup_strings(setup: &Value, key: &str) -> Vec<String> {
setup[key]
.as_array()
.map(|a| a.iter().map(|v| v.as_str().unwrap().to_owned()).collect())
.unwrap_or_default()
}
fn build_settings(setup: &Value) -> Settings {
let config_sampling =
sampling_defaults_from_config(setup.get("config_sampling").unwrap_or(&Value::Null))
.unwrap();
let settings = Settings::new(config_sampling);
if let Some(shared) = setup.get("shared") {
settings.set_shared(shared).unwrap();
}
settings
}
fn api_key_from(setup: &Value, dir: &std::path::Path) -> Option<Arc<leleka_control_plane::auth::ApiKey>> {
setup["api_key"]
.as_str()
.filter(|k| !k.is_empty())
.map(|key| {
let path = dir.join("api-key");
std::fs::write(&path, key).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();
}
Arc::new(leleka_control_plane::auth::ApiKey::from_file(&path).unwrap())
})
}
fn app_state(
setup: &Value,
dir: &std::path::Path,
status: Arc<RwLock<WorkerStatus>>,
(requests, control): (mpsc::Sender<GenerationCommand>, mpsc::Sender<Control>),
) -> AppState {
AppState {
engine: EngineLink {
worker: status,
client: Some(leleka_control_plane::adapters::ChannelEngine::shared(requests)),
control: Some(control),
..Default::default()
},
http: HttpPolicy {
cors: Arc::new(Cors::new(setup_strings(setup, "cors_origins"))),
trusted_origins: Arc::new(setup_strings(setup, "trusted_origins")),
api_key: api_key_from(setup, dir),
},
model: ModelView {
name: Some(setup["model"].as_str().unwrap_or("strata-test").to_owned()),
aliases: Arc::new(setup_strings(setup, "aliases")),
..Default::default()
},
services: Services {
settings: Arc::new(build_settings(setup)),
..Default::default()
},
..Default::default()
}
}
/// The Python scenarios mark a request as running/queued through its status dict.
async fn mark_busy_and_queued(state: &AppState, setup: &Value) -> Vec<Guard> {
let mut guards = Vec::new();
if let Some(status_setup) = setup.get("status") {
let busy = status_setup["busy"].as_bool().unwrap_or(false);
let queued = status_setup["queued"].as_u64().unwrap_or(0);
if busy {
state.engine.worker.write().await.metrics.start();
}
for _ in 0..(queued + u64::from(busy)) {
guards.push(state.lifecycle.generation());
}
}
guards
}
/// Serves `state` on a loopback port and waits for the worker to reach `wanted`.
async fn serve_until(
state: &AppState,
wanted: WorkerState,
) -> (String, tokio::task::JoinHandle<()>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", listener.local_addr().unwrap());
let app = router(state.clone());
let server = tokio::spawn(async move {
let _ = axum::serve(listener, app).await;
});
tokio::time::timeout(Duration::from_secs(10), async {
while state.engine.worker.read().await.state != wanted {
tokio::time::sleep(Duration::from_millis(10)).await;
}
})
.await
.expect("worker state");
(base, server)
}
type SpawnedWorker = (
watch::Sender<bool>,
mpsc::Sender<GenerationCommand>,
mpsc::Sender<Control>,
tokio::task::JoinHandle<()>,
);
/// Runs the supervised worker; returns its stop switch, its two channels and the task.
fn spawn_worker(config: WorkerConfig, status: Arc<RwLock<WorkerStatus>>) -> SpawnedWorker {
let (stop, stop_rx) = watch::channel(false);
let (requests, requests_rx) = mpsc::channel(4);
let (control, control_rx) = mpsc::channel(4);
let worker = tokio::spawn(run_supervised(
config,
status,
stop_rx,
requests_rx,
control_rx,
));
(stop, requests, control, worker)
}
impl Harness {
pub(super) async fn start(name: &str, setup: &Value) -> Self {
let dir = std::env::temp_dir().join(format!("strata-http-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
let context = setup["max_context"].as_u64().unwrap_or(4096);
let loaded = setup["loaded"].as_bool().unwrap_or(true);
let config = worker_config(&dir, context, loaded);
let status = Arc::new(RwLock::new(WorkerStatus::default()));
let (stop, requests, control, worker) = spawn_worker(config, status.clone());
let state = app_state(setup, &dir, status, (requests, control));
let guards = mark_busy_and_queued(&state, setup).await;
let wanted = if loaded {
WorkerState::Ready
} else {
WorkerState::Unloaded
};
let (base, server) = serve_until(&state, wanted).await;
Self {
base,
state,
stop,
worker,
server,
dir,
_guards: guards,
}
}
pub(super) async fn finish(self) {
self.server.abort();
self.stop.send(true).unwrap();
let _ = tokio::time::timeout(Duration::from_secs(25), self.worker).await;
let _ = std::fs::remove_dir_all(self.dir);
}
}