Skip to main content

weirdnet_backends/
node.rs

1//! `/weirdnet-backends/node/1`: how inference nodes drive model nodes over `weirdnet-net`.
2//!
3//! A model node pushes a [`Capability`] record to every subscriber: signed by the node's key,
4//! chained to the user by its [`NodeCert`], with a sequence number and a 90 second expiry,
5//! refreshed every 15 seconds and on every change. It takes [`Command`]s: `Load`, `Unload`,
6//! `Drain`, `GroupUp`/`GroupDown` and `Health`. Inference itself is raw infer/2 framing through
7//! [`ModelHost`], served next to node/1 by [`NodeServer`] on [`RAW_INFER_PROTOCOL`]
8//! (`/weirdnet-backends/infer/1`) and, unless [`NodeServerOptions::legacy_infer2`] is off, on
9//! `/weirdnet-agent/infer/2` as in 0.1.0. Inference nodes dial model nodes through
10//! [`RawInferDialer`](crate::RawInferDialer), which prefers the new id.
11//!
12//! Each stream carries one [`ClientMsg`] (CBOR, with the caller's certificate) and its answers
13//! ([`ServerMsg`]); a `Subscribe` stream stays open for records until either side closes it or
14//! the node withdraws. Which nodes may drive a model node is the [`Authorize`] hook's decision
15//! (`weirdnet_agent::serve::RosterAuth` admits the user's linked devices).
16//!
17//! Swap groups that span machines (a Ray worker or an `rpc-server` bound to a private link)
18//! are started by the application's [`GroupWorkers`]; without one, a node answers `GroupUp`
19//! with `Unsupported` and says `group_jobs: false` in its record.
20
21use std::collections::{HashMap, VecDeque};
22use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, Instant};
25
26use async_trait::async_trait;
27use serde::{Deserialize, Serialize};
28use tokio::sync::watch;
29use weirdnet_agent::remote::infer::{Admission, InferHost};
30use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError, from_cbor, to_cbor};
31use weirdnet_agent::serve::{Server, Serving, channel, stream_limits};
32use weirdnet_model::hw::{Budget, Hardware};
33use weirdnet_net::node::{Message, Node};
34use weirdnet_net::profile::Profile;
35use weirdnet_net::user::NodeCert;
36use weirdnet_net::{AppBody, AppResponse, Keypair, PeerId, PublicKey};
37
38use crate::engine::EngineKind;
39use crate::host::{ModelHost, RAW_INFER_PROTOCOL, Speed};
40use crate::supervisor::{ModelState, ModelStatus, SupervisorEvent};
41
42/// The protocol id.
43pub const PROTOCOL: &str = "/weirdnet-backends/node/1";
44/// The app name model nodes announce (`Node::serve_app`), so inference nodes find them among
45/// the user's linked devices.
46pub const MODEL_NODE_APP: &str = "weirdnet-backends-node";
47/// How long a record is good for.
48pub const RECORD_TTL: Duration = Duration::from_secs(90);
49/// How often a subscriber gets a fresh record when nothing changed.
50pub const REFRESH: Duration = Duration::from_secs(15);
51/// Accepted clock skew on a record's issue time.
52const SKEW_MS: i64 = 60_000;
53/// Signatures cover this, then the record bytes.
54const DOMAIN: &[u8] = b"weirdnet-backends/node/1 capability record\n";
55/// Recent supervisor events kept for health reports.
56const RECENT: usize = 32;
57
58fn now_ms() -> i64 {
59    weirdnet_net::now_ms()
60}
61
62/// What a model node can do right now.
63#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
64#[non_exhaustive]
65pub struct Capability {
66    /// The node's peer id; the record is signed by its key.
67    pub peer: String,
68    /// Increases with every record the node issues.
69    pub seq: u64,
70    pub issued_ms: i64,
71    pub expires_ms: i64,
72    /// Accelerators, memory and interconnects.
73    pub hardware: Option<Hardware>,
74    /// Memory models may use, and how much is free.
75    pub budget: Option<Budget>,
76    /// Engines the node can run.
77    pub engines: Vec<EngineKind>,
78    /// Every model the node is configured for: loaded or loadable from disk.
79    pub models: Vec<ModelEntry>,
80    pub load: Load,
81    /// Hashes of prompt prefixes the engines hold warm (supplied by the application).
82    pub warm_prefixes: Vec<String>,
83    /// Swap groups this node is in.
84    pub groups: Vec<String>,
85    /// Draining: no new requests.
86    pub draining: bool,
87    /// Takes group jobs (`GroupUp`).
88    pub group_jobs: bool,
89}
90
91/// One model in a [`Capability`] record.
92#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93#[non_exhaustive]
94pub struct ModelEntry {
95    pub status: ModelStatus,
96    pub revision: Option<String>,
97    pub quant: Option<String>,
98    /// The last measured load time, else a size-based guess.
99    pub load_secs_estimate: Option<f32>,
100    pub speed: Speed,
101}
102
103/// The node's load.
104#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
105#[non_exhaustive]
106pub struct Load {
107    /// Requests waiting for a slot (all priorities).
108    pub queued: u32,
109    /// Requests holding a slot.
110    pub active: u32,
111    /// Concurrent request slots.
112    pub slots: u32,
113    /// Requests under way in the engines.
114    pub in_flight: u32,
115}
116
117/// A capability record with its signature and certificate.
118#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
119pub struct SignedRecord {
120    /// The CBOR [`Capability`].
121    #[serde(with = "serde_bytes")]
122    pub record: Vec<u8>,
123    /// The node's public key (protobuf).
124    #[serde(with = "serde_bytes")]
125    pub public_key: Vec<u8>,
126    #[serde(with = "serde_bytes")]
127    pub signature: Vec<u8>,
128    /// The user's certificate for the node.
129    pub cert: Option<NodeCert>,
130}
131
132fn signed_bytes(record: &[u8]) -> Vec<u8> {
133    [DOMAIN, record].concat()
134}
135
136impl SignedRecord {
137    /// Signs `cap` with the node's key.
138    pub fn sign(keypair: &Keypair, cap: &Capability, cert: Option<NodeCert>) -> Result<Self, RemoteError> {
139        let record = to_cbor(cap)?;
140        let signature = keypair.sign(&signed_bytes(&record)).map_err(|e| RemoteError::Failed { message: format!("signing: {e}") })?;
141        Ok(Self { record, public_key: keypair.public().encode_protobuf(), signature, cert })
142    }
143
144    /// Checks the signature, that the record is `from_peer`'s own and that it has not expired.
145    /// Says nothing about the user: see [`Verifier`].
146    pub fn verify(&self, from_peer: &str, now_ms: i64) -> Result<Capability, RemoteError> {
147        let bad = |why: &str| RemoteError::protocol(format!("capability record: {why}"));
148        let key = PublicKey::try_decode_protobuf(&self.public_key).map_err(|_| bad("bad public key"))?;
149        if PeerId::from_public_key(&key).to_string() != from_peer {
150            return Err(bad("signed by another node"));
151        }
152        if !key.verify(&signed_bytes(&self.record), &self.signature) {
153            return Err(bad("bad signature"));
154        }
155        let cap: Capability = from_cbor(&self.record)?;
156        if cap.peer != from_peer {
157            return Err(bad("names another node"));
158        }
159        if cap.expires_ms <= now_ms {
160            return Err(bad("expired"));
161        }
162        if cap.issued_ms > now_ms + SKEW_MS {
163            return Err(bad("issued in the future"));
164        }
165        Ok(cap)
166    }
167}
168
169/// Checks records against the user: valid signature, and a valid, unrevoked certificate from
170/// the user for the very node that signed.
171#[derive(Clone)]
172pub struct Verifier {
173    profile: &'static Profile,
174    user: Option<PublicKey>,
175}
176
177impl Verifier {
178    pub fn new(profile: &'static Profile, user: PublicKey) -> Self {
179        Self { profile, user: Some(user) }
180    }
181
182    /// Signature and expiry only (tests, or when the dialer already checked the peer).
183    pub fn signature_only(profile: &'static Profile) -> Self {
184        Self { profile, user: None }
185    }
186
187    pub fn verify(&self, record: &SignedRecord, from_peer: &str, now_ms: i64) -> Result<Capability, RemoteError> {
188        let cap = record.verify(from_peer, now_ms)?;
189        if let Some(user) = &self.user {
190            let ok = match &record.cert {
191                Some(c) => c.peer_id == from_peer && c.active() && self.profile.verify_cert(user, c),
192                None => false,
193            };
194            if !ok {
195                return Err(RemoteError::refused("capability record: no valid certificate from the user"));
196            }
197        }
198        Ok(cap)
199    }
200}
201
202/// A swap group spanning machines, as the coordinator planned it.
203#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
204#[non_exhaustive]
205pub struct GroupPlan {
206    pub group: String,
207    /// The peer that serves the group's model.
208    pub leader: String,
209    pub members: Vec<String>,
210    /// Models to unload here first.
211    pub drop: Vec<String>,
212    /// The model the leader serves.
213    pub model: Option<String>,
214    /// The private link address workers bind to.
215    pub link: Option<String>,
216    /// Worker kind, for example `ray` or `rpc-server`.
217    pub worker: Option<String>,
218    /// Anything else the application's workers need.
219    pub extra: HashMap<String, String>,
220}
221
222impl GroupPlan {
223    pub fn new(group: impl Into<String>, leader: impl Into<String>) -> Self {
224        Self { group: group.into(), leader: leader.into(), ..Default::default() }
225    }
226
227    pub fn with_members(mut self, members: Vec<String>) -> Self {
228        self.members = members;
229        self
230    }
231
232    pub fn with_drop(mut self, drop: Vec<String>) -> Self {
233        self.drop = drop;
234        self
235    }
236
237    pub fn with_model(mut self, model: impl Into<String>) -> Self {
238        self.model = Some(model.into());
239        self
240    }
241
242    pub fn with_link(mut self, link: impl Into<String>) -> Self {
243        self.link = Some(link.into());
244        self
245    }
246
247    pub fn with_worker(mut self, worker: impl Into<String>) -> Self {
248        self.worker = Some(worker.into());
249        self
250    }
251}
252
253/// Starts and stops the processes of a cross-machine swap group (a Ray worker, an
254/// `rpc-server`). The application provides it; this crate has no such adapters.
255#[async_trait]
256pub trait GroupWorkers: Send + Sync {
257    /// Join `plan` as `me` (the leader or a member), after the plan's `drop` models unloaded.
258    async fn up(&self, me: &str, plan: &GroupPlan) -> Result<(), RemoteError>;
259    async fn down(&self, group: &str) -> Result<(), RemoteError>;
260}
261
262/// A node/1 request.
263#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
264#[non_exhaustive]
265pub enum Command {
266    /// Records now and on every change, until either side closes.
267    Subscribe,
268    /// One record.
269    Record,
270    Load {
271        model: String,
272        force: bool,
273    },
274    Unload {
275        model: String,
276    },
277    /// Stop taking requests (`on`) and wait for the ones under way; or take them again.
278    Drain {
279        on: bool,
280    },
281    GroupUp {
282        plan: GroupPlan,
283    },
284    GroupDown {
285        group: String,
286    },
287    Health,
288}
289
290/// What a client sends: its certificate and one command.
291#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
292pub struct ClientMsg {
293    /// The caller's CBOR `NodeCert`, for the authorize hook.
294    #[serde(default, with = "serde_bytes")]
295    pub cert: Option<Vec<u8>>,
296    pub command: Command,
297}
298
299/// What a model node answers.
300#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
301#[non_exhaustive]
302pub enum ServerMsg {
303    Record(SignedRecord),
304    /// The command succeeded.
305    Done,
306    Health(Health),
307    Failed(RemoteError),
308    /// The node is leaving; its records are void.
309    Withdrawn {
310        peer: String,
311        seq: u64,
312    },
313}
314
315/// A health report.
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317#[non_exhaustive]
318pub struct Health {
319    pub peer: String,
320    pub at_ms: i64,
321    /// No model failed or in a crash loop.
322    pub ok: bool,
323    pub draining: bool,
324    pub in_flight: u32,
325    pub uptime_secs: u64,
326    pub models: Vec<ModelHealth>,
327    /// Recent supervisor events, oldest first.
328    pub events: Vec<SupervisorEvent>,
329}
330
331#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
332#[non_exhaustive]
333pub struct ModelHealth {
334    pub id: String,
335    pub state: ModelState,
336    pub crashes: usize,
337}
338
339/// A model's revision and quantization.
340type ModelInfo = (Option<String>, Option<String>);
341
342/// A model node's node/1 side: issues records and runs commands against its [`ModelHost`].
343/// Transport-neutral ([`NodeService::serve`] takes a channel); [`NodeServer`] runs it on a
344/// `weirdnet-net` node.
345pub struct NodeService {
346    host: Arc<ModelHost>,
347    admission: Admission,
348    slots: usize,
349    keypair: Keypair,
350    peer: String,
351    cert: Option<NodeCert>,
352    auth: Arc<dyn Authorize>,
353    hardware: Option<Hardware>,
354    budget: Option<Budget>,
355    engines: Vec<EngineKind>,
356    workers: Option<Arc<dyn GroupWorkers>>,
357    drain_timeout: Duration,
358    info: Mutex<HashMap<String, ModelInfo>>,
359    warm: Mutex<Vec<String>>,
360    groups: Mutex<Vec<String>>,
361    recent: Mutex<VecDeque<SupervisorEvent>>,
362    seq: AtomicU64,
363    withdrawn: AtomicBool,
364    changed: watch::Sender<u64>,
365    started: Instant,
366}
367
368impl NodeService {
369    /// `keypair` is the node's own (records are signed with it); `cert` the user's certificate
370    /// for it; `auth` decides who may drive the node.
371    pub fn new(host: Arc<ModelHost>, keypair: Keypair, cert: Option<NodeCert>, auth: Arc<dyn Authorize>) -> Self {
372        let peer = keypair.public().to_peer_id().to_string();
373        let engines = host.supervisor().status().iter().map(|m| m.engine).fold(Vec::new(), |mut v, e| {
374            if !v.contains(&e) {
375                v.push(e);
376            }
377            v
378        });
379        Self {
380            host,
381            admission: Admission::new(4),
382            slots: 4,
383            keypair,
384            peer,
385            cert,
386            auth,
387            hardware: None,
388            budget: None,
389            engines,
390            workers: None,
391            drain_timeout: Duration::from_secs(60),
392            info: Mutex::default(),
393            warm: Mutex::default(),
394            groups: Mutex::default(),
395            recent: Mutex::default(),
396            seq: AtomicU64::new(now_ms().max(0) as u64),
397            withdrawn: AtomicBool::new(false),
398            changed: watch::Sender::new(0),
399            started: Instant::now(),
400        }
401    }
402
403    /// Infer/2 admission: `slots` concurrent requests, `queue` waiting (default 4 and 0).
404    pub fn with_admission(mut self, slots: usize, queue: usize) -> Self {
405        self.admission = Admission::with_queue(slots, queue);
406        self.slots = slots;
407        self
408    }
409
410    /// The hardware and memory budget for the record (`weirdnet_model::hw::detect` and `budget`).
411    pub fn with_hardware(mut self, hardware: Hardware, budget: Budget) -> Self {
412        self.hardware = Some(hardware);
413        self.budget = Some(budget);
414        self
415    }
416
417    pub fn with_group_workers(mut self, workers: Arc<dyn GroupWorkers>) -> Self {
418        self.workers = Some(workers);
419        self
420    }
421
422    /// How long `Drain` waits for requests under way (default 60 s).
423    pub fn with_drain_timeout(mut self, d: Duration) -> Self {
424        self.drain_timeout = d;
425        self
426    }
427
428    pub fn peer(&self) -> &str {
429        &self.peer
430    }
431
432    pub fn host(&self) -> &Arc<ModelHost> {
433        &self.host
434    }
435
436    pub fn admission(&self) -> &Admission {
437        &self.admission
438    }
439
440    /// A model's revision and quantization, for the record.
441    pub fn set_model_info(&self, model: &str, revision: Option<String>, quant: Option<String>) {
442        self.info.lock().unwrap_or_else(|e| e.into_inner()).insert(model.into(), (revision, quant));
443        self.touch();
444    }
445
446    /// Prefix hashes the engines hold warm.
447    pub fn set_warm_prefixes(&self, hashes: Vec<String>) {
448        *self.warm.lock().unwrap_or_else(|e| e.into_inner()) = hashes;
449        self.touch();
450    }
451
452    /// Something in the record changed: subscribers get a fresh one.
453    pub fn touch(&self) {
454        self.changed.send_modify(|v| *v += 1);
455    }
456
457    /// The node is leaving: subscribers get `Withdrawn` and their streams end.
458    pub fn withdraw(&self) {
459        self.withdrawn.store(true, Ordering::SeqCst);
460        self.touch();
461    }
462
463    /// The current capability.
464    pub fn capability(&self) -> Capability {
465        let issued_ms = now_ms();
466        let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
467        let info = self.info.lock().unwrap_or_else(|e| e.into_inner()).clone();
468        let models = self
469            .host
470            .supervisor()
471            .status()
472            .into_iter()
473            .map(|status| {
474                let (revision, quant) = info.get(&status.id).cloned().unwrap_or_default();
475                // Without a measured load, assume about 1 GB/s from disk plus a few seconds.
476                let load_secs_estimate = status.last_load_secs.or(status.size_bytes.map(|b| b as f32 / 1e9 + 3.0));
477                let speed = self.host.speed(&status.id);
478                ModelEntry { status, revision, quant, load_secs_estimate, speed }
479            })
480            .collect::<Vec<_>>();
481        let in_flight = self.host.supervisor().in_flight() as u32;
482        let free = self.admission.free();
483        let load =
484            Load { queued: self.admission.waiting() as u32, active: self.slots.saturating_sub(free) as u32, slots: self.slots as u32, in_flight };
485        Capability {
486            peer: self.peer.clone(),
487            seq,
488            issued_ms,
489            expires_ms: issued_ms + RECORD_TTL.as_millis() as i64,
490            hardware: self.hardware.clone(),
491            budget: self.budget,
492            engines: self.engines.clone(),
493            models,
494            load,
495            warm_prefixes: self.warm.lock().unwrap_or_else(|e| e.into_inner()).clone(),
496            groups: self.groups.lock().unwrap_or_else(|e| e.into_inner()).clone(),
497            draining: self.host.draining(),
498            group_jobs: self.workers.is_some(),
499        }
500    }
501
502    /// The current capability, signed.
503    pub fn record(&self) -> Result<SignedRecord, RemoteError> {
504        SignedRecord::sign(&self.keypair, &self.capability(), self.cert.clone())
505    }
506
507    pub fn health(&self) -> Health {
508        let status = self.host.supervisor().status();
509        let ok = status.iter().all(|m| !matches!(m.state, ModelState::Failed(_)));
510        Health {
511            peer: self.peer.clone(),
512            at_ms: now_ms(),
513            ok,
514            draining: self.host.draining(),
515            in_flight: self.host.supervisor().in_flight() as u32,
516            uptime_secs: self.started.elapsed().as_secs(),
517            models: status.into_iter().map(|m| ModelHealth { id: m.id, state: m.state, crashes: m.crashes }).collect(),
518            events: self.recent.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect(),
519        }
520    }
521
522    /// Keeps the record current with the supervisor's events. Runs until the supervisor goes.
523    pub fn watch(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
524        let me = self.clone();
525        let mut events = self.host.supervisor().subscribe();
526        tokio::spawn(async move {
527            loop {
528                match events.recv().await {
529                    Ok(ev) => {
530                        let mut recent = me.recent.lock().unwrap_or_else(|e| e.into_inner());
531                        if recent.len() == RECENT {
532                            recent.pop_front();
533                        }
534                        recent.push_back(ev);
535                    }
536                    Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
537                    Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
538                }
539                me.touch();
540            }
541        })
542    }
543
544    async fn run(&self, command: Command) -> Result<ServerMsg, RemoteError> {
545        let sup = self.host.supervisor();
546        let done = match command {
547            Command::Record => return Ok(ServerMsg::Record(self.record()?)),
548            Command::Health => return Ok(ServerMsg::Health(self.health())),
549            Command::Load { model, force } => {
550                if self.host.draining() {
551                    return Err(RemoteError::unavailable("this node is draining"));
552                }
553                sup.load_with(&model, force).await
554            }
555            Command::Unload { model } => sup.unload(&model).await,
556            Command::Drain { on } => {
557                self.host.set_draining(on);
558                self.touch();
559                if on {
560                    let deadline = Instant::now() + self.drain_timeout;
561                    while sup.in_flight() > 0 || self.admission.free() < self.slots {
562                        if Instant::now() >= deadline {
563                            return Err(RemoteError::Timeout);
564                        }
565                        tokio::time::sleep(Duration::from_millis(50)).await;
566                    }
567                }
568                Ok(())
569            }
570            Command::GroupUp { plan } => {
571                let workers = self.workers.as_ref().ok_or_else(|| RemoteError::Unsupported { message: "this node takes no group jobs".into() })?;
572                for model in &plan.drop {
573                    sup.unload(model).await?;
574                }
575                workers.up(&self.peer, &plan).await?;
576                let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
577                if !groups.contains(&plan.group) {
578                    groups.push(plan.group.clone());
579                }
580                Ok(())
581            }
582            Command::GroupDown { group } => {
583                let workers = self.workers.as_ref().ok_or_else(|| RemoteError::Unsupported { message: "this node takes no group jobs".into() })?;
584                workers.down(&group).await?;
585                self.groups.lock().unwrap_or_else(|e| e.into_inner()).retain(|g| *g != group);
586                Ok(())
587            }
588            Command::Subscribe => unreachable!("handled by serve"),
589        };
590        self.touch();
591        done.map(|()| ServerMsg::Done)
592    }
593
594    /// Serves one node/1 stream. `caller` is the transport-authenticated peer.
595    pub async fn serve(&self, mut ch: Channel, caller: Caller) -> Result<(), RemoteError> {
596        let Some(msg) = ch.recv_cbor::<ClientMsg>().await? else { return Ok(()) };
597        let caller = match (caller.cert_bytes.is_some(), msg.cert) {
598            (false, Some(cert)) => caller.with_cert(cert),
599            (_, _) => caller,
600        };
601        if let Err(e) = self.auth.authorize(&caller) {
602            return ch.send_cbor(&ServerMsg::Failed(e)).await;
603        }
604        if msg.command != Command::Subscribe {
605            let answer = self.run(msg.command).await.unwrap_or_else(ServerMsg::Failed);
606            return ch.send_cbor(&answer).await;
607        }
608        let mut changed = self.changed.subscribe();
609        loop {
610            if self.withdrawn.load(Ordering::SeqCst) {
611                let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
612                return ch.send_cbor(&ServerMsg::Withdrawn { peer: self.peer.clone(), seq }).await;
613            }
614            ch.send_cbor(&ServerMsg::Record(self.record()?)).await?;
615            changed.mark_unchanged();
616            tokio::select! {
617                r = changed.changed() => if r.is_err() { return Ok(()) },
618                _ = tokio::time::sleep(REFRESH) => {}
619                r = ch.rx.recv() => match r {
620                    Ok(None) | Err(_) => return Ok(()),
621                    Ok(Some(_)) => return Err(RemoteError::protocol("unexpected message on a subscription")),
622                },
623            }
624        }
625    }
626}
627
628/// How a [`NodeServer`] serves raw inference.
629#[derive(Debug, Clone, Copy, PartialEq, Eq)]
630#[non_exhaustive]
631pub struct NodeServerOptions {
632    /// Also serve raw inference on `/weirdnet-agent/infer/2` (and infer/1), for inference nodes
633    /// on backends 0.1.0. Default on. Turn it off on a node that is also an inference node, so
634    /// its inference role can serve infer/2 to apps.
635    pub legacy_infer2: bool,
636}
637
638impl Default for NodeServerOptions {
639    fn default() -> Self {
640        Self { legacy_infer2: true }
641    }
642}
643
644impl NodeServerOptions {
645    pub fn with_legacy_infer2(mut self, on: bool) -> Self {
646        self.legacy_infer2 = on;
647        self
648    }
649}
650
651/// Serves a [`NodeService`] on a `weirdnet-net` node: node/1, raw inference through the
652/// service's [`ModelHost`] on [`RAW_INFER_PROTOCOL`] (and infer/2, see [`NodeServerOptions`];
653/// no catalog, no inference announcement) and the [`MODEL_NODE_APP`] announcement, which lists
654/// the protocols served. Dropping it stops serving.
655pub struct NodeServer {
656    _infer: Option<Server>,
657    tasks: Vec<tokio::task::JoinHandle<()>>,
658    stop_app: Box<dyn Fn() + Send + Sync>,
659}
660
661impl NodeServer {
662    /// Starts serving with the default [`NodeServerOptions`] (raw inference on both ids). Call
663    /// from a Tokio runtime. The service's key must be the node's.
664    pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, service: Arc<NodeService>) -> Result<NodeServer, RemoteError> {
665        Self::start_with(node, service, NodeServerOptions::default())
666    }
667
668    /// Starts serving with `options`.
669    pub fn start_with<Q: Message, R: Message>(
670        node: &Arc<Node<Q, R>>,
671        service: Arc<NodeService>,
672        options: NodeServerOptions,
673    ) -> Result<NodeServer, RemoteError> {
674        let net = |e: weirdnet_net::NetError| RemoteError::Failed { message: e.to_string() };
675        if node.peer_id().to_string() != service.peer {
676            return Err(RemoteError::Failed { message: "the service's keypair is not this node's".into() });
677        }
678        let host: Arc<dyn InferHost> = service.host.clone();
679        let mut raw = node.accept_streams(RAW_INFER_PROTOCOL, stream_limits()).map_err(net)?;
680        let (h, a) = (host.clone(), service.admission.clone());
681        let raw_accept = tokio::spawn(async move {
682            while let Some(stream) = futures::StreamExt::next(&mut raw).await {
683                let caller = Caller::new(stream.peer().to_string());
684                let (h, a) = (h.clone(), a.clone());
685                tokio::spawn(async move {
686                    let _ = weirdnet_agent::remote::infer::v2::serve(channel(stream), caller, h.as_ref(), &a).await;
687                });
688            }
689        });
690        let infer = if options.legacy_infer2 {
691            Some(Server::start(node, Serving { infer: Some((host, service.admission.clone())), catalog: None, announce: false })?)
692        } else {
693            None
694        };
695        let mut incoming = node.accept_streams(PROTOCOL, stream_limits()).map_err(net)?;
696        let svc = service.clone();
697        let accept = tokio::spawn(async move {
698            while let Some(stream) = futures::StreamExt::next(&mut incoming).await {
699                let caller = Caller::new(stream.peer().to_string());
700                let svc = svc.clone();
701                tokio::spawn(async move {
702                    let _ = svc.serve(channel(stream), caller).await;
703                });
704            }
705        });
706        let mut protocols = vec![PROTOCOL, RAW_INFER_PROTOCOL];
707        if options.legacy_infer2 {
708            protocols.push(weirdnet_agent::remote::infer::v2::PROTOCOL);
709        }
710        let body = to_cbor(&protocols)?;
711        node.serve_app(
712            MODEL_NODE_APP,
713            Arc::new(move |_peer, _req| {
714                let body = body.clone();
715                async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
716            }),
717        )
718        .map_err(|e| RemoteError::Failed { message: e.to_string() })?;
719        let n = node.clone();
720        Ok(NodeServer {
721            _infer: infer,
722            tasks: vec![accept, raw_accept, service.watch()],
723            stop_app: Box::new(move || {
724                n.stop_serving_app(MODEL_NODE_APP);
725            }),
726        })
727    }
728}
729
730impl Drop for NodeServer {
731    fn drop(&mut self) {
732        for t in &self.tasks {
733            t.abort();
734        }
735        (self.stop_app)();
736    }
737}
738
739/// An update on a [`Subscription`].
740#[derive(Debug, Clone, PartialEq)]
741#[non_exhaustive]
742pub enum Update {
743    Record(Box<Capability>),
744    /// The node left; forget its records.
745    Withdrawn,
746}
747
748/// Verified records from one model node.
749pub struct Subscription {
750    ch: Channel,
751    node: String,
752    verifier: Verifier,
753    last_seq: u64,
754    done: bool,
755}
756
757impl Subscription {
758    /// The next update; `None` when the stream ended. Records are verified and their sequence
759    /// numbers must increase.
760    pub async fn next(&mut self) -> Option<Result<Update, RemoteError>> {
761        if self.done {
762            return None;
763        }
764        let msg = match self.ch.recv_cbor::<ServerMsg>().await {
765            Ok(Some(m)) => m,
766            Ok(None) => {
767                self.done = true;
768                return None;
769            }
770            Err(e) => {
771                self.done = true;
772                return Some(Err(e));
773            }
774        };
775        let out = match msg {
776            ServerMsg::Record(r) => self.verifier.verify(&r, &self.node, now_ms()).and_then(|cap| {
777                if cap.seq <= self.last_seq {
778                    return Err(RemoteError::protocol("capability record: sequence went backwards"));
779                }
780                self.last_seq = cap.seq;
781                Ok(Update::Record(Box::new(cap)))
782            }),
783            ServerMsg::Withdrawn { seq, .. } if seq > self.last_seq => Ok(Update::Withdrawn),
784            ServerMsg::Failed(e) => Err(e),
785            other => Err(RemoteError::protocol(format!("unexpected {other:?} on a subscription"))),
786        };
787        if !matches!(out, Ok(Update::Record(_))) {
788            self.done = true;
789        }
790        Some(out)
791    }
792}
793
794/// An inference node's side of node/1: drives model nodes over a [`Dialer`]
795/// (`weirdnet_agent::pool::NetDialer` on Weirdnet).
796pub struct NodeClient {
797    dialer: Arc<dyn Dialer>,
798    verifier: Verifier,
799    cert: Option<Vec<u8>>,
800}
801
802impl NodeClient {
803    pub fn new(dialer: Arc<dyn Dialer>, verifier: Verifier) -> Self {
804        Self { dialer, verifier, cert: None }
805    }
806
807    /// This node's CBOR `NodeCert` (`weirdnet_agent::pool::encode_cert`), presented to model nodes.
808    pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
809        self.cert = cert;
810        self
811    }
812
813    async fn open(&self, node: &str, command: Command) -> Result<Channel, RemoteError> {
814        let mut ch = self.dialer.open(node, PROTOCOL).await?;
815        ch.send_cbor(&ClientMsg { cert: self.cert.clone(), command }).await?;
816        Ok(ch)
817    }
818
819    async fn call(&self, node: &str, command: Command) -> Result<ServerMsg, RemoteError> {
820        let mut ch = self.open(node, command).await?;
821        match ch.recv_cbor::<ServerMsg>().await? {
822            Some(ServerMsg::Failed(e)) => Err(e),
823            Some(m) => Ok(m),
824            None => Err(RemoteError::Closed),
825        }
826    }
827
828    async fn done(&self, node: &str, command: Command) -> Result<(), RemoteError> {
829        match self.call(node, command).await? {
830            ServerMsg::Done => Ok(()),
831            other => Err(RemoteError::protocol(format!("expected done, got {other:?}"))),
832        }
833    }
834
835    /// The node's current record, verified.
836    pub async fn record(&self, node: &str) -> Result<Capability, RemoteError> {
837        match self.call(node, Command::Record).await? {
838            ServerMsg::Record(r) => self.verifier.verify(&r, node, now_ms()),
839            other => Err(RemoteError::protocol(format!("expected a record, got {other:?}"))),
840        }
841    }
842
843    /// Records now and on every change.
844    pub async fn subscribe(&self, node: &str) -> Result<Subscription, RemoteError> {
845        let ch = self.open(node, Command::Subscribe).await?;
846        Ok(Subscription { ch, node: node.into(), verifier: self.verifier.clone(), last_seq: 0, done: false })
847    }
848
849    /// Loads `model` and waits until it is ready. `force` also loads a model in a crash loop.
850    pub async fn load(&self, node: &str, model: &str, force: bool) -> Result<(), RemoteError> {
851        self.done(node, Command::Load { model: model.into(), force }).await
852    }
853
854    pub async fn unload(&self, node: &str, model: &str) -> Result<(), RemoteError> {
855        self.done(node, Command::Unload { model: model.into() }).await
856    }
857
858    /// Drains (waiting for requests under way) or resumes.
859    pub async fn drain(&self, node: &str, on: bool) -> Result<(), RemoteError> {
860        self.done(node, Command::Drain { on }).await
861    }
862
863    pub async fn group_up(&self, node: &str, plan: GroupPlan) -> Result<(), RemoteError> {
864        self.done(node, Command::GroupUp { plan }).await
865    }
866
867    pub async fn group_down(&self, node: &str, group: &str) -> Result<(), RemoteError> {
868        self.done(node, Command::GroupDown { group: group.into() }).await
869    }
870
871    pub async fn health(&self, node: &str) -> Result<Health, RemoteError> {
872        match self.call(node, Command::Health).await? {
873            ServerMsg::Health(h) => Ok(h),
874            other => Err(RemoteError::protocol(format!("expected health, got {other:?}"))),
875        }
876    }
877}
878
879#[cfg(test)]
880mod tests {
881    use super::*;
882    use crate::supervisor::{Supervisor, SupervisorOptions};
883    use weirdnet_net::WEIRDNET;
884
885    fn service() -> (NodeService, Keypair) {
886        let sup = Supervisor::new(vec![], vec![], SupervisorOptions::default());
887        let auth: Arc<dyn Authorize> = Arc::new(|_: &Caller| Ok(()));
888        let host = Arc::new(ModelHost::new(sup, auth.clone()));
889        let kp = Keypair::generate_ed25519();
890        (NodeService::new(host, kp.clone(), None, auth), kp)
891    }
892
893    #[test]
894    fn records_verify_and_tampering_fails() {
895        let (svc, _) = service();
896        let rec = svc.record().unwrap();
897        let v = Verifier::signature_only(&WEIRDNET);
898        let cap = v.verify(&rec, svc.peer(), now_ms()).unwrap();
899        assert_eq!((cap.peer.as_str(), cap.draining, cap.group_jobs), (svc.peer(), false, false));
900        assert!(cap.expires_ms - cap.issued_ms == 90_000);
901        let mut bad = rec.clone();
902        let mid = bad.record.len() / 2;
903        bad.record[mid] ^= 1;
904        assert!(v.verify(&bad, svc.peer(), now_ms()).is_err());
905        assert!(v.verify(&rec, &PeerId::random().to_string(), now_ms()).is_err(), "another peer's record");
906        assert!(v.verify(&rec, svc.peer(), cap.expires_ms).is_err(), "expired");
907        let user = Keypair::generate_ed25519();
908        assert!(Verifier::new(&WEIRDNET, user.public()).verify(&rec, svc.peer(), now_ms()).is_err(), "no certificate");
909        assert!(svc.record().unwrap().verify(svc.peer(), now_ms()).unwrap().seq > cap.seq);
910    }
911}