Skip to main content

weirdnet_agent/
serve.rs

1//! The `serve` feature: the inference side of remote inference over `weirdnet-net`.
2//!
3//! [`Server::start`] accepts `/weirdnet-agent/infer/1`, `/weirdnet-agent/infer/2` and
4//! `/weirdnet-agent/catalog/1` streams on a node and serves each through the transport-neutral
5//! serve functions, with the stream's Noise-authenticated peer as the [`Caller`]. It announces
6//! [`INFERENCE_APP`] so pools find the node (model nodes serving raw infer/2 to inference nodes
7//! pass `announce: false`).
8//!
9//! [`RosterAuth`] is the authorize hook for hosts: `weirdnet_sync::Roster::check_caller` with
10//! the peer and the certificate the caller presented. Hosts call it from
11//! [`InferHost::authorize`] and [`CatalogHost::authorize`].
12
13use std::sync::Arc;
14
15use weirdnet_net::node::Message;
16use weirdnet_net::profile::Profile;
17use weirdnet_net::{AppBody, AppResponse, Incoming, Node, PublicKey};
18use weirdnet_sync::{CallerCheck, Roster};
19
20pub use crate::net::{INFERENCE_APP, channel, decode_cert, encode_cert, stream_limits};
21pub use crate::remote::catalog::{CatalogFeed, CatalogHost};
22pub use crate::remote::infer::v2::{EmbedBackend, InferBackend, ModelAdapter, Output};
23pub use crate::remote::infer::{Admission, InferHost};
24use crate::remote::{Authorize, Caller, RemoteError, catalog, infer};
25
26/// The roster as it is now (the app keeps it current from `weirdnet-sync`).
27pub type RosterView = Arc<dyn Fn() -> Roster + Send + Sync>;
28
29/// Admits only the user's linked devices (`Roster::check_caller`). Refusals carry the roster's
30/// reason (`unknown-device`, `revoked`, `wrong-user`, `needs-admission`).
31pub struct RosterAuth {
32    profile: &'static Profile,
33    user: PublicKey,
34    roster: RosterView,
35}
36
37impl RosterAuth {
38    pub fn new(profile: &'static Profile, user: PublicKey, roster: RosterView) -> Self {
39        Self { profile, user, roster }
40    }
41
42    pub fn check(&self, caller: &Caller) -> CallerCheck {
43        let presented = match caller.cert_bytes.as_deref().map(decode_cert) {
44            None => None,
45            Some(Ok(c)) => Some(c),
46            Some(Err(_)) => return CallerCheck::WrongUser,
47        };
48        (self.roster)().check_caller(self.profile, &self.user, &caller.peer, presented.as_ref())
49    }
50}
51
52impl Authorize for RosterAuth {
53    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
54        match self.check(caller).reason() {
55            None => Ok(()),
56            Some(reason) => Err(RemoteError::refused(reason)),
57        }
58    }
59}
60
61/// Serving tasks on a node; dropping it stops accepting (calls under way carry on).
62pub struct Server {
63    tasks: Vec<tokio::task::JoinHandle<()>>,
64    announced: Option<Box<dyn Fn() + Send + Sync>>,
65}
66
67/// What a [`Server`] serves.
68#[derive(Clone)]
69pub struct Serving {
70    /// infer/1 and infer/2, sharing the admission slots.
71    pub infer: Option<(Arc<dyn InferHost>, Admission)>,
72    pub catalog: Option<Arc<dyn CatalogHost>>,
73    /// Announce [`INFERENCE_APP`] (inference nodes; not model nodes).
74    pub announce: bool,
75}
76
77fn accept_loop(mut incoming: Incoming, serve: impl Fn(crate::remote::Channel, Caller) + Send + 'static) -> tokio::task::JoinHandle<()> {
78    tokio::spawn(async move {
79        while let Some(stream) = incoming.next().await {
80            let caller = Caller::new(stream.peer().to_string());
81            serve(channel(stream), caller);
82        }
83    })
84}
85
86impl Server {
87    /// Starts serving on `node`. Call from a Tokio runtime.
88    pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, serving: Serving) -> Result<Server, RemoteError> {
89        let net = |e: weirdnet_net::NetError| RemoteError::Failed { message: e.to_string() };
90        let mut tasks = Vec::new();
91        if let Some((host, admission)) = serving.infer {
92            let (h, a) = (host.clone(), admission.clone());
93            tasks.push(accept_loop(node.accept_streams(infer::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
94                let (h, a) = (h.clone(), a.clone());
95                tokio::spawn(async move {
96                    let _ = infer::serve(ch, &caller, h.as_ref(), &a).await;
97                });
98            }));
99            tasks.push(accept_loop(node.accept_streams(infer::v2::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
100                let (h, a) = (host.clone(), admission.clone());
101                tokio::spawn(async move {
102                    let _ = infer::v2::serve(ch, caller, h.as_ref(), &a).await;
103                });
104            }));
105        }
106        if let Some(host) = serving.catalog {
107            tasks.push(accept_loop(node.accept_streams(catalog::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
108                let h = host.clone();
109                tokio::spawn(async move {
110                    let _ = catalog::serve(ch, caller, h.as_ref()).await;
111                });
112            }));
113        }
114        let mut announced: Option<Box<dyn Fn() + Send + Sync>> = None;
115        if serving.announce {
116            let protocols = vec![infer::PROTOCOL, infer::v2::PROTOCOL, catalog::PROTOCOL];
117            let body = crate::remote::to_cbor(&protocols)?;
118            node.serve_app(
119                INFERENCE_APP,
120                Arc::new(move |_peer, _req| {
121                    let body = body.clone();
122                    async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
123                }),
124            )
125            .map_err(|e| RemoteError::Failed { message: e.to_string() })?;
126            let n = node.clone();
127            announced = Some(Box::new(move || {
128                n.stop_serving_app(INFERENCE_APP);
129            }));
130        }
131        Ok(Server { tasks, announced })
132    }
133}
134
135impl Drop for Server {
136    fn drop(&mut self) {
137        for t in &self.tasks {
138            t.abort();
139        }
140        if let Some(stop) = self.announced.take() {
141            stop();
142        }
143    }
144}