//! JSONL command-line harness for running a peer without the Tauri GUI. #[cfg(unix)] use std::io::{Cursor, Read as _}; use std::{ collections::HashMap, ffi::OsString, future::Future, io::{self, Write as _}, net::SocketAddr, path::{Path, PathBuf}, pin::Pin, sync::{Arc, Mutex}, task::{Context as TaskContext, Poll}, time::{Duration, Instant}, }; use eyre::Context; use lanspread_compat::catalog_bundle::load_catalog_bundle; use lanspread_db::{ content_manifest::CatalogBundle, db::{Game, GameDB}, }; use lanspread_peer::{ ActiveOperation, ActiveOperationKind, CallToPlayView, DownloadAttemptId, DownloadAttemptKey, DownloadFailureReason, ExternalUnrarStreamProvider, NoopStreamInstallProvider, OutboundTransfers, PeerCommand, PeerEndpoint, PeerEvent, PeerEventReceiver, PeerGameDB, PeerIdentity, PeerRuntimeComponent, PeerSnapshot, PeerStartOptions, RemoteLibraryView, StreamInstallProvider, StreamInstallSettings, load_peer_identity, migrate_legacy_state, peer_event_channel, start_peer_with_options, }; use lanspread_peer_cli::{ CliCommand, CommandEnvelope, DEFAULT_FIXTURE_VERSION, ExternalUnrarUnpacker, FixtureSeed, FixtureUnpacker, error_line, event_line, parse_command_line, result_line, seed_fixture_game, }; use serde_json::{Value, json}; use tokio::{ io::{AsyncBufReadExt, AsyncRead, BufReader, ReadBuf}, sync::{Notify, RwLock, mpsc, oneshot}, task::{JoinError, JoinHandle}, }; #[derive(Debug)] struct Args { name: String, games_dir: PathBuf, state_dir: PathBuf, identity_file: Option, catalog_db: PathBuf, manifests_dir: PathBuf, fixtures: Vec, unrar: Option, } #[derive(Clone)] struct JsonlWriter { lock: Arc>, } impl JsonlWriter { fn new() -> Self { Self { lock: Arc::new(Mutex::new(())), } } fn emit(&self, line: eyre::Result) { let line = match line { Ok(line) => line, Err(err) => { eprintln!("failed to prepare JSONL output: {err}"); return; } }; let Ok(_guard) = self.lock.lock() else { eprintln!("failed to lock stdout"); return; }; let mut stdout = std::io::stdout().lock(); if let Err(err) = writeln!(stdout, "{line}") { eprintln!("failed to write JSONL output: {err}"); } } } #[derive(Default)] struct CliState { local_peer: Option, local_games: Vec, remote_games: Vec, active_operations: Vec, downloads: HashMap, call_to_play_view: CallToPlayView, } #[derive(Clone, serde::Serialize)] struct LocalPeer { peer_id: String, addr: String, } struct DownloadMeasurement { attempt_id: DownloadAttemptId, started_at: Instant, bytes: u64, chunks: u64, } struct SharedState { state: RwLock, peer_game_db: Arc>, catalog_game_db: Arc, catalog_bundle: Option>, call_to_play_display_name: RwLock, active_outbound_transfers: OutboundTransfers, notify: Notify, games_dir: RwLock, state_dir: PathBuf, } #[derive(Debug)] enum CommandLoopExit { Eof, Shutdown { request_id: Option }, Signal, } enum CommandInput { #[cfg(unix)] Pollable(UnixStdin), #[cfg(unix)] Buffered(Cursor>), #[cfg(not(unix))] Blocking(tokio::io::Stdin), } impl CommandInput { #[cfg(unix)] fn open() -> io::Result { let duplicate = rustix::io::dup(std::io::stdin()).map_err(io::Error::from)?; Self::from_unix_file(std::fs::File::from(duplicate)) } #[cfg(unix)] fn from_unix_file(mut file: std::fs::File) -> io::Result { // Tokio reactors do not support ordinary files on every Unix. Read a // finite redirected command file before the peer runtime owns any // resources; a pipe or terminal remains incremental and pollable. if file.metadata()?.is_file() { let mut contents = Vec::new(); file.read_to_end(&mut contents)?; return Ok(Self::Buffered(Cursor::new(contents))); } UnixStdin::new(file).map(Self::Pollable) } #[cfg(not(unix))] #[allow( clippy::unnecessary_wraps, reason = "keeps platform-specific stdin construction behind one fallible API" )] fn open() -> io::Result { Ok(Self::Blocking(tokio::io::stdin())) } } impl AsyncRead for CommandInput { fn poll_read( self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buffer: &mut ReadBuf<'_>, ) -> Poll> { match self.get_mut() { #[cfg(unix)] Self::Pollable(stdin) => Pin::new(stdin).poll_read(cx, buffer), #[cfg(unix)] Self::Buffered(cursor) => Pin::new(cursor).poll_read(cx, buffer), #[cfg(not(unix))] Self::Blocking(stdin) => Pin::new(stdin).poll_read(cx, buffer), } } } #[cfg(unix)] struct UnixStdin { inner: tokio::io::unix::AsyncFd, #[cfg(test)] poll_started: Option>, } #[cfg(unix)] impl UnixStdin { fn new(file: std::fs::File) -> io::Result { use rustix::fs::{OFlags, fcntl_getfl, fcntl_setfl}; let flags = fcntl_getfl(&file).map_err(io::Error::from)?; fcntl_setfl(&file, flags | OFlags::NONBLOCK).map_err(io::Error::from)?; let inner = tokio::io::unix::AsyncFd::with_interest(file, tokio::io::Interest::READABLE)?; Ok(Self { inner, #[cfg(test)] poll_started: None, }) } #[cfg(test)] fn with_poll_started(mut self, poll_started: Arc) -> Self { self.poll_started = Some(poll_started); self } } #[cfg(unix)] impl AsyncRead for UnixStdin { fn poll_read( mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>, buffer: &mut ReadBuf<'_>, ) -> Poll> { if buffer.remaining() == 0 { return Poll::Ready(Ok(())); } #[cfg(test)] if let Some(poll_started) = &self.poll_started { poll_started.notify_one(); } loop { let mut ready = std::task::ready!(self.inner.poll_read_ready_mut(cx))?; match ready.try_io(|inner| { rustix::io::read(inner.get_ref(), buffer.initialize_unfilled()) .map_err(io::Error::from) }) { Ok(Ok(read)) => { buffer.advance(read); return Poll::Ready(Ok(())); } Ok(Err(error)) if error.kind() == io::ErrorKind::Interrupted => {} Ok(Err(error)) => return Poll::Ready(Err(error)), Err(_would_block) => {} } } } } #[derive(Debug)] enum CancelledInputExit { Signal, Failure(eyre::Report), } #[derive(Debug)] enum CliScopeOutcome { Command(CommandLoopExit), CancelledInput(CancelledInputExit), } #[cfg(unix)] const PLATFORM_INPUT_CANCELLATION_IS_QUIESCENT: bool = true; // Tokio's non-Unix stdin uses an uncancellable blocking worker. Once its // command future has been aborted, process termination is the only ownership // boundary that cannot hang while dropping the runtime. #[cfg(not(unix))] const PLATFORM_INPUT_CANCELLATION_IS_QUIESCENT: bool = false; #[tokio::main] async fn main() -> eyre::Result<()> { let args = parse_args()?; let explicit_identity = load_explicit_identity(args.identity_file.as_deref())?; std::fs::create_dir_all(&args.games_dir)?; std::fs::create_dir_all(&args.state_dir)?; let command_input = CommandInput::open().wrap_err("failed to prepare an interruptible stdin command source")?; let (catalog_game_db, catalog_bundle) = load_catalog_authority(&args.catalog_db, &args.manifests_dir, &args.fixtures).await?; let fixture_seeds = seed_fixtures(&args.games_dir, &args.fixtures)?; let migration = migrate_legacy_state(&args.games_dir, &args.state_dir).await; let (tx_events, rx_events) = peer_event_channel(); let peer_game_db = Arc::new(RwLock::new(PeerGameDB::new())); let catalog_game_db = Arc::new(catalog_game_db); let active_outbound_transfers: OutboundTransfers = Arc::new(RwLock::new(HashMap::new())); let unrar_for_streaming = args.unrar.clone().or_else(default_unrar_program); let unpacker: Arc = match args.unrar.clone() { Some(path) => Arc::new(ExternalUnrarUnpacker::new(path)), None => Arc::new(FixtureUnpacker), }; let stream_install_provider: Arc = match unrar_for_streaming { Some(path) => Arc::new(ExternalUnrarStreamProvider::new(path)), None => Arc::new(NoopStreamInstallProvider), }; let handle = start_peer_with_options( args.games_dir.clone(), tx_events, peer_game_db.clone(), unpacker, Arc::clone(&catalog_bundle), PeerStartOptions { state_dir: Some(args.state_dir.clone()), identity: explicit_identity, active_outbound_transfers: Some(active_outbound_transfers.clone()), stream_install_provider: Some(stream_install_provider), local_network_sharing: true, }, )?; let sender = handle.sender(); let accepted_game_dir = handle.accepted_game_dir().to_path_buf(); let shared = Arc::new(SharedState { state: RwLock::new(CliState::default()), peer_game_db, catalog_game_db, catalog_bundle: Some(catalog_bundle), call_to_play_display_name: RwLock::new(args.name.clone()), active_outbound_transfers, notify: Notify::new(), games_dir: RwLock::new(accepted_game_dir.clone()), state_dir: args.state_dir.clone(), }); let writer = JsonlWriter::new(); writer.emit(event_line( "cli-started", json!({ "name": args.name, "games_dir": accepted_game_dir, "state_dir": args.state_dir, "catalog_db": args.catalog_db, "manifests_dir": args.manifests_dir, "migration": migration, "fixtures": fixture_seeds, }), )); let command_task = tokio::spawn(command_loop( command_input, sender, shared.clone(), writer.clone(), )); let event_task = tokio::spawn(event_loop(rx_events, shared, writer.clone())); let shutdown = async move { let mut handle = handle; handle.shutdown(); handle.wait_stopped().await; }; let outcome = join_cli_scope(command_task, event_task, shutdown_signal(), shutdown).await?; let exit = finish_cli_scope( outcome, PLATFORM_INPUT_CANCELLATION_IS_QUIESCENT, |exit_code, failure| { if let Some(failure) = failure { eprintln!("peer CLI stopped exceptionally: {failure:#}"); } std::process::exit(exit_code); }, )?; if let CommandLoopExit::Shutdown { request_id } = exit { writer.emit(result_line( &request_id, "shutdown", json!({"stopped": true}), )); } Ok(()) } fn load_explicit_identity(path: Option<&Path>) -> eyre::Result>> { path.map(load_peer_identity) .transpose() .wrap_err("failed to load explicitly selected peer identity") .map(|identity| identity.map(Arc::new)) } async fn command_loop( input: CommandInput, sender: mpsc::UnboundedSender, shared: Arc, writer: JsonlWriter, ) -> eyre::Result { let mut lines = BufReader::new(input).lines(); while let Some(line) = lines.next_line().await? { if line.trim().is_empty() { continue; } let envelope = match parse_command_line(&line) { Ok(envelope) => envelope, Err(err) => { writer.emit(error_line(&None, None, &err.to_string())); continue; } }; if matches!(&envelope.command, CliCommand::Shutdown) { return Ok(CommandLoopExit::Shutdown { request_id: envelope.request_id, }); } let command_name = envelope.command.name(); match handle_command(&envelope, &sender, &shared).await { Ok(data) => { writer.emit(result_line(&envelope.request_id, command_name, data)); } Err(err) => { writer.emit(error_line( &envelope.request_id, Some(command_name), &err.to_string(), )); } } } Ok(CommandLoopExit::Eof) } #[allow(clippy::too_many_lines)] async fn handle_command( envelope: &CommandEnvelope, sender: &mpsc::UnboundedSender, shared: &Arc, ) -> eyre::Result { match &envelope.command { CliCommand::Status => status(shared).await, CliCommand::ListPeers => list_peers(shared).await, CliCommand::ListGames => list_games(shared).await, CliCommand::ListCallToPlay => { let (reply, result) = oneshot::channel(); sender.send(PeerCommand::GetCallToPlayView { reply: Some(reply) })?; let view = tokio::time::timeout(Duration::from_secs(1), result) .await .wrap_err("timed out waiting for Call to Play view")? .wrap_err("peer stopped before returning Call to Play view")? .map_err(eyre::Report::msg)?; Ok(json!({ "view": view })) } CliCommand::PublishCallToPlay { intent } => { let (reply, result) = oneshot::channel(); sender.send(PeerCommand::ApplyCallToPlayIntent { intent: intent.clone(), display_name: shared.call_to_play_display_name.read().await.clone(), reply, })?; let receipt = result .await .wrap_err("peer stopped before applying Call to Play intent")? .map_err(eyre::Report::msg)?; Ok(json!({"published": true, "receipt": receipt})) } CliCommand::SetCallToPlayDisplayName { display_name } => { let (reply, result) = oneshot::channel(); sender.send(PeerCommand::SetCallToPlayDisplayName { display_name: display_name.clone(), reply, })?; let changed = result .await .wrap_err("peer stopped before updating the Call to Play display name")? .map_err(eyre::Report::msg)?; *shared.call_to_play_display_name.write().await = display_name.clone(); Ok(json!({"changed": changed, "display_name": display_name})) } CliCommand::SetGameDir { path } => set_game_dir(sender, shared, path).await, CliCommand::Download { game_id, install_after_download, } => { ensure_catalog_game(shared, game_id)?; ensure_no_active_operation(shared, game_id).await?; sender.send(PeerCommand::DownloadGameFilesWithOptions { id: game_id.clone(), install_after_download: *install_after_download, })?; Ok(json!({"queued": true, "game_id": game_id, "install": install_after_download})) } CliCommand::StreamInstall { game_id, account_name, language, persona_name, } => { ensure_catalog_game(shared, game_id)?; ensure_no_active_operation(shared, game_id).await?; sender.send(PeerCommand::StreamInstallGame { id: game_id.clone(), settings: StreamInstallSettings::sanitized( account_name.as_deref(), language.as_deref(), persona_name.as_deref(), ), })?; Ok(json!({"queued": true, "game_id": game_id})) } CliCommand::CancelDownload { game_id } => { ensure_catalog_game(shared, game_id)?; sender.send(PeerCommand::CancelDownload { id: game_id.clone(), })?; Ok(json!({"queued": true, "game_id": game_id})) } CliCommand::Install { game_id } => { ensure_catalog_game(shared, game_id)?; ensure_no_active_operation(shared, game_id).await?; sender.send(PeerCommand::InstallGame { id: game_id.clone(), })?; Ok(json!({"queued": true, "game_id": game_id})) } CliCommand::Play { game_id, username, language, } => play(shared, game_id, username, language.as_deref()).await, CliCommand::Uninstall { game_id } => { ensure_catalog_game(shared, game_id)?; ensure_no_active_operation(shared, game_id).await?; sender.send(PeerCommand::UninstallGame { id: game_id.clone(), })?; Ok(json!({"queued": true, "game_id": game_id})) } CliCommand::WaitPeers { count, timeout } => wait_peers(shared, *count, *timeout).await, CliCommand::Connect { endpoint } => { ensure_not_self_connect(shared, *endpoint).await?; sender.send(PeerCommand::ConnectPeer(*endpoint))?; Ok(json!({ "queued": true, "peer_id": endpoint.peer_id, "addr": endpoint.addr.to_string(), })) } CliCommand::Shutdown => eyre::bail!("shutdown must be finalized by the CLI task scope"), } } async fn shutdown_signal() -> eyre::Result<()> { #[cfg(unix)] { use tokio::signal::unix::{SignalKind, signal}; let mut interrupt = signal(SignalKind::interrupt())?; let mut terminate = signal(SignalKind::terminate())?; let received = tokio::select! { received = interrupt.recv() => received, received = terminate.recv() => received, }; if received.is_none() { eyre::bail!("CLI shutdown signal stream closed unexpectedly"); } Ok(()) } #[cfg(not(unix))] { tokio::signal::ctrl_c() .await .wrap_err("failed to listen for Ctrl-C") } } /// Joins the command loop, event loop, and signal listener around one /// unconditional peer-runtime finalizer. /// /// The two loops are spawned only so Tokio can turn their panics and explicit /// cancellation into `JoinError` values. Their handles remain owned here until /// both tasks have settled. Peer shutdown always runs before either outcome is /// returned to `main`. async fn join_cli_scope( mut command_task: JoinHandle>, mut event_task: JoinHandle<()>, signal: Signal, shutdown: Shutdown, ) -> eyre::Result where Signal: Future>, Shutdown: Future, { enum FirstTask { Command(Result, JoinError>), Events(Result<(), JoinError>), Signal(eyre::Result<()>), } let first = tokio::select! { result = &mut command_task => FirstTask::Command(result), result = &mut event_task => FirstTask::Events(result), result = signal => FirstTask::Signal(result), }; match first { FirstTask::Command(command_result) => { // The peer owns every event sender. Stopping it first lets the // still-running event loop drain terminal JSONL events and then // finish naturally when the channel closes. shutdown.await; let event_result = event_task.await; let exit = command_result.wrap_err("peer command loop task failed to join")??; event_result.wrap_err("peer event loop failed to join")?; Ok(CliScopeOutcome::Command(exit)) } FirstTask::Events(event_result) => { // An event-loop exit terminates the CLI scope. Settle the command // future and peer before deciding whether this platform can unwind // its stdin implementation or must use the process boundary. command_task.abort(); let command_result = command_task.await; shutdown.await; match command_result { Ok(result) => { let exit = result?; event_result.wrap_err("peer event loop failed to join")?; Ok(CliScopeOutcome::Command(exit)) } Err(error) if error.is_cancelled() => { let failure = match event_result { Ok(()) => eyre::eyre!("peer event loop stopped before the command loop"), Err(error) => { eyre::Report::new(error).wrap_err("peer event loop failed to join") } }; Ok(CliScopeOutcome::CancelledInput( CancelledInputExit::Failure(failure), )) } Err(error) => { event_result.wrap_err("peer event loop failed to join")?; Err(error).wrap_err("peer command loop task failed to join") } } } FirstTask::Signal(signal_result) => { // SIGINT/SIGTERM/Ctrl-C are owned termination inputs, not an outer // race that is allowed to drop this scope. Cancel the command // future, settle the peer, and drain all terminal events first. command_task.abort(); let command_result = command_task.await; shutdown.await; let event_result = event_task.await; match command_result { Ok(result) => { signal_result.wrap_err("CLI shutdown signal listener failed")?; let exit = result?; event_result.wrap_err("peer event loop failed to join")?; Ok(CliScopeOutcome::Command(exit)) } Err(error) if error.is_cancelled() => { let cancellation = if let Err(error) = signal_result { CancelledInputExit::Failure( error.wrap_err("CLI shutdown signal listener failed"), ) } else if let Err(error) = event_result { CancelledInputExit::Failure( eyre::Report::new(error).wrap_err("peer event loop failed to join"), ) } else { CancelledInputExit::Signal }; Ok(CliScopeOutcome::CancelledInput(cancellation)) } Err(error) => { signal_result.wrap_err("CLI shutdown signal listener failed")?; event_result.wrap_err("peer event loop failed to join")?; Err(error).wrap_err("peer command loop task failed to join") } } } } } /// Resolves the only platform-dependent ownership boundary left by stdin. /// /// Unix's `AsyncFd` command source is quiescent once its future is cancelled. /// Tokio's fallback stdin owns an uncancellable blocking read, so non-Unix must /// terminate the process *after* peer shutdown and task settlement instead of /// returning into runtime destruction. EOF and explicit `shutdown` complete as /// `CliScopeOutcome::Command` and never take this boundary. fn finish_cli_scope( outcome: CliScopeOutcome, input_cancellation_is_quiescent: bool, terminate_process: Terminate, ) -> eyre::Result where Terminate: FnOnce(i32, Option<&eyre::Report>) -> eyre::Result, { match outcome { CliScopeOutcome::Command(exit) => Ok(exit), CliScopeOutcome::CancelledInput(CancelledInputExit::Signal) if input_cancellation_is_quiescent => { Ok(CommandLoopExit::Signal) } CliScopeOutcome::CancelledInput(CancelledInputExit::Signal) => terminate_process(0, None), CliScopeOutcome::CancelledInput(CancelledInputExit::Failure(error)) if input_cancellation_is_quiescent => { Err(error) } CliScopeOutcome::CancelledInput(CancelledInputExit::Failure(error)) => { terminate_process(1, Some(&error)) } } } async fn set_game_dir( sender: &mpsc::UnboundedSender, shared: &SharedState, path: &Path, ) -> eyre::Result { let (reply, result) = oneshot::channel(); sender.send(PeerCommand::SetGameDir { path: path.to_path_buf(), reply, })?; let accepted_path = result .await .wrap_err("peer stopped before acknowledging the game directory")? .map_err(eyre::Report::msg)?; *shared.games_dir.write().await = accepted_path.clone(); Ok(json!({"accepted": true, "path": accepted_path})) } async fn status(shared: &SharedState) -> eyre::Result { let state = shared.state.read().await; let peer_count = shared.peer_game_db.read().await.peer_snapshots().len(); let active_outbound_transfers = { let active = shared.active_outbound_transfers.read().await; active .iter() .map(|(game_id, transfers)| (game_id.clone(), transfers.len())) .collect::>() }; Ok(json!({ "local_peer": state.local_peer.clone(), "peer_count": peer_count, "local_games": state.local_games.len(), "remote_games": state.remote_games.len(), "active_operations": active_operations_json(&state.active_operations), "active_outbound_transfers": active_outbound_transfers, })) } async fn list_peers(shared: &SharedState) -> eyre::Result { let peers = shared.peer_game_db.read().await.peer_snapshots(); Ok(json!({ "peers": peer_snapshots_json(&peers) })) } async fn list_games(shared: &SharedState) -> eyre::Result { let state = shared.state.read().await; Ok(json!({ "local": state.local_games.clone(), "remote": state.remote_games.clone(), "active_operations": active_operations_json(&state.active_operations), })) } async fn play( shared: &SharedState, game_id: &str, username: &str, language: Option<&str>, ) -> eyre::Result { ensure_catalog_game(shared, game_id)?; let game_root = shared.games_dir.read().await.join(game_id); let outcome = lanspread_peer::apply_launch_settings_once( &shared.state_dir, &game_root, game_id, Some(username), language, )?; Ok(json!({ "game_id": game_id, "outcome": outcome })) } fn ensure_catalog_game(shared: &SharedState, game_id: &str) -> eyre::Result<()> { if shared .catalog_bundle .as_ref() .is_some_and(|catalog| catalog.catalog().contains(game_id)) { return Ok(()); } eyre::bail!("game {game_id} is not in the local catalog"); } async fn ensure_no_active_operation(shared: &SharedState, game_id: &str) -> eyre::Result<()> { let state = shared.state.read().await; if state .active_operations .iter() .any(|operation| operation.id == game_id) { eyre::bail!("operation already in progress for game {game_id}"); } Ok(()) } async fn ensure_not_self_connect(shared: &SharedState, endpoint: PeerEndpoint) -> eyre::Result<()> { let state = shared.state.read().await; if state.local_peer.as_ref().is_some_and(|peer| { peer.peer_id == endpoint.peer_id.to_string() || peer.addr == endpoint.addr.to_string() }) { eyre::bail!("cannot connect peer to itself at {}", endpoint.addr); } Ok(()) } async fn wait_peers(shared: &SharedState, count: usize, timeout: Duration) -> eyre::Result { let wait = async { loop { let peer_count = shared.peer_game_db.read().await.peer_snapshots().len(); if peer_count >= count { return peer_count; } shared.notify.notified().await; } }; let peer_count = tokio::time::timeout(timeout, wait) .await .wrap_err("timed out waiting for peers")?; Ok(json!({"peer_count": peer_count})) } async fn event_loop( mut rx_events: PeerEventReceiver, shared: Arc, writer: JsonlWriter, ) { while let Some(event) = rx_events.recv().await { let (event_name, data) = update_state_from_event(&shared, event).await; writer.emit(event_line(event_name, data)); shared.notify.notify_waiters(); } } #[allow(clippy::too_many_lines)] async fn update_state_from_event(shared: &SharedState, event: PeerEvent) -> (&'static str, Value) { match event { PeerEvent::LocalPeerReady { peer_id, addr } => { let local_peer = LocalPeer { peer_id, addr: addr.to_string(), }; shared.state.write().await.local_peer = Some(local_peer.clone()); ("local-peer-ready", json!(local_peer)) } PeerEvent::LocalNetworkSharingStateChanged(state) => ( "local-network-sharing-state-changed", json!({ "state": state }), ), PeerEvent::RemoteLibraryView(view) => { let games = join_remote_library_view(shared, &view); shared.state.write().await.remote_games = games.clone(); ( "remote-library-view", json!({ "view": view, "games": games }), ) } PeerEvent::LocalLibraryChanged { games } => { let mut state = shared.state.write().await; state.local_games.clone_from(&games); ("local-library-changed", json!({ "games": games })) } PeerEvent::OutboundTransferCountChanged(change) => { let event = ("outbound-transfer-count-changed", json!({})); drop(change); event } PeerEvent::ActiveOperationsChanged { active_operations } => { let mut state = shared.state.write().await; state.active_operations.clone_from(&active_operations); ( "active-operations-changed", json!({ "active_operations": active_operations_json(&active_operations) }), ) } PeerEvent::CallToPlayView(view) => { shared.state.write().await.call_to_play_view = view.clone(); ("call-to-play-view", json!({ "view": view })) } PeerEvent::DownloadGameFilesBegin { attempt } => { download_begin_event(shared, attempt).await } PeerEvent::DownloadGameFileChunkFinished { id, peer_id, peer_addr, content_id, relative_path, offset, length, } => { download_chunk_finished_event( shared, DownloadChunkFinishedEvent { id, peer_id: peer_id.to_string(), peer_addr, content_id: content_id.to_string(), relative_path: relative_path.as_str().to_owned(), offset, length, }, ) .await } PeerEvent::DownloadGameFilesProgress(progress) => ( "download-progress", json!({ "game_id": progress.attempt.id, "attempt_id": progress.attempt.attempt_id.to_string(), "downloaded_bytes": progress.downloaded_bytes, "total_bytes": progress.total_bytes, "bytes_per_second": progress.bytes_per_second, "active_peer_count": progress.active_peer_count, }), ), PeerEvent::DownloadGameFilesActivityChanged { attempt, activity } => ( "download-activity-changed", json!({ "game_id": attempt.id, "attempt_id": attempt.attempt_id.to_string(), "activity": activity, }), ), PeerEvent::DownloadGameFilesFinished { attempt } => { download_terminal_event(shared, "download-finished", attempt, None).await } PeerEvent::DownloadGameFilesFailed { attempt, reason } => { download_terminal_event(shared, "download-failed", attempt, Some(reason)).await } PeerEvent::InstallGameFinished { id } => game_id_event("install-finished", id), PeerEvent::InstallGameFailed { id } => game_id_event("install-failed", id), PeerEvent::UninstallGameFinished { id } => game_id_event("uninstall-finished", id), PeerEvent::UninstallGameFailed { id } => game_id_event("uninstall-failed", id), PeerEvent::RemoveDownloadedGameFinished { id } => { game_id_event("remove-download-finished", id) } PeerEvent::RemoveDownloadedGameFailed { id } => game_id_event("remove-download-failed", id), PeerEvent::PeerDiscovered(endpoint) => ("peer-discovered", peer_endpoint_json(endpoint)), PeerEvent::PeerLost(endpoint) => ("peer-lost", peer_endpoint_json(endpoint)), PeerEvent::PeerCountUpdated(count) => ("peer-count-updated", json!({"count": count})), PeerEvent::IncompatibleProtocolDetected { observed, expected } => ( "incompatible-protocol-detected", json!({"observed": observed, "expected": expected}), ), PeerEvent::RuntimeFailed { component, error } => ( "runtime-failed", json!({"component": runtime_component_name(component), "error": error}), ), } } fn join_remote_library_view(shared: &SharedState, view: &RemoteLibraryView) -> Vec { let mut games = view .games .iter() .filter_map(|availability| { let catalog_bundle = shared.catalog_bundle.as_ref()?; let Some(identity) = catalog_bundle.content_identity(&availability.game_id) else { eprintln!( "Ignoring remote availability for unknown catalog game {}", availability.game_id ); return None; }; if identity.content_id != availability.content_id { eprintln!( "Ignoring remote availability for non-catalog content {} ({})", availability.game_id, availability.content_id ); return None; } let mut game = shared .catalog_game_db .get_game_by_id(&availability.game_id)? .clone(); game.peer_count = availability.peer_count; game.set_downloaded(true); Some(game) }) .collect::>(); games.sort(); games } fn game_id_event(kind: &'static str, id: String) -> (&'static str, Value) { (kind, json!({"game_id": id})) } async fn download_begin_event( shared: &SharedState, attempt: DownloadAttemptKey, ) -> (&'static str, Value) { let mut state = shared.state.write().await; let replace = state .downloads .get(&attempt.id) .is_none_or(|measurement| measurement.attempt_id < attempt.attempt_id); if replace { state.downloads.insert( attempt.id.clone(), DownloadMeasurement { attempt_id: attempt.attempt_id, started_at: Instant::now(), bytes: 0, chunks: 0, }, ); } drop(state); ( "download-begin", json!({ "game_id": attempt.id, "attempt_id": attempt.attempt_id.to_string(), }), ) } struct DownloadChunkFinishedEvent { id: String, peer_id: String, peer_addr: SocketAddr, content_id: String, relative_path: String, offset: u64, length: u64, } async fn download_chunk_finished_event( shared: &SharedState, event: DownloadChunkFinishedEvent, ) -> (&'static str, Value) { if let Some(measurement) = shared.state.write().await.downloads.get_mut(&event.id) { measurement.bytes = measurement.bytes.saturating_add(event.length); measurement.chunks = measurement.chunks.saturating_add(1); } ( "download-chunk-finished", json!({ "game_id": event.id, "peer_id": event.peer_id, "peer_addr": event.peer_addr.to_string(), "content_id": event.content_id, "relative_path": event.relative_path, "offset": event.offset, "length": event.length, }), ) } async fn download_terminal_event( shared: &SharedState, kind: &'static str, attempt: DownloadAttemptKey, reason: Option, ) -> (&'static str, Value) { let measurement = { let mut state = shared.state.write().await; let is_current = state .downloads .get(&attempt.id) .is_some_and(|measurement| measurement.attempt_id == attempt.attempt_id); is_current .then(|| state.downloads.remove(&attempt.id)) .flatten() }; let mut data = json!({ "game_id": attempt.id, "attempt_id": attempt.attempt_id.to_string(), }); if let Some(reason) = reason { data["reason"] = json!(reason); } let Some(measurement) = measurement else { return (kind, data); }; let duration = measurement.started_at.elapsed(); let seconds = duration.as_secs_f64().max(f64::EPSILON); #[allow(clippy::cast_precision_loss)] let bytes = measurement.bytes as f64; data["throughput"] = json!({ "bytes": measurement.bytes, "chunks": measurement.chunks, "duration_ms": duration.as_secs_f64() * 1000.0, "mib_per_s": bytes / seconds / 1_048_576.0, "mbit_per_s": bytes * 8.0 / seconds / 1_000_000.0, }); (kind, data) } fn peer_endpoint_json(endpoint: lanspread_peer::PeerEndpoint) -> Value { json!({ "peer_id": endpoint.peer_id.to_string(), "addr": endpoint.addr.to_string(), }) } fn active_operations_json(active_operations: &[ActiveOperation]) -> Vec { active_operations .iter() .map(|operation| { json!({ "game_id": operation.id.clone(), "operation": active_operation_name(operation.operation), }) }) .collect() } fn peer_snapshots_json(peers: &[PeerSnapshot]) -> Vec { peers .iter() .map(|peer| { json!({ "peer_id": peer.peer_id, "addr": peer.addr.to_string(), "endpoint_generation": peer.endpoint_generation.get(), "runtime_session_id": peer.runtime_session_id, "library_revision": peer.library_revision, "call_to_play_revision": peer.call_to_play_revision, "game_count": peer.game_count, "games": peer.games.clone(), }) }) .collect() } fn active_operation_name(operation: ActiveOperationKind) -> &'static str { (&operation).into() } fn runtime_component_name(component: PeerRuntimeComponent) -> &'static str { (&component).into() } fn seed_fixtures(game_dir: &Path, fixtures: &[String]) -> eyre::Result> { fixtures .iter() .map(|fixture| seed_fixture_game(game_dir, fixture)) .collect() } async fn load_catalog_authority( catalog_db: &Path, manifests_dir: &Path, fixtures: &[String], ) -> eyre::Result<(GameDB, Arc)> { let loaded = load_catalog_bundle(catalog_db, manifests_dir) .await .wrap_err_with(|| { format!( "failed to load catalog authority from {} and {}", catalog_db.display(), manifests_dir.display() ) })?; let (game_db, bundle) = loaded.into_parts(); // A selected fixture body can be large and is backed by synchronous, // bounded filesystem reads. This startup gate runs before the peer owns // any tasks; keep the work lexical while letting Tokio compensate for the // blocked CLI executor worker. tokio::task::block_in_place(|| validate_fixture_authority(&bundle, fixtures))?; Ok((game_db, bundle)) } fn validate_fixture_authority( catalog_bundle: &CatalogBundle, fixtures: &[String], ) -> eyre::Result<()> { for fixture in fixtures { let expected_version = catalog_bundle .catalog() .expected_version(fixture) .ok_or_else(|| { eyre::eyre!("fixture {fixture} is not authorized by the selected catalog profile") })?; if expected_version != DEFAULT_FIXTURE_VERSION { eyre::bail!( "fixture {fixture} requires catalog version {DEFAULT_FIXTURE_VERSION}, but the selected profile authorizes {expected_version}" ); } catalog_bundle.manifest(fixture).wrap_err_with(|| { format!("fixture {fixture} has no valid manifest in the selected catalog profile") })?; } Ok(()) } fn parse_args() -> eyre::Result { parse_args_from(std::env::args_os().skip(1)) } fn parse_args_from(mut args: impl Iterator) -> eyre::Result { let mut name = "peer".to_string(); let mut games_dir = PathBuf::from("games"); let mut state_dir = PathBuf::from("state"); let mut identity_file = None; let mut catalog_db = default_catalog_db(); let mut manifests_dir = None; let mut fixtures = Vec::new(); let mut unrar = None; while let Some(arg) = args.next() { match arg.to_str() { Some("--help" | "-h") => { print_help(); std::process::exit(0); } Some("--name") => name = next_string(&mut args, "--name")?, Some("--games-dir") => games_dir = next_path(&mut args, "--games-dir")?, Some("--state-dir") => state_dir = next_path(&mut args, "--state-dir")?, Some("--identity-file") => { identity_file = Some(next_path(&mut args, "--identity-file")?); } Some("--catalog-db") => catalog_db = next_path(&mut args, "--catalog-db")?, Some("--manifests-dir") => { manifests_dir = Some(next_path(&mut args, "--manifests-dir")?); } Some("--fixture") => fixtures.push(next_string(&mut args, "--fixture")?), Some("--unrar") => unrar = Some(next_path(&mut args, "--unrar")?), Some(other) => eyre::bail!("unknown argument: {other}"), None => eyre::bail!("argument is not valid UTF-8: {arg:?}"), } } let manifests_dir = manifests_dir.unwrap_or_else(|| sibling_manifests_dir(&catalog_db)); Ok(Args { name, games_dir, state_dir, identity_file, catalog_db, manifests_dir, fixtures, unrar, }) } fn default_catalog_db() -> PathBuf { let container = PathBuf::from("/app/game.db"); if container.exists() { return container; } PathBuf::from("crates/lanspread-peer-cli/catalogs/default/game.db") } fn sibling_manifests_dir(catalog_db: &Path) -> PathBuf { catalog_db .parent() .unwrap_or_else(|| Path::new(".")) .join("manifests") } fn default_unrar_program() -> Option { [ PathBuf::from("/usr/local/bin/unrar"), PathBuf::from("/usr/bin/unrar"), ] .into_iter() .find(|path| path.exists()) } fn next_string(args: &mut impl Iterator, flag: &str) -> eyre::Result { args.next() .ok_or_else(|| eyre::eyre!("{flag} requires a value"))? .into_string() .map_err(|value| eyre::eyre!("{flag} value is not valid UTF-8: {value:?}")) } fn next_path(args: &mut impl Iterator, flag: &str) -> eyre::Result { Ok(PathBuf::from(next_string(args, flag)?)) } const HELP: &str = "usage: lanspread-peer-cli [--name NAME] [--games-dir PATH] [--state-dir PATH] \ [--identity-file PATH] \ [--catalog-db PATH] [--manifests-dir PATH] [--fixture GAME_ID] [--unrar PATH]\n\ --identity-file loads one existing identity strictly and never repairs or replaces it.\n\ --manifests-dir defaults to the manifests/ sibling of --catalog-db.\n\ Every --fixture must be authorized by the selected catalog profile.\n\ Reads JSONL commands on stdin and writes result/event/error JSONL on stdout."; fn print_help() { eprintln!("{HELP}"); } #[cfg(test)] mod tests { use std::{ collections::BTreeMap, sync::atomic::{AtomicBool, AtomicU64, Ordering}, }; #[cfg(unix)] use std::{os::fd::OwnedFd, process::Stdio}; use lanspread_db::content_manifest::{ Blake3Digest, CATALOG_CONTENT_INDEX_NAME, CatalogContentIndex, CatalogContentManifest, CatalogContentManifestBody, CatalogFileEntry, write_canonical_content_index_atomic, }; use super::*; static NEXT_TEMP_FILE: AtomicU64 = AtomicU64::new(0); struct TestDir(PathBuf); impl TestDir { fn new(label: &str) -> Self { let path = temp_file_path(label); std::fs::create_dir(&path).expect("test directory should be created"); Self(path) } } impl Drop for TestDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } fn temp_file_path(label: &str) -> PathBuf { std::env::temp_dir().join(format!( "lanspread-peer-cli-{label}-{}-{}", std::process::id(), NEXT_TEMP_FILE.fetch_add(1, Ordering::Relaxed) )) } fn fixture_manifest(game_id: &str, version: &str) -> CatalogContentManifest { let archive = format!("fixture archive for {game_id}\n"); let archive_hash = Blake3Digest::hash(archive.as_bytes()); let version_hash = Blake3Digest::hash(version.as_bytes()); CatalogContentManifest::seal( CatalogContentManifestBody::new( game_id, version, vec![ CatalogFileEntry::file( format!("{game_id}.eti"), u64::try_from(archive.len()).expect("fixture archive length should fit"), archive_hash, vec![archive_hash], ) .expect("fixture archive entry should validate"), CatalogFileEntry::file( "version.ini", u64::try_from(version.len()).expect("fixture version length should fit"), version_hash, vec![version_hash], ) .expect("fixture version entry should validate"), ], Vec::new(), ) .expect("fixture manifest body should validate"), ) .expect("fixture manifest should seal") } fn fixture_bundle(game_id: &str, version: &str) -> (TestDir, CatalogBundle) { let root = TestDir::new("catalog-authority"); let manifest = fixture_manifest(game_id, version); let index = CatalogContentIndex::from_manifests([&manifest]) .expect("fixture content index should validate"); write_canonical_content_index_atomic(&root.0.join(CATALOG_CONTENT_INDEX_NAME), &index) .expect("fixture content index should be written"); std::fs::write( root.0.join(format!("{game_id}.json")), manifest .to_canonical_json() .expect("fixture manifest should encode"), ) .expect("fixture manifest should be written"); let bundle = CatalogBundle::new( &root.0, BTreeMap::from([(game_id.to_owned(), version.to_owned())]), ) .expect("fixture catalog bundle should validate"); (root, bundle) } fn game_fixture(game_id: &str, version: &str) -> Game { Game { id: game_id.to_owned(), name: format!("Catalog {game_id}"), description: String::new(), release_year: String::new(), publisher: String::new(), max_players: 4, version: String::new(), genre: String::new(), size: 42, downloaded: false, installed: false, availability: lanspread_db::db::Availability::LocalOnly, eti_game_version: Some(version.to_owned()), local_version: None, peer_count: 0, } } #[test] fn catalog_manifest_path_defaults_to_selected_database_sibling() { let parsed = parse_args_from( ["--catalog-db", "/profiles/solid/game.db"] .into_iter() .map(OsString::from), ) .expect("explicit catalog profile should parse"); assert_eq!(parsed.catalog_db, Path::new("/profiles/solid/game.db")); assert_eq!(parsed.manifests_dir, Path::new("/profiles/solid/manifests")); } #[test] fn help_exposes_catalog_authority_profile_inputs() { assert!(HELP.contains("--catalog-db PATH")); assert!(HELP.contains("--manifests-dir PATH")); assert!(HELP.contains("--identity-file PATH")); assert!(HELP.contains("never repairs or replaces")); assert!(HELP.contains("manifests/ sibling")); assert!(HELP.contains("fixture must be authorized")); } #[test] fn explicit_identity_path_is_preserved_by_argument_parsing() { let parsed = parse_args_from( ["--identity-file", "/identities/alpha.json"] .into_iter() .map(OsString::from), ) .expect("explicit identity path should parse"); assert_eq!( parsed.identity_file.as_deref(), Some(Path::new("/identities/alpha.json")) ); } #[test] fn malformed_explicit_identity_fails_without_mutating_its_directory() { let root = TestDir::new("invalid-explicit-identity"); let identity_path = root.0.join("selected.json"); let invalid = b"not a peer identity\n"; std::fs::write(&identity_path, invalid).expect("invalid identity should be written"); let error = load_explicit_identity(Some(&identity_path)) .expect_err("invalid explicit identity must fail closed"); assert!( error .to_string() .contains("failed to load explicitly selected peer identity") ); assert_eq!( std::fs::read(&identity_path).expect("identity should remain readable"), invalid ); let entries = std::fs::read_dir(&root.0) .expect("identity directory should remain readable") .collect::, _>>() .expect("identity directory entries should be readable"); assert_eq!(entries.len(), 1, "strict loading must not create sidecars"); } #[test] fn explicit_manifest_path_is_independent_of_argument_order() { let parsed = parse_args_from( [ "--manifests-dir", "/profiles/dynamic/authority", "--catalog-db", "/profiles/dynamic/catalog.sqlite", ] .into_iter() .map(OsString::from), ) .expect("explicit profile paths should parse"); assert_eq!( parsed.manifests_dir, Path::new("/profiles/dynamic/authority") ); } #[test] fn selected_fixture_must_have_exact_valid_authority() { let (_root, bundle) = fixture_bundle("fixture-one", DEFAULT_FIXTURE_VERSION); validate_fixture_authority(&bundle, &["fixture-one".to_owned()]) .expect("matching fixture authority should be accepted"); let error = validate_fixture_authority(&bundle, &["fixture-two".to_owned()]) .expect_err("an unknown fixture must not be inserted into authority"); assert!( error .to_string() .contains("is not authorized by the selected catalog profile") ); assert!( !bundle.catalog().contains("fixture-two"), "fixture validation must never extend catalog authority" ); } #[test] fn selected_fixture_rejects_wrong_version_or_malformed_manifest() { let (_root, wrong_version) = fixture_bundle("fixture-one", "20240101"); let error = validate_fixture_authority(&wrong_version, &["fixture-one".to_owned()]) .expect_err("fixture version drift must fail closed"); assert!(error.to_string().contains(DEFAULT_FIXTURE_VERSION)); let root = TestDir::new("malformed-catalog-authority"); let indexed_manifest = fixture_manifest("fixture-one", DEFAULT_FIXTURE_VERSION); let index = CatalogContentIndex::from_manifests([&indexed_manifest]) .expect("fixture content index should validate"); write_canonical_content_index_atomic(&root.0.join(CATALOG_CONTENT_INDEX_NAME), &index) .expect("fixture content index should be written"); std::fs::write(root.0.join("fixture-one.json"), b"not JSON\n") .expect("malformed manifest fixture should be written"); let malformed = CatalogBundle::new( &root.0, BTreeMap::from([("fixture-one".to_owned(), DEFAULT_FIXTURE_VERSION.to_owned())]), ) .expect("bundle coverage should remain lazy"); let error = validate_fixture_authority(&malformed, &["fixture-one".to_owned()]) .expect_err("selected fixture manifest must be eagerly validated"); assert!( error .to_string() .contains("has no valid manifest in the selected catalog profile") ); } #[test] fn remote_view_join_uses_index_without_loading_manifest_body() { let game_id = "fixture-one"; let version = DEFAULT_FIXTURE_VERSION; let (root, bundle) = fixture_bundle(game_id, version); let content_id = bundle .content_identity(game_id) .expect("fixture identity should be indexed") .content_id; std::fs::write( root.0.join(format!("{game_id}.json")), b"broken after load\n", ) .expect("manifest body should become unreadable for the adapter proof"); let mut shared = shared_state(PathBuf::from("games")); shared.catalog_game_db = Arc::new(GameDB::from(vec![game_fixture(game_id, version)])); shared.catalog_bundle = Some(Arc::new(bundle)); let exact = join_remote_library_view( &shared, &RemoteLibraryView { games: vec![lanspread_peer::RemoteGameAvailability { game_id: game_id.to_owned(), content_id, peer_count: 3, }], }, ); assert_eq!(exact.len(), 1); assert_eq!(exact[0].id, game_id); assert_eq!(exact[0].peer_count, 3); let wrong = join_remote_library_view( &shared, &RemoteLibraryView { games: vec![lanspread_peer::RemoteGameAvailability { game_id: game_id.to_owned(), content_id: lanspread_db::content_manifest::ContentId::from_bytes([7; 32]), peer_count: 9, }], }, ); assert!(wrong.is_empty()); assert!( shared .catalog_bundle .as_ref() .expect("fixture bundle should remain configured") .manifest(game_id) .is_err(), "the adapter result must not depend on the now-invalid manifest body" ); } #[tokio::test] async fn missing_catalog_authority_is_a_startup_error() { let root = TestDir::new("missing-catalog-authority"); let error = load_catalog_authority( &root.0.join("missing-game.db"), &root.0.join("missing-manifests"), &[], ) .await .expect_err("missing authority must fail instead of starting with an empty catalog"); assert!( error .to_string() .contains("failed to load catalog authority") ); } fn shared_state(game_dir: PathBuf) -> SharedState { SharedState { state: RwLock::new(CliState::default()), peer_game_db: Arc::new(RwLock::new(PeerGameDB::new())), catalog_game_db: Arc::new(GameDB::empty()), catalog_bundle: None, call_to_play_display_name: RwLock::new("peer-cli".to_owned()), active_outbound_transfers: Arc::new(RwLock::new(HashMap::new())), notify: Notify::new(), games_dir: RwLock::new(game_dir), state_dir: PathBuf::from("state"), } } fn download_attempt(game_id: &str, attempt_id: u64) -> DownloadAttemptKey { serde_json::from_value(json!({ "id": game_id, "attempt_id": attempt_id.to_string(), })) .expect("test attempt key should use the public wire shape") } #[tokio::test] async fn stale_download_terminal_cannot_reap_newer_attempt_measurement() { let shared = shared_state(PathBuf::from("games")); let older = download_attempt("game", 1); let newer = download_attempt("game", 2); let (_, older_begin) = download_begin_event(&shared, older.clone()).await; let (_, newer_begin) = download_begin_event(&shared, newer.clone()).await; assert_eq!(older_begin["attempt_id"], "1"); assert_eq!(newer_begin["attempt_id"], "2"); let (_, stale_terminal) = download_terminal_event( &shared, "download-failed", older, Some(DownloadFailureReason::VerifiedCatalogSourcesExhausted), ) .await; assert_eq!(stale_terminal["attempt_id"], "1"); assert_eq!( stale_terminal["reason"], "verified-catalog-sources-exhausted" ); assert!(stale_terminal.get("throughput").is_none()); let (_, _) = download_chunk_finished_event( &shared, DownloadChunkFinishedEvent { id: "game".to_owned(), peer_id: "peer".to_owned(), peer_addr: "127.0.0.1:1".parse().expect("test address should parse"), content_id: "content".to_owned(), relative_path: "game.eti".to_owned(), offset: 0, length: 64, }, ) .await; let (_, current_terminal) = download_terminal_event(&shared, "download-finished", newer, None).await; assert_eq!(current_terminal["attempt_id"], "2"); assert_eq!(current_terminal["throughput"]["bytes"], 64); assert_eq!(current_terminal["throughput"]["chunks"], 1); } #[tokio::test] async fn download_activity_json_is_attempt_keyed_and_typed() { let shared = shared_state(PathBuf::from("games")); let attempt = download_attempt("game", 42); let (event, data) = update_state_from_event( &shared, PeerEvent::DownloadGameFilesActivityChanged { attempt, activity: Some(lanspread_peer::DownloadVerificationActivity::RetryingInvalidSource), }, ) .await; assert_eq!(event, "download-activity-changed"); assert_eq!(data["game_id"], "game"); assert_eq!(data["attempt_id"], "42"); assert_eq!(data["activity"], "retrying-invalid-source"); } #[tokio::test] async fn set_game_dir_stores_and_returns_only_the_acknowledged_path() { let shared = shared_state(PathBuf::from("previous-games")); let accepted = PathBuf::from("canonical-games"); let (sender, mut commands) = mpsc::unbounded_channel(); let request = set_game_dir(&sender, &shared, Path::new("alias-games")); let reply = async { let Some(PeerCommand::SetGameDir { path, reply }) = commands.recv().await else { panic!("SetGameDir command should carry a reply"); }; assert_eq!(path, Path::new("alias-games")); reply .send(Ok(accepted.clone())) .expect("SetGameDir requester should retain its reply receiver"); }; let (result, ()) = tokio::join!(request, reply); assert_eq!( result.expect("acknowledged directory should succeed"), json!({"accepted": true, "path": accepted}) ); assert_eq!(*shared.games_dir.read().await, accepted); } #[tokio::test] async fn set_game_dir_rejection_preserves_the_previous_path() { let previous = PathBuf::from("previous-games"); let shared = shared_state(previous.clone()); let (sender, mut commands) = mpsc::unbounded_channel(); let request = set_game_dir(&sender, &shared, Path::new("rejected-games")); let reply = async { let Some(PeerCommand::SetGameDir { reply, .. }) = commands.recv().await else { panic!("SetGameDir command should carry a reply"); }; reply .send(Err("operations are active".to_string())) .expect("SetGameDir requester should retain its reply receiver"); }; let (result, ()) = tokio::join!(request, reply); assert!( result .expect_err("rejected directory should fail") .to_string() .contains("operations are active") ); assert_eq!(*shared.games_dir.read().await, previous); } async fn assert_abnormal_command_finalizes( command_task: JoinHandle>, ) -> eyre::Report { let event_stop = tokio_util::sync::CancellationToken::new(); let shutdown_ran = Arc::new(AtomicBool::new(false)); let event_finished = Arc::new(AtomicBool::new(false)); let event_task = tokio::spawn({ let event_stop = event_stop.clone(); let shutdown_ran = shutdown_ran.clone(); let event_finished = event_finished.clone(); async move { event_stop.cancelled().await; assert!( shutdown_ran.load(Ordering::SeqCst), "the runtime finalizer must release the event loop" ); event_finished.store(true, Ordering::SeqCst); } }); let shutdown = { let shutdown_ran = shutdown_ran.clone(); async move { shutdown_ran.store(true, Ordering::SeqCst); event_stop.cancel(); } }; let signal = std::future::pending::>(); let error = join_cli_scope(command_task, event_task, signal, shutdown) .await .expect_err("an abnormal command task must fail the CLI scope"); assert!(shutdown_ran.load(Ordering::SeqCst)); assert!( event_finished.load(Ordering::SeqCst), "the CLI scope must join its event task before returning" ); error } #[tokio::test] async fn command_loop_panic_still_finalizes_runtime_and_event_loop() { async fn panic_command_loop() -> eyre::Result { tokio::task::yield_now().await; panic!("injected command-loop panic"); } let command_task = tokio::spawn(panic_command_loop()); let error = assert_abnormal_command_finalizes(command_task).await; assert!( error .to_string() .contains("command loop task failed to join") ); } #[tokio::test] async fn command_loop_cancellation_still_finalizes_runtime_and_event_loop() { let command_task = tokio::spawn(std::future::pending::>()); command_task.abort(); let error = assert_abnormal_command_finalizes(command_task).await; assert!( error .to_string() .contains("command loop task failed to join") ); } #[cfg(unix)] #[tokio::test] async fn regular_file_commands_are_preloaded_before_runtime_ownership() { let path = temp_file_path("regular-stdin"); std::fs::write(&path, b"first\nsecond\n").expect("should create redirected stdin file"); let file = std::fs::File::open(&path).expect("should reopen redirected stdin file"); let input = CommandInput::from_unix_file(file).expect("regular input should preload"); assert!(matches!(&input, CommandInput::Buffered(_))); let mut lines = BufReader::new(input).lines(); assert_eq!( lines.next_line().await.expect("first line should decode"), Some("first".to_string()) ); assert_eq!( lines.next_line().await.expect("second line should decode"), Some("second".to_string()) ); assert_eq!(lines.next_line().await.expect("EOF should decode"), None); std::fs::remove_file(path).expect("should remove redirected stdin fixture"); } #[cfg(unix)] #[tokio::test] async fn pending_pollable_stdin_is_quiescent_before_exceptional_exit_policy() { let (read_end, _write_end) = std::os::unix::net::UnixStream::pair().expect("should create pending stdin socket"); let poll_started = Arc::new(Notify::new()); let file = std::fs::File::from(OwnedFd::from(read_end)); let stdin = UnixStdin::new(file) .expect("socket should be pollable") .with_poll_started(poll_started.clone()); let input = CommandInput::Pollable(stdin); let (sender, _commands) = mpsc::unbounded_channel(); let command_task = tokio::spawn(command_loop( input, sender, Arc::new(shared_state(PathBuf::from("games"))), JsonlWriter::new(), )); let event_task = tokio::spawn(async move { poll_started.notified().await; }); let shutdown_ran = Arc::new(AtomicBool::new(false)); let shutdown = { let shutdown_ran = shutdown_ran.clone(); async move { shutdown_ran.store(true, Ordering::SeqCst); } }; let outcome = tokio::time::timeout( Duration::from_secs(2), join_cli_scope( command_task, event_task, std::future::pending::>(), shutdown, ), ) .await .expect("pollable stdin cancellation must not hang") .expect("event-first settlement should produce a scope outcome"); assert!(shutdown_ran.load(Ordering::SeqCst)); let process_boundary_called = Arc::new(AtomicBool::new(false)); let error = finish_cli_scope(outcome, false, { let process_boundary_called = process_boundary_called.clone(); move |exit_code, failure| { assert!(shutdown_ran.load(Ordering::SeqCst)); assert_eq!(exit_code, 1); assert!(failure.is_some()); process_boundary_called.store(true, Ordering::SeqCst); eyre::bail!("injected process boundary") } }) .expect_err("the injected process boundary should return its error"); assert_eq!(error.to_string(), "injected process boundary"); assert!(process_boundary_called.load(Ordering::SeqCst)); } struct DropFlag(Arc); impl Drop for DropFlag { fn drop(&mut self) { self.0.store(true, Ordering::SeqCst); } } #[tokio::test] async fn injected_signal_settles_command_peer_and_events_before_returning() { let command_started = Arc::new(Notify::new()); let command_dropped = Arc::new(AtomicBool::new(false)); let command_task = tokio::spawn({ let command_started = command_started.clone(); let command_dropped = command_dropped.clone(); async move { let _drop_flag = DropFlag(command_dropped); command_started.notify_one(); std::future::pending::<()>().await; Ok(CommandLoopExit::Eof) } }); let event_stop = tokio_util::sync::CancellationToken::new(); let event_finished = Arc::new(AtomicBool::new(false)); let event_task = tokio::spawn({ let event_stop = event_stop.clone(); let event_finished = event_finished.clone(); async move { event_stop.cancelled().await; event_finished.store(true, Ordering::SeqCst); } }); let shutdown_ran = Arc::new(AtomicBool::new(false)); let shutdown = { let shutdown_ran = shutdown_ran.clone(); async move { shutdown_ran.store(true, Ordering::SeqCst); event_stop.cancel(); } }; let (send_signal, receive_signal) = oneshot::channel(); let signal = async move { receive_signal .await .wrap_err("injected signal sender disappeared") }; let scope = join_cli_scope(command_task, event_task, signal, shutdown); let trigger = async move { command_started.notified().await; send_signal .send(()) .expect("scope should retain its injected signal receiver"); }; let (outcome, ()) = tokio::join!(scope, trigger); let outcome = outcome.expect("injected signal should settle cleanly"); assert!(command_dropped.load(Ordering::SeqCst)); assert!(shutdown_ran.load(Ordering::SeqCst)); assert!(event_finished.load(Ordering::SeqCst)); let process_boundary_called = Arc::new(AtomicBool::new(false)); let exit = finish_cli_scope(outcome, true, { let process_boundary_called = process_boundary_called.clone(); move |_, _| { process_boundary_called.store(true, Ordering::SeqCst); eyre::bail!("signal should not require a Unix process boundary") } }) .expect("an injected signal should become a clean CLI exit"); assert!(matches!(exit, CommandLoopExit::Signal)); assert!(!process_boundary_called.load(Ordering::SeqCst)); } #[test] fn normal_command_exits_never_take_the_process_boundary() { let process_boundary_called = Arc::new(AtomicBool::new(false)); for exit in [ CommandLoopExit::Eof, CommandLoopExit::Shutdown { request_id: Some(json!(42)), }, ] { finish_cli_scope(CliScopeOutcome::Command(exit), false, { let process_boundary_called = process_boundary_called.clone(); move |_, _| { process_boundary_called.store(true, Ordering::SeqCst); eyre::bail!("normal command exit must not terminate the process") } }) .expect("normal command exit should remain ordinary"); } assert!(!process_boundary_called.load(Ordering::SeqCst)); } #[cfg(unix)] const SIGNAL_HELPER_ENV: &str = "LANSPREAD_TEST_SIGTERM_SCOPE_HELPER"; #[cfg(unix)] #[tokio::test(flavor = "current_thread")] async fn unix_sigterm_scope_helper() { if std::env::var_os(SIGNAL_HELPER_ENV).is_none() { return; } let input = CommandInput::open().expect("helper stdin should be pollable"); let (sender, _commands) = mpsc::unbounded_channel(); let command_task = tokio::spawn(command_loop( input, sender, Arc::new(shared_state(PathBuf::from("games"))), JsonlWriter::new(), )); let event_stop = tokio_util::sync::CancellationToken::new(); let event_task = tokio::spawn({ let event_stop = event_stop.clone(); async move { event_stop.cancelled().await; } }); let shutdown = async move { event_stop.cancel(); }; let scope_task = tokio::spawn(join_cli_scope( command_task, event_task, shutdown_signal(), shutdown, )); tokio::task::yield_now().await; println!("SIGNAL-SCOPE-READY"); std::io::stdout() .flush() .expect("helper readiness should flush"); let outcome = tokio::time::timeout(Duration::from_secs(5), scope_task) .await .expect("SIGTERM scope should not hang") .expect("SIGTERM scope task should join") .expect("SIGTERM scope should settle cleanly"); let exit = finish_cli_scope(outcome, true, |_, _| { eyre::bail!("Unix SIGTERM must not need process termination") }) .expect("SIGTERM should become a clean CLI exit"); assert!(matches!(exit, CommandLoopExit::Signal)); println!("SIGNAL-SCOPE-SETTLED"); std::io::stdout() .flush() .expect("helper settlement should flush"); } #[cfg(unix)] #[tokio::test] async fn real_sigterm_settles_scope_while_stdin_remains_open() { let executable = std::env::current_exe().expect("test executable path should exist"); let mut command = tokio::process::Command::new(executable); command .arg("--exact") .arg("tests::unix_sigterm_scope_helper") .arg("--nocapture") .env(SIGNAL_HELPER_ENV, "1") .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped()) .kill_on_drop(true); let mut child = command.spawn().expect("SIGTERM helper should spawn"); let _open_stdin = child .stdin .take() .expect("SIGTERM helper stdin should remain open"); let stdout = child .stdout .take() .expect("SIGTERM helper stdout should be piped"); let mut lines = BufReader::new(stdout).lines(); loop { let line = tokio::time::timeout(Duration::from_secs(5), lines.next_line()) .await .expect("SIGTERM helper readiness should not time out") .expect("SIGTERM helper stdout should be readable") .expect("SIGTERM helper should announce readiness"); if line.contains("SIGNAL-SCOPE-READY") { break; } } let raw_pid = i32::try_from(child.id().expect("SIGTERM helper should have a PID")) .expect("SIGTERM helper PID should fit a Unix pid_t"); let pid = rustix::process::Pid::from_raw(raw_pid).expect("SIGTERM helper PID should be nonzero"); rustix::process::kill_process(pid, rustix::process::Signal::TERM) .expect("SIGTERM should be delivered to helper"); let mut settled = false; while let Some(line) = tokio::time::timeout(Duration::from_secs(5), lines.next_line()) .await .expect("SIGTERM helper settlement should not time out") .expect("SIGTERM helper stdout should remain readable") { if line.contains("SIGNAL-SCOPE-SETTLED") { settled = true; } } let status = tokio::time::timeout(Duration::from_secs(5), child.wait()) .await .expect("SIGTERM helper process should not hang") .expect("SIGTERM helper process should be waitable"); assert!(status.success(), "SIGTERM helper failed with {status}"); assert!(settled, "SIGTERM helper must report settled ownership"); } }