Skip to main content

adk_server/background/
table.rs

1//! A live table of agent targets that [`DurableWorker`](super::DurableWorker)s read on
2//! every claim (spec 3.3 §10 S4).
3//!
4//! A worker built with [`with_agent`](super::DurableWorker::with_agent) knows its targets
5//! from the start. A host that adds agents while its workers run — the kernel's agents a
6//! person adds (spec 3.3 §5.7) — shares one [`AgentTable`] with every worker through
7//! [`with_agent_table`](super::DurableWorker::with_agent_table) and changes it in place: a
8//! target [`insert`](AgentTable::insert)ed serves the next claim on every queue, and a
9//! target [`remove`](AgentTable::remove)d is refused from the next claim on.
10//!
11//! A replica that has not built a target yet still knows it should: the host marks it
12//! [`expect`](AgentTable::expect)ed, and a worker hands a claimed run of an expected target
13//! that is not built back to its queue for a later claim instead of failing it.
14//!
15//! | Target | A claim of its run |
16//! |---|---|
17//! | Built (in the table) | Runs on the table's runner |
18//! | Expected, not built | Handed back, claimable again one poll interval later ([`ParkReason::HandedBack`](super::ParkReason::HandedBack)) |
19//! | Neither | Fails without retry, as an unknown target always has |
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::sync::{Arc, RwLock};
23
24use adk_runner::Runner;
25
26/// A shared, cloneable map of agent target → [`Runner`], with the set of targets the host
27/// expects to serve (spec 3.3 §10 S4). Clones share one table.
28///
29/// # Example
30///
31/// ```rust
32/// use adk_server::background::AgentTable;
33///
34/// let table = AgentTable::new();
35/// table.expect("finance");
36/// assert!(table.is_expected("finance"));
37/// assert!(table.get("finance").is_none(), "expected, not built yet");
38/// assert!(table.forget("finance"));
39/// assert!(!table.is_expected("finance"));
40/// ```
41#[derive(Clone, Default)]
42pub struct AgentTable {
43    // A std lock: workers read it from the synchronous `has_target`, and no guard is held
44    // across an await.
45    inner: Arc<RwLock<Entries>>,
46}
47
48#[derive(Default)]
49struct Entries {
50    agents: BTreeMap<String, Arc<Runner>>,
51    expected: BTreeSet<String>,
52}
53
54impl std::fmt::Debug for AgentTable {
55    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56        let entries = self.read();
57        f.debug_struct("AgentTable")
58            .field("agents", &entries.agents.keys().collect::<Vec<_>>())
59            .field("expected", &entries.expected)
60            .finish()
61    }
62}
63
64impl AgentTable {
65    /// An empty table.
66    pub fn new() -> Self {
67        Self::default()
68    }
69
70    fn read(&self) -> std::sync::RwLockReadGuard<'_, Entries> {
71        self.inner.read().unwrap_or_else(|e| e.into_inner())
72    }
73
74    fn write(&self) -> std::sync::RwLockWriteGuard<'_, Entries> {
75        self.inner.write().unwrap_or_else(|e| e.into_inner())
76    }
77
78    /// Hosts `runner` as `target`, replacing the runner it had; returns the replaced one.
79    ///
80    /// A claim already running on the replaced runner finishes on it; the next claim of
81    /// `target` runs on `runner`.
82    ///
83    /// # Example
84    ///
85    /// ```rust,ignore
86    /// let table = AgentTable::new();
87    /// assert!(table.insert("finance", Arc::new(runner)).is_none());
88    /// assert!(table.contains("finance"));
89    /// ```
90    pub fn insert(&self, target: impl Into<String>, runner: Arc<Runner>) -> Option<Arc<Runner>> {
91        self.write().agents.insert(target.into(), runner)
92    }
93
94    /// Stops hosting `target`; returns its runner. The target stays expected until
95    /// [`forget`](Self::forget), so a claim of it is handed back rather than failed.
96    ///
97    /// # Example
98    ///
99    /// ```rust
100    /// use adk_server::background::AgentTable;
101    ///
102    /// assert!(AgentTable::new().remove("finance").is_none());
103    /// ```
104    pub fn remove(&self, target: &str) -> Option<Arc<Runner>> {
105        self.write().agents.remove(target)
106    }
107
108    /// The runner hosted as `target`, if any.
109    ///
110    /// # Example
111    ///
112    /// ```rust
113    /// use adk_server::background::AgentTable;
114    ///
115    /// assert!(AgentTable::new().get("finance").is_none());
116    /// ```
117    pub fn get(&self, target: &str) -> Option<Arc<Runner>> {
118        self.read().agents.get(target).cloned()
119    }
120
121    /// Whether a runner is hosted as `target`.
122    ///
123    /// # Example
124    ///
125    /// ```rust
126    /// use adk_server::background::AgentTable;
127    ///
128    /// assert!(!AgentTable::new().contains("finance"));
129    /// ```
130    pub fn contains(&self, target: &str) -> bool {
131        self.read().agents.contains_key(target)
132    }
133
134    /// The hosted targets, sorted.
135    ///
136    /// # Example
137    ///
138    /// ```rust
139    /// use adk_server::background::AgentTable;
140    ///
141    /// assert!(AgentTable::new().targets().is_empty());
142    /// ```
143    pub fn targets(&self) -> Vec<String> {
144        self.read().agents.keys().cloned().collect()
145    }
146
147    /// Marks `target` as one the host serves, built or not: a claim of it before it is
148    /// built is handed back for a later claim.
149    ///
150    /// # Example
151    ///
152    /// ```rust
153    /// use adk_server::background::AgentTable;
154    ///
155    /// let table = AgentTable::new();
156    /// table.expect("finance");
157    /// assert_eq!(table.expected(), ["finance"]);
158    /// ```
159    pub fn expect(&self, target: impl Into<String>) {
160        self.write().expected.insert(target.into());
161    }
162
163    /// Stops expecting `target`; returns whether it was expected. A claim of it that no
164    /// runner serves then fails as an unknown target's does.
165    ///
166    /// # Example
167    ///
168    /// ```rust
169    /// use adk_server::background::AgentTable;
170    ///
171    /// assert!(!AgentTable::new().forget("finance"));
172    /// ```
173    pub fn forget(&self, target: &str) -> bool {
174        self.write().expected.remove(target)
175    }
176
177    /// Whether the host expects to serve `target`.
178    ///
179    /// # Example
180    ///
181    /// ```rust
182    /// use adk_server::background::AgentTable;
183    ///
184    /// assert!(!AgentTable::new().is_expected("finance"));
185    /// ```
186    pub fn is_expected(&self, target: &str) -> bool {
187        self.read().expected.contains(target)
188    }
189
190    /// The expected targets, sorted.
191    ///
192    /// # Example
193    ///
194    /// ```rust
195    /// use adk_server::background::AgentTable;
196    ///
197    /// assert!(AgentTable::new().expected().is_empty());
198    /// ```
199    pub fn expected(&self) -> Vec<String> {
200        self.read().expected.iter().cloned().collect()
201    }
202}