agentmux_srv/drone/
host.rs1use 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 static HOST: std::cell::Cell<Option<&'static AppState>> = const { std::cell::Cell::new(None) };
26}
27
28#[cfg(not(test))]
30pub(crate) fn install(state: &AppState) {
31 let _ = HOST.set(state.clone());
32}
33
34#[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
54pub(crate) trait DroneLookup: Send + Sync {
56 fn graph(&self, id: &str, version: Option<i64>) -> Result<(crate::drone::types::DroneGraph, i64), String>;
59}
60
61struct 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
90pub(crate) fn lookup() -> Option<Arc<dyn DroneLookup>> {
92 current().map(|_| Arc::new(Saved) as Arc<dyn DroneLookup>)
93}
94
95pub(crate) fn state() -> Result<&'static AppState, String> {
97 current().ok_or_else(|| "AgentMux isn't ready for this block yet".to_string())
98}