Add --headless mode (no stdin read, runs until SIGTERM/exit) + systemd/NixOS examples
ci / check (push) Successful in 2m44s

This commit is contained in:
Sausage Agent
2026-10-18 15:24:20 +00:00
parent c204e1ef0c
commit 01a821ab72
7 changed files with 144 additions and 9 deletions
+2 -1
View File
@@ -3,7 +3,8 @@
//! - `@<actor> <json>` sends a JSON body. `@<actor> <text>` sends
//! `{"type": "text", "text": ...}`.
//! - A line without `@` goes to `agent` as text.
//! - `/help`, `/quit`. EOF on stdin also quits.
//! - `/help`, `/quit`. EOF on stdin also quits (not with `--headless`, which
//! never reads stdin).
use std::sync::Arc;
+37 -7
View File
@@ -17,6 +17,11 @@ static AGENT_SOURCE: Dir<'_> = include_dir!("$CARGO_MANIFEST_DIR/../agent");
#[derive(Parser)]
#[command(version, about)]
struct Cli {
/// Run without a terminal (for a service): do not read stdin, so EOF
/// does not stop the world. It runs until SIGTERM (or SIGINT), or until
/// an actor sends `@broker {"type":"exit"}`. Also set by SAUSAGE_HEADLESS=1.
#[arg(long, global = true)]
headless: bool,
#[command(subcommand)]
command: Option<Cmd>,
}
@@ -91,13 +96,36 @@ async fn init(dir: PathBuf) -> Result<()> {
Ok(())
}
async fn run(dir: PathBuf) -> Result<()> {
/// Resolves on SIGTERM or SIGINT.
async fn termination() {
use tokio::signal::unix::{SignalKind, signal};
let mut term = signal(SignalKind::terminate()).expect("install SIGTERM handler");
let mut int = signal(SignalKind::interrupt()).expect("install SIGINT handler");
tokio::select! {
_ = term.recv() => {}
_ = int.recv() => {}
}
}
async fn run(dir: PathBuf, headless: bool) -> Result<()> {
// Install the signal handlers before the host starts, so a signal that
// arrives early is never the default (kill) action.
let signals = headless.then(|| tokio::spawn(termination()));
let host = Host::start(&dir).await?;
tokio::spawn(console::run_mailbox(host.mailbox(console::ID)));
let broker = host.broker.clone();
let exit = tokio::select! {
_ = console::run_input(host.broker.clone()) => false,
_ = broker.exit_requested() => true,
let exit = match signals {
Some(signals) => {
println!("Sausage headless: running until SIGTERM or an exit request.");
tokio::select! {
_ = signals => false,
_ = broker.exit_requested() => true,
}
}
None => tokio::select! {
_ = console::run_input(host.broker.clone()) => false,
_ = broker.exit_requested() => true,
},
};
println!("Stopping actors …");
host.stop().await;
@@ -113,16 +141,18 @@ async fn run(dir: PathBuf) -> Result<()> {
#[tokio::main]
async fn main() -> Result<()> {
match Cli::parse().command {
let cli = Cli::parse();
let headless = cli.headless || std::env::var("SAUSAGE_HEADLESS").is_ok_and(|v| !v.is_empty() && v != "0");
match cli.command {
Some(Cmd::Init { dir }) => init(dir).await,
Some(Cmd::Run { dir }) => run(dir).await,
Some(Cmd::Run { dir }) => run(dir, headless).await,
None => {
let dir = PathBuf::from("world");
if !dir.join("actor").is_dir() {
println!("No world in ./world yet, creating it (same as `sausage init`).");
init(dir.clone()).await?;
}
run(dir).await
run(dir, headless).await
}
}
}
+31
View File
@@ -39,3 +39,34 @@ fn bare_command_without_a_world_starts_init() {
// It asks before it creates anything.
assert!(!dir.join("world").exists());
}
/// `--headless` never reads stdin: with stdin at EOF the world stays up, and
/// SIGTERM stops it cleanly (exit code 0).
#[test]
fn headless_ignores_stdin_eof_and_stops_cleanly_on_sigterm() {
use std::io::{BufRead, BufReader};
let dir = empty_dir("headless");
let world = dir.join("world");
sausage::World::create(&world).unwrap();
let mut child = Command::new(env!("CARGO_BIN_EXE_sausage"))
.args(["run", "--headless"])
.arg(&world)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut lines = BufReader::new(child.stdout.take().unwrap()).lines();
// The host prints this once it runs and the signal handlers are installed.
let line = lines.next().expect("host exited before it started").unwrap();
assert!(line.contains("headless"), "unexpected first line: {line}");
// The host reaches EOF on stdin immediately; it must still be running.
std::thread::sleep(std::time::Duration::from_millis(500));
assert!(child.try_wait().unwrap().is_none(), "headless host exited on stdin EOF");
let pid = child.id().to_string();
assert!(Command::new("kill").args(["-TERM", &pid]).status().unwrap().success());
let rest: Vec<String> = lines.map(|l| l.unwrap()).collect();
let status = child.wait().unwrap();
assert!(status.success(), "exit status {status:?}, output {rest:?}");
assert!(rest.iter().any(|l| l.contains("Stopping actors")), "output {rest:?}");
}