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