host: review fixes for cargo.build, the test runner, the console, and main; tests for every PROTOCOL.md rule
cargo.build and the runner (review T22R): builds use the network again; core.unlock and core.notify in order under the runner; quiet test output; manifest preparation keeps [workspace], target tables, renamed and optional entries; cargo.rpc.discover; -32004 with data.output; retention of 10 builds; light, empty test worlds with an in-memory journal; only CARGO_/RUST_/SAUSAGE_ variables; stdin is null; the runner through --config. A compile cache that cannot be created is not fatal. Activation replaces plugin.wasm without a gap. Console and main: init ships the workspace Cargo.lock and creates the world atomically; each console command runs in its own task, so ps, stop, and kill work during a slow call; SAUSAGE_HEADLESS; the terminal mode is restored; signals during boot; chat text is not taken as a command. Tests: 20 more tests for PROTOCOL.md sections 2 to 10; the cargo tests choose the libtest binary from cargo's JSON output and time out.
This commit is contained in:
+152
-68
@@ -1,6 +1,6 @@
|
||||
//! Console commands, readable results, and line editing with live notifications.
|
||||
use crate::Host;
|
||||
use anyhow::{Result, bail};
|
||||
use anyhow::Result;
|
||||
use rustyline::{DefaultEditor, ExternalPrinter, error::ReadlineError};
|
||||
use sausage_vfs::{Layer, Open};
|
||||
use serde_json::{Value, json};
|
||||
@@ -77,8 +77,9 @@ pub async fn execute_line(host: &Host, line: &str) -> Result<String> {
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"))
|
||||
}
|
||||
"cat" if !rest.is_empty() => Ok(String::from_utf8(read(host, rest).await?)?),
|
||||
"cat" if words.len() == 1 => Ok(String::from_utf8(read(host, rest).await?)?),
|
||||
"methods" if words.len() == 1 => {
|
||||
let _activation = host.0.activations.lock().await;
|
||||
host.refresh_graph()
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!("{error}"))?;
|
||||
@@ -156,10 +157,10 @@ pub async fn execute_line(host: &Host, line: &str) -> Result<String> {
|
||||
while i < words.len() {
|
||||
if words[i] == "-n" {
|
||||
i += 1;
|
||||
let count: u64 = words
|
||||
.get(i)
|
||||
.ok_or_else(|| anyhow::anyhow!("log -n requires a count"))?
|
||||
.parse()?;
|
||||
let Some(count) = words.get(i).and_then(|value| value.parse::<u64>().ok())
|
||||
else {
|
||||
return call(host, "agent.chat", json!({"text":line}), true).await;
|
||||
};
|
||||
params["limit"] = json!(count);
|
||||
} else if params.get("pid").is_none() && params.get("plugin").is_none() {
|
||||
let key = if words[i].len() > 36
|
||||
@@ -173,7 +174,7 @@ pub async fn execute_line(host: &Host, line: &str) -> Result<String> {
|
||||
};
|
||||
params[key] = json!(words[i]);
|
||||
} else {
|
||||
bail!("usage: log [plugin or pid] [-n N]");
|
||||
return call(host, "agent.chat", json!({"text":line}), true).await;
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
@@ -218,7 +219,13 @@ pub async fn execute_line(host: &Host, line: &str) -> Result<String> {
|
||||
"revert" if words.len() == 1 => {
|
||||
call(host, "core.revert", json!({"plugin":words[0]}), false).await
|
||||
}
|
||||
"stop" | "kill" if words.len() == 1 => {
|
||||
"stop" | "kill"
|
||||
if words.len() == 1
|
||||
&& words[0].rsplit_once('-').is_some()
|
||||
&& words[0]
|
||||
.get(words[0].len().saturating_sub(36)..)
|
||||
.is_some_and(|id| uuid::Uuid::try_parse(id).is_ok()) =>
|
||||
{
|
||||
call(
|
||||
host,
|
||||
&format!("core.{command}"),
|
||||
@@ -227,11 +234,10 @@ pub async fn execute_line(host: &Host, line: &str) -> Result<String> {
|
||||
)
|
||||
.await
|
||||
}
|
||||
"help" | "quit" | "ls" | "methods" | "ps" | "activate" | "revert" | "stop" | "kill"
|
||||
| "cat" => bail!("invalid arguments for {command}; use help"),
|
||||
_ if command
|
||||
.split_once('.')
|
||||
.is_some_and(|(plugin, method)| !plugin.is_empty() && !method.is_empty()) =>
|
||||
_ if (rest.is_empty() || rest.starts_with('{'))
|
||||
&& command
|
||||
.split_once('.')
|
||||
.is_some_and(|(plugin, method)| !plugin.is_empty() && !method.is_empty()) =>
|
||||
{
|
||||
call(
|
||||
host,
|
||||
@@ -279,9 +285,7 @@ pub async fn run_input(host: Host) -> Result<()> {
|
||||
}
|
||||
let history = host.0.world.state_dir("core").join("history");
|
||||
let (ready, started) = tokio::sync::oneshot::channel();
|
||||
let (sender, mut lines) = tokio::sync::mpsc::unbounded_channel::<
|
||||
Result<(String, tokio::sync::oneshot::Sender<bool>)>,
|
||||
>();
|
||||
let (sender, lines) = tokio::sync::mpsc::unbounded_channel::<Result<String>>();
|
||||
// A detached terminal thread does not hold Tokio shutdown open at a blocked readline.
|
||||
std::thread::spawn(move || {
|
||||
let setup = (|| -> Result<_> {
|
||||
@@ -306,15 +310,15 @@ pub async fn run_input(host: Host) -> Result<()> {
|
||||
Ok(line) => {
|
||||
editor.add_history_entry(&line)?;
|
||||
editor.save_history(&history)?;
|
||||
let (done, wait) = tokio::sync::oneshot::channel();
|
||||
if sender.send(Ok((line, done))).is_err()
|
||||
|| !wait.blocking_recv().unwrap_or(false)
|
||||
{
|
||||
if sender.send(Ok(line)).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ReadlineError::Interrupted | ReadlineError::Eof) => {
|
||||
if sender.send(Ok("quit".into())).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(ReadlineError::Interrupted) => break,
|
||||
Err(ReadlineError::Eof) => break,
|
||||
Err(error) => return Err(error.into()),
|
||||
}
|
||||
}
|
||||
@@ -325,71 +329,151 @@ pub async fn run_input(host: Host) -> Result<()> {
|
||||
}
|
||||
});
|
||||
let mut printer = started.await??;
|
||||
let mut notifications = host.subscribe();
|
||||
let print_notifications = async move {
|
||||
loop {
|
||||
match notifications.recv().await {
|
||||
Ok(value) => printer.print(format!("{}\n", indent(¬ification_text(&value))))?,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return Ok(()),
|
||||
}
|
||||
}
|
||||
};
|
||||
let commands = async {
|
||||
while let Some(line) = lines.recv().await {
|
||||
let (line, done) = line?;
|
||||
let text = execute_line(&host, &line)
|
||||
.await
|
||||
.unwrap_or_else(|error| format!("error: {error}"));
|
||||
if !text.is_empty() {
|
||||
println!("{}", indent(&text));
|
||||
}
|
||||
let quit = line.trim() == "quit";
|
||||
let _ = done.send(!quit);
|
||||
if quit {
|
||||
break;
|
||||
}
|
||||
}
|
||||
run_commands(host, lines, move |text| {
|
||||
printer.print(format!("{text}\n"))?;
|
||||
Ok(())
|
||||
};
|
||||
tokio::select! {result=commands=>result,result=print_notifications=>result}
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Read plain lines from stdin, without line editing or history. A detached
|
||||
/// thread reads them, so that a blocked read does not hold the runtime open.
|
||||
async fn run_plain(host: Host) -> Result<()> {
|
||||
let (sender, mut lines) = tokio::sync::mpsc::unbounded_channel::<String>();
|
||||
let (sender, lines) = tokio::sync::mpsc::unbounded_channel::<Result<String>>();
|
||||
std::thread::spawn(move || {
|
||||
for line in std::io::stdin().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
let line = line.map_err(Into::into);
|
||||
if sender.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
run_commands(host, lines, |text| {
|
||||
use std::io::Write;
|
||||
writeln!(std::io::stdout(), "{text}")?;
|
||||
Ok(())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
// Both input modes keep the prompt available and label asynchronous results.
|
||||
async fn run_commands(
|
||||
host: Host,
|
||||
mut lines: tokio::sync::mpsc::UnboundedReceiver<Result<String>>,
|
||||
mut print: impl FnMut(String) -> Result<()>,
|
||||
) -> Result<()> {
|
||||
let mut notifications = host.subscribe();
|
||||
let print_notifications = async move {
|
||||
loop {
|
||||
match notifications.recv().await {
|
||||
Ok(value) => println!("{}", indent(¬ification_text(&value))),
|
||||
let mut commands = tokio::task::JoinSet::new();
|
||||
let mut input_open = true;
|
||||
loop {
|
||||
if !input_open && commands.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
tokio::select! {
|
||||
biased;
|
||||
notification = notifications.recv() => match notification {
|
||||
Ok(value) => print(indent(¬ification_text(&value)))?,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
|
||||
Err(tokio::sync::broadcast::error::RecvError::Closed) => return Ok(()),
|
||||
}
|
||||
},
|
||||
result = commands.join_next(), if !commands.is_empty() => {
|
||||
let (line,result): (String,Result<String>) = result.unwrap()?;
|
||||
let text = result.unwrap_or_else(|error|format!("error: {error}"));
|
||||
if !text.is_empty() { print(format!("> {line}\n{}",indent(&text)))?; }
|
||||
},
|
||||
line = lines.recv(), if input_open => match line {
|
||||
Some(line) => {
|
||||
let line = line?;
|
||||
if line.trim()=="quit" { print("> quit\n Goodbye.".into())?; return Ok(()); }
|
||||
let host = host.clone();
|
||||
commands.spawn(async move {
|
||||
let result=execute_line(&host,&line).await;
|
||||
(line,result)
|
||||
});
|
||||
},
|
||||
None => input_open=false,
|
||||
},
|
||||
}
|
||||
};
|
||||
let commands = async {
|
||||
while let Some(line) = lines.recv().await {
|
||||
let text = execute_line(&host, &line)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[tokio::test]
|
||||
async fn methods_waits_for_activation() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let world = crate::world::World::create(&folder.path().join("world")).unwrap();
|
||||
let host = Host::start_with_cache(&world.root, &folder.path().join("cache"))
|
||||
.await
|
||||
.unwrap();
|
||||
let guard = host.0.activations.lock().await;
|
||||
let mut methods = Box::pin(execute_line(&host, "methods missing"));
|
||||
assert!(
|
||||
tokio::time::timeout(std::time::Duration::from_millis(100), &mut methods)
|
||||
.await
|
||||
.unwrap_or_else(|error| format!("error: {error}"));
|
||||
if !text.is_empty() {
|
||||
println!("{}", indent(&text));
|
||||
}
|
||||
if line.trim() == "quit" {
|
||||
.is_err()
|
||||
);
|
||||
drop(guard);
|
||||
assert!(methods.await.is_err());
|
||||
host.stop().await;
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn commands_remain_available_and_notifications_precede_results() {
|
||||
let folder = tempfile::tempdir().unwrap();
|
||||
let world = crate::world::World::create(&folder.path().join("world")).unwrap();
|
||||
let host = Host::start_with_cache(&world.root, &folder.path().join("cache"))
|
||||
.await
|
||||
.unwrap();
|
||||
host.register_native(
|
||||
"slow",
|
||||
std::sync::Arc::new(|ctx, _, _| {
|
||||
Box::pin(async move {
|
||||
ctx.notify("ready", json!({"pid":ctx.pid}));
|
||||
std::future::pending().await
|
||||
})
|
||||
}),
|
||||
);
|
||||
host.register_native(
|
||||
"fast",
|
||||
std::sync::Arc::new(|ctx, _, _| {
|
||||
Box::pin(async move {
|
||||
ctx.notify("text", json!("before"));
|
||||
Ok(json!("after"))
|
||||
})
|
||||
}),
|
||||
);
|
||||
let mut events = host.subscribe();
|
||||
let (sender, lines) = tokio::sync::mpsc::unbounded_channel();
|
||||
let (printed, mut output) = tokio::sync::mpsc::unbounded_channel();
|
||||
let runner = tokio::spawn(run_commands(host.clone(), lines, move |text| {
|
||||
printed.send(text).unwrap();
|
||||
Ok(())
|
||||
}));
|
||||
sender.send(Ok("slow.wait".into())).unwrap();
|
||||
let event = events.recv().await.unwrap();
|
||||
let pid = event["params"]["params"]["pid"].as_str().unwrap();
|
||||
sender.send(Ok("ps".into())).unwrap();
|
||||
loop {
|
||||
let text = output.recv().await.unwrap();
|
||||
if text.starts_with("> ps") {
|
||||
assert!(text.contains(pid));
|
||||
break;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
tokio::select! {result=commands=>result,result=print_notifications=>result}
|
||||
sender.send(Ok(format!("kill {pid}"))).unwrap();
|
||||
let mut killed = false;
|
||||
let mut answered = false;
|
||||
while !killed || !answered {
|
||||
let text = output.recv().await.unwrap();
|
||||
killed |= text.starts_with("> kill ");
|
||||
answered |= text.starts_with("> slow.wait");
|
||||
}
|
||||
sender.send(Ok("fast.go".into())).unwrap();
|
||||
assert!(output.recv().await.unwrap().contains("before"));
|
||||
assert!(output.recv().await.unwrap().contains("after"));
|
||||
sender.send(Ok("quit".into())).unwrap();
|
||||
runner.await.unwrap().unwrap();
|
||||
host.stop().await;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user