Skip to main content

agentmux_srv/drone/
host.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The server a running drone's blocks reach AgentMux through.
5//!
6//! A block is `run(node, &scope)` and has no server handle in its signature
7//! (the engine's rule: Drone phase 2, the Drone real-world jobs spec ยง4.2).
8//! The blocks that act on AgentMux itself (App query, Message, Task, Spawn, Notify) read it here.
9//! Set once at startup, the way `server::job_actions::install` and `server::jekt_cold::install` are.
10
11use std::sync::Arc;
12#[cfg(not(test))]
13use std::sync::OnceLock;
14
15use crate::server::AppState;
16
17#[cfg(not(test))]
18static HOST: OnceLock<AppState> = OnceLock::new();
19
20#[cfg(test)]
21thread_local! {
22    /// In a test the server is the test's own, on its own thread: a process-wide one set by one test would
23    /// reach every test after it when they share a process (the nightly's `cargo test`), and a block that
24    /// has no server there would find one.
25    static HOST: std::cell::Cell<Option<&'static AppState>> = const { std::cell::Cell::new(None) };
26}
27
28/// Give the drone blocks the server. Later calls change nothing.
29#[cfg(not(test))]
30pub(crate) fn install(state: &AppState) {
31    let _ = HOST.set(state.clone());
32}
33
34/// Give the drone blocks the server, for the test's own thread only.
35#[cfg(test)]
36pub(crate) fn install(state: &AppState) {
37    HOST.with(|h| {
38        if h.get().is_none() {
39            h.set(Some(Box::leak(Box::new(state.clone()))));
40        }
41    });
42}
43
44#[cfg(not(test))]
45fn current() -> Option<&'static AppState> {
46    HOST.get()
47}
48
49#[cfg(test)]
50fn current() -> Option<&'static AppState> {
51    HOST.with(std::cell::Cell::get)
52}
53
54/// Where a Drone block finds the drone it calls.
55pub(crate) trait DroneLookup: Send + Sync {
56    /// The graph of drone `id` at saved `version` (as it is saved now when none),
57    /// with the number of the version it is (0 for a graph that is no saved version).
58    fn graph(&self, id: &str, version: Option<i64>) -> Result<(crate::drone::types::DroneGraph, i64), String>;
59}
60
61/// The drones this AgentMux has saved.
62struct Saved;
63
64impl DroneLookup for Saved {
65    fn graph(&self, id: &str, version: Option<i64>) -> Result<(crate::drone::types::DroneGraph, i64), String> {
66        use crate::backend::storage::drone_store::DroneStore;
67        use crate::drone::versions::{graph_hash, DroneVersionStore, Pin};
68        let state = state()?;
69        if let Some(n) = version {
70            return match state.id_store.version_get(id, n) {
71                Ok(Some(v)) => Ok((v.graph, v.version)),
72                Ok(None) => Err(format!("drone {id} has no saved version {n}")),
73                Err(e) => Err(format!("drone {id} cannot be read: {e}")),
74            };
75        }
76        match state.id_store.drone_get(id) {
77            Ok(Some(d)) => {
78                let number = match state.id_store.version_resolve(id, Pin::Latest) {
79                    Ok(Some(v)) if v.hash == graph_hash(&d.graph) => v.version,
80                    _ => 0,
81                };
82                Ok((d.graph, number))
83            }
84            Ok(None) => Err(format!("there is no drone {id}")),
85            Err(e) => Err(format!("drone {id} cannot be read: {e}")),
86        }
87    }
88}
89
90/// The lookup a run gives its Drone blocks: the saved drones, once the server is set.
91pub(crate) fn lookup() -> Option<Arc<dyn DroneLookup>> {
92    current().map(|_| Arc::new(Saved) as Arc<dyn DroneLookup>)
93}
94
95/// The server, or why a block can't act yet.
96pub(crate) fn state() -> Result<&'static AppState, String> {
97    current().ok_or_else(|| "AgentMux isn't ready for this block yet".to_string())
98}