OXYGENHUB

Coverage / src/cli/serve.rs 79.5%

70 of 88 lines run, 10 of 28 functions · run #15 on main · run missed

1
//! `spectra serve`: the daemon (spec §7.1, §21.1). It holds the ledger,
2
//! serves Tuner (and, as they land, the API and Radar) on the Unix socket
3
//! and on a loopback port, and writes a checkpoint when it stops.
4
5
use super::{ui, Ctx};
6
use anyhow::{bail, Context, Result};
7
use spectra_core::daemon::Daemon;
8
use spectra_mcp::client::Client;
9
use spectra_mcp::http::{AppState, PeerInfo};
10
use std::net::SocketAddr;
11
use std::sync::Arc;
12
1310×
pub async fn serve(ctx: &Ctx, bind: &str, insecure: bool, open: bool) -> Result<i32> {
1410×
    let addr: SocketAddr = bind.parse().with_context(|| format!("--bind {bind} is not an address and port"))?;
1510×
    if !addr.ip().is_loopback() && !insecure {
160×
        bail!("Spectra serves loopback only unless it has TLS (spec §21.1); pass --insecure to bind {addr} in plain HTTP anyway");
1710×
    }
1810×
    let socket = ctx.socket();
1910×
    if socket.exists() {
200×
        if Client::alive(&socket).await {
210×
            bail!("Spectra is already serving {} (its socket answers)", ctx.data.display());
220×
        }
230×
        std::fs::remove_file(&socket).ok();
2410×
    }
2510×
    let daemon = Daemon::start(&ctx.data).await?;
2610×
    let unix = tokio::net::UnixListener::bind(&socket).with_context(|| format!("binding {}", socket.display()))?;
27
    #[cfg(unix)]
28
    {
29
        use std::os::unix::fs::PermissionsExt;
3010×
        std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o660))?;
31
    }
3210×
    let tcp = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
3310×
    let port = tcp.local_addr()?.port();
3410×
    let origins = vec![format!("http://127.0.0.1:{port}"), format!("http://localhost:{port}"), format!("http://{addr}")];
3510×
    let state = AppState { daemon: daemon.clone(), origins: Arc::new(origins), sessions: Default::default() };
3610×
    let app = spectra_mcp::http::router(state.clone()).merge(spectra_mcp::api::router(state.clone())).merge(radar::router(state));
37
3810×
    let (head, _) = daemon.ledger.head().await;
3910×
    let agents = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM agents WHERE disabled_ms IS NULL")
4010×
        .fetch_one(daemon.ledger.pool())
4110×
        .await
4210×
        .unwrap_or(0);
4310×
    println!("{} {}", ui::done("Serving"), ui::subject("Spectra"));
4410×
    println!("{}", ui::kv("socket", ui::path(socket.display())));
4510×
    println!("{}", ui::kv("http", format!("http://127.0.0.1:{port}")));
4610×
    println!("{}", ui::kv("ledger", format!("{head} events{}{agents} agent(s)", ui::sep())));
4710×
    println!("  {} {}", ui::note(), ui::dim("agents connect with: spectra mcp --agent NAME"));
4810×
    println!("  {} {}", ui::note(), ui::dim("open Radar with: spectra open"));
4910×
    if open {
500×
        let ctx2 = Ctx { data: ctx.data.clone() };
510×
        tokio::spawn(async move {
52
            // Once the socket answers, sign the link as the owner and open it.
530×
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
540×
            if let Err(e) = super::open::open(&ctx2, None, true).await {
550×
                eprintln!("{} {e:#}", ui::caution());
560×
            }
570×
        });
5810×
    }
59
6010×
    let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
6120×
    let stop = |mut rx: tokio::sync::watch::Receiver<bool>| async move {
6220×
        let _ = rx.wait_for(|s| *s).await;
6340×
    };
6410×
    let unix_srv =
6510×
        axum::serve(unix, app.clone().into_make_service_with_connect_info::<PeerInfo>()).with_graceful_shutdown(stop(stop_rx.clone()));
6610×
    let tcp_srv = axum::serve(tcp, app.into_make_service_with_connect_info::<PeerInfo>()).with_graceful_shutdown(stop(stop_rx));
6710×
    let signal = async move {
6810×
        shutdown_signal().await;
6910×
        let _ = stop_tx.send(true);
7010×
    };
71
    // After the signal, open connections get five seconds to finish: a
72
    // `subscriptions/listen` stream never does by itself.
7310×
    let (stopping_tx, mut stopping) = tokio::sync::watch::channel(false);
7410×
    tokio::spawn(async move {
7510×
        signal.await;
7610×
        let _ = stopping_tx.send(true);
7710×
    });
7810×
    let servers = async { tokio::join!(unix_srv, tcp_srv) };
7910×
    tokio::select! {
8010×
        (u, t) = servers => {
8110×
            u?;
8210×
            t?;
83
        }
8410×
        _ = async {
8510×
            let _ = stopping.wait_for(|s| *s).await;
866×
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
870×
        } => {
880×
            tracing::info!("connections still open five seconds after the signal; stopping anyway");
89
        }
90
    }
9110×
    daemon.shutdown().await;
9210×
    std::fs::remove_file(&socket).ok();
9310×
    println!("{} {}", ui::done("Stopped"), ui::dim(format!("ledger checkpointed at {} events", daemon.ledger.head().await.0)));
9410×
    Ok(0)
9510×
}
96
9710×
async fn shutdown_signal() {
98
    #[cfg(unix)]
99
    {
10010×
        let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("a SIGTERM handler");
10110×
        tokio::select! {
10210×
            _ = tokio::signal::ctrl_c() => {}
10310×
            _ = term.recv() => {}
104
        }
105
    }
106
    #[cfg(not(unix))]
107
    let _ = tokio::signal::ctrl_c().await;
10810×
}