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