1use 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
32pub type RosterView = Arc<dyn Fn() -> Roster + Send + Sync>;
34
35pub type RoleView = Arc<dyn Fn(&str) -> Option<Vec<String>> + Send + Sync>;
38
39pub 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 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
92pub struct Server {
94 tasks: Vec<tokio::task::JoinHandle<()>>,
95 announced: Option<Box<dyn Fn() + Send + Sync>>,
96}
97
98#[derive(Clone)]
100pub struct Serving {
101 pub infer: Option<(Arc<dyn InferHost>, Admission)>,
103 pub catalog: Option<Arc<dyn CatalogHost>>,
104 pub announce: bool,
106}
107
108#[derive(Clone, Default)]
111#[non_exhaustive]
112pub struct ServingExtras {
113 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 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 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}