OXYGENHUB
# 39f5c913f617 spectra / src / cli / serve.rs
4.7 KiB · Rust · last changed Radar: Live, channels, threads and the log for the owner, signed in by a CLI-signed link; ledger writes survive a cancelled caller (#10) 2 days ago source blame history raw
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
13
pub async fn serve(ctx: &Ctx, bind: &str, insecure: bool, open: bool) -> Result<i32> {
14
    let addr: SocketAddr = bind.parse().with_context(|| format!("--bind {bind} is not an address and port"))?;
15
    if !addr.ip().is_loopback() && !insecure {
16
        bail!("Spectra serves loopback only unless it has TLS (spec §21.1); pass --insecure to bind {addr} in plain HTTP anyway");
17
    }
18
    let socket = ctx.socket();
19
    if socket.exists() {
20
        if Client::alive(&socket).await {
21
            bail!("Spectra is already serving {} (its socket answers)", ctx.data.display());
22
        }
23
        std::fs::remove_file(&socket).ok();
24
    }
25
    let daemon = Daemon::start(&ctx.data).await?;
26
    let unix = tokio::net::UnixListener::bind(&socket).with_context(|| format!("binding {}", socket.display()))?;
27
    #[cfg(unix)]
28
    {
29
        use std::os::unix::fs::PermissionsExt;
30
        std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o660))?;
31
    }
32
    let tcp = tokio::net::TcpListener::bind(addr).await.with_context(|| format!("binding {addr}"))?;
33
    let port = tcp.local_addr()?.port();
34
    let origins = vec![format!("http://127.0.0.1:{port}"), format!("http://localhost:{port}"), format!("http://{addr}")];
35
    let state = AppState { daemon: daemon.clone(), origins: Arc::new(origins) };
36
    let app = spectra_mcp::http::router(state.clone()).merge(radar::router(state));
37
38
    let (head, _) = daemon.ledger.head().await;
39
    let agents = sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM agents WHERE disabled_ms IS NULL")
40
        .fetch_one(daemon.ledger.pool())
41
        .await
42
        .unwrap_or(0);
43
    println!("{} {}", ui::done("Serving"), ui::subject("Spectra"));
44
    println!("{}", ui::kv("socket", ui::path(socket.display())));
45
    println!("{}", ui::kv("http", format!("http://127.0.0.1:{port}")));
46
    println!("{}", ui::kv("ledger", format!("{head} events{}{agents} agent(s)", ui::sep())));
47
    println!("  {} {}", ui::note(), ui::dim("agents connect with: spectra mcp --agent NAME"));
48
    println!("  {} {}", ui::note(), ui::dim("open Radar with: spectra open"));
49
    if open {
50
        let ctx2 = Ctx { data: ctx.data.clone() };
51
        tokio::spawn(async move {
52
            // Once the socket answers, sign the link as the owner and open it.
53
            tokio::time::sleep(std::time::Duration::from_millis(200)).await;
54
            if let Err(e) = super::open::open(&ctx2, None, true).await {
55
                eprintln!("{} {e:#}", ui::caution());
56
            }
57
        });
58
    }
59
60
    let (stop_tx, stop_rx) = tokio::sync::watch::channel(false);
61
    let stop = |mut rx: tokio::sync::watch::Receiver<bool>| async move {
62
        let _ = rx.wait_for(|s| *s).await;
63
    };
64
    let unix_srv =
65
        axum::serve(unix, app.clone().into_make_service_with_connect_info::<PeerInfo>()).with_graceful_shutdown(stop(stop_rx.clone()));
66
    let tcp_srv = axum::serve(tcp, app.into_make_service_with_connect_info::<PeerInfo>()).with_graceful_shutdown(stop(stop_rx));
67
    let signal = async move {
68
        shutdown_signal().await;
69
        let _ = stop_tx.send(true);
70
    };
71
    // After the signal, open connections get five seconds to finish: a
72
    // `subscriptions/listen` stream never does by itself.
73
    let (stopping_tx, mut stopping) = tokio::sync::watch::channel(false);
74
    tokio::spawn(async move {
75
        signal.await;
76
        let _ = stopping_tx.send(true);
77
    });
78
    let servers = async { tokio::join!(unix_srv, tcp_srv) };
79
    tokio::select! {
80
        (u, t) = servers => {
81
            u?;
82
            t?;
83
        }
84
        _ = async {
85
            let _ = stopping.wait_for(|s| *s).await;
86
            tokio::time::sleep(std::time::Duration::from_secs(5)).await;
87
        } => {
88
            tracing::info!("connections still open five seconds after the signal; stopping anyway");
89
        }
90
    }
91
    daemon.shutdown().await;
92
    std::fs::remove_file(&socket).ok();
93
    println!("{} {}", ui::done("Stopped"), ui::dim(format!("ledger checkpointed at {} events", daemon.ledger.head().await.0)));
94
    Ok(0)
95
}
96
97
async fn shutdown_signal() {
98
    #[cfg(unix)]
99
    {
100
        let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("a SIGTERM handler");
101
        tokio::select! {
102
            _ = tokio::signal::ctrl_c() => {}
103
            _ = term.recv() => {}
104
        }
105
    }
106
    #[cfg(not(unix))]
107
    let _ = tokio::signal::ctrl_c().await;
108
}