Skip to main content

gent_daemon/
lib.rs

1//! Native daemon with local agent RPC and encrypted configuration/message sync.
2mod access;
3pub mod backend;
4pub mod config;
5pub mod configuration_log;
6mod connection;
7pub mod encrypted;
8pub mod entitlements;
9pub mod file_objects;
10pub mod file_transport;
11pub mod hosted;
12pub mod invitation_transport;
13pub mod messages;
14pub mod pairing;
15mod receive;
16pub mod recovery;
17pub mod release_channel;
18pub mod replica;
19mod runtime;
20pub mod shutdown;
21mod storage;
22pub use receive::receive_file;
23pub mod store;
24pub mod sync;
25
26use anyhow::{Context, Result, ensure};
27use gent_protocol::{MAX_FRAME_BYTES, Request, Response};
28use std::{
29    fs,
30    os::unix::fs::PermissionsExt,
31    path::Path,
32    sync::{Arc, Mutex},
33    time::Duration,
34};
35use tokio::{
36    io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
37    net::{UnixListener, UnixStream},
38    sync::{OwnedSemaphorePermit, Semaphore},
39};
40
41pub async fn request(home: &Path, request: Request) -> Result<serde_json::Value> {
42    recovery::ensure_active(home)?;
43    let timeout = if matches!(
44        &request,
45        Request::Owner {
46            action: gent_protocol::OwnerOp::HistoryImport { .. }
47                | gent_protocol::OwnerOp::AgentRecover { .. },
48            ..
49        }
50    ) {
51        Duration::from_secs(185)
52    } else {
53        Duration::from_secs(15)
54    };
55    let operation = async {
56        // Status is a liveness probe used by service management and must report
57        // a stopped daemon immediately. Ordinary calls bridge a brief restart.
58        let probe = matches!(
59            &request,
60            Request::Owner {
61                action: gent_protocol::OwnerOp::Status,
62                ..
63            }
64        );
65        let mut socket = connection::connect(home, !probe).await?;
66        let mut data = serde_json::to_vec(&request)?;
67        data.push(b'\n');
68        ensure!(data.len() <= MAX_FRAME_BYTES, "request too large");
69        socket.write_all(&data).await?;
70        let mut data = Vec::new();
71        BufReader::new(socket.take(MAX_FRAME_BYTES as u64 + 1))
72            .read_until(b'\n', &mut data)
73            .await?;
74        ensure!(
75            data.len() <= MAX_FRAME_BYTES && data.last() == Some(&b'\n'),
76            "invalid daemon response"
77        );
78        match serde_json::from_slice(&data)? {
79            Response::Ok(value) => Ok(value),
80            Response::Error(message) => Err(anyhow::anyhow!(message)),
81        }
82    };
83    tokio::time::timeout(timeout, operation)
84        .await
85        .context("daemon request timed out")?
86}
87
88pub async fn run(home: &Path) -> Result<()> {
89    run_until(home, std::future::pending()).await
90}
91
92/// Ownership acquired before update recovery or opening the node database.
93pub struct DaemonLock {
94    home: std::path::PathBuf,
95    _file: fs::File,
96    build_info: serde_json::Value,
97}
98
99impl DaemonLock {
100    pub fn acquire(home: &Path) -> Result<Self> {
101        recovery::ensure_active(home)?;
102        config::private_dir(home)?;
103        Ok(Self {
104            home: home.to_owned(),
105            _file: config::state_lock(home, "daemon.lock")?,
106            build_info: serde_json::Value::Null,
107        })
108    }
109
110    pub fn home(&self) -> &Path {
111        &self.home
112    }
113
114    /// Executable metadata reported only by authenticated owner status calls.
115    pub fn with_build_info(mut self, build_info: serde_json::Value) -> Self {
116        self.build_info = build_info;
117        self
118    }
119}
120
121/// A cooperative update stops accepting new RPCs, drains accepted requests,
122/// and waits for in-progress database transactions before releasing ownership.
123pub async fn run_until(home: &Path, shutdown: impl std::future::Future<Output = ()>) -> Result<()> {
124    run_locked(DaemonLock::acquire(home)?, shutdown).await
125}
126
127pub async fn run_locked(
128    lock: DaemonLock,
129    shutdown: impl std::future::Future<Output = ()>,
130) -> Result<()> {
131    run_locked_until(lock, shutdown::with_signals(shutdown)?).await
132}
133
134/// Run until the caller requests shutdown, without installing signal handlers.
135/// Supervisors use this to drain dependent services before stopping native RPC.
136pub async fn run_locked_until(
137    lock: DaemonLock,
138    shutdown: impl std::future::Future<Output = ()>,
139) -> Result<()> {
140    tokio::pin!(shutdown);
141    let home = lock.home();
142    let build_info = Arc::new(lock.build_info.clone());
143    let store = Arc::new(Mutex::new(store::Store::open(home)?));
144    let socket = home.join("daemon.sock");
145    if socket.exists() {
146        fs::remove_file(&socket)?;
147    }
148    let listener = UnixListener::bind(&socket)?;
149    fs::set_permissions(&socket, fs::Permissions::from_mode(0o600))?;
150    let permits = Arc::new(Semaphore::new(32));
151    let uploads = Arc::new(Semaphore::new(2));
152    let refresh_waiters = Arc::new(Semaphore::new(64));
153    let mut maintenance = tokio::time::interval(Duration::from_secs(15 * 60));
154    maintenance.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
155    let mut maintenance_tasks = tokio::task::JoinSet::new();
156    let mut requests = tokio::task::JoinSet::new();
157    let mut busy = serde_json::to_vec(&Response::Error(
158        "daemon is busy; retry the same request".into(),
159    ))?;
160    busy.push(b'\n');
161    let sync_task = sync::start(store.clone())?;
162    let invitation_task = invitation_transport::owner::start(store.clone());
163    eprintln!("Gent daemon listening at {}", socket.display());
164    loop {
165        tokio::select! {
166            _=&mut shutdown=>break,
167            _=maintenance.tick(), if maintenance_tasks.is_empty()=> {
168                let store = store.clone();
169                maintenance_tasks.spawn(access::run(store, "maintenance", |store| store.maintain()));
170            }
171            result=maintenance_tasks.join_next(), if !maintenance_tasks.is_empty()=> {
172                if let Some(result) = result
173                    && let Err(error) = result? {
174                    eprintln!("Gent configuration maintenance pending: {error}");
175                }
176            }
177            _=requests.join_next(), if !requests.is_empty()=> {}
178            connection=listener.accept()=> {
179                let (stream,_)=connection?;
180                let Ok(permit)=permits.clone().try_acquire_owned() else {
181                    let _ = stream.try_write(&busy);
182                    continue;
183                };
184                let store=store.clone();
185                let uploads=uploads.clone();
186                let refresh_waiters=refresh_waiters.clone();
187                let build_info=build_info.clone();
188                requests.spawn(async move {
189                    let _=serve(stream,store,uploads,permit,build_info,refresh_waiters).await;
190                });
191            }
192        }
193    }
194    drop(listener);
195    fs::remove_file(&socket)?;
196    if let Some(task) = sync_task {
197        task.abort();
198        let _ = task.await;
199    }
200    invitation_task.stop().await;
201    // Request handlers already enforce their own deadlines. Dropping them here
202    // could lose the response after a committed send; let accepted RPCs finish.
203    while requests.join_next().await.is_some() {}
204    while maintenance_tasks.join_next().await.is_some() {}
205    access::run(store, "shutdown", |_| Ok(())).await?;
206    Ok(())
207}
208
209async fn serve(
210    stream: UnixStream,
211    store: Arc<Mutex<store::Store>>,
212    uploads: Arc<Semaphore>,
213    permit: OwnedSemaphorePermit,
214    build_info: Arc<serde_json::Value>,
215    refresh_waiters: Arc<Semaphore>,
216) -> Result<()> {
217    let started = tokio::time::Instant::now();
218    let mut stream = BufReader::new(stream);
219    let mut frame = Vec::new();
220    tokio::time::timeout(
221        Duration::from_secs(10),
222        (&mut stream)
223            .take(MAX_FRAME_BYTES as u64 + 1)
224            .read_until(b'\n', &mut frame),
225    )
226    .await
227    .context("request frame timed out")??;
228    ensure!(
229        frame.len() <= MAX_FRAME_BYTES && frame.last() == Some(&b'\n'),
230        "invalid request frame"
231    );
232    let decoded = serde_json::from_slice::<Request>(&frame);
233    let report_build = matches!(
234        &decoded,
235        Ok(Request::Owner {
236            action: gent_protocol::OwnerOp::Status,
237            ..
238        })
239    );
240    let deadline = started
241        + if matches!(
242            &decoded,
243            Ok(Request::Owner {
244                action: gent_protocol::OwnerOp::HistoryImport { .. }
245                    | gent_protocol::OwnerOp::AgentRecover { .. },
246                ..
247            })
248        ) {
249            Duration::from_secs(180)
250        } else {
251            Duration::from_secs(10)
252        };
253    let mut response = match decoded {
254        Ok(
255            request @ (Request::Owner {
256                action: gent_protocol::OwnerOp::DashboardGrant { .. },
257                ..
258            }
259            | Request::DashboardDelegate { .. }),
260        ) => {
261            match tokio::time::timeout_at(
262                deadline,
263                sync::direct::board_grant::route(store, request),
264            )
265            .await
266            {
267                Ok(Ok(value)) => Response::Ok(value),
268                Ok(Err(error)) => Response::Error(error.to_string()),
269                Err(_) => Response::Error(
270                    "board grant operation timed out; check the current revision".into(),
271                ),
272            }
273        }
274        Ok(Request::Owner {
275            credential,
276            action: gent_protocol::OwnerOp::DashboardRemoteHtml { boards },
277        }) => {
278            let read = sync::direct::board_html::read(store, credential, boards);
279            match tokio::time::timeout_at(deadline, read).await {
280                Ok(Ok(rows)) => Response::Ok(serde_json::json!(rows)),
281                Ok(Err(error)) => Response::Error(error.to_string()),
282                Err(_) => Response::Error("board carrier timed out".into()),
283            }
284        }
285        Ok(Request::Owner {
286            credential,
287            action: gent_protocol::OwnerOp::RefreshStats,
288        }) => {
289            // Move long-lived waiters out of the ordinary request pool as soon
290            // as the frame is classified. Bound their sockets independently.
291            drop(permit);
292            match refresh_waiters.try_acquire_owned() {
293                Ok(_slot) => {
294                    let refresh = async {
295                        let wait =
296                            access::run(store.clone(), "start statistics refresh", move |s| {
297                                s.begin_stats_refresh(&credential)
298                            })
299                            .await?;
300                        let id = wait.wait(deadline - Duration::from_secs(1)).await;
301                        access::run(store, "read refreshed statistics", move |s| {
302                            s.stats_snapshot(Some(id))
303                        })
304                        .await
305                    };
306                    match tokio::time::timeout_at(deadline, refresh).await {
307                        Ok(Ok(value)) => Response::Ok(value),
308                        Ok(Err(error)) => Response::Error(error.to_string()),
309                        Err(_) => Response::Error(
310                            "statistics request timed out waiting for local storage".into(),
311                        ),
312                    }
313                }
314                Err(_) => {
315                    Response::Error("too many statistics refresh waiters; retry shortly".into())
316                }
317            }
318        }
319        Ok(request) => {
320            if matches!(
321                &request,
322                Request::Agent {
323                    action: gent_protocol::AgentOp::FileReceive { .. },
324                    ..
325                } | Request::HostedAgent {
326                    action: gent_protocol::AgentOp::FileReceive { .. },
327                    ..
328                }
329            ) {
330                return tokio::time::timeout_at(
331                    deadline,
332                    receive::serve(stream, store, uploads, request),
333                )
334                .await
335                .context("file receive timed out")?;
336            }
337            match tokio::time::timeout_at(
338                deadline,
339                access::run(store, "local request", move |store| {
340                    // Keep capacity reserved until the transaction or cancelled
341                    // queue entry exits, even after its socket times out.
342                    let _permit = permit;
343                    Ok(store.handle(request))
344                }),
345            )
346            .await {
347                Ok(result) => result?,
348                Err(_) => Response::Error("daemon operation timed out; local storage is busy or the operation is still finishing; retry with the same request ID".into()),
349            }
350        }
351        Err(_) => Response::Error("invalid request".into()),
352    };
353    if report_build
354        && !build_info.is_null()
355        && let Response::Ok(value) = &mut response
356    {
357        value["build"] = (*build_info).clone();
358    }
359    let mut response = serde_json::to_vec(&response)?;
360    response.push(b'\n');
361    ensure!(response.len() <= MAX_FRAME_BYTES, "response too large");
362    // A timed-out transaction still deserves a complete protocol error frame.
363    tokio::time::timeout(
364        Duration::from_secs(2),
365        stream.get_mut().write_all(&response),
366    )
367    .await
368    .context("response write timed out")??;
369    Ok(())
370}
371
372#[cfg(test)]
373mod tests;