#[path = "steps/caller.rs"]
mod caller;
#[path = "steps/limits.rs"]
mod limits;
#[path = "steps/live.rs"]
mod live;
#[cfg(feature = "rmcp")]
#[path = "steps/mcp.rs"]
mod mcp;
#[path = "steps/model.rs"]
mod model;
#[cfg(feature = "monty-pool")]
#[path = "steps/pool.rs"]
mod pool;
#[path = "steps/schema.rs"]
mod schema;
#[path = "steps/spans.rs"]
mod spans;
#[path = "steps/test_host.rs"]
mod test_host;
use std::fmt;
use std::time::{Duration, Instant};
use cucumber::World as _;
use cucumber::writer::Stats as _;
use futures::future::{self, BoxFuture, FutureExt};
use ghostmode::backend::{Backend, Monty};
use ghostmode::host::Tool;
use ghostmode::{Builder, Limits, Sandbox, Status};
use tokio::runtime::{Handle, RuntimeFlavor};
use tracing::Dispatch;
use tracing::instrument::WithSubscriber;
#[derive(Default, cucumber::World)]
struct World {
host: test_host::TestHost,
execute_wait: Option<Duration>,
poll_wait: Option<Duration>,
limits: Option<Limits>,
signing_key: Option<[u8; 32]>,
backend: TestBackend,
sandbox: Option<Box<dyn AnySandbox>>,
#[cfg(feature = "monty-pool")]
other_sandboxes: Vec<Box<dyn AnySandbox>>,
status: serde_json::Value,
live_replies: Vec<Result<String, String>>,
cancel_returned: Option<bool>,
dump: Option<Vec<u8>>,
caller_error: Option<ghostmode::Error>,
build_after_failed_restore: Option<BoxFuture<'static, Box<dyn AnySandbox>>>,
host_error: Option<Box<dyn std::error::Error + Send + Sync>>,
request_duration: Duration,
dispatch: Dispatch,
span_capture: spans::SpanCapture,
#[cfg(feature = "rmcp")]
mcp: mcp::Connection,
}
impl fmt::Debug for World {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("World")
}
}
enum Request {
Execute { code: String, restart: bool },
Poll(u64),
Cancel(u64),
Reset,
Dump,
}
enum Reply {
Status(Status),
Cancel(bool),
Reset,
Dump(Result<Vec<u8>, ghostmode::Error>),
}
#[derive(Clone, Default)]
enum TestBackend {
#[default]
Monty,
#[cfg(feature = "monty-pool")]
MontyPool(ghostmode::backend::MontyPool),
}
type NewSandbox =
Result<Box<dyn AnySandbox>, (ghostmode::Error, BoxFuture<'static, Box<dyn AnySandbox>>)>;
trait AnySandbox: Send + fmt::Debug {
fn reply(&mut self, request: Request) -> BoxFuture<'_, Reply>;
fn tools(&self) -> &[Tool];
}
impl<B: Backend + Send + 'static> AnySandbox for Sandbox<test_host::TestHost, B> {
fn reply(&mut self, request: Request) -> BoxFuture<'_, Reply> {
async move {
match request {
Request::Execute { code, restart } => {
Reply::Status(self.execute(&code, restart).await)
}
Request::Poll(run_id) => Reply::Status(self.poll(run_id).await),
Request::Cancel(run_id) => Reply::Cancel(self.cancel(run_id).await),
Request::Reset => {
self.reset().await;
Reply::Reset
}
Request::Dump => Reply::Dump(self.dump().await),
}
}
.boxed()
}
fn tools(&self) -> &[Tool] {
Sandbox::tools(self)
}
}
impl World {
async fn new_sandbox(&self, dump: Option<&[u8]>) -> NewSandbox {
match &self.backend {
TestBackend::Monty => build(self.builder(Monty::default()), dump).await,
#[cfg(feature = "monty-pool")]
TestBackend::MontyPool(pool) => build(self.builder(pool.clone()), dump).await,
}
}
fn builder<B: Backend>(&self, backend: B) -> Builder<test_host::TestHost, B> {
let mut builder = Builder::new(self.host.clone(), backend);
if let Some(wait) = self.execute_wait {
builder = builder.execute_wait(wait);
}
if let Some(wait) = self.poll_wait {
builder = builder.poll_wait(wait);
}
if let Some(limits) = self.limits.clone() {
builder = builder.limits(limits);
}
if let Some(key) = self.signing_key {
builder = builder.signing_key(key);
}
builder
}
async fn send(&mut self, request: Request) {
let mut sandbox = self.take_sandbox().await;
let answer = async move {
let reply = sandbox.reply(request).await;
(sandbox, reply)
}
.with_subscriber(self.dispatch.clone());
let started = Instant::now();
let multi_thread = Handle::try_current()
.is_ok_and(|handle| handle.runtime_flavor() == RuntimeFlavor::MultiThread);
let (sandbox, reply) = if multi_thread {
tokio::spawn(answer).await.expect("sandbox task")
} else {
answer.await
};
self.request_duration = started.elapsed();
self.sandbox = Some(sandbox);
match reply {
Reply::Status(status) => {
self.status = serde_json::to_value(status).expect("status serializes");
}
Reply::Cancel(was_open) => self.cancel_returned = Some(was_open),
Reply::Reset => {}
Reply::Dump(Ok(bytes)) => self.dump = Some(bytes),
Reply::Dump(Err(error)) => self.caller_error = Some(error),
}
}
async fn take_sandbox(&mut self) -> Box<dyn AnySandbox> {
match self.sandbox.take() {
Some(sandbox) => sandbox,
None => match self.new_sandbox(None).await {
Ok(sandbox) => sandbox,
Err((error, _)) => panic!("a sandbox without a dump fails to build: {error:?}"),
},
}
}
async fn sandbox_tools(&mut self) -> &[Tool] {
let sandbox = self.take_sandbox().await;
self.sandbox.insert(sandbox).tools()
}
async fn restore(&mut self, bytes: &[u8]) {
match self.new_sandbox(Some(bytes)).await {
Ok(sandbox) => self.sandbox = Some(sandbox),
Err((error, build)) => {
self.caller_error = Some(error);
self.build_after_failed_restore = Some(build);
}
}
}
}
async fn build<B: Backend + Send + 'static>(
builder: Builder<test_host::TestHost, B>,
dump: Option<&[u8]>,
) -> NewSandbox {
let sandbox = match dump {
Some(bytes) => builder.restore(bytes).await.map_err(|(error, builder)| {
let build = async move { Box::new(builder.build().await) as Box<dyn AnySandbox> };
(error, build.boxed())
})?,
None => builder.build().await,
};
Ok(Box::new(sandbox))
}
async fn run_scenarios(on_tokio: bool, backend: TestBackend) -> bool {
let run_rmcp = on_tokio && cfg!(feature = "rmcp");
let backend_tag = match backend {
TestBackend::Monty => "monty",
#[cfg(feature = "monty-pool")]
TestBackend::MontyPool(_) => "monty-pool",
};
let mut cli = cucumber::cli::Opts::parsed();
let name_filter = cli.re_filter.take();
let live_run = live::credential().is_some();
World::cucumber()
.max_concurrent_scenarios(1)
.fail_on_skipped()
.before(move |_, _, _, world| {
world.backend = backend.clone();
future::ready(()).boxed_local()
})
.with_cli::<cucumber::cli::Empty>(cli)
.filter_run("tests/features", move |feature, _, scenario| {
let mut tags = feature.tags.iter().chain(&scenario.tags);
let runs_rmcp = run_rmcp || !tags.clone().any(|tag| tag == "rmcp");
let is_live = tags.clone().any(|tag| tag == "live");
let runs_here = tags
.all(|tag| !["monty", "monty-pool"].contains(&tag.as_str()) || tag == backend_tag);
let named = name_filter
.as_ref()
.is_none_or(|name| name.is_match(&scenario.name));
runs_rmcp && runs_here && named && is_live == live_run
})
.await
.execution_has_failed()
}
#[cfg(feature = "monty-pool")]
fn find_worker_binary() -> std::path::PathBuf {
let file_name = format!("monty{}", std::env::consts::EXE_SUFFIX);
let path = std::env::var_os("PATH").unwrap_or_default();
std::env::split_paths(&path)
.map(|dir| dir.join(&file_name))
.find(|binary| binary.is_file())
.expect("the `monty` worker binary on PATH")
}
fn main() {
if live::credential().is_some() {
println!("executor: futures::executor::block_on, live scenarios only");
let failed = futures::executor::block_on(run_scenarios(false, TestBackend::Monty));
live::print_run_usage();
std::process::exit(i32::from(failed));
}
println!("executor: futures::executor::block_on");
let mut failed = futures::executor::block_on(run_scenarios(false, TestBackend::Monty));
println!("executor: Tokio current-thread runtime");
let runtime = tokio::runtime::Builder::new_current_thread()
.build()
.expect("current-thread runtime");
failed |= runtime.block_on(run_scenarios(true, TestBackend::Monty));
println!("executor: Tokio multi-thread runtime");
let runtime = tokio::runtime::Builder::new_multi_thread()
.enable_all()
.build()
.expect("multi-thread runtime");
failed |= runtime.block_on(run_scenarios(true, TestBackend::Monty));
#[cfg(feature = "monty-pool")]
{
println!("executor: Tokio multi-thread runtime, against monty-pool workers");
failed |= runtime.block_on(async {
let mut options = ghostmode::backend::WorkerOptions::new(find_worker_binary());
options.min_workers = 0;
let pool = ghostmode::backend::MontyPool::new(options)
.await
.expect("monty-pool takes the `monty` worker's options");
run_scenarios(true, TestBackend::MontyPool(pool)).await
});
}
if failed {
std::process::exit(1);
}
}