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::{Arc, Mutex};
13use std::time::{Duration, Instant};
14
15use async_trait::async_trait;
16use weirdnet_net::node::Message;
17use weirdnet_net::user::NodeCert;
18use weirdnet_net::{Multiaddr, Node, Path, PeerId};
19use weirdnet_sync::Roster;
20
21use crate::net::open_error;
22pub use crate::net::{INFERENCE_APP, channel, decode_cert, encode_cert, stream_limits};
23pub use crate::remote::pool::{Answer, CatalogWatch, EventSink, Interrupted, Job, NoEvents, NodeSource, Pool, PoolEvent, PoolOptions, Stall};
24use crate::remote::{Channel, Dialer, RemoteError};
25
26/// Opens agent streams over a `weirdnet-net` node. Node ids are peer ids.
27pub struct NetDialer<Q: Message, R: Message> {
28    node: Arc<Node<Q, R>>,
29    hints: Mutex<HashMap<PeerId, Vec<Multiaddr>>>,
30}
31
32impl<Q: Message, R: Message> NetDialer<Q, R> {
33    pub fn new(node: Arc<Node<Q, R>>) -> Self {
34        Self { node, hints: Mutex::new(HashMap::new()) }
35    }
36
37    /// Addresses to try for a peer (LAN, fixed or relay circuit addresses).
38    pub fn hint(&self, peer: PeerId, addrs: Vec<Multiaddr>) {
39        self.hints.lock().unwrap_or_else(|e| e.into_inner()).insert(peer, addrs);
40    }
41}
42
43#[async_trait]
44impl<Q: Message, R: Message> Dialer for NetDialer<Q, R> {
45    async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError> {
46        let peer: PeerId = node.parse().map_err(|_| RemoteError::Unreachable { message: format!("{node} is not a peer id") })?;
47        let addrs = self.hints.lock().unwrap_or_else(|e| e.into_inner()).get(&peer).cloned().unwrap_or_default();
48        let stream = self.node.open_stream_async(peer, &addrs, protocol, stream_limits()).await.map_err(open_error)?;
49        Ok(channel(stream))
50    }
51}
52
53/// The roster as it is now (the app keeps it current from `weirdnet-sync`).
54pub type RosterView = Arc<dyn Fn() -> Roster + Send + Sync>;
55
56/// The inference nodes among the user's linked devices.
57pub struct LinkedNodes<Q: Message, R: Message> {
58    node: Arc<Node<Q, R>>,
59    roster: RosterView,
60    hints: HashMap<PeerId, Vec<Multiaddr>>,
61    wait: Duration,
62}
63
64impl<Q: Message, R: Message> LinkedNodes<Q, R> {
65    pub fn new(node: Arc<Node<Q, R>>, roster: RosterView) -> Self {
66        Self { node, roster, hints: HashMap::new(), wait: Duration::from_secs(3) }
67    }
68
69    /// Addresses to connect to a device through.
70    pub fn with_hint(mut self, peer: PeerId, addrs: Vec<Multiaddr>) -> Self {
71        self.hints.insert(peer, addrs);
72        self
73    }
74
75    /// How long to wait to connect to and identify each device (default 3 s).
76    pub fn with_wait(mut self, wait: Duration) -> Self {
77        self.wait = wait;
78        self
79    }
80}
81
82#[async_trait]
83impl<Q: Message, R: Message> NodeSource for LinkedNodes<Q, R> {
84    async fn nodes(&self) -> Vec<String> {
85        let me = self.node.peer_id().to_string();
86        let roster = (self.roster)();
87        let peers: Vec<PeerId> = roster.active().filter(|c: &&NodeCert| c.peer_id != me).filter_map(|c| c.peer_id.parse().ok()).collect();
88        let mut found = Vec::new();
89        for peer in peers {
90            let node = self.node.clone();
91            let addrs = self.hints.get(&peer).cloned().unwrap_or_default();
92            let wait = self.wait;
93            let r = tokio::task::spawn_blocking(move || {
94                let announced = |apps: Option<Vec<String>>| apps.is_some_and(|a| a.iter().any(|a| a == INFERENCE_APP));
95                let mut apps = node.peer_apps(peer);
96                if apps.is_none() {
97                    let _ = node.connect(peer, &addrs);
98                    let until = Instant::now() + wait;
99                    while apps.is_none() && Instant::now() < until {
100                        std::thread::sleep(Duration::from_millis(25));
101                        apps = node.peer_apps(peer);
102                    }
103                }
104                if !announced(apps) {
105                    return None;
106                }
107                let direct = node.paths(peer).map(|p| p.contains(&Path::Direct)).unwrap_or(false);
108                Some(direct)
109            })
110            .await;
111            if let Ok(Some(direct)) = r {
112                found.push((!direct, peer.to_string()));
113            }
114        }
115        found.sort_by_key(|(relayed, _)| *relayed);
116        found.into_iter().map(|(_, p)| p).collect()
117    }
118}
119
120/// A [`Pool`] over `node`: inference nodes among the roster's linked devices, presenting
121/// `cert` (this device's certificate) with every request.
122pub fn connect<Q: Message, R: Message>(node: Arc<Node<Q, R>>, roster: RosterView, cert: Option<&NodeCert>) -> Pool {
123    let opts = PoolOptions::default().with_cert(cert.map(encode_cert));
124    Pool::new(Arc::new(NetDialer::new(node.clone())), LinkedNodes::new(node, roster)).with_options(opts)
125}