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