1use 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
45pub const PROTOCOL: &str = "/weirdnet-backends/node/1";
47pub const MODEL_NODE_APP: &str = "weirdnet-backends-node";
50pub const RECORD_TTL: Duration = Duration::from_secs(90);
52pub const REFRESH: Duration = Duration::from_secs(15);
54const SKEW_MS: i64 = 60_000;
56const DOMAIN: &[u8] = b"weirdnet-backends/node/1 capability record\n";
58const RECENT: usize = 32;
60
61fn now_ms() -> i64 {
62 weirdnet_net::now_ms()
63}
64
65#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
67#[non_exhaustive]
68pub struct Capability {
69 pub peer: String,
71 pub seq: u64,
73 pub issued_ms: i64,
74 pub expires_ms: i64,
75 pub hardware: Option<Hardware>,
77 pub budget: Option<Budget>,
79 pub engines: Vec<EngineKind>,
81 pub models: Vec<ModelEntry>,
83 pub load: Load,
84 pub warm_prefixes: Vec<String>,
86 pub groups: Vec<String>,
88 pub draining: bool,
90 pub group_jobs: bool,
92 #[serde(default, skip_serializing_if = "Option::is_none")]
96 pub reserved: Option<Reservation>,
97 #[serde(default, skip_serializing_if = "Vec::is_empty")]
100 pub links: Vec<LinkInfo>,
101}
102
103#[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 pub load_secs_estimate: Option<f32>,
112 pub speed: Speed,
113 #[serde(default, skip_serializing_if = "Option::is_none")]
117 pub origin: Option<String>,
118 #[serde(default, skip_serializing_if = "Option::is_none")]
121 pub license: Option<String>,
122}
123
124#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
126#[non_exhaustive]
127pub struct Load {
128 pub queued: u32,
130 pub active: u32,
132 pub slots: u32,
134 pub in_flight: u32,
136}
137
138#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
140pub struct SignedRecord {
141 #[serde(with = "serde_bytes")]
143 pub record: Vec<u8>,
144 #[serde(with = "serde_bytes")]
146 pub public_key: Vec<u8>,
147 #[serde(with = "serde_bytes")]
148 pub signature: Vec<u8>,
149 pub cert: Option<NodeCert>,
151}
152
153fn signed_bytes(record: &[u8]) -> Vec<u8> {
154 [DOMAIN, record].concat()
155}
156
157impl SignedRecord {
158 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 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#[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 pub fn signature_only(profile: &'static Profile) -> Self {
208 Self { profile, user: None, roster: None }
209 }
210
211 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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
245#[non_exhaustive]
246pub struct GroupPlan {
247 pub group: String,
248 pub leader: String,
250 pub members: Vec<String>,
251 pub drop: Vec<String>,
253 pub model: Option<String>,
255 pub link: Option<String>,
257 pub worker: Option<String>,
259 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#[async_trait]
297pub trait GroupWorkers: Send + Sync {
298 async fn up(&self, me: &str, plan: &GroupPlan) -> Result<(), RemoteError>;
300 async fn down(&self, group: &str) -> Result<(), RemoteError>;
301}
302
303#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
305#[non_exhaustive]
306pub enum Command {
307 Subscribe,
309 Record,
311 Load {
312 model: String,
313 force: bool,
314 },
315 Unload {
316 model: String,
317 },
318 Drain {
320 on: bool,
321 },
322 Reserve {
326 holder: String,
327 },
328 Release {
330 holder: String,
331 },
332 GroupUp {
333 plan: GroupPlan,
334 },
335 GroupDown {
336 group: String,
337 },
338 Health,
339}
340
341#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
343pub struct ClientMsg {
344 #[serde(default, with = "serde_bytes")]
346 pub cert: Option<Vec<u8>>,
347 pub command: Command,
348}
349
350#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
352#[non_exhaustive]
353pub enum ServerMsg {
354 Record(SignedRecord),
355 Done,
357 Health(Health),
358 Failed(RemoteError),
359 Withdrawn {
361 peer: String,
362 seq: u64,
363 },
364}
365
366#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
368#[non_exhaustive]
369pub struct Health {
370 pub peer: String,
371 pub at_ms: i64,
372 pub ok: bool,
374 pub draining: bool,
375 #[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 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#[derive(Debug, Clone, Default)]
395struct ModelInfo {
396 revision: Option<String>,
397 quant: Option<String>,
398 origin: Option<String>,
399 license: Option<String>,
400}
401
402pub 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 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 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 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 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 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 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 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 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 pub fn touch(&self) {
537 self.changed.send_modify(|v| *v += 1);
538 }
539
540 pub fn withdraw(&self) {
542 self.withdrawn.store(true, Ordering::SeqCst);
543 self.touch();
544 }
545
546 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
732#[non_exhaustive]
733pub struct NodeServerOptions {
734 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
753pub 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 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 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#[derive(Debug, Clone, PartialEq)]
843#[non_exhaustive]
844pub enum Update {
845 Record(Box<Capability>),
846 Withdrawn,
848}
849
850pub struct Subscription {
852 ch: Channel,
853 node: String,
854 verifier: Verifier,
855 last_seq: u64,
856 done: bool,
857}
858
859impl Subscription {
860 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
896pub 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 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 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 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 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 pub async fn drain(&self, node: &str, on: bool) -> Result<(), RemoteError> {
962 self.done(node, Command::Drain { on }).await
963 }
964
965 pub async fn reserve(&self, node: &str, holder: &str) -> Result<(), RemoteError> {
968 self.done(node, Command::Reserve { holder: holder.into() }).await
969 }
970
971 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}