diff --git a/services/flysim/Cargo.lock b/services/flysim/Cargo.lock index a7a3b26..1676957 100644 --- a/services/flysim/Cargo.lock +++ b/services/flysim/Cargo.lock @@ -416,6 +416,23 @@ dependencies = [ "serde", ] +[[package]] +name = "fly-control-edge" +version = "0.1.1" +dependencies = [ + "anyhow", + "axum", + "clap", + "flybus", + "flysim", + "serde_json", + "tempfile", + "tokio", + "tower", + "tracing", + "tracing-subscriber", +] + [[package]] name = "fly-edge" version = "0.1.1" @@ -442,6 +459,7 @@ dependencies = [ "anyhow", "axum", "clap", + "fly-control-edge", "fly-session", "flybrain-core", "flybrain-gb", diff --git a/services/flysim/Cargo.toml b/services/flysim/Cargo.toml index d98e038..89a995a 100644 --- a/services/flysim/Cargo.toml +++ b/services/flysim/Cargo.toml @@ -1,6 +1,7 @@ [workspace] resolver = "3" members = [ + "crates/fly-control-edge", "crates/fly-edge", "crates/fly-legacy-session", "crates/fly-session", diff --git a/services/flysim/crates/fly-control-edge/Cargo.toml b/services/flysim/crates/fly-control-edge/Cargo.toml new file mode 100644 index 0000000..1f67712 --- /dev/null +++ b/services/flysim/crates/fly-control-edge/Cargo.toml @@ -0,0 +1,35 @@ +[package] +name = "fly-control-edge" +version.workspace = true +edition = "2024" +rust-version.workspace = true +license.workspace = true +publish = false +description = "The control API (:7401) served from flysim's control services on the bus (FLY_CONTROL_VIA=bus)." + +[lib] +name = "fly_control_edge" +path = "src/lib.rs" + +[[bin]] +name = "fly-control-edge" +path = "src/main.rs" + +[dependencies] +# The HTTP layer, the request/reply types and the bus encoding are flysim's own modules (`api`, +# `control`, `controlbus`), so the edge writes the :7401 bytes with the code flysim uses in direct +# mode and cannot disagree with the services about the encoding. +flysim = { path = "../flysim" } +flybus = { path = "../flybus" } + +anyhow = "1.0" +axum = "0.8" +clap = { version = "4.5", features = ["derive"] } +serde_json = { workspace = true } +tokio = { version = "1", features = ["rt-multi-thread", "net", "sync", "time", "signal", "macros"] } +tracing = "0.1" +tracing-subscriber = { version = "0.3", features = ["env-filter"] } + +[dev-dependencies] +tempfile = "3" +tower = { version = "0.5", features = ["util"] } diff --git a/services/flysim/crates/fly-control-edge/src/lib.rs b/services/flysim/crates/fly-control-edge/src/lib.rs new file mode 100644 index 0000000..c9f7344 --- /dev/null +++ b/services/flysim/crates/fly-control-edge/src/lib.rs @@ -0,0 +1,429 @@ +//! `fly-control-edge`: the control API on `:7401`, answered by flysim's control services on the +//! bus (CTRL-01, `docs/design/flybus.md`, "Control over the bus"). +//! +//! With `FLY_CONTROL_VIA=bus` flysim (either runtime) does not bind `control.bind`. It registers +//! the control services on its embedded router (`flysim::controlbus`), and this process serves the +//! HTTP surface of `docs/control-api.md` to the bridge, the stage, the infra scripts and the +//! operator's `curl` by calling them. The HTTP layer is flysim's own `api::router_with`, so the +//! routes, the 404s, the extractors, the headers and the body encoding are the code direct mode +//! runs; this crate only adds a [`BusBackend`] that carries each request across the bus. +//! +//! Lifecycle (as `fly-edge` for the feed): +//! +//! - the control port is bound only once the control services answer, so before that a client +//! is refused exactly as it is by a flysim that has not started; +//! - when the bus goes away (flysim stopped or restarted) the edge unbinds the port, again what a +//! stopped flysim looks like, and reconnects every `retry` until a router answers. +//! +//! Failures on the bus side map onto the 503s direct mode answers for the same failure (the +//! words are `flysim::control::unavailable`), so a client cannot tell which side was in trouble. + +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::{AtomicU64, Ordering}; +use std::time::Duration; + +use anyhow::{Context, Result, anyhow}; +use axum::extract::State; +use axum::http::StatusCode; +use axum::response::IntoResponse; +use axum::routing::get; +use flybus::{BusError, Client, ClientConfig, Dispatch, ErrorCode}; +use flysim::api::ControlBackend; +use flysim::control::{COMMAND_TIMEOUT, ControlReply, ControlRequest, unavailable}; +use flysim::controlbus::{self, Role, Scope}; +use flysim::feedbus; +use flysim::metrics::metric; +use tokio::sync::oneshot; + +/// How much longer than the services' own [`COMMAND_TIMEOUT`] the edge waits before it gives up +/// on a timed request and cancels it. The services answer a wedged loop with their own 503 at +/// [`COMMAND_TIMEOUT`]; this guard only covers a bus or a host that stopped answering at all. +pub const DEADLINE_MARGIN: Duration = Duration::from_secs(2); + +/// What the edge needs to know, from flysim's own configuration. +#[derive(Debug, Clone)] +pub struct EdgeConfig { + /// `feed.bus_dir`: the router's sockets and store root. + pub bus_dir: PathBuf, + /// `control.bind`, the port flysim leaves alone in bus mode. + pub control_bind: SocketAddr, + /// `FLY_CONTROL_EDGE_METRICS_ADDR`: the edge's own `/metrics` and `/healthz`, when set. + pub metrics_bind: Option, + /// Delay between attempts to reach the bus. + pub retry: Duration, + /// The session and agents whose services `:7401` addresses. + pub scope: Scope, +} + +impl EdgeConfig { + pub fn from_flysim(config: &flysim::config::Config, metrics_bind: Option) -> Self { + Self { + bus_dir: config.feed.bus_dir.clone(), + control_bind: config.control.bind, + metrics_bind, + retry: Duration::from_millis(500), + scope: Scope::live(), + } + } +} + +/// The edge's counters. +#[derive(Debug, Default)] +pub struct EdgeMetrics { + /// 1 while connected and serving. + pub connected: AtomicU64, + /// Requests carried across the bus. + pub calls: AtomicU64, + /// Requests that ended in a bus failure rather than a reply (each a 503 or 403 to the + /// client). + pub call_failures: AtomicU64, + /// Requests the edge cancelled at its own deadline. + pub cancelled: AtomicU64, + /// Serving sessions ended by the bus going away. + pub bus_lost: AtomicU64, + /// Sessions that reached the bus but could not bind the control port. + pub bind_failures: AtomicU64, +} + +impl EdgeMetrics { + pub fn render(&self) -> String { + let mut out = String::with_capacity(1_024); + for (name, kind, help, value) in [ + ( + "fly_control_edge_bus_connected", + "gauge", + "1 while the edge is connected to the control bus and serving.", + &self.connected, + ), + ( + "fly_control_edge_calls_total", + "counter", + "Control requests carried across the bus.", + &self.calls, + ), + ( + "fly_control_edge_call_failures_total", + "counter", + "Control requests that ended in a bus failure instead of a reply.", + &self.call_failures, + ), + ( + "fly_control_edge_cancelled_total", + "counter", + "Control requests the edge cancelled at its own deadline.", + &self.cancelled, + ), + ( + "fly_control_edge_bus_lost_total", + "counter", + "Serving sessions ended by the control bus going away.", + &self.bus_lost, + ), + ( + "fly_control_edge_bind_failures_total", + "counter", + "Times the bus was reachable but the control port could not be bound.", + &self.bind_failures, + ), + ] { + metric(&mut out, name, kind, help, value.load(Ordering::Relaxed)); + } + out + } +} + +/// A [`ControlBackend`] that answers each request by calling the control services on the bus. +#[derive(Clone)] +pub struct BusBackend { + client: Client, + scope: Scope, + metrics: Arc, +} + +impl BusBackend { + pub fn new(client: Client, scope: Scope, metrics: Arc) -> BusBackend { + BusBackend { + client, + scope, + metrics, + } + } + + /// The bus connection. + pub fn client(&self) -> &Client { + &self.client + } + + /// The service a request goes to: the session's, or the first agent's for the agent-scoped + /// families (`:7401` addresses the one live fly; a second fly has no HTTP surface). + fn service(&self, family: controlbus::Family) -> String { + let agent = self.scope.agent_ids().next().unwrap_or(""); + self.scope.service(family, agent) + } + + /// Carry one request across the bus and wait for its reply, under the edge's deadline. + pub async fn call(&self, request: ControlRequest) -> ControlReply { + self.metrics.calls.fetch_add(1, Ordering::Relaxed); + let deadline = if request.waits_for_a_write() { + None + } else { + Some(COMMAND_TIMEOUT + DEADLINE_MARGIN) + }; + let (family, method, payload) = controlbus::encode_request(&request); + let service = self.service(family); + let mut pending = match self.client.call(&service, None, method, payload, &[]).await { + Ok(pending) => pending, + Err(error) => return self.failed(&error), + }; + let result = match deadline { + None => pending.result().await, + Some(deadline) => match tokio::time::timeout(deadline, pending.result()).await { + Ok(result) => result, + Err(_) => { + // Cancelled before dispatch, the loop never sees it; dispatched, it may still + // act, exactly as a direct request whose caller timed out. + let state = pending.cancel().await; + self.metrics.cancelled.fetch_add(1, Ordering::Relaxed); + tracing::warn!(method, ?state, "a control call passed the edge's deadline"); + return ControlReply::error(503, unavailable::TIMED_OUT); + } + }, + }; + let result = match result { + Ok(result) => result, + Err(error) => return self.failed(&error), + }; + let artifact = if controlbus::has_body_artifact(result.outcome()) { + match result.artifact(controlbus::BODY_ARTIFACT) { + Ok(artifact) => match artifact.read_all().await { + Ok(bytes) => Some(bytes), + Err(error) => return self.failed(&error), + }, + Err(error) => return self.failed(&error), + } + } else { + None + }; + match controlbus::decode_reply(result.outcome(), artifact) { + Ok(reply) => reply, + Err(error) => { + self.metrics.call_failures.fetch_add(1, Ordering::Relaxed); + tracing::warn!(%error, method, "an undecodable control reply"); + ControlReply::error(502, format!("the control service answered badly: {error}")) + } + } + } + + fn failed(&self, error: &BusError) -> ControlReply { + self.metrics.call_failures.fetch_add(1, Ordering::Relaxed); + tracing::debug!(%error, "a control call failed on the bus"); + bus_failure(error) + } +} + +impl ControlBackend for BusBackend { + fn handle( + &self, + request: ControlRequest, + ) -> impl std::future::Future + Send { + let backend = self.clone(); + async move { backend.call(request).await } + } +} + +/// The reply a client gets for a request the bus did not deliver, in the words direct mode uses +/// for the same failure. +pub fn bus_failure(error: &BusError) -> ControlReply { + match error.code { + // The service's queue and in-flight slots are full: the direct API's full command queue. + ErrorCode::Backpressure => ControlReply::error(503, unavailable::QUEUE_FULL), + // Nobody is serving it: before dispatch the loop never saw it, as a closed command queue. + ErrorCode::NoService if error.dispatch == Dispatch::NotDispatched => { + ControlReply::error(503, unavailable::STOPPED) + } + ErrorCode::NoService | ErrorCode::CallGone | ErrorCode::RouterLost => { + ControlReply::error(503, unavailable::DROPPED) + } + ErrorCode::NotAuthorized => ControlReply::error( + 403, + format!("not authorized on the control bus: {}", error.message), + ), + code => ControlReply::error( + 503, + format!("the control bus refused the request: {}", code.as_str()), + ), + } +} + +/// Serve until the process is stopped. Only a metrics listener that cannot bind is fatal; +/// everything about the bus is retried. +pub async fn run(config: EdgeConfig, metrics: Arc) -> Result<()> { + config.scope.validate()?; + if let Some(addr) = config.metrics_bind { + let listener = tokio::net::TcpListener::bind(addr) + .await + .with_context(|| format!("binding the edge metrics listener on {addr}"))?; + let app = axum::Router::new() + .route("/metrics", get(prometheus)) + .route("/healthz", get(healthz)) + .with_state(Arc::clone(&metrics)); + tokio::spawn(async move { + if let Err(error) = axum::serve(listener, app).await { + tracing::error!(%error, "the edge metrics listener stopped"); + } + }); + } + let mut last: Option<&'static str> = None; + loop { + let end = session(&config, &metrics).await; + match &end { + SessionEnd::BusLost => { + tracing::warn!("the control bus went away; :7401 unbound, reconnecting"); + } + SessionEnd::Unreachable(error) if last != Some(end.kind()) => { + tracing::info!(error = format!("{error:#}"), "waiting for the control bus"); + } + SessionEnd::BindFailed(error) if last != Some(end.kind()) => { + // The bus is fine; the port is not ours. Most likely flysim is still in direct + // mode and holds it (FLY_CONTROL_VIA is not bus), or another process does. + tracing::warn!( + error = format!("{error:#}"), + "the bus is up but the control port cannot be bound; retrying" + ); + } + _ => {} + } + last = match end { + SessionEnd::BusLost => None, + other => Some(other.kind()), + }; + tokio::time::sleep(config.retry).await; + } +} + +enum SessionEnd { + Unreachable(anyhow::Error), + BindFailed(anyhow::Error), + BusLost, +} + +impl SessionEnd { + fn kind(&self) -> &'static str { + match self { + Self::Unreachable(_) => "unreachable", + Self::BindFailed(_) => "bind", + Self::BusLost => "lost", + } + } +} + +async fn prometheus(State(metrics): State>) -> impl IntoResponse { + ( + [( + axum::http::header::CONTENT_TYPE, + "text/plain; version=0.0.4", + )], + metrics.render(), + ) +} + +async fn healthz(State(metrics): State>) -> impl IntoResponse { + if metrics.connected.load(Ordering::Relaxed) == 1 { + (StatusCode::OK, "ok") + } else { + ( + StatusCode::SERVICE_UNAVAILABLE, + "waiting for the control bus", + ) + } +} + +/// Connect as [`controlbus::EDGE`] and wait until the control services answer. +pub async fn connect(config: &EdgeConfig, metrics: &Arc) -> Result { + let client = Client::connect_unix( + controlbus::socket_path(&config.bus_dir, Role::Edge), + ClientConfig::new(controlbus::EDGE, feedbus::store_root(&config.bus_dir)), + ) + .await + .map_err(|error| anyhow!("connecting to the control bus: {error}"))?; + let backend = BusBackend::new(client, config.scope.clone(), Arc::clone(metrics)); + // The host registers its services right after the router starts; until it has, a call is + // NO_SERVICE. Bind :7401 only once one is answered, whatever it answers. + let (family, method, payload) = controlbus::encode_request(&ControlRequest::Healthz); + let service = backend.service(family); + for _ in 0..20 { + match backend + .client + .call(&service, None, method, payload.clone(), &[]) + .await + { + Ok(mut pending) => match pending.result().await { + Ok(_) => return Ok(backend), + Err(error) if error.code == ErrorCode::NoService => {} + Err(error) => return Err(anyhow!("the control services did not answer: {error}")), + }, + Err(error) if error.code == ErrorCode::NoService => {} + Err(error) => return Err(anyhow!("calling the control services: {error}")), + } + tokio::time::sleep(Duration::from_millis(100)).await; + } + Err(anyhow!( + "the control services are not registered on the bus" + )) +} + +async fn session(config: &EdgeConfig, metrics: &Arc) -> SessionEnd { + let backend = match connect(config, metrics).await { + Ok(backend) => backend, + Err(error) => return SessionEnd::Unreachable(error), + }; + let listener = match tokio::net::TcpListener::bind(config.control_bind).await { + Ok(listener) => listener, + Err(error) => { + metrics.bind_failures.fetch_add(1, Ordering::Relaxed); + return SessionEnd::BindFailed(anyhow::Error::new(error).context(format!( + "binding the control listener on {}", + config.control_bind + ))); + } + }; + serve(config, metrics, backend, listener).await; + SessionEnd::BusLost +} + +/// Serve `listener` until the bus connection closes. +async fn serve( + config: &EdgeConfig, + metrics: &EdgeMetrics, + backend: BusBackend, + listener: tokio::net::TcpListener, +) { + tracing::info!(control = %config.control_bind, bus = %config.bus_dir.display(), "serving the control API from the bus"); + metrics.connected.store(1, Ordering::Relaxed); + let client = backend.client.clone(); + let (stop, stopped) = oneshot::channel::<()>(); + let server = tokio::spawn(async move { + let result = axum::serve(listener, flysim::api::router_with(backend)) + .with_graceful_shutdown(async move { + let _ = stopped.await; + }) + .await; + if let Err(error) = result { + tracing::error!(%error, "the control listener stopped"); + } + }); + while client.closed().is_none() { + tokio::time::sleep(Duration::from_millis(100)).await; + } + metrics.connected.store(0, Ordering::Relaxed); + metrics.bus_lost.fetch_add(1, Ordering::Relaxed); + let _ = stop.send(()); + if tokio::time::timeout(Duration::from_secs(5), server) + .await + .is_err() + { + tracing::warn!("the control listener took more than 5 s to stop"); + } +} diff --git a/services/flysim/crates/fly-control-edge/src/main.rs b/services/flysim/crates/fly-control-edge/src/main.rs new file mode 100644 index 0000000..015191c --- /dev/null +++ b/services/flysim/crates/fly-control-edge/src/main.rs @@ -0,0 +1,81 @@ +//! `fly-control-edge`: serve the control API (`:7401`) from flysim's control services on the bus. +//! +//! ```sh +//! FLY_CONTROL_VIA=bus flysim-session & +//! fly-control-edge +//! ``` +//! +//! Configured through the same environment as flysim (`FLY_CONTROL_BIND`, `FLY_BUS_DIR`, or +//! `--config flysim.toml`), plus `FLY_CONTROL_EDGE_METRICS_ADDR` for its own `/metrics` and +//! `/healthz`. `infra/units/flycontrol-edge.service` runs it with no arguments. + +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::Parser; +use fly_control_edge::{EdgeConfig, EdgeMetrics}; + +#[derive(Debug, Parser)] +#[command( + name = "fly-control-edge", + about = "The control API, served from flysim's control services on the bus.", + version +)] +struct Args { + /// Path to `flysim.toml`, read for `[control]` and `[feed] bus_dir`. Environment overrides + /// apply as they do for flysim. + #[arg(long, value_name = "PATH")] + config: Option, +} + +fn main() -> Result<()> { + let args = Args::parse(); + init_tracing(); + let config = flysim::config::Config::load(args.config.as_deref())?; + let metrics_bind = match std::env::var("FLY_CONTROL_EDGE_METRICS_ADDR") { + Ok(value) if !value.is_empty() => Some(value.parse().with_context(|| { + format!("FLY_CONTROL_EDGE_METRICS_ADDR: {value:?} is not a host:port address") + })?), + _ => None, + }; + let edge = EdgeConfig::from_flysim(&config, metrics_bind); + if config.control.via != flysim::config::ControlVia::Bus { + tracing::warn!( + "FLY_CONTROL_VIA is not \"bus\": flysim serves the control API itself and binds {}; \ + this edge will wait for control services that are not there", + edge.control_bind + ); + } + tracing::info!(config = ?edge, "fly-control-edge starting"); + + let runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("fly-control-edge") + .enable_all() + .build() + .context("building the tokio runtime")?; + runtime.block_on(async move { + let metrics = Arc::new(EdgeMetrics::default()); + let mut terminate = + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .context("installing the SIGTERM handler")?; + tokio::select! { + result = fly_control_edge::run(edge, metrics) => result, + _ = tokio::signal::ctrl_c() => { tracing::info!("SIGINT: shutting down"); Ok(()) } + _ = terminate.recv() => { tracing::info!("SIGTERM: shutting down"); Ok(()) } + } + }) +} + +/// Logs to stderr, like flysim, under `FLY_CONTROL_EDGE_LOG` (or `RUST_LOG`). +fn init_tracing() { + use tracing_subscriber::EnvFilter; + let filter = EnvFilter::try_from_env("FLY_CONTROL_EDGE_LOG") + .or_else(|_| EnvFilter::try_from_default_env()) + .unwrap_or_else(|_| EnvFilter::new("info")); + tracing_subscriber::fmt() + .with_env_filter(filter) + .with_writer(std::io::stderr) + .with_target(false) + .init(); +} diff --git a/services/flysim/crates/fly-control-edge/tests/backpressure.rs b/services/flysim/crates/fly-control-edge/tests/backpressure.rs new file mode 100644 index 0000000..c91c74e --- /dev/null +++ b/services/flysim/crates/fly-control-edge/tests/backpressure.rs @@ -0,0 +1,313 @@ +//! Backpressure, cancellation and the edge's lifecycle. +//! +//! - a family whose service is full refuses with the direct API's "queue is full" 503, and the +//! other families keep answering; +//! - a call cancelled before dispatch never reaches the loop; a caller that goes away, or a call +//! past the edge's deadline, leaves no call on the router; +//! - the edge unbinds `:7401` when the bus goes away and binds it again when a router is back. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::Ordering; +use std::time::{Duration, Instant}; + +use axum::http::{Method, StatusCode}; +use common::{exchange, rig}; +use flybus::{CancelState, Client, ClientConfig, Policy, Router, RouterConfig}; +use flysim::control::{ControlRequest, unavailable}; +use flysim::controlbus::{self, Family, Role, Scope}; +use serde_json::json; + +async fn until(what: &str, mut check: impl FnMut() -> bool) { + let started = Instant::now(); + while !check() { + assert!( + started.elapsed() < Duration::from_secs(30), + "timed out waiting for {what}" + ); + tokio::time::sleep(Duration::from_millis(10)).await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_full_service_is_a_503_and_the_other_families_still_answer() { + let rig = rig(|_| {}).await; + rig.sim.hold.store(true, Ordering::SeqCst); + let slots = + (controlbus::SERVICE_CONFIG.max_in_flight + controlbus::SERVICE_CONFIG.max_queued) as usize; + // The first 16 fill the service's in-flight slots and reach the (wedged) loop; only then + // the next 16 fill its queue. (Sent as one burst, the queue bound can be met before the + // router has dispatched the first ones: a bounded queue refuses what it cannot hold at that + // instant, which is the point, but not what this test counts.) + let in_flight = controlbus::SERVICE_CONFIG.max_in_flight as usize; + let mut pauses = Vec::new(); + for batch in [in_flight, slots - in_flight] { + for _ in 0..batch { + let edge = rig.edge.clone(); + pauses.push(tokio::spawn(async move { + edge.call(ControlRequest::Pause).await + })); + } + until("the in-flight pauses", || rig.sim.received("pause") == in_flight).await; + } + let started = Instant::now(); + while (rig.bus.router.stats().calls as usize) < slots { + if started.elapsed() > Duration::from_secs(30) { + let mut finished = Vec::new(); + for pause in pauses.iter_mut().filter(|p| p.is_finished()) { + finished.push(format!("{:?}", pause.await.unwrap())); + } + panic!( + "not every pause admitted: {:?}, received {}, finished {finished:?}", + rig.bus.router.stats(), + rig.sim.received("pause") + ); + } + tokio::time::sleep(Duration::from_millis(10)).await; + } + + // One more is refused at once, in the direct API's words. + let started = Instant::now(); + let refused = exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]).await; + assert_eq!(refused.status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(refused.json(), json!({"error": unavailable::QUEUE_FULL})); + assert!( + started.elapsed() < Duration::from_secs(1), + "a full service made the caller wait" + ); + + // Reads, sugar and chat are other services: they answer while ops is saturated. + let status = exchange(rig.via_edge(), &Method::GET, "/status", None, &[]).await; + assert_eq!(status.status, StatusCode::OK); + let healthz = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await; + assert_eq!(healthz.status, StatusCode::OK); + + // A queued pause cancelled before dispatch never reaches the loop. + let operator = Client::connect_unix( + controlbus::socket_path(&rig.config.bus_dir, Role::Operator), + ClientConfig::new( + Role::Operator.participant(), + flysim::feedbus::store_root(&rig.config.bus_dir), + ), + ) + .await + .unwrap(); + // Let the loop go: the held pauses are dropped (503 "dropped"), the queued ones answered. + rig.sim.hold.store(false, Ordering::SeqCst); + rig.sim.release_held(); + for pause in pauses { + let reply = pause.await.unwrap(); + // The 16 the wedged loop dropped answer "dropped"; the 16 queued ones were answered. + assert!( + reply.status == 200 || reply.json_error() == Some(unavailable::DROPPED), + "{reply:?}" + ); + } + let answered = rig.sim.received("pause"); + assert_eq!(answered, slots); + + // Wedge it again with 16 of the operator's own in flight; the 17th waits in the queue and + // is cancelled there. + rig.sim.hold.store(true, Ordering::SeqCst); + let (family, method, payload) = controlbus::encode_request(&ControlRequest::Pause); + let service = Scope::live().service(family, ""); + let mut holders = Vec::new(); + for _ in 0..controlbus::SERVICE_CONFIG.max_in_flight { + holders.push( + operator + .call(&service, None, method, payload.clone(), &[]) + .await + .unwrap(), + ); + } + until("the in-flight pauses", || { + rig.sim.received("pause") == slots + controlbus::SERVICE_CONFIG.max_in_flight as usize + }) + .await; + let queued = operator + .call(&service, None, method, payload.clone(), &[]) + .await + .unwrap(); + assert_eq!( + queued.cancel().await.unwrap(), + CancelState::CancelledBeforeDispatch + ); + rig.sim.hold.store(false, Ordering::SeqCst); + rig.sim.release_held(); + for mut holder in holders { + let _ = holder.result().await; + } + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!( + rig.sim.received("pause"), + slots + controlbus::SERVICE_CONFIG.max_in_flight as usize, + "the cancelled pause reached the loop" + ); + until("no calls left on the router", || { + rig.bus.router.stats().calls == 0 + }) + .await; +} + +trait ErrorText { + fn json_error(&self) -> Option<&str>; +} + +impl ErrorText for flysim::control::ControlReply { + fn json_error(&self) -> Option<&str> { + match &self.body { + flysim::control::ReplyBody::Json(value) => value["error"].as_str(), + flysim::control::ReplyBody::Text(_) => None, + } + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_client_that_goes_away_leaves_no_call_behind() { + let rig = rig(|_| {}).await; + rig.sim.hold.store(true, Ordering::SeqCst); + // An HTTP client that gives up on a pause (which waits for a durable write, so has no + // deadline of its own): axum drops the handler, the edge drops the pending call. + let gave_up = tokio::time::timeout( + Duration::from_millis(300), + exchange(rig.via_edge(), &Method::POST, "/pause", None, &[]), + ) + .await; + assert!(gave_up.is_err()); + until("the dropped call to be dispatched", || { + rig.sim.received("pause") == 1 + }) + .await; + // The host still holds it (the loop has it), so the router keeps the correlation until the + // host answers; then the detached result is discarded and nothing is left. + rig.sim.hold.store(false, Ordering::SeqCst); + rig.sim.release_held(); + until("no calls left on the router", || { + rig.bus.router.stats().calls == 0 + }) + .await; + // And the edge is fine afterwards. + let ok = exchange(rig.via_edge(), &Method::POST, "/resume", None, &[]).await; + assert_eq!(ok.status, StatusCode::OK); +} + +/// A host that registered the services but never answers: the edge gives up at its own deadline, +/// cancels, and answers the direct API's timeout 503. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_edge_cancels_at_its_deadline_when_the_host_never_answers() { + let dir = tempfile::tempdir().unwrap(); + let scope = Scope::live(); + let mut config = RouterConfig::new(dir.path()); + config.policy = controlbus::policy(Policy::closed(), &scope); + let router = Router::new(config).unwrap(); + let silent = Client::connect( + router.connect_in_memory_as(controlbus::HOST), + ClientConfig::new(controlbus::HOST, router.store_root()), + ) + .await + .unwrap(); + let name = scope.service(Family::Sugar, controlbus::LIVE_AGENT); + let mut service = silent + .register(&name, controlbus::SERVICE_CONFIG) + .await + .unwrap(); + let held = tokio::spawn(async move { + let mut kept = Vec::new(); + while let Some(request) = service.next().await { + kept.push(request); + } + }); + let edge_client = Client::connect( + router.connect_in_memory_as(controlbus::EDGE), + ClientConfig::new(controlbus::EDGE, router.store_root()), + ) + .await + .unwrap(); + let metrics = Arc::new(fly_control_edge::EdgeMetrics::default()); + let backend = fly_control_edge::BusBackend::new(edge_client, scope, Arc::clone(&metrics)); + let started = Instant::now(); + let reply = exchange( + flysim::api::router_with(backend), + &Method::POST, + "/stimulate", + Some("application/json"), + &serde_json::to_vec(&json!({"by": "v", "source": "chat"})).unwrap(), + ) + .await; + let waited = started.elapsed(); + assert_eq!(reply.status, StatusCode::SERVICE_UNAVAILABLE); + assert_eq!(reply.json(), json!({"error": unavailable::TIMED_OUT})); + let deadline = flysim::control::COMMAND_TIMEOUT + fly_control_edge::DEADLINE_MARGIN; + assert!( + waited >= deadline && waited < deadline + Duration::from_secs(2), + "{waited:?}" + ); + assert_eq!(metrics.cancelled.load(Ordering::Relaxed), 1); + held.abort(); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn the_edge_unbinds_when_the_bus_goes_and_binds_again_when_it_is_back() { + let mut rig = rig(|_| {}).await; + // The edge process connects as the edge participant, which the router admits once. + rig.close_edge().await; + let addr = common::free_port(); + let config = fly_control_edge::EdgeConfig { + control_bind: addr, + ..rig.config.clone() + }; + let metrics = Arc::new(fly_control_edge::EdgeMetrics::default()); + let edge = tokio::spawn(fly_control_edge::run(config, Arc::clone(&metrics))); + until("the edge to bind", || { + metrics.connected.load(Ordering::Relaxed) == 1 + }) + .await; + let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; + let served = common::raw_http(addr, request).await.unwrap(); + assert!( + served.starts_with(b"HTTP/1.1 200"), + "{}", + String::from_utf8_lossy(&served) + ); + + // flysim stops: its router goes, and the port with it. + rig.host.take(); + rig.bus.router.shutdown(); + until("the edge to notice", || { + metrics.bus_lost.load(Ordering::Relaxed) == 1 + }) + .await; + let started = Instant::now(); + while common::raw_http(addr, request).await.is_some() { + assert!( + started.elapsed() < Duration::from_secs(10), + ":7401 stayed bound" + ); + tokio::time::sleep(Duration::from_millis(20)).await; + } + + // flysim is back: a new router on the same directory, the services registered again. + let scope = Scope::live(); + let uses = flysim::bus::Uses { + feed: false, + control: true, + }; + let bus = flysim::bus::start(&rig.config.bus_dir, uses, &scope) + .await + .unwrap(); + let _host = controlbus::serve(&bus.router, rig.state.clone(), &scope) + .await + .unwrap(); + until("the edge to bind again", || { + metrics.connected.load(Ordering::Relaxed) == 1 + }) + .await; + let served = common::raw_http(addr, request).await.unwrap(); + assert!( + served.starts_with(b"HTTP/1.1 200"), + "{}", + String::from_utf8_lossy(&served) + ); + edge.abort(); +} diff --git a/services/flysim/crates/fly-control-edge/tests/common/mod.rs b/services/flysim/crates/fly-control-edge/tests/common/mod.rs new file mode 100644 index 0000000..f631567 --- /dev/null +++ b/services/flysim/crates/fly-control-edge/tests/common/mod.rs @@ -0,0 +1,320 @@ +#![allow(dead_code)] + +//! A control rig: flysim's control state with a scripted stand-in for the loop behind it, the +//! embedded router with the control services registered, and the edge connected over its socket. +//! Every request can be sent to both sides — `direct` (flysim's own `:7401` router) and `edge` +//! (the same router over the bus) — and the answers compared byte for byte. + +use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::Duration; + +use axum::body::Body; +use axum::http::{HeaderMap, Method, Request, StatusCode}; +use fly_control_edge::{BusBackend, EdgeConfig, EdgeMetrics}; +use flysim::AppState; +use flysim::bus::{EmbeddedBus, Uses}; +use flysim::chat::{ChatRefusal, RejectReason}; +use flysim::controlbus::{ControlHost, Scope}; +use flysim::eventlog::{EventLog, EventRing, NewEvent}; +use flysim::ratelimit::Refusal; +use flysim::simloop::{Command, Shared, booting_snapshot}; +use flysim::snapshot::{FeedEventKind, FeedStatus, MacroMode, Snapshot}; +use tokio::sync::{mpsc, watch}; +use tower::ServiceExt; + +/// The stand-in loop: answers every command deterministically from what the request says, so +/// the same request gets the same answer however often (and from whichever side) it is sent. +#[derive(Default)] +pub struct FakeSim { + /// Commands received, by kind. + pub received: Mutex>, + /// Hold every command without answering (a wedged loop). + pub hold: AtomicBool, + /// Answer `/checkpoint` with a failure. + pub fail_checkpoint: AtomicBool, + /// Held commands: kept so their reply channels stay open. + pub held: Mutex>, + pub answered: AtomicU64, +} + +impl FakeSim { + pub fn received(&self, kind: &str) -> usize { + self.received + .lock() + .unwrap() + .iter() + .filter(|k| **k == kind) + .count() + } + + pub fn release_held(&self) { + self.held.lock().unwrap().clear(); + } + + fn answer(&self, command: Command) { + let kind = match &command { + Command::Stimulate { .. } => "stimulate", + Command::Reward { .. } => "reward", + Command::Chat { .. } => "chat", + Command::Checkpoint { .. } => "checkpoint", + Command::Pause { .. } => "pause", + Command::Resume { .. } => "resume", + Command::Shutdown { .. } => "shutdown", + }; + self.received.lock().unwrap().push(kind); + if self.hold.load(Ordering::SeqCst) { + self.held.lock().unwrap().push(command); + return; + } + self.answered.fetch_add(1, Ordering::SeqCst); + match command { + Command::Stimulate { by, reply, .. } => { + let answer = match by.as_str() { + "pulse" => Err(Refusal::PulseActive { + retry_after_ms: 250, + }), + "spent" => Err(Refusal::RateLimited { + retry_after_ms: 41_500, + }), + "drop" => return, + "hang" => { + self.held.lock().unwrap().push(Command::Stimulate { + duration_ms: None, + by, + source: String::new(), + reply, + }); + return; + } + _ => Ok(41), + }; + let _ = reply.send(answer); + } + Command::Reward { reply, .. } => { + let _ = reply.send(42); + } + Command::Chat { + by, text, reply, .. + } => { + let answer = if text.contains("http") { + Err(ChatRefusal::Rejected(RejectReason::Url)) + } else if by == "fast" { + Err(ChatRefusal::RateLimited { + retry_after_ms: 1_999, + }) + } else { + Ok(43) + }; + let _ = reply.send(answer); + } + Command::Checkpoint { reply } => { + let answer = if self.fail_checkpoint.load(Ordering::SeqCst) { + Err("disk full".to_owned()) + } else { + Ok(12) + }; + let _ = reply.send(answer); + } + Command::Pause { reply } => { + let _ = reply.send(FeedStatus::Paused); + } + Command::Resume { reply } => { + let _ = reply.send(FeedStatus::Running); + } + Command::Shutdown { reply } => { + let _ = reply.send(()); + } + } + } +} + +pub struct Rig { + pub state: AppState, + pub sim: Arc, + pub snapshots: watch::Sender>, + pub bus: EmbeddedBus, + pub host: Option, + pub edge: BusBackend, + pub metrics: Arc, + pub config: EdgeConfig, + pub dir: tempfile::TempDir, + _log: EventLog, +} + +/// A snapshot with a few fields that are not the boot defaults, so `/status` has content. +fn snapshot() -> Snapshot { + let mut snapshot = booting_snapshot(4_242, 1_757_000_000_000, MacroMode::Raw); + let header = &mut snapshot.header; + header.status = FeedStatus::Running; + header.realtime_factor = 1.0312; + header.uptime_seconds = 612.5; + header.brain_ms = 3_600_250.0; + header.frame = 215_089; + header.population_rate = 12.375; + header.learning.signal = -0.125; + snapshot +} + +/// The rig, with `configure` applied to flysim's configuration. +pub async fn rig(configure: impl FnOnce(&mut flysim::config::Config)) -> Rig { + rig_with( + configure, + Uses { + feed: false, + control: true, + }, + ) + .await +} + +pub async fn rig_with(configure: impl FnOnce(&mut flysim::config::Config), uses: Uses) -> Rig { + let dir = tempfile::tempdir().unwrap(); + let mut config = flysim::config::Config::default(); + config.feed.bus_dir = dir.path().join("bus"); + config.control.via = flysim::config::ControlVia::Bus; + configure(&mut config); + let shared = Arc::new(Shared::new(config.clone(), EventRing::new())); + let (commands, mut command_rx) = mpsc::channel::(flysim::simloop::COMMAND_QUEUE); + let (snapshots, receiver) = watch::channel(Arc::new(snapshot())); + let state = AppState { + shared: Arc::clone(&shared), + commands, + snapshots: receiver, + }; + // A short event log, so `/events` has pages to turn. + let mut log = EventLog::open(&dir.path().join("events"), state.shared.events.clone()).unwrap(); + for index in 0..7u64 { + log.append( + 1_000 + index, + index as f64 * 0.5, + NewEvent::new(FeedEventKind::System, format!("event {index}")).value(index as f64), + ); + } + state.shared.beat(); + + let sim = Arc::new(FakeSim::default()); + { + let sim = Arc::clone(&sim); + tokio::spawn(async move { + while let Some(command) = command_rx.recv().await { + sim.answer(command); + } + }); + } + + let scope = Scope::live(); + let bus = flysim::bus::start(&config.feed.bus_dir, uses, &scope) + .await + .unwrap(); + let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope) + .await + .unwrap(); + let edge_config = EdgeConfig { + retry: Duration::from_millis(50), + ..EdgeConfig::from_flysim(&config, None) + }; + let metrics = Arc::new(EdgeMetrics::default()); + let edge = fly_control_edge::connect(&edge_config, &metrics) + .await + .unwrap(); + Rig { + state, + sim, + snapshots, + bus, + host: Some(host), + edge, + metrics, + config: edge_config, + dir, + _log: log, + } +} + +impl Rig { + pub fn direct(&self) -> axum::Router { + flysim::api::router(self.state.clone()) + } + + /// Close the rig's own edge connection, so an edge process can connect as the edge (the + /// router admits one live connection per participant). + pub async fn close_edge(&self) { + self.edge.client().clone().close().await; + } + + pub fn via_edge(&self) -> axum::Router { + flysim::api::router_with(self.edge.clone()) + } +} + +/// One HTTP exchange as the bytes a client sees: status, every header, body. +#[derive(Debug, PartialEq, Eq)] +pub struct Exchange { + pub status: StatusCode, + pub headers: Vec<(String, Vec)>, + pub body: Vec, +} + +impl Exchange { + pub fn json(&self) -> serde_json::Value { + serde_json::from_slice(&self.body).unwrap_or(serde_json::Value::Null) + } +} + +pub async fn exchange( + router: axum::Router, + method: &Method, + uri: &str, + content_type: Option<&str>, + body: &[u8], +) -> Exchange { + let mut request = Request::builder().method(method.clone()).uri(uri); + if let Some(content_type) = content_type { + request = request.header("content-type", content_type); + } + let request = request.body(Body::from(body.to_vec())).unwrap(); + let response = router.oneshot(request).await.unwrap(); + let status = response.status(); + let headers = sorted(response.headers()); + let body = axum::body::to_bytes(response.into_body(), 64 << 20) + .await + .unwrap() + .to_vec(); + Exchange { + status, + headers, + body, + } +} + +fn sorted(headers: &HeaderMap) -> Vec<(String, Vec)> { + let mut out: Vec<(String, Vec)> = headers + .iter() + .map(|(name, value)| (name.as_str().to_owned(), value.as_bytes().to_vec())) + .collect(); + out.sort(); + out +} + +/// A free loopback port (bound, read, released). +pub fn free_port() -> std::net::SocketAddr { + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + listener.local_addr().unwrap() +} + +/// A raw HTTP/1.1 exchange over TCP: the whole response, with the `date` header line removed +/// (the one header that differs from second to second). `None` when nothing listens. +pub async fn raw_http(addr: std::net::SocketAddr, request: &str) -> Option> { + use tokio::io::{AsyncReadExt as _, AsyncWriteExt as _}; + let mut stream = tokio::net::TcpStream::connect(addr).await.ok()?; + stream.write_all(request.as_bytes()).await.ok()?; + let mut out = Vec::new(); + stream.read_to_end(&mut out).await.ok()?; + let text = String::from_utf8_lossy(&out).into_owned(); + let kept: Vec<&str> = text + .split("\r\n") + .filter(|line| !line.to_ascii_lowercase().starts_with("date:")) + .collect(); + Some(kept.join("\r\n").into_bytes()) +} diff --git a/services/flysim/crates/fly-control-edge/tests/grants.rs b/services/flysim/crates/fly-control-edge/tests/grants.rs new file mode 100644 index 0000000..838948d --- /dev/null +++ b/services/flysim/crates/fly-control-edge/tests/grants.rs @@ -0,0 +1,388 @@ +//! The grant table refuses what it should, over the router's real sockets. +//! +//! - each native role calls exactly its families, and a refused call never reaches the loop; +//! - no role can register a service (so none can stand in for the control host), publish, +//! subscribe or manage a topic; +//! - a socket is bound to its role: claiming another identity on it is refused at hello; +//! - on a router shared with a service that does take input (an environment's, say), no control +//! participant can call it: "nothing can press buttons" holds for the grant table, not only for +//! the list of control methods; +//! - per-agent scoping: a player may sugar their own fly and not another. + +mod common; + +use std::sync::Arc; +use std::sync::atomic::Ordering; + +use axum::http::{Method, StatusCode}; +use common::{exchange, rig, rig_with}; +use flybus::{ + BusError, Client, ClientConfig, Dispatch, ErrorCode, Grants, Pattern, Policy, Retained, Router, + RouterConfig, ServiceConfig, +}; +use flysim::bus::Uses; +use flysim::control::ControlRequest; +use flysim::controlbus::{self, Family, Role, Scope}; +use serde_json::{Map, json}; + +fn request_of(family: Family) -> ControlRequest { + match family { + Family::Read | Family::Status => ControlRequest::Status, + Family::Sugar => ControlRequest::Stimulate { + body: Some(json!({"by": "viewer", "source": "points"})), + }, + Family::Reward => ControlRequest::Reward { + body: Some(json!({"value": 1.0, "by": "op", "source": "operator"})), + }, + Family::Chat => ControlRequest::Chat { + body: Some(json!({"by": "viewer", "text": "hi"})), + }, + Family::Ops => ControlRequest::Resume, + } +} + +async fn call( + client: &Client, + scope: &Scope, + family: Family, + agent: &str, +) -> Result, BusError> { + let (encoded_family, method, payload) = controlbus::encode_request(&request_of(family)); + // An agent's status service answers the same method the session's read does. + if family != Family::Status { + assert_eq!(encoded_family, family); + } + let service = scope.service(family, agent); + let result = client + .call_and_wait(&service, None, method, payload, &[]) + .await?; + Ok(result.outcome().clone()) +} + +fn assert_refused(result: Result, what: &str) { + let error = result.expect_err(what); + assert_eq!(error.code, ErrorCode::NotAuthorized, "{what}: {error}"); + assert_eq!(error.dispatch, Dispatch::NotDispatched, "{what}"); +} + +async fn connect_role( + bus_dir: &std::path::Path, + role: Role, + claimed: &str, +) -> Result { + Client::connect_unix( + controlbus::socket_path(bus_dir, role), + ClientConfig::new(claimed, flysim::feedbus::store_root(bus_dir)), + ) + .await +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn each_role_calls_exactly_its_families_and_nothing_else() { + let rig = rig_with( + |_| {}, + Uses { + feed: true, + control: true, + }, + ) + .await; + rig.close_edge().await; + let bus_dir = rig.config.bus_dir.clone(); + let scope = Scope::live(); + for role in Role::ALL { + let client = connect_role(&bus_dir, role, role.participant()) + .await + .unwrap(); + for family in Family::ALL { + let before = rig.sim.received.lock().unwrap().len(); + let result = call(&client, &scope, family, controlbus::LIVE_AGENT).await; + if role.families().contains(&family) { + let outcome = result.unwrap_or_else(|e| panic!("{role:?} {family:?}: {e}")); + assert!(outcome["status"].as_u64().is_some(), "{role:?} {family:?}"); + } else { + assert_refused(result, &format!("{role:?} {family:?}")); + assert_eq!( + rig.sim.received.lock().unwrap().len(), + before, + "{role:?} {family:?}: a refused call reached the loop" + ); + } + } + + // Nobody but the in-process host may register anything, a control name least of all. + for name in [ + scope.service(Family::Ops, ""), + scope.service(Family::Sugar, controlbus::LIVE_AGENT), + "fly.control.s.main.buttons".to_owned(), + "anything".to_owned(), + ] { + assert_refused( + client + .register(&name, ServiceConfig::default()) + .await + .map(|_| ()), + &format!("{role:?} registering {name}"), + ); + } + // No topics: not the feed, not a new one. + assert_refused( + client + .subscribe(flysim::feedbus::TOPIC, flybus::SubscriptionConfig::latest()) + .await + .map(|_| ()), + &format!("{role:?} subscribing to the feed"), + ); + assert_refused( + client + .declare_topic("fly.control.events", Retained::None) + .await + .map(|_| ()), + &format!("{role:?} declaring a topic"), + ); + assert_refused( + client + .publish(flysim::feedbus::TOPIC, Map::new(), &[]) + .await + .map(|_| ()), + &format!("{role:?} publishing on the feed"), + ); + client.close().await; + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_socket_admits_only_its_own_role() { + let rig = rig(|_| {}).await; + let bus_dir = rig.config.bus_dir.clone(); + for (socket, claimed) in [ + (Role::Stage, Role::Operator.participant()), + (Role::Bridge, controlbus::HOST), + (Role::Watchdog, controlbus::EDGE), + (Role::Edge, Role::Operator.participant()), + ] { + let result = connect_role(&bus_dir, socket, claimed).await; + assert!( + result.is_err(), + "{claimed} was admitted on {socket:?}'s socket" + ); + } + // No socket is bound to the host. + assert!( + !bus_dir.join("control").join("flysim-control.sock").exists() + && std::fs::read_dir(bus_dir.join("control")).unwrap().count() == Role::NATIVE.len() + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn on_a_shared_router_no_control_participant_can_reach_an_input_service() { + let dir = tempfile::tempdir().unwrap(); + let scope = Scope::live(); + // An environment that takes input lives on the same router as the control services. + let input = "fly.env.s.main.input"; + let policy = controlbus::policy( + Policy::closed().client( + "env", + Grants { + register: vec![Pattern::exact(input)], + ..Grants::default() + }, + ), + &scope, + ); + let mut config = RouterConfig::new(dir.path()); + config.policy = policy; + let router = Router::new(config).unwrap(); + let env = Client::connect( + router.connect_in_memory_as("env"), + ClientConfig::new("env", router.store_root()), + ) + .await + .unwrap(); + let mut service = env.register(input, ServiceConfig::default()).await.unwrap(); + let pressed = Arc::new(std::sync::atomic::AtomicU64::new(0)); + { + let pressed = Arc::clone(&pressed); + tokio::spawn(async move { + while let Some(request) = service.next().await { + pressed.fetch_add(1, Ordering::SeqCst); + let _ = request.reply(Map::new(), &[]).await; + } + }); + } + for role in Role::ALL { + let client = Client::connect( + router.connect_in_memory_as(role.participant()), + ClientConfig::new(role.participant(), router.store_root()), + ) + .await + .unwrap(); + for method in ["Environment.Step", "Control.Stimulate", "Press"] { + let mut payload = Map::new(); + payload.insert("buttons".into(), json!(1)); + assert_refused( + client + .call(input, None, method, payload, &[]) + .await + .map(|_| ()), + &format!("{role:?} calling {input} {method}"), + ); + } + client.close().await; + } + assert_eq!(pressed.load(Ordering::SeqCst), 0); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_player_sugars_their_own_fly_and_no_other() { + // Two flies on two controller ports; one player backs the fly on port 1 and another is + // granted by id. Single-fly is the same table with one agent. + let dir = tempfile::tempdir().unwrap(); + let scope = Scope { + session: "arena".to_owned(), + agents: vec![ + controlbus::AgentScope::new("fly-a", Some(1)), + controlbus::AgentScope::new("fly-b", Some(2)), + ], + }; + let policy = controlbus::policy(Policy::closed(), &scope) + .client( + "player-a", + controlbus::player_grants(&scope, controlbus::Agents::Port(1)), + ) + .client( + "player-b", + controlbus::player_grants(&scope, controlbus::Agents::Id("fly-b")), + ); + let mut config = RouterConfig::new(dir.path()); + config.policy = policy; + let router = Router::new(config).unwrap(); + let rig = rig(|_| {}).await; + let _host = controlbus::serve(&router, rig.state.clone(), &scope) + .await + .unwrap(); + let player = Client::connect( + router.connect_in_memory_as("player-a"), + ClientConfig::new("player-a", router.store_root()), + ) + .await + .unwrap(); + let other = Client::connect( + router.connect_in_memory_as("player-b"), + ClientConfig::new("player-b", router.store_root()), + ) + .await + .unwrap(); + assert_eq!( + call(&other, &scope, Family::Sugar, "fly-b").await.unwrap()["status"], + json!(202) + ); + assert_refused( + call(&other, &scope, Family::Sugar, "fly-a").await, + "player-b sugar on fly-a", + ); + assert_eq!( + call(&player, &scope, Family::Status, "fly-a").await.unwrap()["status"], + json!(200) + ); + assert_refused( + call(&player, &scope, Family::Status, "fly-b").await, + "status of fly-b", + ); + let outcome = call(&player, &scope, Family::Sugar, "fly-a").await.unwrap(); + assert_eq!(outcome["status"], json!(202)); + assert_eq!(outcome["body"], json!({"eventId": 41})); + assert_eq!( + call(&player, &scope, Family::Read, "").await.unwrap()["status"], + json!(200) + ); + assert_refused( + call(&player, &scope, Family::Sugar, "fly-b").await, + "sugar on fly-b", + ); + assert_refused( + call(&player, &scope, Family::Reward, "fly-a").await, + "reward on fly-a", + ); + assert_refused(call(&player, &scope, Family::Chat, "").await, "chat"); + assert_refused(call(&player, &scope, Family::Ops, "").await, "ops"); + // The live session's names are not the arena's. + assert_refused( + call(&player, &Scope::live(), Family::Read, "").await, + "another session's read", + ); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_method_the_service_does_not_have_is_a_404_and_reaches_nothing() { + let rig = rig(|_| {}).await; + let operator = connect_role( + &rig.config.bus_dir, + Role::Operator, + Role::Operator.participant(), + ) + .await + .unwrap(); + let scope = Scope::live(); + for (family, method) in [ + (Family::Read, "Control.Pause"), + (Family::Sugar, "Control.Press"), + (Family::Ops, "Control.Buttons"), + (Family::Chat, "Control.Stimulate"), + ] { + let result = operator + .call_and_wait( + &scope.service(family, controlbus::LIVE_AGENT), + None, + method, + Map::new(), + &[], + ) + .await + .unwrap(); + assert_eq!( + result.outcome()["status"], + json!(404), + "{family:?} {method}" + ); + } + assert!(rig.sim.received.lock().unwrap().is_empty()); +} + +/// An HTTP edge holding a narrower role answers what the role may not do with a 403, and the +/// loop never sees it. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn an_edge_on_a_narrow_role_refuses_over_http() { + let rig = rig(|_| {}).await; + let stage = connect_role(&rig.config.bus_dir, Role::Stage, Role::Stage.participant()) + .await + .unwrap(); + let backend = fly_control_edge::BusBackend::new(stage, Scope::live(), Arc::clone(&rig.metrics)); + let router = || flysim::api::router_with(backend.clone()); + let ok = exchange(router(), &Method::GET, "/healthz", None, &[]).await; + assert_eq!(ok.status, StatusCode::OK); + for (uri, body) in [ + ("/stimulate", json!({"by": "v", "source": "chat"})), + ("/chat", json!({"by": "v", "text": "hi"})), + ("/pause", json!({})), + ("/checkpoint", json!({})), + ] { + let refused = exchange( + router(), + &Method::POST, + uri, + Some("application/json"), + &serde_json::to_vec(&body).unwrap(), + ) + .await; + assert_eq!(refused.status, StatusCode::FORBIDDEN, "{uri}"); + assert!( + refused.json()["error"] + .as_str() + .unwrap() + .starts_with("not authorized on the control bus"), + "{uri}" + ); + } + assert!(rig.sim.received.lock().unwrap().is_empty()); +} diff --git a/services/flysim/crates/fly-control-edge/tests/parity.rs b/services/flysim/crates/fly-control-edge/tests/parity.rs new file mode 100644 index 0000000..2a48aa8 --- /dev/null +++ b/services/flysim/crates/fly-control-edge/tests/parity.rs @@ -0,0 +1,356 @@ +//! Every `docs/control-api.md` endpoint through the edge equals direct, byte for byte. +//! +//! Each case is sent twice, to flysim's own `:7401` router (`control.via = direct`) and to the +//! same router over the bus (`fly-control-edge`'s [`BusBackend`]), and the status, every header +//! and the body bytes must be equal. The stand-in loop answers each command from what the request +//! says, so both sends get the same answer. The last test does it over real TCP sockets against +//! the running edge, where the whole HTTP response must be equal but for its `date` line. + +mod common; + +use std::sync::atomic::Ordering; +use std::time::Duration; + +use axum::http::{Method, StatusCode}; +use common::{exchange, rig}; +use serde_json::json; + +/// `(method, uri, content type, body)`. +type Case = (Method, &'static str, Option<&'static str>, Vec); + +fn json_case(method: Method, uri: &'static str, body: serde_json::Value) -> Case { + ( + method, + uri, + Some("application/json"), + serde_json::to_vec(&body).unwrap(), + ) +} + +fn bare(method: Method, uri: &'static str) -> Case { + (method, uri, None, Vec::new()) +} + +fn raw(method: Method, uri: &'static str, body: &str) -> Case { + ( + method, + uri, + Some("application/json"), + body.as_bytes().to_vec(), + ) +} + +/// The cases every configuration runs: each endpoint, its validation and its refusals. +fn cases() -> Vec { + use Method as M; + vec![ + bare(M::GET, "/status"), + bare(M::GET, "/status.json"), + bare(M::GET, "/healthz"), + bare(M::GET, "/metrics"), + // /events: the page, its parameters and the lenient defaults. + bare(M::GET, "/events"), + bare(M::GET, "/events?since=3"), + bare(M::GET, "/events?since=0&limit=2"), + bare(M::GET, "/events?since=99"), + bare(M::GET, "/events?since=abc&limit=abc"), + bare(M::GET, "/events?since=&limit="), + bare(M::GET, "/events?limit=0"), + bare(M::GET, "/events?since=-1&limit=100000"), + bare(M::GET, "/events?since=1&since=2"), + bare(M::GET, "/events?unknown=1"), + // /stimulate: accepted, both refusals, every malformed shape. + json_case( + M::POST, + "/stimulate", + json!({"by": "viewer", "source": "points"}), + ), + json_case( + M::POST, + "/stimulate", + json!({"by": "viewer", "source": "chat", "durationMs": 300}), + ), + json_case( + M::POST, + "/stimulate", + json!({"by": "op", "source": "operator", "durationMs": null}), + ), + json_case( + M::POST, + "/stimulate", + json!({"by": "pulse", "source": "points"}), + ), + json_case( + M::POST, + "/stimulate", + json!({"by": "spent", "source": "chat"}), + ), + json_case( + M::POST, + "/stimulate", + json!({"by": "viewer", "source": "bridge"}), + ), + json_case(M::POST, "/stimulate", json!({"by": "viewer"})), + json_case(M::POST, "/stimulate", json!({"source": "points"})), + json_case( + M::POST, + "/stimulate", + json!({"by": "viewer", "source": "points", "durationMs": -5}), + ), + json_case( + M::POST, + "/stimulate", + json!({"by": "viewer", "source": "points", "durationMs": "400"}), + ), + json_case(M::POST, "/stimulate", json!([1, 2, 3])), + raw(M::POST, "/stimulate", "{not json"), + raw(M::POST, "/stimulate", "\"a string\""), + bare(M::POST, "/stimulate"), + ( + M::POST, + "/stimulate", + Some("text/plain"), + b"{\"by\":\"v\",\"source\":\"chat\"}".to_vec(), + ), + (M::POST, "/stimulate", None, vec![0xff, 0xfe, 0x00]), + // The loop dropped the request: the 503 both sides answer. + json_case( + M::POST, + "/stimulate", + json!({"by": "drop", "source": "chat"}), + ), + // /reward: 403 unless enabled; its validation once it is. + json_case( + M::POST, + "/reward", + json!({"value": 0.5, "by": "op", "source": "operator"}), + ), + json_case( + M::POST, + "/reward", + json!({"value": "x", "by": "op", "source": "operator"}), + ), + bare(M::POST, "/reward"), + // /chat: accepted, both refusals, the body rules. + json_case( + M::POST, + "/chat", + json!({"by": "viewer_two", "text": "go fly go"}), + ), + json_case( + M::POST, + "/chat", + json!({"by": "bot", "text": "hello", "bot": true}), + ), + json_case( + M::POST, + "/chat", + json!({"by": "viewer", "text": "see http://x.example"}), + ), + json_case(M::POST, "/chat", json!({"by": "fast", "text": "again"})), + json_case( + M::POST, + "/chat", + json!({"by": "viewer", "text": "hi", "bot": "yes"}), + ), + json_case(M::POST, "/chat", json!({"by": "viewer"})), + json_case(M::POST, "/chat", json!({"text": 5})), + raw(M::POST, "/chat", "]"), + bare(M::POST, "/chat"), + // /checkpoint, /pause, /resume. + bare(M::POST, "/checkpoint"), + bare(M::POST, "/pause"), + bare(M::POST, "/resume"), + json_case(M::POST, "/pause", json!({"ignored": true})), + // Everything that is not a route is the same 404, the wrong method on a route included. + bare(M::GET, "/stimulate"), + bare(M::POST, "/status"), + bare(M::PUT, "/pause"), + bare(M::DELETE, "/checkpoint"), + json_case(M::POST, "/button", json!({"button": "a"})), + bare(M::GET, "/joypad"), + bare(M::POST, "/memory"), + bare(M::GET, "/"), + bare(M::GET, "/status/"), + ] +} + +async fn compare_all( + configure: impl FnOnce(&mut flysim::config::Config), + cases: &[Case], +) -> Vec<(String, StatusCode)> { + let rig = rig(configure).await; + let mut seen = Vec::new(); + for (method, uri, content_type, body) in cases { + let direct = exchange(rig.direct(), method, uri, *content_type, body).await; + let edge = exchange(rig.via_edge(), method, uri, *content_type, body).await; + assert_eq!( + direct, + edge, + "{method} {uri}: direct {} {:?} vs edge {} {:?}", + direct.status, + String::from_utf8_lossy(&direct.body), + edge.status, + String::from_utf8_lossy(&edge.body) + ); + seen.push((format!("{method} {uri}"), direct.status)); + } + assert_eq!(rig.metrics.call_failures.load(Ordering::Relaxed), 0); + seen +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn every_endpoint_through_the_edge_equals_direct() { + let seen = compare_all(|_| {}, &cases()).await; + // The cases reach every status code control-api.md names, so the comparison is not of + // twenty identical 200s. + let codes: std::collections::BTreeSet = seen.iter().map(|(_, s)| s.as_u16()).collect(); + for code in [200, 202, 400, 403, 404, 422, 429, 503] { + assert!(codes.contains(&code), "no case answered {code}: {seen:?}"); + } +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn with_reward_enabled_and_chat_disabled_too() { + let seen = compare_all( + |config| { + config.control.allow_reward = true; + config.chat.enabled = false; + }, + &cases(), + ) + .await; + let status = |what: &str| seen.iter().find(|(w, _)| w == what).unwrap().1; + assert_eq!(status("POST /chat"), StatusCode::FORBIDDEN); + assert_eq!(status("POST /reward"), StatusCode::ACCEPTED); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_failed_checkpoint_an_unhealthy_loop_and_a_timeout_match_too() { + let rig = rig(|_| {}).await; + rig.sim.fail_checkpoint.store(true, Ordering::SeqCst); + for (method, uri, body) in [ + (Method::POST, "/checkpoint", Vec::new()), + // The loop takes the command but never answers: both sides wait COMMAND_TIMEOUT and 503. + ( + Method::POST, + "/stimulate", + serde_json::to_vec(&json!({"by": "hang", "source": "chat"})).unwrap(), + ), + ] { + let direct = exchange(rig.direct(), &method, uri, Some("application/json"), &body).await; + let edge = exchange( + rig.via_edge(), + &method, + uri, + Some("application/json"), + &body, + ) + .await; + assert_eq!(direct, edge, "{method} {uri}"); + assert!( + direct.status.is_server_error(), + "{method} {uri}: {}", + direct.status + ); + } + // A loop that has not advanced for 2 s. + tokio::time::sleep(Duration::from_millis(2_100)).await; + let direct = exchange(rig.direct(), &Method::GET, "/healthz", None, &[]).await; + let edge = exchange(rig.via_edge(), &Method::GET, "/healthz", None, &[]).await; + assert_eq!(direct, edge); + assert_eq!(direct.status, StatusCode::SERVICE_UNAVAILABLE); +} + +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn a_large_events_page_rides_as_an_artifact_and_still_matches() { + let rig = rig(|_| {}).await; + // Enough events that the page is far over one envelope. + let mut log = flysim::eventlog::EventLog::open( + &rig.dir.path().join("more-events"), + rig.state.shared.events.clone(), + ) + .unwrap(); + for index in 0..2_000u64 { + log.append( + 2_000 + index, + index as f64, + flysim::eventlog::NewEvent::new( + flysim::snapshot::FeedEventKind::Reward, + format!("a reasonably long reward label number {index}"), + ) + .value(0.25), + ); + } + let uri = "/events?since=0&limit=4096"; + let direct = exchange(rig.direct(), &Method::GET, uri, None, &[]).await; + let edge = exchange(rig.via_edge(), &Method::GET, uri, None, &[]).await; + assert!( + direct.body.len() > flysim::controlbus::INLINE_MAX, + "{} bytes", + direct.body.len() + ); + assert_eq!(direct, edge); + // The artifact is released once read. + tokio::time::sleep(Duration::from_millis(200)).await; + assert_eq!(rig.bus.router.stats().artifacts, 0); +} + +/// The running edge over real sockets: the whole HTTP/1.1 response equals flysim's own listener's, +/// `date` aside, for a request of every kind. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn over_tcp_the_edge_answers_the_same_bytes_as_flysim() { + let rig = rig(|_| {}).await; + rig.close_edge().await; + // flysim's own listener, as direct mode binds it. + let direct_addr = common::free_port(); + let listener = tokio::net::TcpListener::bind(direct_addr).await.unwrap(); + let router = rig.direct(); + tokio::spawn(async move { axum::serve(listener, router).await }); + // The edge process's loop, on another port. + let edge_addr = common::free_port(); + let config = fly_control_edge::EdgeConfig { + control_bind: edge_addr, + ..rig.config.clone() + }; + let metrics = std::sync::Arc::new(fly_control_edge::EdgeMetrics::default()); + let edge = tokio::spawn(fly_control_edge::run( + config, + std::sync::Arc::clone(&metrics), + )); + let mut waited = 0; + while metrics.connected.load(Ordering::Relaxed) == 0 { + tokio::time::sleep(Duration::from_millis(20)).await; + waited += 1; + assert!(waited < 250, "the edge never bound"); + } + let body = r#"{"by":"viewer","source":"points","durationMs":300}"#; + let chat = r#"{"by":"viewer","text":"see http://x.example"}"#; + for request in [ + "GET /status HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(), + "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(), + "GET /metrics HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(), + "GET /events?since=2&limit=3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(), + format!( + "POST /stimulate HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}", + body.len() + ), + format!( + "POST /chat HTTP/1.1\r\nHost: localhost\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{chat}", + chat.len() + ), + "POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(), + "POST /reward HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n".to_owned(), + "GET /buttons HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n".to_owned(), + ] { + let direct = common::raw_http(direct_addr, &request).await.unwrap(); + let via_edge = common::raw_http(edge_addr, &request).await.unwrap(); + assert_eq!( + String::from_utf8_lossy(&direct), + String::from_utf8_lossy(&via_edge), + "{request}" + ); + assert!(direct.starts_with(b"HTTP/1.1 "), "{}", String::from_utf8_lossy(&direct)); + } + edge.abort(); +} diff --git a/services/flysim/crates/fly-control-edge/tests/serve.rs b/services/flysim/crates/fly-control-edge/tests/serve.rs new file mode 100644 index 0000000..d0906a7 --- /dev/null +++ b/services/flysim/crates/fly-control-edge/tests/serve.rs @@ -0,0 +1,90 @@ +//! `flysim::serve` with `control.via = bus`: flysim leaves the control port alone, registers the +//! control services on its embedded router, and the edge process serves the port from them. +//! This is the wiring both runtimes share (`flysim` and `flysim-session` both run `serve`). + +mod common; + +use std::sync::Arc; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::time::{Duration, Instant}; + +use flysim::config::{Config, ControlVia}; +use flysim::simloop::Command; +use flysim::snapshot::FeedStatus; + +#[test] +fn serve_in_control_bus_mode_leaves_the_port_to_the_edge() { + let dir = tempfile::tempdir().unwrap(); + let mut config = Config::default(); + config.feed.bind = common::free_port(); + config.control.bind = common::free_port(); + config.control.via = ControlVia::Bus; + config.feed.bus_dir = dir.path().join("bus"); + let control_bind = config.control.bind; + + let stop = Arc::new(AtomicBool::new(false)); + let serving = { + let config = config.clone(); + let stop = Arc::clone(&stop); + std::thread::spawn(move || { + flysim::serve( + config, + move |shared, _snapshots, mut commands, _notifier| { + // A stand-in loop: beats, answers pauses, stops when told. + while !stop.load(Ordering::SeqCst) { + shared.beat(); + while let Ok(command) = commands.try_recv() { + if let Command::Pause { reply } = command { + let _ = reply.send(FeedStatus::Paused); + } + } + std::thread::sleep(Duration::from_millis(10)); + } + Ok(()) + }, + ) + }) + }; + + let runtime = tokio::runtime::Runtime::new().unwrap(); + runtime.block_on(async { + let request = "GET /healthz HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"; + // The router's sockets appear; flysim never binds the control port. + let started = Instant::now(); + while !dir.path().join("bus/control-edge.sock").exists() { + assert!(started.elapsed() < Duration::from_secs(20), "no control socket"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + assert!(common::raw_http(control_bind, request).await.is_none(), "flysim bound :7401"); + for role in ["stage", "bridge", "watchdog", "operator"] { + assert!(dir.path().join(format!("bus/control/{role}.sock")).exists(), "{role}"); + } + // The feed is still direct: no feed socket. + assert!(!dir.path().join("bus/edge.sock").exists()); + + let edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None); + let metrics = Arc::new(fly_control_edge::EdgeMetrics::default()); + let edge = tokio::spawn(fly_control_edge::run(edge_config, Arc::clone(&metrics))); + let started = Instant::now(); + while metrics.connected.load(Ordering::Relaxed) == 0 { + assert!(started.elapsed() < Duration::from_secs(20), "the edge never bound"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + let health = common::raw_http(control_bind, request).await.unwrap(); + assert!(health.starts_with(b"HTTP/1.1 200"), "{}", String::from_utf8_lossy(&health)); + let pause = "POST /pause HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"; + let paused = String::from_utf8(common::raw_http(control_bind, pause).await.unwrap()).unwrap(); + assert!(paused.starts_with("HTTP/1.1 200"), "{paused}"); + assert!(paused.ends_with("{\"status\":\"paused\"}"), "{paused}"); + + // flysim stops: the edge lets go of the port. + stop.store(true, Ordering::SeqCst); + let started = Instant::now(); + while common::raw_http(control_bind, request).await.is_some() { + assert!(started.elapsed() < Duration::from_secs(20), ":7401 stayed bound"); + tokio::time::sleep(Duration::from_millis(20)).await; + } + edge.abort(); + }); + serving.join().unwrap().unwrap(); +} diff --git a/services/flysim/crates/fly-legacy-session/Cargo.toml b/services/flysim/crates/fly-legacy-session/Cargo.toml index 803adaf..e71d838 100644 --- a/services/flysim/crates/fly-legacy-session/Cargo.toml +++ b/services/flysim/crates/fly-legacy-session/Cargo.toml @@ -42,6 +42,8 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } [dev-dependencies] +# CTRL-01: the service contracts with the control API on the bus (`tests/service_parity.rs`). +fly-control-edge = { path = "../fly-control-edge" } tempfile = "3" axum = "0.8" futures-util = "0.3" diff --git a/services/flysim/crates/fly-legacy-session/tests/service_parity.rs b/services/flysim/crates/fly-legacy-session/tests/service_parity.rs index c6245b6..15546d4 100644 --- a/services/flysim/crates/fly-legacy-session/tests/service_parity.rs +++ b/services/flysim/crates/fly-legacy-session/tests/service_parity.rs @@ -19,6 +19,10 @@ //! - **store**: the event log file, the journal lines (minus `wallMs`, the boot header's runtime //! and wall clock), and the final durable checkpoint decoded (minus `wallMs`). //! +//! The in-process session runs a second time with its control API on the bus (CTRL-01): the +//! same script through `fly-control-edge`'s router and the control services on an embedded +//! router, compared against the legacy run the same way. +//! //! Gated on `FLY_ROM` (source `bin/rom-env.sh`). `toy_raw_*` uses the committed toy connectome and //! a store seeded by a legacy fresh start; `fafb_*` (also `FLY_SERVE01_FAFB`) the real connectome //! from the ENV-01 service trace's `rollback` checkpoint, which rolls back on its first boundary. @@ -70,6 +74,10 @@ fn sha(bytes: &[u8]) -> String { enum Runtime { Legacy, Session(ExecutionMode), + /// The session runtime with its control API on the bus (`FLY_CONTROL_VIA=bus`, CTRL-01): the + /// script goes through `fly-control-edge`'s router, over the edge's Unix socket, to the + /// control services on the embedded router. + SessionOverBus(ExecutionMode), } impl Runtime { @@ -77,6 +85,9 @@ impl Runtime { match self { Runtime::Legacy => "legacy".to_owned(), Runtime::Session(mode) => format!("session ({})", mode.label()), + Runtime::SessionOverBus(mode) => { + format!("session ({}) over the control bus", mode.label()) + } } } } @@ -245,7 +256,7 @@ fn record( let mut sim = Sim::boot(loop_shared, snapshots_tx, command_rx)?; sim.run(¬ifier) } - Runtime::Session(mode) => { + Runtime::Session(mode) | Runtime::SessionOverBus(mode) => { let options = ServiceOptions { mode, profile, @@ -261,7 +272,23 @@ fn record( .enable_all() .build() .unwrap(); - let router = flysim::api::router(state.clone()); + let bus_dir = config.paths.save_dir.parent().unwrap().join("bus"); + let (router, _control_bus) = match runtime { + Runtime::SessionOverBus(_) => driver.block_on(async { + let scope = flysim::controlbus::Scope::live(); + let uses = flysim::bus::Uses { feed: false, control: true }; + let bus = flysim::bus::start(&bus_dir, uses, &scope).await.unwrap(); + let host = flysim::controlbus::serve(&bus.router, state.clone(), &scope) + .await + .unwrap(); + let mut edge_config = fly_control_edge::EdgeConfig::from_flysim(&config, None); + edge_config.bus_dir = bus_dir.clone(); + let metrics = Arc::new(fly_control_edge::EdgeMetrics::default()); + let backend = fly_control_edge::connect(&edge_config, &metrics).await.unwrap(); + (flysim::api::router_with(backend), Some((bus, host))) + }), + _ => (flysim::api::router(state.clone()), None), + }; let metrics_router = flysim::api::metrics_router(state.clone()); let recording = driver.block_on(async { let mut snapshots = snapshots; @@ -627,10 +654,22 @@ fn run_pair( let started = Instant::now(); let legacy = run(Runtime::Legacy, "legacy"); eprintln!("{label}: legacy {} running snapshots in {:.1?}", legacy.running.len(), started.elapsed()); - for exec in modes() { + let runtimes = modes() + .into_iter() + .map(Runtime::Session) + .chain([Runtime::SessionOverBus(ExecutionMode::InProcess)]); + for runtime in runtimes { let started = Instant::now(); - let session = run(Runtime::Session(exec), &format!("session-{}", exec.label())); - let label = format!("{label}, {}", exec.label()); + let exec = match runtime { + Runtime::Session(exec) | Runtime::SessionOverBus(exec) => exec, + Runtime::Legacy => unreachable!(), + }; + let name = match runtime { + Runtime::SessionOverBus(_) => format!("session-bus-{}", exec.label()), + _ => format!("session-{}", exec.label()), + }; + let session = run(runtime, &name); + let label = format!("{label}, {}", runtime.label()); compare(&legacy, &session, &label); let rewards = legacy .events diff --git a/services/flysim/crates/flysim/README.md b/services/flysim/crates/flysim/README.md index 00dc0de..290f1f5 100644 --- a/services/flysim/crates/flysim/README.md +++ b/services/flysim/crates/flysim/README.md @@ -96,7 +96,10 @@ snapshot is consistent; the write and the fsyncs happen on the store thread. | `pacing` | absolute frame deadlines, `loop.speed`, the lag accounting, the realtime window | | `snapshot` | the feed protocol types, the exact framing, the spike bitset, the audio conversion | | `feed` | the WebSocket listener and the client hello | -| `api` | the control routes, built from one route table | +| `api` | the control routes, built from one route table, over a `ControlBackend` | +| `control` | what each control request does: validation, the command, the status code (both transports) | +| `controlbus` | the control API as flybus services, the grant table, the encoding (`FLY_CONTROL_VIA=bus`) | +| `bus` | the embedded router shared by the feed and control when either rides the bus | | `ratelimit` | the per-minute sugar budget and the no-overlap rule | | `store` | the `FLYSIM01` envelope, atomic commits, generations, milestone archives, restore order | | `eventlog` | append-only JSONL plus the in-memory tail the feed and `/events` read | @@ -202,6 +205,11 @@ router is built from it, and `tests/api.rs` asserts both over the table and agai router for thirteen spellings of such a route. The prototype's `manualButtons` field and its `learn: false` suppression are dropped, not disabled. +On the bus (`FLY_CONTROL_VIA=bus`) the same guarantee is a grant table: no control service has +an input method, every grant is an exact call on a control service, only the in-process host +registers, and the policy is closed (`controlbus`, `crates/fly-control-edge/tests/grants.rs`, +`docs/design/flybus.md` "Control over the bus"). + ## Tests ```sh diff --git a/services/flysim/crates/flysim/src/api.rs b/services/flysim/crates/flysim/src/api.rs index 62c981b..f3b57d6 100644 --- a/services/flysim/crates/flysim/src/api.rs +++ b/services/flysim/crates/flysim/src/api.rs @@ -1,4 +1,4 @@ -//! The control API, `http://127.0.0.1:7401`. +//! The control API, `http://127.0.0.1:7401`: the HTTP layer. //! //! Binding contract: `docs/control-api.md`. Behavioural reference: //! `packages/feed/src/fake/server.ts`, which this must be a drop-in replacement for — same @@ -9,8 +9,15 @@ //! //! [`ROUTES`] is the entire surface; the router is built from it, so a route cannot be added //! without appearing in that table, and `tests/api.rs` asserts on the table itself. +//! +//! This module only turns HTTP into a [`ControlRequest`] and a [`ControlReply`] back into HTTP. +//! What a request does is [`crate::control::handle`]'s, reached through a [`ControlBackend`]: +//! [`AppState`] calls it in this process (`control.via = direct`), and `fly-control-edge` calls +//! it across the bus (`control.via = bus`, [`crate::controlbus`]). The extractors, the 404s, the +//! headers and the body encoding are this one copy in both cases, so the bytes on `:7401` do not +//! depend on which side of the bus answered. -use std::time::Duration; +use std::future::Future; use axum::Router; use axum::body::Bytes; @@ -20,17 +27,24 @@ use axum::response::{IntoResponse, Response}; use axum::routing::{get, post}; use serde::Deserialize; use serde_json::{Value, json}; -use tokio::sync::oneshot; -use crate::chat::ChatRefusal; -use crate::eventlog::now_wall_ms; -use crate::simloop::Command; -use crate::{AppState, metrics}; +pub use crate::control::COMMAND_TIMEOUT; +use crate::AppState; +use crate::control::{ControlReply, ControlRequest, METRICS_CONTENT_TYPE, ReplyBody}; + +/// Whatever answers a [`ControlRequest`]: the sim in this process, or the control services on +/// the bus. +pub trait ControlBackend: Clone + Send + Sync + 'static { + fn handle(&self, request: ControlRequest) -> impl Future + Send; +} + +impl ControlBackend for AppState { + fn handle(&self, request: ControlRequest) -> impl Future + Send { + let state = self.clone(); + async move { crate::control::handle(&state, request).await } + } +} -/// Every route the control API serves, in the order `docs/control-api.md` lists them. -/// -/// `/status.json` is an alias of `/status` (the read-only metrics listener that -/// `infra/bin/fly-watchdog` scrapes asks for that name); `/metrics` is Prometheus text. pub const ROUTES: &[(&str, &str)] = &[ ("GET", "/status"), ("GET", "/status.json"), @@ -54,39 +68,40 @@ pub const READ_ONLY_ROUTES: &[(&str, &str)] = &[ ("GET", "/metrics"), ]; -/// How long a caller waits for the sim thread to pick a command up. One frame is 16.7 ms, so -/// this is generous; exceeding it means the loop is wedged, which is a 503, not a hang. -pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(2); - pub fn router(state: AppState) -> Router { + router_with(state) +} + +/// The full control router over any backend: [`ROUTES`] and a 404 for everything else. +pub fn router_with(backend: B) -> Router { Router::new() - .route("/status", get(status)) - .route("/status.json", get(status)) - .route("/stimulate", post(stimulate)) - .route("/reward", post(reward)) - .route("/chat", post(chat)) - .route("/checkpoint", post(checkpoint)) - .route("/pause", post(pause)) - .route("/resume", post(resume)) - .route("/events", get(events)) - .route("/healthz", get(healthz)) - .route("/metrics", get(prometheus)) + .route("/status", get(status::)) + .route("/status.json", get(status::)) + .route("/stimulate", post(stimulate::)) + .route("/reward", post(reward::)) + .route("/chat", post(chat::)) + .route("/checkpoint", post(checkpoint::)) + .route("/pause", post(pause::)) + .route("/resume", post(resume::)) + .route("/events", get(events::)) + .route("/healthz", get(healthz::)) + .route("/metrics", get(prometheus::)) .fallback(not_found) // The reference server answers every unmatched method-and-path pair with the same 404, // so `GET /stimulate` is "no such route" rather than a 405. Being a drop-in replacement // for it matters more here than the distinction does. .method_not_allowed_fallback(not_found) .layer(axum::middleware::map_response(no_store)) - .with_state(state) + .with_state(backend) } /// The read-only listener: [`READ_ONLY_ROUTES`] and nothing else. pub fn metrics_router(state: AppState) -> Router { Router::new() - .route("/status", get(status)) - .route("/status.json", get(status)) - .route("/healthz", get(healthz)) - .route("/metrics", get(prometheus)) + .route("/status", get(status::)) + .route("/status.json", get(status::)) + .route("/healthz", get(healthz::)) + .route("/metrics", get(prometheus::)) .fallback(not_found) .method_not_allowed_fallback(not_found) .layer(axum::middleware::map_response(no_store)) @@ -100,107 +115,25 @@ async fn no_store(mut response: Response) -> Response { response } -fn body(status: StatusCode, value: Value) -> Response { - (status, axum::Json(value)).into_response() -} - -fn error(status: StatusCode, message: impl std::fmt::Display) -> Response { - body(status, json!({ "error": message.to_string() })) -} - -// -- GET /status ------------------------------------------------------------------------------ - -/// The feed header minus `events` and `attachments`, plus `version` and `checkpoint`. -/// -/// Built by reshaping the header itself rather than by a parallel struct, so "same fields as the -/// feed header" cannot drift. -async fn status(State(state): State) -> Response { - let snapshot = state.snapshot(); - let mut value = match serde_json::to_value(&snapshot.header) { - Ok(Value::Object(map)) => map, - _ => return error(StatusCode::INTERNAL_SERVER_ERROR, "could not render the status"), - }; - value.remove("events"); - value.remove("attachments"); - let versions = state.shared.versions.get().cloned().unwrap_or_default(); - value.insert("version".to_string(), serde_json::to_value(versions).unwrap_or(Value::Null)); - let checkpoint = state - .shared - .checkpoint - .lock() - .map(|status| *status) - .unwrap_or_default(); - value.insert("checkpoint".to_string(), serde_json::to_value(checkpoint).unwrap_or(Value::Null)); - // The readout's own numbers, additive: one row per channel with the role it reads, the resting - // rate it is normalized against and the score the last decode computed, plus the roles a - // restore has left for the next decode to calibrate (`docs/readout.md`). - let decoder = state - .shared - .decoder - .lock() - .map(|status| status.clone()) - .unwrap_or_default(); - value.insert("decoder".to_string(), serde_json::to_value(decoder).unwrap_or(Value::Null)); - body(StatusCode::OK, Value::Object(value)) -} - -// -- GET /healthz ----------------------------------------------------------------------------- - -/// 200 while the loop advanced in the last 2 seconds, else 503. This is what systemd's -/// `wait-for-health` helper and `infra/bin/fly-watchdog` check first. -async fn healthz(State(state): State) -> Response { - if state.shared.healthy(now_wall_ms()) { - body(StatusCode::OK, json!({ "status": "ok" })) - } else { - error( - StatusCode::SERVICE_UNAVAILABLE, - "loop has not advanced in the last 2 seconds", - ) +/// A [`ControlReply`] as HTTP: JSON bodies as `axum::Json` writes them, `/metrics` as +/// Prometheus text. +pub fn into_response(reply: ControlReply) -> Response { + let status = + StatusCode::from_u16(reply.status).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR); + match reply.body { + ReplyBody::Json(value) => (status, axum::Json(value)).into_response(), + ReplyBody::Text(text) => { + (status, [(header::CONTENT_TYPE, METRICS_CONTENT_TYPE)], text).into_response() + } } } -// -- GET /metrics ----------------------------------------------------------------------------- - -async fn prometheus(State(state): State) -> Response { - let snapshot = state.snapshot(); - let text = metrics::render(&state.shared.metrics, &snapshot, now_wall_ms()); - ( - StatusCode::OK, - [(header::CONTENT_TYPE, "text/plain; version=0.0.4; charset=utf-8")], - text, - ) - .into_response() +async fn answer(backend: &B, request: ControlRequest) -> Response { + into_response(backend.handle(request).await) } -// -- GET /events ------------------------------------------------------------------------------ - -#[derive(Debug, Deserialize)] -struct EventsQuery { - since: Option, - limit: Option, -} - -/// `?since=&limit=`, parsed as leniently as the reference server's -/// `Number.parseInt(...) || 0`: anything unreadable falls back to the default. -async fn events(State(state): State, Query(query): Query) -> Response { - let since = query - .since - .as_deref() - .and_then(|value| value.parse::().ok()) - .unwrap_or(0); - let limit = query - .limit - .as_deref() - .and_then(|value| value.parse::().ok()) - .filter(|limit| *limit > 0) - .unwrap_or(100) - .min(crate::eventlog::RING_CAPACITY); - let events = state.shared.events.page(since, limit); - body(StatusCode::OK, json!({ "events": events })) -} - -// -- POST /stimulate -------------------------------------------------------------------------- - +/// The request body as JSON, or `None` when it is empty or not JSON (the reference server's +/// "malformed body"). fn parse_json(bytes: &Bytes) -> Option { if bytes.is_empty() { return None; @@ -208,217 +141,64 @@ fn parse_json(bytes: &Bytes) -> Option { serde_json::from_slice(bytes).ok() } -/// `chat`, `points` or `operator`, as `isActionSource` in the reference server. -fn action_source(value: Option<&Value>) -> Option<&str> { - match value.and_then(Value::as_str) { - Some(source @ ("chat" | "points" | "operator")) => Some(source), - _ => None, - } +async fn status(State(backend): State) -> Response { + answer(&backend, ControlRequest::Status).await } -async fn stimulate(State(state): State, bytes: Bytes) -> Response { - let Some(request) = parse_json(&bytes) else { - return error(StatusCode::BAD_REQUEST, "expected { durationMs?, by, source }"); - }; - let (Some(by), Some(source)) = ( - request.get("by").and_then(Value::as_str), - action_source(request.get("source")), - ) else { - return error(StatusCode::BAD_REQUEST, "expected { durationMs?, by, source }"); - }; - let duration_ms = match request.get("durationMs") { - None | Some(Value::Null) => None, - Some(value) => match value.as_f64().filter(|value| value.is_finite() && *value > 0.0) { - Some(value) => Some(value), - None => { - return error(StatusCode::BAD_REQUEST, "durationMs must be a positive number"); - } - }, - }; - - let (reply, response) = oneshot::channel(); - let command = Command::Stimulate { - duration_ms, - by: by.to_string(), - source: source.to_string(), - reply, - }; - match dispatch(&state, command, response).await { - Ok(Ok(event_id)) => body(StatusCode::ACCEPTED, json!({ "eventId": event_id })), - Ok(Err(refusal)) => body( - StatusCode::TOO_MANY_REQUESTS, - json!({ "retryAfterMs": refusal.retry_after_ms() }), - ), - Err(response) => response, - } +async fn healthz(State(backend): State) -> Response { + answer(&backend, ControlRequest::Healthz).await } -// -- POST /reward ----------------------------------------------------------------------------- - -async fn reward(State(state): State, bytes: Bytes) -> Response { - if !state.shared.config.control.allow_reward { - // Present so that the later "who trains the fly" work does not change the API. - return error( - StatusCode::FORBIDDEN, - "reward is disabled (control.allow_reward = false)", - ); - } - let Some(request) = parse_json(&bytes) else { - return error(StatusCode::BAD_REQUEST, "expected { value, by, source }"); - }; - let (Some(value), Some(by), Some(source)) = ( - request.get("value").and_then(Value::as_f64).filter(|value| value.is_finite()), - request.get("by").and_then(Value::as_str), - action_source(request.get("source")), - ) else { - return error(StatusCode::BAD_REQUEST, "expected { value, by, source }"); - }; - - let (reply, response) = oneshot::channel(); - let command = Command::Reward { - value, - by: by.to_string(), - source: source.to_string(), - reply, - }; - match dispatch(&state, command, response).await { - Ok(event_id) => body(StatusCode::ACCEPTED, json!({ "eventId": event_id })), - Err(response) => response, - } +async fn prometheus(State(backend): State) -> Response { + answer(&backend, ControlRequest::Metrics).await } -// -- POST /chat ------------------------------------------------------------------------------- +#[derive(Debug, Deserialize)] +struct EventsQuery { + since: Option, + limit: Option, +} -/// `{ by, text, bot? }`: one line for the feed header's chat ring. -/// -/// The kill switch is answered here, because it is pure configuration and a 403 should not need -/// the sim thread. Everything else — the name rule, the sanitizer, the deny list and the two rate -/// limits — is decided on the sim thread, which owns the ring, the limiter and the event log. -/// -/// Status codes, per `docs/control-api.md`: 202 with the event id, 403 while chat is disabled, -/// 422 when a rule refused the line, 429 when a rate limit did, 400 for a malformed body. -async fn chat(State(state): State, bytes: Bytes) -> Response { - if !state.shared.config.chat.enabled { - return error(StatusCode::FORBIDDEN, "chat is disabled (chat.enabled = false)"); - } - let Some(request) = parse_json(&bytes) else { - return error(StatusCode::BAD_REQUEST, "expected { by, text, bot? }"); +async fn events( + State(backend): State, + Query(query): Query, +) -> Response { + let request = ControlRequest::Events { + since: query.since, + limit: query.limit, }; - let (Some(by), Some(text)) = ( - request.get("by").and_then(Value::as_str), - request.get("text").and_then(Value::as_str), - ) else { - state - .shared - .metrics - .chat_rejected(crate::chat::RejectReason::Malformed); - return error(StatusCode::BAD_REQUEST, "expected { by, text, bot? }"); - }; - let bot = match request.get("bot") { - None | Some(Value::Null) => false, - Some(Value::Bool(value)) => *value, - Some(_) => return error(StatusCode::BAD_REQUEST, "bot must be a boolean"), - }; - - let (reply, response) = oneshot::channel(); - let command = Command::Chat { by: by.to_string(), text: text.to_string(), bot, reply }; - match dispatch(&state, command, response).await { - Ok(Ok(event_id)) => body(StatusCode::ACCEPTED, json!({ "eventId": event_id })), - Ok(Err(ChatRefusal::Rejected(reason))) => body( - StatusCode::UNPROCESSABLE_ENTITY, - json!({ "error": format!("chat line refused: {}", reason.as_str()) }), - ), - Ok(Err(ChatRefusal::RateLimited { retry_after_ms })) => body( - StatusCode::TOO_MANY_REQUESTS, - json!({ "retryAfterMs": retry_after_ms }), - ), - Err(response) => response, - } + answer(&backend, request).await } -// -- POST /checkpoint, /pause, /resume -------------------------------------------------------- - -async fn checkpoint(State(state): State) -> Response { - let (reply, response) = oneshot::channel(); - // A forced checkpoint answers only once the bytes are on disk, so a caller that is about to - // restart the service can rely on it. - match dispatch_with_timeout(&state, Command::Checkpoint { reply }, response, None).await { - Ok(Ok(generation)) => body(StatusCode::OK, json!({ "generation": generation })), - Ok(Err(message)) => error(StatusCode::INTERNAL_SERVER_ERROR, message), - Err(response) => response, - } +async fn stimulate(State(backend): State, bytes: Bytes) -> Response { + answer(&backend, ControlRequest::Stimulate { body: parse_json(&bytes) }).await } -async fn pause(State(state): State) -> Response { - let (reply, response) = oneshot::channel(); - // A pause takes an implicit durable checkpoint, so it can take as long as one write. - match dispatch_with_timeout(&state, Command::Pause { reply }, response, None).await { - Ok(status) => body(StatusCode::OK, json!({ "status": status })), - Err(response) => response, - } +async fn reward(State(backend): State, bytes: Bytes) -> Response { + answer(&backend, ControlRequest::Reward { body: parse_json(&bytes) }).await } -async fn resume(State(state): State) -> Response { - let (reply, response) = oneshot::channel(); - match dispatch(&state, Command::Resume { reply }, response).await { - Ok(status) => body(StatusCode::OK, json!({ "status": status })), - Err(response) => response, - } +async fn chat(State(backend): State, bytes: Bytes) -> Response { + answer(&backend, ControlRequest::Chat { body: parse_json(&bytes) }).await } -// -- plumbing --------------------------------------------------------------------------------- +async fn checkpoint(State(backend): State) -> Response { + answer(&backend, ControlRequest::Checkpoint).await +} + +async fn pause(State(backend): State) -> Response { + answer(&backend, ControlRequest::Pause).await +} + +async fn resume(State(backend): State) -> Response { + answer(&backend, ControlRequest::Resume).await +} async fn not_found(method: axum::http::Method, uri: axum::http::Uri) -> Response { - error( - StatusCode::NOT_FOUND, - format!("no such route: {method} {}", uri.path()), - ) -} - -async fn dispatch( - state: &AppState, - command: Command, - response: oneshot::Receiver, -) -> Result { - dispatch_with_timeout(state, command, response, Some(COMMAND_TIMEOUT)).await -} - -/// Queue a command and wait for its reply. -/// -/// The queue is bounded: a full queue is a 503 rather than a wait, because the only way to fill -/// it is a wedged loop or a flood, and neither is improved by blocking the caller. -async fn dispatch_with_timeout( - state: &AppState, - command: Command, - response: oneshot::Receiver, - timeout: Option, -) -> Result { - if let Err(error) = state.commands.try_send(command) { - return Err(match error { - tokio::sync::mpsc::error::TrySendError::Full(_) => self::error( - StatusCode::SERVICE_UNAVAILABLE, - "the simulation command queue is full", - ), - tokio::sync::mpsc::error::TrySendError::Closed(_) => { - self::error(StatusCode::SERVICE_UNAVAILABLE, "the simulation has stopped") - } - }); - } - let awaited = match timeout { - Some(timeout) => match tokio::time::timeout(timeout, response).await { - Ok(result) => result, - Err(_) => { - return Err(self::error( - StatusCode::SERVICE_UNAVAILABLE, - "the simulation did not answer in time", - )); - } - }, - None => response.await, - }; - awaited.map_err(|_| { - self::error(StatusCode::SERVICE_UNAVAILABLE, "the simulation dropped the request") - }) + into_response(ControlReply::json( + 404, + json!({ "error": format!("no such route: {method} {}", uri.path()) }), + )) } #[cfg(test)] @@ -447,15 +227,4 @@ mod tests { assert!(ROUTES.contains(&(method, path)), "{path} is not a control route"); } } - - #[test] - fn action_sources_are_the_three_the_contract_names() { - for source in ["chat", "points", "operator"] { - assert_eq!(action_source(Some(&json!(source))), Some(source)); - } - for rejected in [json!("bridge"), json!(1), json!(null), Value::Null] { - assert_eq!(action_source(Some(&rejected)), None); - } - assert_eq!(action_source(None), None); - } } diff --git a/services/flysim/crates/flysim/src/bus.rs b/services/flysim/crates/flysim/src/bus.rs new file mode 100644 index 0000000..3c219f3 --- /dev/null +++ b/services/flysim/crates/flysim/src/bus.rs @@ -0,0 +1,127 @@ +//! The embedded flybus router: one router under `feed.bus_dir` for whatever rides the bus +//! (`FLY_FEED_VIA=bus`, `FLY_CONTROL_VIA=bus`, or both). +//! +//! The feed's half is `crate::feedbus` (its topic, its policy, its limits and `edge.sock`), the +//! control's half is `crate::controlbus` (its services, its grant table and its sockets); this +//! module only composes them on one router, so a box with both on the bus runs one router, one +//! store and one closed policy. + +use std::os::unix::fs::DirBuilderExt as _; +use std::path::Path; + +use anyhow::{Context as _, Result}; +use flybus::{Limits, Policy, Router, RouterConfig, UnixListenerHandle}; + +use crate::controlbus::{self, Role, Scope}; +use crate::feedbus; + +/// What rides the bus. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Uses { + pub feed: bool, + pub control: bool, +} + +/// A running router and its sockets. Dropping it stops listening; the router stops with the +/// runtime it was started on. +pub struct EmbeddedBus { + pub router: Router, + _listeners: Vec, +} + +/// The router limits: the feed's (`docs/design/flybus.md`, amendment "Feed sizing"), with room +/// for the control participants when control rides the bus too: the in-process host, the edge +/// and one connection per native role, pending handshakes included, and the control services. +pub fn limits(uses: Uses) -> Limits { + let feed = feedbus::limits(); + if !uses.control { + return feed; + } + Limits { + max_clients: feed.max_clients + 8, + max_services: feed.max_services + 8, + ..feed + } +} + +/// The closed policy for `uses`. +pub fn policy(uses: Uses, scope: &Scope) -> Policy { + let base = if uses.feed { + feedbus::policy() + } else { + Policy::closed() + }; + if uses.control { + controlbus::policy(base, scope) + } else { + base + } +} + +fn private_dir(path: &Path) -> Result<()> { + std::fs::DirBuilder::new() + .recursive(true) + .mode(0o700) + .create(path) + .with_context(|| format!("creating {}", path.display())) +} + +fn remove_stale(socket: &Path) -> Result<()> { + match std::fs::remove_file(socket) { + Ok(()) => { + tracing::info!(socket = %socket.display(), "removed a stale bus socket"); + Ok(()) + } + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error).with_context(|| format!("removing {}", socket.display())), + } +} + +/// Start the router under `bus_dir` and listen on every socket `uses` needs: `edge.sock` for the +/// feed edge, `control-edge.sock` for the control edge and `control/.sock` for each native +/// control role, each launcher-bound to its participant. +/// +/// Must run inside a Tokio runtime. `Router::new` removes store directories a previous flysim +/// left behind; stale socket files are removed here, because a socket outlives its listener. +pub async fn start(bus_dir: &Path, uses: Uses, scope: &Scope) -> Result { + private_dir(bus_dir)?; + let root = feedbus::store_root(bus_dir); + private_dir(&root)?; + let mut config = RouterConfig::new(root); + config.limits = limits(uses); + config.policy = policy(uses, scope); + let router = Router::new(config).context("starting the flybus router")?; + + let mut sockets = Vec::new(); + if uses.feed { + sockets.push((feedbus::socket_path(bus_dir), feedbus::EDGE)); + } + if uses.control { + private_dir(&bus_dir.join(controlbus::ROLE_SOCKET_DIR))?; + for role in Role::ALL { + sockets.push((controlbus::socket_path(bus_dir, role), role.participant())); + } + } + let mut listeners = Vec::new(); + for (socket, participant) in sockets { + remove_stale(&socket)?; + listeners.push( + router + .listen_unix_as(&socket, participant) + .await + .with_context(|| format!("listening on {}", socket.display()))?, + ); + } + tracing::info!( + bus = %bus_dir.display(), + feed = uses.feed, + control = uses.control, + store = %router.store_dir().display(), + router = router.router_id(), + "bus listening" + ); + Ok(EmbeddedBus { + router, + _listeners: listeners, + }) +} diff --git a/services/flysim/crates/flysim/src/config.rs b/services/flysim/crates/flysim/src/config.rs index 3580217..75d297e 100644 --- a/services/flysim/crates/flysim/src/config.rs +++ b/services/flysim/crates/flysim/src/config.rs @@ -9,7 +9,7 @@ //! - the `FLY_*` names the systemd units already set (`FLY_GAME`, `FLY_ROM`, `FLY_DATASET`, //! `FLY_STATE`, `FLY_STATE_HOT`, `FLY_FEED_BIND`, `FLY_CONTROL_BIND`, `FLY_METRICS_ADDR`, //! `FLY_ROM_SHA256`, `FLY_ROM_PLATFORMER_SHA256`, `FLY_CHAT_ENABLED`, `FLY_CHAT_DENY_LIST`, -//! `FLY_MACRO_MODE`, `FLY_FEED_VIA`, `FLY_BUS_DIR`, `RAYON_NUM_THREADS`); +//! `FLY_MACRO_MODE`, `FLY_FEED_VIA`, `FLY_CONTROL_VIA`, `FLY_BUS_DIR`, `RAYON_NUM_THREADS`); //! - `FLYSIM_
_` for everything, e.g. `FLYSIM_LOOP_SPEED=0`. //! //! Nothing here is secret (`docs/control-api.md`: "No secrets live in this service or its @@ -139,6 +139,8 @@ impl FeedVia { #[serde(default, deny_unknown_fields)] pub struct Control { pub bind: SocketAddr, + /// Who serves `control.bind` (`docs/design/flybus.md`, "Control over the bus"). + pub via: ControlVia, /// Optional extra read-only listener carrying `/metrics`, `/status`, `/status.json` and /// `/healthz` only (`infra/units/flysim.service` sets `FLY_METRICS_ADDR=0.0.0.0:9101`). pub metrics_bind: Option, @@ -152,6 +154,31 @@ pub struct Control { pub expect_rom_sha256: Option, } +/// Where the control API is served from (CTRL-01). +/// +/// `direct` is the default and the behaviour that predates the bus: flysim binds +/// `control.bind` itself. `bus` registers the control services on the embedded flybus router +/// (under `feed.bus_dir`, shared with the feed when that is on the bus too) and leaves +/// `control.bind` to the `fly-control-edge` process, which serves the same HTTP bytes by calling +/// them. The read-only `control.metrics_bind` listener stays in flysim in both modes. Outside the +/// simulation loop and outside the compatibility string. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum ControlVia { + #[default] + Direct, + Bus, +} + +impl ControlVia { + pub const fn as_str(self) -> &'static str { + match self { + Self::Direct => "direct", + Self::Bus => "bus", + } + } +} + /// `[macros]` (`docs/design/macros.md` sections 1 and 4): what the fly's channels mean. /// /// One knob, and deliberately only one. `raw` is the default and stays the default until the @@ -236,6 +263,7 @@ impl Default for Control { fn default() -> Self { Self { bind: "127.0.0.1:7401".parse().expect("literal address"), + via: ControlVia::Direct, metrics_bind: None, allow_reward: false, sugar_default_ms: 400.0, @@ -295,6 +323,9 @@ impl Config { if let Some(value) = get("FLY_CONTROL_BIND") { self.control.bind = parse_addr("FLY_CONTROL_BIND", value)?; } + if let Some(value) = get("FLY_CONTROL_VIA") { + self.control.via = parse_control_via("FLY_CONTROL_VIA", value)?; + } if let Some(value) = get("FLY_METRICS_ADDR") { self.control.metrics_bind = Some(parse_addr("FLY_METRICS_ADDR", value)?); } @@ -376,6 +407,9 @@ impl Config { if let Some(value) = get("FLYSIM_CONTROL_BIND") { self.control.bind = parse_addr("FLYSIM_CONTROL_BIND", value)?; } + if let Some(value) = get("FLYSIM_CONTROL_VIA") { + self.control.via = parse_control_via("FLYSIM_CONTROL_VIA", value)?; + } if let Some(value) = get("FLYSIM_CONTROL_METRICS_BIND") { self.control.metrics_bind = Some(parse_addr("FLYSIM_CONTROL_METRICS_BIND", value)?); } @@ -525,6 +559,14 @@ fn parse_feed_via(name: &str, value: &str) -> Result { } } +fn parse_control_via(name: &str, value: &str) -> Result { + match value.to_ascii_lowercase().as_str() { + "direct" => Ok(ControlVia::Direct), + "bus" => Ok(ControlVia::Bus), + _ => bail!("{name}: {value:?} is not a control path; expected \"direct\" or \"bus\""), + } +} + fn parse_addr(name: &str, value: &str) -> Result { value .parse() @@ -771,6 +813,28 @@ mod tests { assert_eq!(toml::from_str::("[feed]\nvia = \"bus\"\n").unwrap().feed.via, FeedVia::Bus); } + #[test] + fn the_control_path_is_direct_unless_the_environment_says_bus() { + assert_eq!(Config::default().control.via, ControlVia::Direct); + + let mut config = Config::default(); + config.apply_env(&env(&[("FLY_CONTROL_VIA", "Bus")])).unwrap(); + assert_eq!(config.control.via, ControlVia::Bus); + // Independent of the feed's switch. + assert_eq!(config.feed.via, FeedVia::Direct); + + let mut config = Config::default(); + config.apply_env(&env(&[("FLYSIM_CONTROL_VIA", "direct")])).unwrap(); + assert_eq!(config.control.via, ControlVia::Direct); + + let error = Config::default().apply_env(&env(&[("FLY_CONTROL_VIA", "http")])).unwrap_err(); + assert!(error.to_string().contains("FLY_CONTROL_VIA"), "{error}"); + assert_eq!( + toml::from_str::("[control]\nvia = \"bus\"\n").unwrap().control.via, + ControlVia::Bus + ); + } + #[test] fn the_bus_dir_must_be_absolute_and_not_empty() { Config::default().validate().unwrap(); diff --git a/services/flysim/crates/flysim/src/control.rs b/services/flysim/crates/flysim/src/control.rs new file mode 100644 index 0000000..31b09ca --- /dev/null +++ b/services/flysim/crates/flysim/src/control.rs @@ -0,0 +1,451 @@ +//! The control API's semantics, independent of how a request arrives (CTRL-01). +//! +//! Binding contract: `docs/control-api.md`. Every endpoint there is one [`ControlRequest`] +//! variant, and [`handle`] is the only code that decides what it does: the HTTP listener on +//! `:7401` ([`crate::api`]) and the control services on the bus ([`crate::controlbus`]) both call +//! it, so the status codes, the bodies and the commands the loop receives are one copy whichever +//! way the caller came in. +//! +//! [`ControlRequest`] is the whole surface. It has no variant that presses a button, edits game +//! memory or changes the reward catalog, and [`crate::simloop::Command`] has none either: the +//! structural guarantee of `docs/control-api.md` is a property of these two types. + +use std::time::Duration; + +use serde_json::{Value, json}; +use tokio::sync::oneshot; + +use crate::chat::ChatRefusal; +use crate::eventlog::now_wall_ms; +use crate::simloop::Command; +use crate::{AppState, metrics}; + +/// How long a caller waits for the sim thread to pick a command up. One frame is 16.7 ms, so +/// this is generous; exceeding it means the loop is wedged, which is a 503, not a hang. +pub const COMMAND_TIMEOUT: Duration = Duration::from_secs(2); + +/// The Prometheus text exposition's content type (`GET /metrics`). +pub const METRICS_CONTENT_TYPE: &str = "text/plain; version=0.0.4; charset=utf-8"; + +/// One control request, as `docs/control-api.md` lists them. +/// +/// Bodies are carried as the caller sent them, parsed (`None` when the body was empty or not +/// JSON), and the `/events` query as its raw strings, so validation, its lenient defaults and +/// its error messages live in [`handle`] alone. +#[derive(Debug, Clone, PartialEq)] +pub enum ControlRequest { + /// `GET /status` (and its alias `/status.json`). + Status, + /// `GET /healthz`. + Healthz, + /// `GET /metrics`. + Metrics, + /// `GET /events?since=&limit=`. + Events { + since: Option, + limit: Option, + }, + /// `POST /stimulate`: a sugar (PAM) pulse. + Stimulate { body: Option }, + /// `POST /reward`: disabled unless `control.allow_reward`. + Reward { body: Option }, + /// `POST /chat`: one line for the chat ring; never reaches the simulation. + Chat { body: Option }, + /// `POST /checkpoint`. + Checkpoint, + /// `POST /pause`. + Pause, + /// `POST /resume`. + Resume, +} + +impl ControlRequest { + /// The `docs/control-api.md` path this request is (for logs and tables). + pub fn path(&self) -> &'static str { + match self { + Self::Status => "/status", + Self::Healthz => "/healthz", + Self::Metrics => "/metrics", + Self::Events { .. } => "/events", + Self::Stimulate { .. } => "/stimulate", + Self::Reward { .. } => "/reward", + Self::Chat { .. } => "/chat", + Self::Checkpoint => "/checkpoint", + Self::Pause => "/pause", + Self::Resume => "/resume", + } + } + + /// Whether the loop is waited on without a deadline: a forced checkpoint answers once the + /// bytes are on disk, and a pause takes an implicit durable checkpoint. + pub fn waits_for_a_write(&self) -> bool { + matches!(self, Self::Checkpoint | Self::Pause) + } +} + +/// A reply body: JSON for every endpoint but `/metrics`, which is Prometheus text. +#[derive(Debug, Clone, PartialEq)] +pub enum ReplyBody { + Json(Value), + Text(String), +} + +/// What [`handle`] answers: the `docs/control-api.md` status code and body. +#[derive(Debug, Clone, PartialEq)] +pub struct ControlReply { + pub status: u16, + pub body: ReplyBody, +} + +impl ControlReply { + pub fn json(status: u16, value: Value) -> ControlReply { + ControlReply { + status, + body: ReplyBody::Json(value), + } + } + + pub fn error(status: u16, message: impl std::fmt::Display) -> ControlReply { + ControlReply::json(status, json!({ "error": message.to_string() })) + } + + pub fn text(status: u16, text: String) -> ControlReply { + ControlReply { + status, + body: ReplyBody::Text(text), + } + } +} + +/// The messages a failed hand-off to the loop answers with (503). The bus edge uses the same +/// words for the same failures on its side of the bus, so a client cannot tell them apart. +pub mod unavailable { + pub const QUEUE_FULL: &str = "the simulation command queue is full"; + pub const STOPPED: &str = "the simulation has stopped"; + pub const TIMED_OUT: &str = "the simulation did not answer in time"; + pub const DROPPED: &str = "the simulation dropped the request"; +} + +/// Answer one control request. +pub async fn handle(state: &AppState, request: ControlRequest) -> ControlReply { + match request { + ControlRequest::Status => status(state), + ControlRequest::Healthz => healthz(state), + ControlRequest::Metrics => prometheus(state), + ControlRequest::Events { since, limit } => events(state, since, limit), + ControlRequest::Stimulate { body } => stimulate(state, body).await, + ControlRequest::Reward { body } => reward(state, body).await, + ControlRequest::Chat { body } => chat(state, body).await, + ControlRequest::Checkpoint => checkpoint(state).await, + ControlRequest::Pause => pause(state).await, + ControlRequest::Resume => resume(state).await, + } +} + +// -- GET /status ------------------------------------------------------------------------------ + +/// The feed header minus `events` and `attachments`, plus `version` and `checkpoint`. +/// +/// Built by reshaping the header itself rather than by a parallel struct, so "same fields as the +/// feed header" cannot drift. +fn status(state: &AppState) -> ControlReply { + let snapshot = state.snapshot(); + let mut value = match serde_json::to_value(&snapshot.header) { + Ok(Value::Object(map)) => map, + _ => return ControlReply::error(500, "could not render the status"), + }; + value.remove("events"); + value.remove("attachments"); + let versions = state.shared.versions.get().cloned().unwrap_or_default(); + value.insert( + "version".to_string(), + serde_json::to_value(versions).unwrap_or(Value::Null), + ); + let checkpoint = state + .shared + .checkpoint + .lock() + .map(|status| *status) + .unwrap_or_default(); + value.insert( + "checkpoint".to_string(), + serde_json::to_value(checkpoint).unwrap_or(Value::Null), + ); + // The readout's own numbers, additive: one row per channel with the role it reads, the resting + // rate it is normalized against and the score the last decode computed, plus the roles a + // restore has left for the next decode to calibrate (`docs/readout.md`). + let decoder = state + .shared + .decoder + .lock() + .map(|status| status.clone()) + .unwrap_or_default(); + value.insert( + "decoder".to_string(), + serde_json::to_value(decoder).unwrap_or(Value::Null), + ); + ControlReply::json(200, Value::Object(value)) +} + +// -- GET /healthz ----------------------------------------------------------------------------- + +/// 200 while the loop advanced in the last 2 seconds, else 503. This is what systemd's +/// `wait-for-health` helper and `infra/bin/fly-watchdog` check first. +fn healthz(state: &AppState) -> ControlReply { + if state.shared.healthy(now_wall_ms()) { + ControlReply::json(200, json!({ "status": "ok" })) + } else { + ControlReply::error(503, "loop has not advanced in the last 2 seconds") + } +} + +// -- GET /metrics ----------------------------------------------------------------------------- + +fn prometheus(state: &AppState) -> ControlReply { + let snapshot = state.snapshot(); + ControlReply::text( + 200, + metrics::render(&state.shared.metrics, &snapshot, now_wall_ms()), + ) +} + +// -- GET /events ------------------------------------------------------------------------------ + +/// `?since=&limit=`, parsed as leniently as the reference server's +/// `Number.parseInt(...) || 0`: anything unreadable falls back to the default. +fn events(state: &AppState, since: Option, limit: Option) -> ControlReply { + let since = since + .as_deref() + .and_then(|value| value.parse::().ok()) + .unwrap_or(0); + let limit = limit + .as_deref() + .and_then(|value| value.parse::().ok()) + .filter(|limit| *limit > 0) + .unwrap_or(100) + .min(crate::eventlog::RING_CAPACITY); + let events = state.shared.events.page(since, limit); + ControlReply::json(200, json!({ "events": events })) +} + +// -- POST /stimulate -------------------------------------------------------------------------- + +/// `chat`, `points` or `operator`, as `isActionSource` in the reference server. +pub fn action_source(value: Option<&Value>) -> Option<&str> { + match value.and_then(Value::as_str) { + Some(source @ ("chat" | "points" | "operator")) => Some(source), + _ => None, + } +} + +async fn stimulate(state: &AppState, request: Option) -> ControlReply { + let Some(request) = request else { + return ControlReply::error(400, "expected { durationMs?, by, source }"); + }; + let (Some(by), Some(source)) = ( + request.get("by").and_then(Value::as_str), + action_source(request.get("source")), + ) else { + return ControlReply::error(400, "expected { durationMs?, by, source }"); + }; + let duration_ms = match request.get("durationMs") { + None | Some(Value::Null) => None, + Some(value) => match value + .as_f64() + .filter(|value| value.is_finite() && *value > 0.0) + { + Some(value) => Some(value), + None => { + return ControlReply::error(400, "durationMs must be a positive number"); + } + }, + }; + + let (reply, response) = oneshot::channel(); + let command = Command::Stimulate { + duration_ms, + by: by.to_string(), + source: source.to_string(), + reply, + }; + match dispatch(state, command, response).await { + Ok(Ok(event_id)) => ControlReply::json(202, json!({ "eventId": event_id })), + Ok(Err(refusal)) => { + ControlReply::json(429, json!({ "retryAfterMs": refusal.retry_after_ms() })) + } + Err(reply) => reply, + } +} + +// -- POST /reward ----------------------------------------------------------------------------- + +async fn reward(state: &AppState, request: Option) -> ControlReply { + if !state.shared.config.control.allow_reward { + // Present so that the later "who trains the fly" work does not change the API. + return ControlReply::error(403, "reward is disabled (control.allow_reward = false)"); + } + let Some(request) = request else { + return ControlReply::error(400, "expected { value, by, source }"); + }; + let (Some(value), Some(by), Some(source)) = ( + request + .get("value") + .and_then(Value::as_f64) + .filter(|value| value.is_finite()), + request.get("by").and_then(Value::as_str), + action_source(request.get("source")), + ) else { + return ControlReply::error(400, "expected { value, by, source }"); + }; + + let (reply, response) = oneshot::channel(); + let command = Command::Reward { + value, + by: by.to_string(), + source: source.to_string(), + reply, + }; + match dispatch(state, command, response).await { + Ok(event_id) => ControlReply::json(202, json!({ "eventId": event_id })), + Err(reply) => reply, + } +} + +// -- POST /chat ------------------------------------------------------------------------------- + +/// `{ by, text, bot? }`: one line for the feed header's chat ring. +/// +/// The kill switch is answered here, because it is pure configuration and a 403 should not need +/// the sim thread. Everything else — the name rule, the sanitizer, the deny list and the two rate +/// limits — is decided on the sim thread, which owns the ring, the limiter and the event log. +/// +/// Status codes, per `docs/control-api.md`: 202 with the event id, 403 while chat is disabled, +/// 422 when a rule refused the line, 429 when a rate limit did, 400 for a malformed body. +async fn chat(state: &AppState, request: Option) -> ControlReply { + if !state.shared.config.chat.enabled { + return ControlReply::error(403, "chat is disabled (chat.enabled = false)"); + } + let Some(request) = request else { + return ControlReply::error(400, "expected { by, text, bot? }"); + }; + let (Some(by), Some(text)) = ( + request.get("by").and_then(Value::as_str), + request.get("text").and_then(Value::as_str), + ) else { + state + .shared + .metrics + .chat_rejected(crate::chat::RejectReason::Malformed); + return ControlReply::error(400, "expected { by, text, bot? }"); + }; + let bot = match request.get("bot") { + None | Some(Value::Null) => false, + Some(Value::Bool(value)) => *value, + Some(_) => return ControlReply::error(400, "bot must be a boolean"), + }; + + let (reply, response) = oneshot::channel(); + let command = Command::Chat { + by: by.to_string(), + text: text.to_string(), + bot, + reply, + }; + match dispatch(state, command, response).await { + Ok(Ok(event_id)) => ControlReply::json(202, json!({ "eventId": event_id })), + Ok(Err(ChatRefusal::Rejected(reason))) => ControlReply::json( + 422, + json!({ "error": format!("chat line refused: {}", reason.as_str()) }), + ), + Ok(Err(ChatRefusal::RateLimited { retry_after_ms })) => { + ControlReply::json(429, json!({ "retryAfterMs": retry_after_ms })) + } + Err(reply) => reply, + } +} + +// -- POST /checkpoint, /pause, /resume -------------------------------------------------------- + +async fn checkpoint(state: &AppState) -> ControlReply { + let (reply, response) = oneshot::channel(); + // A forced checkpoint answers only once the bytes are on disk, so a caller that is about to + // restart the service can rely on it. + match dispatch_with_timeout(state, Command::Checkpoint { reply }, response, None).await { + Ok(Ok(generation)) => ControlReply::json(200, json!({ "generation": generation })), + Ok(Err(message)) => ControlReply::error(500, message), + Err(reply) => reply, + } +} + +async fn pause(state: &AppState) -> ControlReply { + let (reply, response) = oneshot::channel(); + // A pause takes an implicit durable checkpoint, so it can take as long as one write. + match dispatch_with_timeout(state, Command::Pause { reply }, response, None).await { + Ok(status) => ControlReply::json(200, json!({ "status": status })), + Err(reply) => reply, + } +} + +async fn resume(state: &AppState) -> ControlReply { + let (reply, response) = oneshot::channel(); + match dispatch(state, Command::Resume { reply }, response).await { + Ok(status) => ControlReply::json(200, json!({ "status": status })), + Err(reply) => reply, + } +} + +// -- plumbing --------------------------------------------------------------------------------- + +async fn dispatch( + state: &AppState, + command: Command, + response: oneshot::Receiver, +) -> Result { + dispatch_with_timeout(state, command, response, Some(COMMAND_TIMEOUT)).await +} + +/// Queue a command and wait for its reply. +/// +/// The queue is bounded: a full queue is a 503 rather than a wait, because the only way to fill +/// it is a wedged loop or a flood, and neither is improved by blocking the caller. +async fn dispatch_with_timeout( + state: &AppState, + command: Command, + response: oneshot::Receiver, + timeout: Option, +) -> Result { + if let Err(error) = state.commands.try_send(command) { + return Err(match error { + tokio::sync::mpsc::error::TrySendError::Full(_) => { + ControlReply::error(503, unavailable::QUEUE_FULL) + } + tokio::sync::mpsc::error::TrySendError::Closed(_) => { + ControlReply::error(503, unavailable::STOPPED) + } + }); + } + let awaited = match timeout { + Some(timeout) => match tokio::time::timeout(timeout, response).await { + Ok(result) => result, + Err(_) => return Err(ControlReply::error(503, unavailable::TIMED_OUT)), + }, + None => response.await, + }; + awaited.map_err(|_| ControlReply::error(503, unavailable::DROPPED)) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn action_sources_are_the_three_the_contract_names() { + for source in ["chat", "points", "operator"] { + assert_eq!(action_source(Some(&json!(source))), Some(source)); + } + for rejected in [json!("bridge"), json!(1), json!(null), Value::Null] { + assert_eq!(action_source(Some(&rejected)), None); + } + assert_eq!(action_source(None), None); + } +} diff --git a/services/flysim/crates/flysim/src/controlbus.rs b/services/flysim/crates/flysim/src/controlbus.rs new file mode 100644 index 0000000..fe3df27 --- /dev/null +++ b/services/flysim/crates/flysim/src/controlbus.rs @@ -0,0 +1,955 @@ +//! The control API as flybus RPC services with per-client grants (CTRL-01, +//! `docs/design/flybus.md`, "Control over the bus"). +//! +//! Both halves of the encoding live here, so the services flysim registers and the edge that +//! calls them (`fly-control-edge`) cannot drift apart: +//! +//! - [`encode_request`] / [`decode_request`]: a [`ControlRequest`] as `(service, method, +//! payload)`. The service is a [`Family`] in a [`Scope`]; the method is `Control.`. +//! - [`encode_reply`] / [`decode_reply`]: a [`ControlReply`] as an RPC outcome +//! `{"status": , "body": }` or `{"status": , "text": "..."}`, with a body too +//! large for an envelope carried as a `body` artifact instead. +//! +//! The `status` is the `docs/control-api.md` status code of the same request, used as the +//! outcome's vocabulary rather than as transport: a bus caller reads `429 {retryAfterMs}` +//! exactly as an HTTP caller does, and the edge turns it back into HTTP with no table of its own. +//! +//! **Grants.** Bus grants are per service name, so the surface is split into five service +//! families and every participant is granted the families its role needs, by exact name, and +//! nothing else ([`Role`], [`grants`]). [`host_grants`] is the only grant that may register a +//! control service, and it belongs to an in-process participant no socket is bound to. No family +//! has a method that presses a button, edits game memory or changes the reward catalog, and no +//! role is granted `Any`, a prefix, `register`, `publish`, `subscribe` or topic management, so on +//! a router shared with environment or agent services a control client still cannot name them: +//! the "no button endpoint" guarantee is the grant table. + +use std::io::Write as _; +use std::path::{Path, PathBuf}; + +use anyhow::{Context as _, Result, bail}; +use flybus::{ + Artifact, BusError, Client, ClientConfig, Grants, Pattern, Policy, Request, Router, + ServiceConfig, +}; +use serde_json::{Map, Value, json}; + +use crate::AppState; +use crate::control::{ControlReply, ControlRequest, ReplyBody}; + +/// The in-process participant that registers the control services. Never bound to a socket. +pub const HOST: &str = "flysim-control"; +/// The participant `fly-control-edge` connects as, on [`EDGE_SOCKET`]. +pub const EDGE: &str = "fly-control-edge"; +/// `/control-edge.sock`, launcher-bound to [`EDGE`]. +pub const EDGE_SOCKET: &str = "control-edge.sock"; +/// `/control/.sock`, one per native [`Role`], each launcher-bound to that role. +pub const ROLE_SOCKET_DIR: &str = "control"; +/// The one session today: the live fly. +pub const LIVE_SESSION: &str = "main"; +/// The one agent today (the session runtime's agent id). +pub const LIVE_AGENT: &str = "fly"; +/// Every service name starts with this. +pub const PREFIX: &str = "fly.control."; +/// Replies up to this many JSON bytes ride in the envelope; anything larger becomes a `body` +/// artifact. Well under flybus's 65,536-byte envelope, leaving room for the router's ids. An +/// `/events` page can be far larger (4,096 events), `/status` is a few KB. +pub const INLINE_MAX: usize = 48 * 1024; +/// The attachment name of an out-of-line body. +pub const BODY_ARTIFACT: &str = "body"; +/// Per-service bounds. A full service refuses with `BACKPRESSURE` (the edge's 503 "queue is +/// full") instead of queueing without limit; each family has its own, so a stuck checkpoint +/// cannot hold up `/status`. +pub const SERVICE_CONFIG: ServiceConfig = ServiceConfig { + max_queued: 16, + max_in_flight: 16, +}; + +/// A group of control methods behind one service name, the unit a grant names. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] +pub enum Family { + /// `Control.Status`, `Control.Healthz`, `Control.Metrics`, `Control.Events`. Session-scoped: + /// the session's status (the one fly's, while a session has one), its health, its metrics + /// and its event log. + Read, + /// `Control.Status` for one agent. Agent-scoped. With one fly per session it answers what + /// the session's `Control.Status` does; with N flies it is where each fly's own view lives. + Status, + /// `Control.Stimulate`: a sugar pulse into one agent's brain. Agent-scoped. + Sugar, + /// `Control.Reward`: a reinforcement pulse into one agent's plasticity. Agent-scoped. + Reward, + /// `Control.Chat`: a line for the session's on-screen ring. Session-scoped. + Chat, + /// `Control.Checkpoint`, `Control.Pause`, `Control.Resume`. Session-scoped. + Ops, +} + +impl Family { + pub const ALL: [Family; 6] = [ + Family::Read, + Family::Status, + Family::Sugar, + Family::Reward, + Family::Chat, + Family::Ops, + ]; + + pub const fn as_str(self) -> &'static str { + match self { + Family::Read => "read", + Family::Status => "status", + Family::Sugar => "sugar", + Family::Reward => "reward", + Family::Chat => "chat", + Family::Ops => "ops", + } + } + + /// Whether the family acts on one agent (and so has one service per agent). + pub const fn agent_scoped(self) -> bool { + matches!(self, Family::Status | Family::Sugar | Family::Reward) + } + + /// Every method the family's service answers. + pub const fn methods(self) -> &'static [&'static str] { + match self { + Family::Read => &[ + "Control.Status", + "Control.Healthz", + "Control.Metrics", + "Control.Events", + ], + Family::Status => &["Control.Status"], + Family::Sugar => &["Control.Stimulate"], + Family::Reward => &["Control.Reward"], + Family::Chat => &["Control.Chat"], + Family::Ops => &["Control.Checkpoint", "Control.Pause", "Control.Resume"], + } + } +} + +/// One agent (fly) of a session, and the controller port it plays on, if the environment has +/// ports. A Game Boy has one pad, so the live fly is port 0; a console with four controller ports +/// can carry four flies, one per port. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct AgentScope { + pub id: String, + pub port: Option, +} + +impl AgentScope { + pub fn new(id: &str, port: Option) -> AgentScope { + AgentScope { + id: id.to_owned(), + port, + } + } +} + +/// Which agents of a scope a grant covers. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Agents<'a> { + /// Every agent of the session. + All, + /// One agent, by id. + Id(&'a str), + /// The agent bound to one controller port. + Port(u32), +} + +/// Which session, and which agents in it, a set of services addresses. +/// +/// Session-scoped families are `fly.control.s..`; agent-scoped ones are +/// `fly.control.s..a..`, one per agent. With N flies in a session each +/// fly has its own status, sugar and reward services, so a grant can name one fly (or the fly on +/// one port); with M sessions on a router each has its own names, so a grant can name one +/// session. A single-fly deployment is the same design with one agent: multi-fly is +/// configuration, not a new surface. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Scope { + pub session: String, + pub agents: Vec, +} + +impl Scope { + /// The live fly: session [`LIVE_SESSION`], agent [`LIVE_AGENT`] on port 0 (the Game Boy's + /// one pad). + pub fn live() -> Scope { + Scope { + session: LIVE_SESSION.to_owned(), + agents: vec![AgentScope::new(LIVE_AGENT, Some(0))], + } + } + + /// Refuse ids that would not make a valid, unambiguous service name segment, and two agents + /// with one id or on one port. + pub fn validate(&self) -> Result<()> { + let segment = |s: &str| { + !s.is_empty() + && s.len() <= 48 + && s.bytes().all(|c| { + c.is_ascii_lowercase() || c.is_ascii_digit() || matches!(c, b'_' | b'-') + }) + }; + if !segment(&self.session) { + bail!( + "control scope: session id {:?} is not [a-z0-9_-]{{1,48}}", + self.session + ); + } + if self.agents.is_empty() { + bail!("control scope: no agents"); + } + for (index, agent) in self.agents.iter().enumerate() { + if !segment(&agent.id) { + bail!("control scope: agent id {:?} is not [a-z0-9_-]{{1,48}}", agent.id); + } + for other in &self.agents[..index] { + if other.id == agent.id { + bail!("control scope: agent {:?} twice", agent.id); + } + if agent.port.is_some() && other.port == agent.port { + bail!( + "control scope: agents {:?} and {:?} on one port", + other.id, + agent.id + ); + } + } + } + Ok(()) + } + + /// The agent ids, in order. + pub fn agent_ids(&self) -> impl Iterator { + self.agents.iter().map(|agent| agent.id.as_str()) + } + + /// The agent bound to `port`. + pub fn agent_on_port(&self, port: u32) -> Option<&str> { + self.agents + .iter() + .find(|agent| agent.port == Some(port)) + .map(|agent| agent.id.as_str()) + } + + /// The service name of a session-scoped `family`, or of an agent-scoped one for `agent`. + pub fn service(&self, family: Family, agent: &str) -> String { + if family.agent_scoped() { + format!("{PREFIX}s.{}.a.{agent}.{}", self.session, family.as_str()) + } else { + format!("{PREFIX}s.{}.{}", self.session, family.as_str()) + } + } + + /// Every service in this scope, with its family and its agent (`None` for a session-scoped + /// one): what the host registers. + pub fn services(&self) -> Vec<(Family, Option<&str>, String)> { + let mut out = Vec::new(); + for family in Family::ALL { + if family.agent_scoped() { + for agent in self.agent_ids() { + out.push((family, Some(agent), self.service(family, agent))); + } + } else { + out.push((family, None, self.service(family, ""))); + } + } + out + } + + /// The services of `families` in this scope: session-scoped ones, and agent-scoped ones for + /// the `agents` selected. A port no agent is bound to selects no agent. + pub fn services_of(&self, families: &[Family], agents: Agents<'_>) -> Vec { + let selected = match agents { + Agents::All => None, + Agents::Id(id) => Some(Some(id)), + Agents::Port(port) => Some(self.agent_on_port(port)), + }; + self.services() + .into_iter() + .filter(|(family, agent, _)| { + families.contains(family) + && match (agent, selected) { + (Some(agent), Some(selected)) => selected == Some(*agent), + _ => true, + } + }) + .map(|(_, _, name)| name) + .collect() + } +} + +/// The clients of the control API today, by what they need (`docs/design/flybus.md`, "Control +/// over the bus", grant table). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum Role { + /// The broadcast page: it waits for `/healthz` and may read `/status`. + Stage, + /// The Twitch bridge: reads, sugar from points and chat commands, on-screen chat lines. + Bridge, + /// The watchdog, the probation and shadow guards, the loop-recover ladder and the stream + /// check: reads only. A restart is systemd's, never a control call. + Watchdog, + /// The operator's own hand: everything the control API has. + Operator, + /// `fly-control-edge`, which serves the unchanged HTTP surface on `:7401`. Loopback HTTP has + /// no caller identity, so the edge carries exactly the authority `:7401` has today: every + /// family. Narrowing a client is moving it off HTTP onto its own role. + Edge, +} + +impl Role { + pub const ALL: [Role; 5] = [ + Role::Stage, + Role::Bridge, + Role::Watchdog, + Role::Operator, + Role::Edge, + ]; + /// The roles with a socket of their own under [`ROLE_SOCKET_DIR`]. + pub const NATIVE: [Role; 4] = [Role::Stage, Role::Bridge, Role::Watchdog, Role::Operator]; + + /// The participant id the router binds to this role's socket. + pub const fn participant(self) -> &'static str { + match self { + Role::Stage => "fly-stage", + Role::Bridge => "fly-bridge", + Role::Watchdog => "fly-watchdog", + Role::Operator => "fly-operator", + Role::Edge => EDGE, + } + } + + /// The socket file name (under [`ROLE_SOCKET_DIR`] for native roles). + pub const fn socket_name(self) -> &'static str { + match self { + Role::Stage => "stage.sock", + Role::Bridge => "bridge.sock", + Role::Watchdog => "watchdog.sock", + Role::Operator => "operator.sock", + Role::Edge => EDGE_SOCKET, + } + } + + /// The families this role may call. + pub const fn families(self) -> &'static [Family] { + match self { + Role::Stage | Role::Watchdog => &[Family::Read, Family::Status], + Role::Bridge => &[Family::Read, Family::Status, Family::Sugar, Family::Chat], + Role::Operator | Role::Edge => &Family::ALL, + } + } +} + +/// `/control-edge.sock` or `/control/.sock`. +pub fn socket_path(bus_dir: &Path, role: Role) -> PathBuf { + match role { + Role::Edge => bus_dir.join(EDGE_SOCKET), + native => bus_dir.join(ROLE_SOCKET_DIR).join(native.socket_name()), + } +} + +/// Exact `call` grants on `families` in `scope`, for the `agents` selected, nothing else. +pub fn call_grants(scope: &Scope, families: &[Family], agents: Agents<'_>) -> Grants { + Grants { + call: scope + .services_of(families, agents) + .iter() + .map(|name| Pattern::exact(name)) + .collect(), + ..Grants::default() + } +} + +/// What `role` may do: call its families' services in `scope`, for every agent, by exact name. +pub fn grants(role: Role, scope: &Scope) -> Grants { + call_grants(scope, role.families(), Agents::All) +} + +/// What `role` may do, limited to the `agents` selected: the same families, but the agent-scoped +/// ones only for that fly (or the fly on that port). A bridge for one fly of several, say. +pub fn grants_for(role: Role, scope: &Scope, agents: Agents<'_>) -> Grants { + call_grants(scope, role.families(), agents) +} + +/// A player backing one fly (by id or by port) in a multi-fly session: read the session, see +/// and sugar that fly, nothing else. Not wired to a socket yet; it is how per-agent scoping is +/// granted when players arrive. +pub fn player_grants(scope: &Scope, agents: Agents<'_>) -> Grants { + call_grants(scope, &[Family::Read, Family::Status, Family::Sugar], agents) +} + +/// The host's grant: register every control service of `scope`, by exact name, and nothing else. +pub fn host_grants(scope: &Scope) -> Grants { + Grants { + register: scope + .services() + .iter() + .map(|(_, _, name)| Pattern::exact(name)) + .collect(), + ..Grants::default() + } +} + +/// `base` plus the control participants: the host and every [`Role`]. +pub fn policy(base: Policy, scope: &Scope) -> Policy { + let mut policy = base.client(HOST, host_grants(scope)); + for role in Role::ALL { + policy = policy.client(role.participant(), grants(role, scope)); + } + policy +} + +// -- encoding --------------------------------------------------------------------------------- + +/// A request as `(family, method, payload)`. +pub fn encode_request(request: &ControlRequest) -> (Family, &'static str, Map) { + let mut payload = Map::new(); + let mut body = |value: &Option| { + if let Some(value) = value { + payload.insert("request".to_owned(), value.clone()); + } + }; + let (family, method) = match request { + ControlRequest::Status => (Family::Read, "Control.Status"), + ControlRequest::Healthz => (Family::Read, "Control.Healthz"), + ControlRequest::Metrics => (Family::Read, "Control.Metrics"), + ControlRequest::Events { .. } => (Family::Read, "Control.Events"), + ControlRequest::Stimulate { body: value } => { + body(value); + (Family::Sugar, "Control.Stimulate") + } + ControlRequest::Reward { body: value } => { + body(value); + (Family::Reward, "Control.Reward") + } + ControlRequest::Chat { body: value } => { + body(value); + (Family::Chat, "Control.Chat") + } + ControlRequest::Checkpoint => (Family::Ops, "Control.Checkpoint"), + ControlRequest::Pause => (Family::Ops, "Control.Pause"), + ControlRequest::Resume => (Family::Ops, "Control.Resume"), + }; + if let ControlRequest::Events { since, limit } = request { + if let Some(since) = since { + payload.insert("since".to_owned(), Value::String(since.clone())); + } + if let Some(limit) = limit { + payload.insert("limit".to_owned(), Value::String(limit.clone())); + } + } + (family, method, payload) +} + +/// Why a bus request could not be read: answered as a control-API reply. +#[derive(Debug, Clone, PartialEq)] +pub struct Undecodable(pub ControlReply); + +/// The request a `(family, method, payload)` names. A method the family does not have is a 404, +/// as an unknown route is over HTTP; an unknown or mistyped payload field is a 400. +pub fn decode_request( + family: Family, + method: &str, + payload: &Map, +) -> Result { + if !family.methods().contains(&method) { + return Err(Undecodable(ControlReply::error( + 404, + format!( + "no such method: {method} on the {} service", + family.as_str() + ), + ))); + } + let allowed: &[&str] = match method { + "Control.Events" => &["since", "limit"], + "Control.Stimulate" | "Control.Reward" | "Control.Chat" => &["request"], + _ => &[], + }; + if let Some(field) = payload.keys().find(|key| !allowed.contains(&key.as_str())) { + return Err(Undecodable(ControlReply::error( + 400, + format!("{method}: unknown field {field:?}"), + ))); + } + let string = |key: &str| -> Result, Undecodable> { + match payload.get(key) { + None => Ok(None), + Some(Value::String(value)) => Ok(Some(value.clone())), + Some(_) => Err(Undecodable(ControlReply::error( + 400, + format!("{method}: {key} must be a string"), + ))), + } + }; + let body = || payload.get("request").cloned(); + Ok(match method { + "Control.Status" => ControlRequest::Status, + "Control.Healthz" => ControlRequest::Healthz, + "Control.Metrics" => ControlRequest::Metrics, + "Control.Events" => ControlRequest::Events { + since: string("since")?, + limit: string("limit")?, + }, + "Control.Stimulate" => ControlRequest::Stimulate { body: body() }, + "Control.Reward" => ControlRequest::Reward { body: body() }, + "Control.Chat" => ControlRequest::Chat { body: body() }, + "Control.Checkpoint" => ControlRequest::Checkpoint, + "Control.Pause" => ControlRequest::Pause, + "Control.Resume" => ControlRequest::Resume, + _ => unreachable!("every method of every family is listed above"), + }) +} + +/// A body too large for an envelope: its bytes and content type. +pub type OutOfLine = (Vec, &'static str); + +/// A reply as an outcome, plus the bytes of an out-of-line body (and their content type) when +/// the body is larger than [`INLINE_MAX`]. +pub fn encode_reply(reply: &ControlReply) -> (Map, Option) { + let mut outcome = Map::new(); + outcome.insert("status".to_owned(), json!(reply.status)); + match &reply.body { + ReplyBody::Json(value) => { + let bytes = serde_json::to_vec(value).unwrap_or_default(); + if bytes.len() <= INLINE_MAX { + outcome.insert("body".to_owned(), value.clone()); + (outcome, None) + } else { + outcome.insert("bodyArtifact".to_owned(), json!("application/json")); + (outcome, Some((bytes, "application/json"))) + } + } + ReplyBody::Text(text) => { + if text.len() <= INLINE_MAX { + outcome.insert("text".to_owned(), Value::String(text.clone())); + (outcome, None) + } else { + outcome.insert("bodyArtifact".to_owned(), json!("text/plain")); + (outcome, Some((text.clone().into_bytes(), "text/plain"))) + } + } + } +} + +/// The reply an outcome carries; `artifact` is the `body` attachment's bytes, read by the caller +/// only when the outcome names one. +pub fn decode_reply( + outcome: &Map, + artifact: Option>, +) -> Result { + let status = outcome + .get("status") + .and_then(Value::as_u64) + .filter(|status| (100..=599).contains(status)) + .ok_or("a control outcome without a status")? as u16; + if let Some(value) = outcome.get("body") { + return Ok(ControlReply::json(status, value.clone())); + } + if let Some(Value::String(text)) = outcome.get("text") { + return Ok(ControlReply::text(status, text.clone())); + } + match outcome.get("bodyArtifact").and_then(Value::as_str) { + Some(kind) => { + let bytes = artifact.ok_or("a control outcome whose body artifact is missing")?; + match kind { + "application/json" => serde_json::from_slice(&bytes) + .map(|value| ControlReply::json(status, value)) + .map_err(|error| format!("a control body artifact is not JSON: {error}")), + "text/plain" => String::from_utf8(bytes) + .map(|text| ControlReply::text(status, text)) + .map_err(|_| "a control text artifact is not UTF-8".to_owned()), + other => Err(format!("a control body artifact of kind {other:?}")), + } + } + None => Err("a control outcome without a body".to_owned()), + } +} + +/// Whether an outcome's body travels as an artifact. +pub fn has_body_artifact(outcome: &Map) -> bool { + outcome.contains_key("bodyArtifact") +} + +// -- the host --------------------------------------------------------------------------------- + +/// The registered control services. Dropping it unregisters them and stops answering. +pub struct ControlHost { + tasks: Vec>, + _client: Client, +} + +impl Drop for ControlHost { + fn drop(&mut self) { + for task in &self.tasks { + task.abort(); + } + } +} + +/// Connect to `router` in process as [`HOST`] and register every service of `scope`, each +/// answered by [`crate::control::handle`] over `state`. +/// +/// One flysim process runs one fly, so its scope is [`Scope::live`] and every agent-scoped +/// service answers for that fly. A multi-fly host would hand each agent's services that agent's +/// state; the names, the grants and the encoding stay as they are. +/// +/// Requests are taken in the order the router dispatches them (FIFO per service) and answered +/// concurrently, each in a task of its own, up to [`SERVICE_CONFIG`]'s in-flight bound: a pause +/// waiting on a durable write does not hold up a resume, as two HTTP requests do not wait on each +/// other. A caller that cancels or goes away has its result discarded by the router. +pub async fn serve(router: &Router, state: AppState, scope: &Scope) -> Result { + scope.validate()?; + let transport = router.connect_in_memory_as(HOST); + let client = Client::connect(transport, ClientConfig::new(HOST, router.store_root())) + .await + .map_err(|error| anyhow::anyhow!("the control host could not connect: {error}"))?; + let mut tasks = Vec::new(); + for (family, _agent, name) in scope.services() { + let mut service = client + .register(&name, SERVICE_CONFIG) + .await + .map_err(|error| anyhow::anyhow!("registering {name}: {error}")) + .context("starting the control services")?; + let state = state.clone(); + let client = client.clone(); + tasks.push(tokio::spawn(async move { + while let Some(request) = service.next().await { + let state = state.clone(); + let client = client.clone(); + tokio::spawn(async move { answer(&client, &state, family, request).await }); + } + })); + } + tracing::info!( + session = %scope.session, + agents = ?scope.agents, + services = scope.services().len(), + "control services registered on the bus" + ); + Ok(ControlHost { + tasks, + _client: client, + }) +} + +async fn answer(client: &Client, state: &AppState, family: Family, request: Request) { + let reply = match decode_request(family, request.method(), request.payload()) { + Ok(decoded) => crate::control::handle(state, decoded).await, + Err(Undecodable(reply)) => reply, + }; + let (outcome, out_of_line) = encode_reply(&reply); + let result = match out_of_line { + None => request.reply(outcome, &[]).await, + Some((bytes, content_type)) => match seal(client, &bytes, content_type).await { + Ok(artifact) => request.reply(outcome, &[(BODY_ARTIFACT, &artifact)]).await, + Err(error) => { + tracing::warn!(%error, "a control reply body could not be sealed"); + let (outcome, _) = encode_reply(&ControlReply::error( + 503, + "the reply could not be stored on the bus", + )); + request.reply(outcome, &[]).await + } + }, + }; + if let Err(error) = result { + // The caller is gone or the bus is closing; there is no one left to tell. + tracing::debug!(%error, method = request.method(), "a control reply was not delivered"); + } +} + +async fn seal(client: &Client, bytes: &[u8], content_type: &str) -> Result { + let mut writer = client + .artifacts() + .allocate(bytes.len() as u64, content_type) + .await?; + writer + .write_all(bytes) + .map_err(|error| BusError::new(flybus::ErrorCode::StoreFailure, error.to_string()))?; + writer.seal().await +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Words no control service or method may contain (`docs/control-api.md`, the structural + /// guarantee; the same list `api.rs` checks its routes against). + const FORBIDDEN: [&str; 10] = [ + "button", "buttons", "input", "press", "joypad", "key", "poke", "write", "memory", + "catalog", + ]; + + fn two_flies() -> Scope { + Scope { + session: "arena".to_owned(), + agents: vec![ + AgentScope::new("fly-a", Some(1)), + AgentScope::new("fly-b", Some(2)), + ], + } + } + + fn names(scope: &Scope) -> Vec { + scope.services().into_iter().map(|(_, _, n)| n).collect() + } + + #[test] + fn no_service_or_method_names_an_input() { + for scope in [Scope::live(), two_flies()] { + for (family, _, name) in scope.services() { + assert!(flybus::wire::is_name(&name), "{name} is not a bus name"); + assert!(name.starts_with(PREFIX), "{name}"); + for method in family.methods() { + let lowered = format!("{name} {method}").to_ascii_lowercase(); + for forbidden in FORBIDDEN { + assert!( + !lowered.contains(forbidden), + "{lowered} contains {forbidden}" + ); + } + } + } + } + // One method per control-api.md endpoint (the `/status.json` alias is HTTP-only), plus + // the per-agent status. + let mut methods: Vec<&str> = Family::ALL + .iter() + .flat_map(|f| f.methods()) + .copied() + .collect(); + assert_eq!(methods.len(), 11, "{methods:?}"); + methods.sort(); + methods.dedup(); + assert_eq!(methods.len(), 10, "{methods:?}"); + } + + #[test] + fn the_live_names_are_these() { + assert_eq!( + names(&Scope::live()), + [ + "fly.control.s.main.read", + "fly.control.s.main.a.fly.status", + "fly.control.s.main.a.fly.sugar", + "fly.control.s.main.a.fly.reward", + "fly.control.s.main.chat", + "fly.control.s.main.ops", + ] + ); + } + + #[test] + fn every_grant_is_an_exact_call_on_a_control_service_and_nothing_else() { + for scope in [Scope::live(), two_flies()] { + let services = names(&scope); + let mut all: Vec = Role::ALL.iter().map(|r| grants(*r, &scope)).collect(); + for role in Role::ALL { + all.push(grants_for(role, &scope, Agents::Port(1))); + all.push(grants_for(role, &scope, Agents::Id("fly"))); + } + all.push(player_grants(&scope, Agents::Id(&scope.agents[0].id))); + all.push(player_grants(&scope, Agents::Port(7))); + for grant in &all { + assert!(grant.register.is_empty() && grant.publish.is_empty()); + assert!(grant.subscribe.is_empty() && grant.manage_topics.is_empty()); + for pattern in &grant.call { + match pattern { + Pattern::Exact(name) => assert!(services.contains(name), "{name}"), + other => panic!("a non-exact grant: {other:?}"), + } + } + } + let host = host_grants(&scope); + assert!(host.call.is_empty() && host.publish.is_empty() && host.subscribe.is_empty()); + assert!(host.manage_topics.is_empty()); + assert_eq!(host.register.len(), services.len()); + for pattern in &host.register { + assert!(matches!(pattern, Pattern::Exact(name) if services.contains(name))); + } + } + } + + #[test] + fn the_grant_table() { + let scope = Scope::live(); + let can = |role: Role, family: Family| { + let name = scope.service(family, LIVE_AGENT); + grants(role, &scope).call.iter().any(|p| p.matches(&name)) + }; + use Family::*; + let table = [ + (Role::Stage, [true, true, false, false, false, false]), + (Role::Bridge, [true, true, true, false, true, false]), + (Role::Watchdog, [true, true, false, false, false, false]), + (Role::Operator, [true, true, true, true, true, true]), + (Role::Edge, [true, true, true, true, true, true]), + ]; + for (role, row) in table { + for (family, expected) in [Read, Status, Sugar, Reward, Chat, Ops].into_iter().zip(row) + { + assert_eq!(can(role, family), expected, "{role:?} {family:?}"); + } + } + } + + #[test] + fn a_player_sugars_only_their_own_fly_by_id_or_by_port() { + let scope = two_flies(); + for grant in [ + player_grants(&scope, Agents::Id("fly-a")), + player_grants(&scope, Agents::Port(1)), + ] { + let allowed = |name: &str| grant.call.iter().any(|p| p.matches(name)); + assert!(allowed(&scope.service(Family::Sugar, "fly-a"))); + assert!(allowed(&scope.service(Family::Status, "fly-a"))); + assert!(!allowed(&scope.service(Family::Sugar, "fly-b"))); + assert!(!allowed(&scope.service(Family::Status, "fly-b"))); + assert!(allowed(&scope.service(Family::Read, ""))); + assert!(!allowed(&scope.service(Family::Chat, ""))); + assert!(!allowed(&scope.service(Family::Ops, ""))); + assert!(!allowed(&scope.service(Family::Reward, "fly-a"))); + } + // A port nobody plays on reaches no fly, only the session's read. + let empty = player_grants(&scope, Agents::Port(4)); + assert_eq!(empty.call, vec![Pattern::exact(&scope.service(Family::Read, ""))]); + } + + #[test] + fn a_role_limited_to_one_fly_keeps_its_families_for_that_fly_only() { + let scope = two_flies(); + let bridge_b = grants_for(Role::Bridge, &scope, Agents::Port(2)); + let allowed = |name: &str| bridge_b.call.iter().any(|p| p.matches(name)); + assert!(allowed(&scope.service(Family::Sugar, "fly-b"))); + assert!(!allowed(&scope.service(Family::Sugar, "fly-a"))); + assert!(allowed(&scope.service(Family::Chat, ""))); + assert!(!allowed(&scope.service(Family::Reward, "fly-b"))); + // The live, single-fly table is the same table with one agent. + let live = Scope::live(); + assert_eq!( + grants_for(Role::Bridge, &live, Agents::Port(0)), + grants(Role::Bridge, &live) + ); + } + + #[test] + fn scopes_refuse_ids_that_would_break_a_name() { + for (session, agent) in [ + ("", "fly"), + ("a.b", "fly"), + ("main", "Fly"), + ("main", "a.b"), + ] { + let scope = Scope { + session: session.to_owned(), + agents: vec![AgentScope::new(agent, None)], + }; + assert!(scope.validate().is_err(), "{session:?} {agent:?}"); + } + assert!(Scope::live().validate().is_ok()); + assert!(two_flies().validate().is_ok()); + let mut same_port = two_flies(); + same_port.agents[1].port = Some(1); + assert!(same_port.validate().is_err()); + let mut same_id = two_flies(); + same_id.agents[1].id = "fly-a".to_owned(); + assert!(same_id.validate().is_err()); + let mut no_ports = two_flies(); + no_ports.agents.iter_mut().for_each(|a| a.port = None); + assert!(no_ports.validate().is_ok()); + } + + #[test] + fn requests_round_trip_through_the_encoding() { + let requests = [ + ControlRequest::Status, + ControlRequest::Healthz, + ControlRequest::Metrics, + ControlRequest::Events { + since: None, + limit: None, + }, + ControlRequest::Events { + since: Some("12".into()), + limit: Some("x".into()), + }, + ControlRequest::Stimulate { body: None }, + ControlRequest::Stimulate { + body: Some(json!({"by": "a", "source": "chat"})), + }, + ControlRequest::Reward { + body: Some(json!([1, 2])), + }, + ControlRequest::Chat { + body: Some(json!("text")), + }, + ControlRequest::Checkpoint, + ControlRequest::Pause, + ControlRequest::Resume, + ]; + for request in requests { + let (family, method, payload) = encode_request(&request); + assert_eq!( + decode_request(family, method, &payload), + Ok(request.clone()) + ); + } + // An agent's status service answers the status method. + assert_eq!( + decode_request(Family::Status, "Control.Status", &Map::new()), + Ok(ControlRequest::Status) + ); + assert!(decode_request(Family::Status, "Control.Healthz", &Map::new()).is_err()); + } + + #[test] + fn a_method_on_the_wrong_service_is_a_404_and_a_stray_field_a_400() { + let Err(Undecodable(reply)) = decode_request(Family::Read, "Control.Pause", &Map::new()) + else { + panic!("decoded"); + }; + assert_eq!(reply.status, 404); + let Err(Undecodable(reply)) = decode_request(Family::Read, "Control.Press", &Map::new()) + else { + panic!("decoded"); + }; + assert_eq!(reply.status, 404); + let mut payload = Map::new(); + payload.insert("buttons".into(), json!(1)); + let Err(Undecodable(reply)) = decode_request(Family::Sugar, "Control.Stimulate", &payload) + else { + panic!("decoded"); + }; + assert_eq!(reply.status, 400); + let mut payload = Map::new(); + payload.insert("since".into(), json!(3)); + assert!(decode_request(Family::Read, "Control.Events", &payload).is_err()); + } + + #[test] + fn replies_round_trip_inline_and_out_of_line() { + let big = "x".repeat(INLINE_MAX + 1); + for reply in [ + ControlReply::json(202, json!({"eventId": 7})), + ControlReply::json(429, json!({"retryAfterMs": 1250.5})), + ControlReply::text(200, "# HELP x\nx 1\n".into()), + ControlReply::json(200, json!({ "events": [big.clone()] })), + ControlReply::text(200, big.clone()), + ] { + let (outcome, artifact) = encode_reply(&reply); + assert_eq!(has_body_artifact(&outcome), artifact.is_some()); + let encoded = serde_json::to_vec(&outcome).unwrap(); + assert!( + encoded.len() <= INLINE_MAX + 64, + "{} bytes inline", + encoded.len() + ); + let decoded = decode_reply(&outcome, artifact.map(|(bytes, _)| bytes)).unwrap(); + assert_eq!(decoded, reply); + } + assert!(decode_reply(&Map::new(), None).is_err()); + } +} diff --git a/services/flysim/crates/flysim/src/lib.rs b/services/flysim/crates/flysim/src/lib.rs index ceb0721..9888b26 100644 --- a/services/flysim/crates/flysim/src/lib.rs +++ b/services/flysim/crates/flysim/src/lib.rs @@ -20,10 +20,17 @@ //! //! There is deliberately **no endpoint that presses buttons**. The decoder is the only writer of //! joypad state; `api::ROUTES` is the whole surface and `tests/api.rs` asserts on it. +//! +//! With `FLY_CONTROL_VIA=bus` the control API is not bound here: `control` answers the same +//! requests as RPC services on the embedded router (`controlbus`, `bus`), and `fly-control-edge` +//! serves `:7401` with this crate's own `api` router calling them. pub mod api; +pub mod bus; pub mod chat; pub mod config; +pub mod control; +pub mod controlbus; pub mod eventlog; pub mod feed; pub mod feedbus; @@ -46,7 +53,7 @@ use std::sync::Arc; use anyhow::{Context, Result}; use tokio::sync::{mpsc, watch}; -use crate::config::{Config, FeedVia}; +use crate::config::{Config, ControlVia, FeedVia}; use crate::eventlog::{EventRing, now_wall_ms}; use crate::simloop::{COMMAND_QUEUE, Command, Shared, Sim, booting_snapshot}; use crate::snapshot::Snapshot; @@ -129,6 +136,7 @@ where let control_addr = config.control.bind; let metrics_addr = config.control.metrics_bind; let via = config.feed.via; + let control_via = config.control.via; let listeners = runtime.block_on(async { // In bus mode the feed port belongs to `fly-edge`; binding it here would take it away. let feed = match via { @@ -139,9 +147,15 @@ where ), FeedVia::Bus => None, }; - let control = tokio::net::TcpListener::bind(control_addr) - .await - .with_context(|| format!("binding the control listener on {control_addr}"))?; + // Likewise the control port belongs to `fly-control-edge` when control rides the bus. + let control = match control_via { + ControlVia::Direct => Some( + tokio::net::TcpListener::bind(control_addr) + .await + .with_context(|| format!("binding the control listener on {control_addr}"))?, + ), + ControlVia::Bus => None, + }; let metrics = match metrics_addr { Some(addr) => Some( tokio::net::TcpListener::bind(addr) @@ -157,6 +171,7 @@ where feed = %feed_addr, feed_via = via.as_str(), control = %control_addr, + control_via = control_via.as_str(), metrics = ?metrics_addr, "listening" ); @@ -171,25 +186,38 @@ where } // The bus gets a runtime of its own, so neither its router nor the artifact copies can take // a worker from the control API; and it is fed from the watch slot, never from the sim thread. - let bus_runtime = match via { - FeedVia::Direct => None, - FeedVia::Bus => { - let bus_runtime = tokio::runtime::Builder::new_multi_thread() - .worker_threads(2) - .thread_name("flysim-bus") - .enable_all() - .build() - .context("building the bus runtime")?; - let bus = bus_runtime.block_on(feedbus::start_router(&config.feed.bus_dir))?; + // One router for whatever rides the bus (`bus`): the feed publisher and the control + // services are two participants on it. + let uses = bus::Uses { + feed: via == FeedVia::Bus, + control: control_via == ControlVia::Bus, + }; + let bus_runtime = if uses.feed || uses.control { + let bus_runtime = tokio::runtime::Builder::new_multi_thread() + .worker_threads(2) + .thread_name("flysim-bus") + .enable_all() + .build() + .context("building the bus runtime")?; + let scope = controlbus::Scope::live(); + let bus = bus_runtime.block_on(bus::start(&config.feed.bus_dir, uses, &scope))?; + if uses.feed { bus_runtime.spawn(feedbus::run_publisher( bus.router.clone(), state.snapshots.clone(), Arc::clone(&state.shared.metrics), )); - Some((bus_runtime, bus)) } + let control_host = if uses.control { + Some(bus_runtime.block_on(controlbus::serve(&bus.router, state.clone(), &scope))?) + } else { + None + }; + Some((bus_runtime, bus, control_host)) + } else { + None }; - { + if let Some(control_listener) = control_listener { let state = state.clone(); runtime.spawn(async move { if let Err(error) = axum::serve(control_listener, api::router(state)).await { @@ -210,10 +238,11 @@ where let notifier = sdnotify::Notifier::from_env(); let result = sim(shared, snapshots_tx, command_rx, ¬ifier); - if let Some((bus_runtime, bus)) = bus_runtime { + if let Some((bus_runtime, bus, control_host)) = bus_runtime { // The publisher ends by itself once the watch sender is gone; stopping the runtime under // it, rather than the router first, keeps a last in-flight publish from being logged as - // a refusal. The edge sees the socket close either way. + // a refusal. The edges see their sockets close either way. + drop(control_host); drop(bus); bus_runtime.shutdown_timeout(std::time::Duration::from_secs(1)); }