Skip to main content

weirdnet_agent/
pool.rs

1//! The `pool` feature: the app side of remote inference over `weirdnet-net`.
2//!
3//! - [`NetDialer`]: a [`Dialer`] that opens agent protocol streams to peers by id.
4//! - [`LinkedNodes`]: a [`NodeSource`] of the inference nodes among the user's linked devices
5//!   (active certs in the `weirdnet-sync` roster whose node announces [`INFERENCE_APP`]),
6//!   direct connections before relayed ones.
7//! - [`connect`]: a [`Pool`] over both, presenting this device's certificate.
8//!
9//! The pool itself ([`crate::remote::pool`]) is transport-neutral.
10
11use std::collections::HashMap;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::sync::{Arc, Mutex};
14use std::time::{Duration, Instant};
15
16use async_trait::async_trait;
17use tokio::sync::watch;
18use weirdnet_net::Event;
19use weirdnet_net::node::Message;
20use weirdnet_net::user::NodeCert;
21use weirdnet_net::{Multiaddr, Node, Path, PeerId};
22use weirdnet_sync::Roster;
23
24use crate::net::open_error;
25pub use crate::net::{INFERENCE_APP, channel, decode_cert, encode_cert, stream_limits};
26pub use crate::remote::pool::{Answer, CatalogWatch, EventSink, Interrupted, Job, NoEvents, NodeSource, Pool, PoolEvent, PoolOptions, Stall};
27use crate::remote::{Channel, Dialer, RemoteError};
28
29/// Opens agent streams over a `weirdnet-net` node. Node ids are peer ids.
30pub struct NetDialer<Q: Message, R: Message> {
31    node: Arc<Node<Q, R>>,
32    hints: Mutex<HashMap<PeerId, Vec<Multiaddr>>>,
33}
34
35impl<Q: Message, R: Message> NetDialer<Q, R> {
36    pub fn new(node: Arc<Node<Q, R>>) -> Self {
37        Self { node, hints: Mutex::new(HashMap::new()) }
38    }
39
40    /// Addresses to try for a peer (LAN, fixed or relay circuit addresses).
41    pub fn hint(&self, peer: PeerId, addrs: Vec<Multiaddr>) {
42        self.hints.lock().unwrap_or_else(|e| e.into_inner()).insert(peer, addrs);
43    }
44}
45
46#[async_trait]
47impl<Q: Message, R: Message> Dialer for NetDialer<Q, R> {
48    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
49        let peer: PeerId = node.parse().map_err(|_| RemoteError::Unreachable { message: format!("{node} is not a peer id") })?;
50        let addrs = self.hints.lock().unwrap_or_else(|e| e.into_inner()).get(&peer).cloned().unwrap_or_default();
51        let stream = self.node.open_stream_async(peer, &addrs, protocol, stream_limits()).await.map_err(open_error)?;
52        Ok(channel(stream))
53    }
54}
55
56/// The roster as it is now (the app keeps it current from `weirdnet-sync`).
57pub type RosterView = Arc<dyn Fn() -> Roster + Send + Sync>;
58
59/// How long a probe's `connect` may take (the node's own limit).
60const CONNECT_LIMIT: Duration = Duration::from_secs(30);
61/// Once a probe finds an inference node, how long to keep waiting for the other probes.
62const SETTLE: Duration = Duration::from_millis(250);
63
64/// What the last look at a linked device found.
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
66enum Seen {
67    /// A probe (connect, then wait for identify) is under way.
68    Probing,
69    /// Identified and announces [`INFERENCE_APP`]; `direct` if a direct connection is open.
70    Inference { direct: bool },
71    /// Identified, not an inference node.
72    Other,
73    /// Could not be connected to, or did not identify in time.
74    Unreachable,
75}
76
77/// State shared by every call to [`LinkedNodes::nodes`] and its background probes.
78struct Shared {
79    seen: Mutex<HashMap<PeerId, (Seen, Instant)>>,
80    /// Bumped whenever a probe finishes.
81    changed: watch::Sender<u64>,
82    watching: AtomicBool,
83}
84
85impl Shared {
86    fn seen(&self) -> std::sync::MutexGuard<'_, HashMap<PeerId, (Seen, Instant)>> {
87        self.seen.lock().unwrap_or_else(|e| e.into_inner())
88    }
89
90    fn record(&self, peer: PeerId, seen: Seen) {
91        self.seen().insert(peer, (seen, Instant::now()));
92        self.changed.send_modify(|n| *n = n.wrapping_add(1));
93    }
94
95    /// Try unreachable devices again on the next call (`None`: all of them).
96    fn forget_unreachable(&self, peer: Option<PeerId>) {
97        self.seen().retain(|p, (s, _)| *s != Seen::Unreachable || peer.is_some_and(|q| q != *p));
98    }
99}
100
101/// What `node` knows about `peer` without dialing (`None`: not connected or not identified).
102fn identified<Q: Message, R: Message>(node: &Node<Q, R>, peer: PeerId) -> Option<Seen> {
103    let apps = node.peer_apps(peer)?;
104    if !apps.iter().any(|a| a == INFERENCE_APP) {
105        return Some(Seen::Other);
106    }
107    let direct = node.paths(peer).map(|p| p.contains(&Path::Direct)).unwrap_or(false);
108    Some(Seen::Inference { direct })
109}
110
111/// The inference nodes among the user's linked devices.
112///
113/// [`NodeSource::nodes`] answers at once with the devices that are connected and announce
114/// [`INFERENCE_APP`]; devices not known yet are probed in the background. Only when none is
115/// known does it wait, for all probes together, at most [`LinkedNodes::with_wait`]. A device
116/// that can't be connected to (no addresses, dial refused) is given up on at once; one that
117/// can't be reached or doesn't identify is skipped for [`LinkedNodes::with_retry_after`], or
118/// until it connects, the network changes or the node resumes.
119pub struct LinkedNodes<Q: Message, R: Message> {
120    node: Arc<Node<Q, R>>,
121    roster: RosterView,
122    hints: HashMap<PeerId, Vec<Multiaddr>>,
123    wait: Duration,
124    retry_after: Duration,
125    shared: Arc<Shared>,
126}
127
128impl<Q: Message, R: Message> LinkedNodes<Q, R> {
129    pub fn new(node: Arc<Node<Q, R>>, roster: RosterView) -> Self {
130        let shared = Arc::new(Shared { seen: Mutex::new(HashMap::new()), changed: watch::channel(0).0, watching: AtomicBool::new(false) });
131        Self { node, roster, hints: HashMap::new(), wait: Duration::from_secs(3), retry_after: Duration::from_secs(30), shared }
132    }
133
134    /// Addresses to connect to a device through.
135    pub fn with_hint(mut self, peer: PeerId, addrs: Vec<Multiaddr>) -> Self {
136        self.hints.insert(peer, addrs);
137        self
138    }
139
140    /// When no inference node is known yet, how long to wait for the devices to connect and
141    /// identify (one deadline for all of them; default 3 s). Also how long each probe waits
142    /// for identify once connected.
143    pub fn with_wait(mut self, wait: Duration) -> Self {
144        self.wait = wait;
145        self
146    }
147
148    /// How long a device that couldn't be reached or identified is skipped before it is
149    /// probed again (default 30 s).
150    pub fn with_retry_after(mut self, retry_after: Duration) -> Self {
151        self.retry_after = retry_after;
152        self
153    }
154
155    /// Forget unreachable devices when one connects, the network changes or the node resumes.
156    fn watch_events(&self) {
157        if self.shared.watching.swap(true, Ordering::SeqCst) {
158            return;
159        }
160        let Ok(rt) = tokio::runtime::Handle::try_current() else {
161            self.shared.watching.store(false, Ordering::SeqCst);
162            return;
163        };
164        let mut events = self.node.events();
165        let shared = Arc::downgrade(&self.shared);
166        rt.spawn(async move {
167            use futures::StreamExt;
168            while let Some(ev) = events.next().await {
169                let Some(shared) = shared.upgrade() else { break };
170                match ev {
171                    Event::Connected { peer, .. } => shared.forget_unreachable(Some(peer)),
172                    Event::NetworkChanged | Event::Resumed => shared.forget_unreachable(None),
173                    _ => {}
174                }
175            }
176        });
177    }
178
179    /// Connect to `peer` and wait (at most `wait`) for it to identify, in the background.
180    fn probe(&self, peer: PeerId) {
181        let node = self.node.clone();
182        let addrs = self.hints.get(&peer).cloned().unwrap_or_default();
183        let wait = self.wait;
184        let shared = Arc::downgrade(&self.shared);
185        tokio::task::spawn_blocking(move || {
186            let t = Instant::now();
187            let seen = match node.connect(peer, &addrs) {
188                Err(e) => {
189                    tracing::debug!(%peer, error = %e, "linked device unreachable");
190                    Seen::Unreachable
191                }
192                Ok(()) => {
193                    let until = Instant::now() + wait;
194                    loop {
195                        if let Some(s) = identified(&node, peer) {
196                            break s;
197                        }
198                        if Instant::now() >= until {
199                            tracing::debug!(%peer, "linked device connected but did not identify in time");
200                            break Seen::Unreachable;
201                        }
202                        std::thread::sleep(Duration::from_millis(25));
203                    }
204                }
205            };
206            tracing::debug!(%peer, ?seen, took = ?t.elapsed(), "probed linked device");
207            if let Some(shared) = shared.upgrade() {
208                shared.record(peer, seen);
209            }
210        });
211    }
212}
213
214#[async_trait]
215impl<Q: Message, R: Message> NodeSource for LinkedNodes<Q, R> {
216    async fn nodes(&self) -> Vec<String> {
217        let started = Instant::now();
218        self.watch_events();
219        let me = self.node.peer_id();
220        let roster = (self.roster)();
221        let mut peers: Vec<PeerId> = Vec::new();
222        for p in roster.active().filter_map(|c: &NodeCert| c.peer_id.parse::<PeerId>().ok()) {
223            if p != me && !peers.contains(&p) {
224                peers.push(p);
225            }
226        }
227        // What the node knows now, without dialing (one blocking call per device, together:
228        // each node query is a round trip to its event loop).
229        let known: Vec<Option<Seen>> = futures::future::join_all(peers.iter().map(|p| {
230            let (node, p) = (self.node.clone(), *p);
231            tokio::task::spawn_blocking(move || identified(&node, p))
232        }))
233        .await
234        .into_iter()
235        .map(|r| r.ok().flatten())
236        .collect();
237        let mut changed = self.shared.changed.subscribe();
238        let mut state: Vec<Option<Seen>> = vec![None; peers.len()];
239        let mut probe = Vec::new();
240        {
241            let now = Instant::now();
242            let mut seen = self.shared.seen();
243            for (i, peer) in peers.iter().enumerate() {
244                if let Some(s) = known[i] {
245                    seen.insert(*peer, (s, now));
246                    state[i] = Some(s);
247                    continue;
248                }
249                match seen.get(peer) {
250                    Some((Seen::Unreachable, at)) if now.duration_since(*at) < self.retry_after => state[i] = Some(Seen::Unreachable),
251                    Some((Seen::Probing, at)) if now.duration_since(*at) < CONNECT_LIMIT + self.wait => {}
252                    _ => {
253                        seen.insert(*peer, (Seen::Probing, now));
254                        probe.push(*peer);
255                    }
256                }
257            }
258        }
259        for peer in &probe {
260            self.probe(*peer);
261        }
262        let is_inference = |s: &Option<Seen>| matches!(s, Some(Seen::Inference { .. }));
263        // Inference nodes already known: answer now; probes carry on in the background.
264        if !state.iter().any(is_inference) {
265            let deadline = started + self.wait;
266            let mut first_found: Option<Instant> = None;
267            loop {
268                {
269                    let seen = self.shared.seen();
270                    for (i, peer) in peers.iter().enumerate() {
271                        if state[i].is_none()
272                            && let Some((s, _)) = seen.get(peer)
273                            && *s != Seen::Probing
274                        {
275                            state[i] = Some(*s);
276                        }
277                    }
278                }
279                let now = Instant::now();
280                if state.iter().all(Option::is_some) || now >= deadline {
281                    break;
282                }
283                let until = if state.iter().any(is_inference) { (*first_found.get_or_insert(now) + SETTLE).min(deadline) } else { deadline };
284                if now >= until {
285                    break;
286                }
287                if tokio::time::timeout_at(until.into(), changed.changed()).await.is_ok_and(|r| r.is_err()) {
288                    break;
289                }
290            }
291        }
292        let mut found: Vec<(bool, String)> = peers
293            .iter()
294            .zip(&state)
295            .filter_map(|(p, s)| match s {
296                Some(Seen::Inference { direct }) => Some((!direct, p.to_string())),
297                _ => None,
298            })
299            .collect();
300        found.sort_by_key(|(relayed, _)| *relayed);
301        tracing::debug!(
302            took = ?started.elapsed(),
303            linked = peers.len(),
304            found = found.len(),
305            probing = state.iter().filter(|s| s.is_none()).count(),
306            "LinkedNodes::nodes"
307        );
308        found.into_iter().map(|(_, p)| p).collect()
309    }
310}
311
312/// A [`Pool`] over `node`: inference nodes among the roster's linked devices, presenting
313/// `cert` (this device's certificate) with every request.
314pub fn connect<Q: Message, R: Message>(node: Arc<Node<Q, R>>, roster: RosterView, cert: Option<&NodeCert>) -> Pool {
315    let opts = PoolOptions::default().with_cert(cert.map(encode_cert));
316    Pool::new(Arc::new(NetDialer::new(node.clone())), LinkedNodes::new(node, roster)).with_options(opts)
317}