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