Skip to main content

weirdnet_agent/remote/
catalog.rs

1//! `/weirdnet-agent/catalog/1`: the models an inference node offers.
2//!
3//! ```text
4//! asking node                     inference node
5//!   Query { cert } ->             <- Catalog | Failed
6//!   Subscribe { cert } ->         <- Catalog, then Catalog again on every change (until closed)
7//! ```
8//!
9//! One entry per model with its state, an estimated speed and how many replicas serve it, but
10//! no model-node addresses: apps only ever talk to inference nodes. Messages are CBOR.
11
12use std::sync::Arc;
13
14use serde::{Deserialize, Serialize};
15use tokio::sync::watch;
16
17use super::{Authorize, Caller, Channel, RemoteError, bytes};
18
19/// Stream protocol id.
20pub const PROTOCOL: &str = "/weirdnet-agent/catalog/1";
21
22/// What a model is for.
23#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25#[non_exhaustive]
26pub enum Purpose {
27    #[default]
28    Chat,
29    Embedding,
30}
31
32/// A model's state across the pool.
33#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum ModelState {
37    /// Loaded somewhere and ready.
38    Warm,
39    /// Not loaded, but a node can load it.
40    #[default]
41    Loadable,
42    Loading,
43    /// Loaded, but every replica is full.
44    Busy,
45}
46
47/// One catalog entry.
48#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
49#[non_exhaustive]
50pub struct CatalogModel {
51    pub id: String,
52    #[serde(default)]
53    pub purpose: Purpose,
54    #[serde(default)]
55    pub state: ModelState,
56    /// Model nodes that have it loaded.
57    #[serde(default)]
58    pub replicas: u32,
59    /// Estimated decode speed.
60    #[serde(default, skip_serializing_if = "Option::is_none")]
61    pub tokens_per_sec: Option<f32>,
62    /// Context window in tokens.
63    #[serde(default, skip_serializing_if = "Option::is_none")]
64    pub context: Option<u32>,
65    #[serde(default, skip_serializing_if = "Option::is_none")]
66    pub revision: Option<String>,
67    /// The model that answers while this one loads, if the pool policy names one.
68    #[serde(default, skip_serializing_if = "Option::is_none")]
69    pub standin: Option<String>,
70}
71
72impl CatalogModel {
73    pub fn new(id: impl Into<String>, purpose: Purpose, state: ModelState) -> Self {
74        Self { id: id.into(), purpose, state, ..Default::default() }
75    }
76
77    pub fn with_replicas(mut self, replicas: u32) -> Self {
78        self.replicas = replicas;
79        self
80    }
81
82    pub fn with_speed(mut self, tokens_per_sec: f32) -> Self {
83        self.tokens_per_sec = Some(tokens_per_sec);
84        self
85    }
86
87    pub fn with_context(mut self, tokens: u32) -> Self {
88        self.context = Some(tokens);
89        self
90    }
91}
92
93/// The models on offer. `rev` grows with every change.
94#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
95#[non_exhaustive]
96pub struct Catalog {
97    pub rev: u64,
98    pub models: Vec<CatalogModel>,
99}
100
101impl Catalog {
102    pub fn new(rev: u64, models: Vec<CatalogModel>) -> Self {
103        Self { rev, models }
104    }
105
106    pub fn find(&self, id: &str) -> Option<&CatalogModel> {
107        self.models.iter().find(|m| m.id == id)
108    }
109}
110
111/// Asking node to inference node.
112#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
113#[serde(rename_all = "snake_case")]
114#[non_exhaustive]
115pub enum ClientMsg {
116    Query {
117        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
118        cert: Option<Vec<u8>>,
119    },
120    Subscribe {
121        #[serde(default, skip_serializing_if = "Option::is_none", with = "bytes::opt")]
122        cert: Option<Vec<u8>>,
123    },
124}
125
126/// Inference node to asking node.
127#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
128#[serde(rename_all = "snake_case")]
129#[non_exhaustive]
130pub enum ServerMsg {
131    Catalog(Catalog),
132    Failed { error: RemoteError },
133}
134
135/// The serving side's catalog (an inference node's merged view).
136pub trait CatalogHost: Send + Sync {
137    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError>;
138
139    /// The catalog for this caller, and its changes.
140    fn watch(&self, caller: &Caller) -> Result<watch::Receiver<Catalog>, RemoteError>;
141}
142
143/// A ready [`CatalogHost`]: publish the models, and subscribers hear about it.
144#[derive(Clone)]
145pub struct CatalogFeed {
146    tx: Arc<watch::Sender<Catalog>>,
147    auth: Arc<dyn Authorize>,
148}
149
150impl CatalogFeed {
151    /// A feed whose callers `auth` admits.
152    pub fn new(auth: Arc<dyn Authorize>) -> Self {
153        Self { tx: Arc::new(watch::channel(Catalog::default()).0), auth }
154    }
155
156    /// Replaces the models; `rev` goes up by one.
157    pub fn publish(&self, models: Vec<CatalogModel>) {
158        self.tx.send_modify(|c| {
159            c.rev += 1;
160            c.models = models;
161        });
162    }
163
164    pub fn current(&self) -> Catalog {
165        self.tx.borrow().clone()
166    }
167}
168
169impl CatalogHost for CatalogFeed {
170    fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
171        self.auth.authorize(caller)
172    }
173
174    fn watch(&self, _caller: &Caller) -> Result<watch::Receiver<Catalog>, RemoteError> {
175        Ok(self.tx.subscribe())
176    }
177}
178
179/// Serve one catalog/1 stream. `caller` is the transport-authenticated peer; the certificate the
180/// request presents is attached when the transport gave none, and the host authorizes it first.
181pub async fn serve(mut ch: Channel, caller: Caller, host: &dyn CatalogHost) -> Result<(), RemoteError> {
182    let (cert, follow) = match ch.recv_cbor::<ClientMsg>().await? {
183        Some(ClientMsg::Query { cert }) => (cert, false),
184        Some(ClientMsg::Subscribe { cert }) => (cert, true),
185        None => return Ok(()),
186    };
187    let caller = caller.presenting(cert);
188    let mut rx = match host.authorize(&caller).and_then(|()| host.watch(&caller)) {
189        Ok(rx) => rx,
190        Err(error) => return ch.send_cbor(&ServerMsg::Failed { error }).await,
191    };
192    let now = rx.borrow_and_update().clone();
193    ch.send_cbor(&ServerMsg::Catalog(now)).await?;
194    if !follow {
195        return Ok(());
196    }
197    loop {
198        tokio::select! {
199            changed = rx.changed() => {
200                if changed.is_err() {
201                    return Ok(());
202                }
203                let now = rx.borrow_and_update().clone();
204                ch.send_cbor(&ServerMsg::Catalog(now)).await?;
205            }
206            m = ch.rx.recv() => match m {
207                Ok(Some(_)) => {}
208                Ok(None) | Err(_) => return Ok(()),
209            },
210        }
211    }
212}
213
214/// Asks once.
215pub async fn query(ch: &mut Channel, cert: Option<Vec<u8>>) -> Result<Catalog, RemoteError> {
216    ch.send_cbor(&ClientMsg::Query { cert }).await?;
217    match ch.recv_cbor::<ServerMsg>().await? {
218        Some(ServerMsg::Catalog(c)) => Ok(c),
219        Some(ServerMsg::Failed { error }) => Err(error),
220        None => Err(RemoteError::Closed),
221    }
222}
223
224/// Subscribes and hands every catalog to `on`, until the stream ends (`Ok`) or fails.
225pub async fn subscribe(ch: &mut Channel, cert: Option<Vec<u8>>, mut on: impl FnMut(Catalog)) -> Result<(), RemoteError> {
226    ch.send_cbor(&ClientMsg::Subscribe { cert }).await?;
227    loop {
228        match ch.recv_cbor::<ServerMsg>().await? {
229            Some(ServerMsg::Catalog(c)) => on(c),
230            Some(ServerMsg::Failed { error }) => return Err(error),
231            None => return Ok(()),
232        }
233    }
234}
235
236#[cfg(test)]
237mod tests {
238    use super::*;
239    use crate::remote::memory_pair;
240
241    fn anyone() -> Arc<dyn Authorize> {
242        Arc::new(|_: &Caller| Ok(()))
243    }
244
245    #[tokio::test]
246    async fn query_and_subscribe_see_changes() {
247        let feed = CatalogFeed::new(anyone());
248        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Warm).with_replicas(2)]);
249        let (mut ours, theirs) = memory_pair();
250        let f = feed.clone();
251        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
252        let c = query(&mut ours, None).await.unwrap();
253        assert_eq!(c.rev, 1);
254        assert_eq!(c.find("gemma").unwrap().replicas, 2);
255
256        let (mut ours, theirs) = memory_pair();
257        let f = feed.clone();
258        tokio::spawn(async move { serve(theirs, Caller::new("phone"), &f).await });
259        let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
260        tokio::spawn(async move { subscribe(&mut ours, None, |c| tx.send(c).unwrap()).await });
261        assert_eq!(rx.recv().await.unwrap().rev, 1);
262        feed.publish(vec![CatalogModel::new("gemma", Purpose::Chat, ModelState::Loading)]);
263        let next = rx.recv().await.unwrap();
264        assert_eq!((next.rev, next.models[0].state), (2, ModelState::Loading));
265    }
266
267    #[tokio::test]
268    async fn the_host_authorizes_with_the_presented_cert() {
269        let auth: Arc<dyn Authorize> = Arc::new(|c: &Caller| {
270            if c.peer == "laptop" && c.cert_bytes.as_deref() == Some(b"cert") { Ok(()) } else { Err(RemoteError::refused("unknown-device")) }
271        });
272        let feed = CatalogFeed::new(auth);
273        for (peer, cert, ok) in [("laptop", Some(b"cert".to_vec()), true), ("laptop", None, false), ("stranger", Some(b"cert".to_vec()), false)] {
274            let (mut ours, theirs) = memory_pair();
275            let f = feed.clone();
276            tokio::spawn(async move { serve(theirs, Caller::new(peer), &f).await });
277            let r = query(&mut ours, cert).await;
278            assert_eq!(r.is_ok(), ok, "{peer}");
279            if !ok {
280                assert_eq!(r.unwrap_err(), RemoteError::refused("unknown-device"));
281            }
282        }
283    }
284
285    #[test]
286    fn wire_is_cbor_with_byte_string_certs() {
287        let m = ClientMsg::Query { cert: Some(vec![1, 2, 3]) };
288        let b = crate::remote::to_cbor(&m).unwrap();
289        // map(1) "query" map(1) "cert" bytes(3)
290        assert!(b.windows(4).any(|w| w == [0x43, 1, 2, 3]), "{b:x?}");
291        assert_eq!(crate::remote::from_cbor::<ClientMsg>(&b).unwrap(), m);
292    }
293}