Skip to main content

gent_daemon/
hosted.rs

1//! A web node's local socket carries scoped RPCs to its native hosting daemon.
2//! It owns no replicated store, sync loop, notification socket or updater.
3pub use crate::store::hosted::snapshot::{
4    Snapshot, export as checkpoint, export_for_epoch as checkpoint_for_epoch,
5};
6use crate::{config, connection};
7use anyhow::{Context, Result, ensure};
8use gent_protocol::{AgentOp, MAX_FRAME_BYTES, OwnerOp, Request, Response};
9use std::{fs, os::unix::fs::PermissionsExt, path::Path, sync::Arc, time::Duration};
10use tokio::{
11    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
12    net::{UnixListener, UnixStream},
13    sync::Semaphore,
14};
15
16fn wrap(request: Request, node: &str, gateway: &str, epoch: Option<u64>) -> Result<Request> {
17    match request {
18        Request::Agent { credential, action } => {
19            ensure!(
20                !matches!(
21                    action,
22                    AgentOp::FilePaths | AgentOp::FileImport { .. } | AgentOp::FileExport { .. }
23                ),
24                "local filesystem tools are unavailable to hosted chats"
25            );
26            Ok(Request::HostedAgent {
27                node_id: node.into(),
28                gateway_credential: gateway.into(),
29                epoch,
30                credential,
31                action,
32            })
33        }
34        Request::Owner {
35            credential,
36            action: OwnerOp::Status,
37        } if credential == gateway => Ok(Request::HostedStatus {
38            node_id: node.into(),
39            gateway_credential: gateway.into(),
40        }),
41        _ => anyhow::bail!("operation unavailable on a hosted node"),
42    }
43}
44
45async fn serve(
46    stream: UnixStream,
47    parent: &Path,
48    node: &str,
49    key: &str,
50    epoch: Option<u64>,
51) -> Result<()> {
52    let mut stream = BufReader::new(stream);
53    let mut frame = Vec::new();
54    (&mut stream)
55        .take(MAX_FRAME_BYTES as u64 + 1)
56        .read_until(b'\n', &mut frame)
57        .await?;
58    ensure!(
59        frame.len() <= MAX_FRAME_BYTES && frame.last() == Some(&b'\n'),
60        "invalid hosted request"
61    );
62    let request = serde_json::from_slice(&frame)
63        .map_err(anyhow::Error::from)
64        .and_then(|request| wrap(request, node, key, epoch));
65    let request = match request {
66        Ok(request) => request,
67        Err(_) => {
68            let mut error = serde_json::to_vec(&Response::Error(
69                "operation unavailable on a hosted node".into(),
70            ))?;
71            error.push(b'\n');
72            stream.write_all(&error).await?;
73            return Ok(());
74        }
75    };
76    let mut upstream = connection::connect(parent, true).await?;
77    let mut data = serde_json::to_vec(&request)?;
78    data.push(b'\n');
79    ensure!(data.len() <= MAX_FRAME_BYTES, "hosted request too large");
80    upstream.write_all(&data).await?;
81    // Keep buffered binary upload bytes, and stream both response phases. The
82    // parent rechecks child membership and the chat credential at each commit.
83    tokio::io::copy_bidirectional(&mut stream, &mut upstream).await?;
84    Ok(())
85}
86
87/// All web nodes supervised by one native daemon share this descriptor budget.
88#[derive(Clone)]
89pub struct ConnectionBudget(Arc<Semaphore>);
90
91impl Default for ConnectionBudget {
92    fn default() -> Self {
93        Self(Arc::new(Semaphore::new(16)))
94    }
95}
96
97pub async fn run(home: &Path, shutdown: impl std::future::Future<Output = ()>) -> Result<()> {
98    run_with_budget(home, shutdown, ConnectionBudget::default()).await
99}
100
101pub async fn run_with_budget(
102    home: &Path,
103    shutdown: impl std::future::Future<Output = ()>,
104    budget: ConnectionBudget,
105) -> Result<()> {
106    run_scoped(home, shutdown, budget, None).await
107}
108
109pub async fn run_with_epoch(
110    home: &Path,
111    shutdown: impl std::future::Future<Output = ()>,
112    budget: ConnectionBudget,
113    epoch: u64,
114) -> Result<()> {
115    run_scoped(home, shutdown, budget, Some(epoch)).await
116}
117
118async fn run_scoped(
119    home: &Path,
120    shutdown: impl std::future::Future<Output = ()>,
121    budget: ConnectionBudget,
122    epoch: Option<u64>,
123) -> Result<()> {
124    tokio::pin!(shutdown);
125    let cfg = config::load_for_runtime(home)?;
126    let parent = cfg
127        .hosted_parent()?
128        .context("web node has no hosting daemon")?;
129    let host = config::load_for_runtime(&parent.home)?;
130    ensure!(
131        host.node.id == parent.node_id
132            && host.cluster.id == cfg.cluster.id
133            && host.hosted_parent()?.is_none(),
134        "hosting daemon identity changed"
135    );
136    let _lock = config::state_lock(home, "daemon.lock")?;
137    let key = Arc::new(zeroize::Zeroizing::new(config::read_private(
138        &home.join("owner.key"),
139    )?));
140    crate::request(
141        &parent.home,
142        Request::HostedStatus {
143            node_id: cfg.node.id.clone(),
144            gateway_credential: (**key).clone(),
145        },
146    )
147    .await?;
148    let socket = home.join("daemon.sock");
149    if socket.exists() {
150        fs::remove_file(&socket)?;
151    }
152    let listener = UnixListener::bind(&socket)?;
153    fs::set_permissions(&socket, fs::Permissions::from_mode(0o600))?;
154    let permits = budget.0;
155    let mut pending = tokio::task::JoinSet::new();
156    loop {
157        tokio::select! {
158            _=&mut shutdown=>break,
159            _=pending.join_next(), if !pending.is_empty()=>{},
160            accepted=listener.accept()=> {
161                let (socket,_) = accepted?;
162                let Ok(permit)=permits.clone().try_acquire_owned() else {continue;};
163                let parent=parent.home.clone();
164                let node=cfg.node.id.clone();
165                let key=key.clone();
166                pending.spawn(async move {
167                    let _permit=permit;
168                    let _=tokio::time::timeout(Duration::from_secs(35),serve(socket,&parent,&node,&key,epoch)).await;
169                });
170            }
171        }
172    }
173    drop(listener);
174    fs::remove_file(socket)?;
175    while pending.join_next().await.is_some() {}
176    Ok(())
177}