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`]. With
12//! [`require_roles`](RosterAuth::require_roles) it also needs one of the device roles the user
13//! granted the caller (the grants in the `weirdnet-sync` 0.7 or later roster, `Roster::roles_of`).
14//!
15//! [`Server::start_with`] also serves `/weirdnet-agent/task/1` ([`ServingExtras::tasks`]): each
16//! task is admitted by the given [`Authorize`] and built by [`TaskHost::session_for`].
17
18use std::sync::Arc;
19
20use weirdnet_net::node::Message;
21use weirdnet_net::profile::Profile;
22use weirdnet_net::{AppBody, AppResponse, Incoming, Node, PublicKey};
23use weirdnet_sync::{CallerCheck, Roster};
24
25pub use crate::net::{INFERENCE_APP, channel, decode_cert, encode_cert, stream_limits};
26pub use crate::remote::catalog::{CatalogFeed, CatalogHost};
27pub use crate::remote::infer::v2::{EmbedBackend, InferBackend, ModelAdapter, Output};
28pub use crate::remote::infer::{Admission, InferHost};
29pub use crate::remote::task::TaskHost;
30use crate::remote::{Admitted, Authorize, Caller, RemoteError, catalog, infer, task};
31
32/// The roster as it is now (the app keeps it current from `weirdnet-sync`).
33pub type RosterView = Arc<dyn Fn() -> Roster + Send + Sync>;
34
35/// The device roles a peer holds, `None` without a grant. With `weirdnet-sync` 0.7 or later:
36/// `Arc::new(move |peer| identity.roster().roles_of(peer))`.
37pub type RoleView = Arc<dyn Fn(&str) -> Option<Vec<String>> + Send + Sync>;
38
39/// Admits only the user's linked devices (`Roster::check_caller`). Refusals carry the roster's
40/// reason (`unknown-device`, `revoked`, `wrong-user`, `needs-admission`).
41///
42/// With [`require_roles`](Self::require_roles) a linked caller also needs one of the roles
43/// (refused with `role` otherwise); without it any linked device is let in, as before.
44pub struct RosterAuth {
45    profile: &'static Profile,
46    user: PublicKey,
47    roster: RosterView,
48    roles: Option<RoleView>,
49    any_of: Vec<String>,
50}
51
52impl RosterAuth {
53    pub fn new(profile: &'static Profile, user: PublicKey, roster: RosterView) -> Self {
54        Self { profile, user, roster, roles: None, any_of: Vec::new() }
55    }
56
57    /// Needs one of `any_of` among the caller's granted roles. An empty `any_of` needs none but
58    /// still reports roles in [`admit`](Authorize::admit).
59    pub fn require_roles(mut self, any_of: &[&str], roles: RoleView) -> Self {
60        self.any_of = any_of.iter().map(|r| r.to_string()).collect();
61        self.roles = Some(roles);
62        self
63    }
64
65    pub fn check(&self, caller: &Caller) -> CallerCheck {
66        let presented = match caller.cert_bytes.as_deref().map(decode_cert) {
67            None => None,
68            Some(Ok(c)) => Some(c),
69            Some(Err(_)) => return CallerCheck::WrongUser,
70        };
71        (self.roster)().check_caller(self.profile, &self.user, &caller.peer, presented.as_ref())
72    }
73}
74
75impl Authorize for RosterAuth {
76    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
77        self.admit(caller).map(|_| ())
78    }
79
80    fn admit(&self, caller: &Caller) -> Result<Admitted, RemoteError> {
81        if let Some(reason) = self.check(caller).reason() {
82            return Err(RemoteError::refused(reason));
83        }
84        let roles = self.roles.as_ref().and_then(|view| view(&caller.peer));
85        if !self.any_of.is_empty() && !roles.as_ref().is_some_and(|have| have.iter().any(|r| self.any_of.contains(r))) {
86            return Err(RemoteError::refused("role"));
87        }
88        Ok(Admitted::new(caller.peer.clone(), roles))
89    }
90}
91
92/// Serving tasks on a node; dropping it stops accepting (calls under way carry on).
93pub struct Server {
94    tasks: Vec<tokio::task::JoinHandle<()>>,
95    announced: Option<Box<dyn Fn() + Send + Sync>>,
96}
97
98/// What a [`Server`] serves.
99#[derive(Clone)]
100pub struct Serving {
101    /// infer/1 and infer/2, sharing the admission slots.
102    pub infer: Option<(Arc<dyn InferHost>, Admission)>,
103    pub catalog: Option<Arc<dyn CatalogHost>>,
104    /// Announce [`INFERENCE_APP`] (inference nodes; not model nodes).
105    pub announce: bool,
106}
107
108/// What a [`Server`] serves beyond [`Serving`] (a separate struct so `Serving` literals keep
109/// compiling in 0.4.x; it folds into `Serving` in 0.5).
110#[derive(Clone, Default)]
111#[non_exhaustive]
112pub struct ServingExtras {
113    /// task/1: whole agent tasks, admitted by the `Authorize` (usually a [`RosterAuth`]).
114    pub tasks: Option<(Arc<dyn TaskHost>, Arc<dyn Authorize>)>,
115}
116
117impl ServingExtras {
118    pub fn tasks(mut self, host: Arc<dyn TaskHost>, auth: Arc<dyn Authorize>) -> Self {
119        self.tasks = Some((host, auth));
120        self
121    }
122}
123
124fn accept_loop(mut incoming: Incoming, serve: impl Fn(crate::remote::Channel, Caller) + Send + 'static) -> tokio::task::JoinHandle<()> {
125    tokio::spawn(async move {
126        while let Some(stream) = incoming.next().await {
127            let caller = Caller::new(stream.peer().to_string());
128            serve(channel(stream), caller);
129        }
130    })
131}
132
133impl Server {
134    /// Starts serving on `node`. Call from a Tokio runtime.
135    pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, serving: Serving) -> Result<Server, RemoteError> {
136        Self::start_with(node, serving, ServingExtras::default())
137    }
138
139    /// [`start`](Self::start) plus [`ServingExtras`]. When tasks are served, task/1 is added to
140    /// the [`INFERENCE_APP`] announcement.
141    pub fn start_with<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, serving: Serving, extras: ServingExtras) -> Result<Server, RemoteError> {
142        let net = |e: weirdnet_net::NetError| RemoteError::Failed { message: e.to_string() };
143        let mut tasks = Vec::new();
144        if let Some((host, admission)) = serving.infer {
145            let (h, a) = (host.clone(), admission.clone());
146            tasks.push(accept_loop(node.accept_streams(infer::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
147                let (h, a) = (h.clone(), a.clone());
148                tokio::spawn(async move {
149                    let _ = infer::serve(ch, &caller, h.as_ref(), &a).await;
150                });
151            }));
152            tasks.push(accept_loop(node.accept_streams(infer::v2::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
153                let (h, a) = (host.clone(), admission.clone());
154                tokio::spawn(async move {
155                    let _ = infer::v2::serve(ch, caller, h.as_ref(), &a).await;
156                });
157            }));
158        }
159        if let Some(host) = serving.catalog {
160            tasks.push(accept_loop(node.accept_streams(catalog::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
161                let h = host.clone();
162                tokio::spawn(async move {
163                    let _ = catalog::serve(ch, caller, h.as_ref()).await;
164                });
165            }));
166        }
167        let serves_tasks = extras.tasks.is_some();
168        if let Some((host, auth)) = extras.tasks {
169            tasks.push(accept_loop(node.accept_streams(task::PROTOCOL, stream_limits()).map_err(net)?, move |ch, caller| {
170                let (h, a) = (host.clone(), auth.clone());
171                tokio::spawn(async move {
172                    let _ = task::serve_for(ch, caller, a.as_ref(), h.as_ref()).await;
173                });
174            }));
175        }
176        let mut announced: Option<Box<dyn Fn() + Send + Sync>> = None;
177        if serving.announce {
178            let mut protocols = vec![infer::PROTOCOL, infer::v2::PROTOCOL, catalog::PROTOCOL];
179            if serves_tasks {
180                protocols.push(task::PROTOCOL);
181            }
182            let body = crate::remote::to_cbor(&protocols)?;
183            node.serve_app(
184                INFERENCE_APP,
185                Arc::new(move |_peer, _req| {
186                    let body = body.clone();
187                    async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
188                }),
189            )
190            .map_err(|e| RemoteError::Failed { message: e.to_string() })?;
191            let n = node.clone();
192            announced = Some(Box::new(move || {
193                n.stop_serving_app(INFERENCE_APP);
194            }));
195        }
196        Ok(Server { tasks, announced })
197    }
198}
199
200impl Drop for Server {
201    fn drop(&mut self) {
202        for t in &self.tasks {
203            t.abort();
204        }
205        if let Some(stop) = self.announced.take() {
206            stop();
207        }
208    }
209}