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