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}
114
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
117#[non_exhaustive]
118pub struct Load {
119 pub queued: u32,
121 pub active: u32,
123 pub slots: u32,
125 pub in_flight: u32,
127}
128
129#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
131pub struct SignedRecord {
132 #[serde(with = "serde_bytes")]
134 pub record: Vec<u8>,
135 #[serde(with = "serde_bytes")]
137 pub public_key: Vec<u8>,
138 #[serde(with = "serde_bytes")]
139 pub signature: Vec<u8>,
140 pub cert: Option<NodeCert>,
142}
143
144fn signed_bytes(record: &[u8]) -> Vec<u8> {
145 [DOMAIN, record].concat()
146}
147
148impl SignedRecord {
149 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 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#[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 pub fn signature_only(profile: &'static Profile) -> Self {
199 Self { profile, user: None, roster: None }
200 }
201
202 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#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
236#[non_exhaustive]
237pub struct GroupPlan {
238 pub group: String,
239 pub leader: String,
241 pub members: Vec<String>,
242 pub drop: Vec<String>,
244 pub model: Option<String>,
246 pub link: Option<String>,
248 pub worker: Option<String>,
250 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#[async_trait]
288pub trait GroupWorkers: Send + Sync {
289 async fn up(&self, me: &str, plan: &GroupPlan) -> Result<(), RemoteError>;
291 async fn down(&self, group: &str) -> Result<(), RemoteError>;
292}
293
294#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
296#[non_exhaustive]
297pub enum Command {
298 Subscribe,
300 Record,
302 Load {
303 model: String,
304 force: bool,
305 },
306 Unload {
307 model: String,
308 },
309 Drain {
311 on: bool,
312 },
313 Reserve {
317 holder: String,
318 },
319 Release {
321 holder: String,
322 },
323 GroupUp {
324 plan: GroupPlan,
325 },
326 GroupDown {
327 group: String,
328 },
329 Health,
330}
331
332#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
334pub struct ClientMsg {
335 #[serde(default, with = "serde_bytes")]
337 pub cert: Option<Vec<u8>>,
338 pub command: Command,
339}
340
341#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
343#[non_exhaustive]
344pub enum ServerMsg {
345 Record(SignedRecord),
346 Done,
348 Health(Health),
349 Failed(RemoteError),
350 Withdrawn {
352 peer: String,
353 seq: u64,
354 },
355}
356
357#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
359#[non_exhaustive]
360pub struct Health {
361 pub peer: String,
362 pub at_ms: i64,
363 pub ok: bool,
365 pub draining: bool,
366 #[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 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
384type ModelInfo = (Option<String>, Option<String>);
386
387pub 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 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 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 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 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 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 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 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 pub fn touch(&self) {
508 self.changed.send_modify(|v| *v += 1);
509 }
510
511 pub fn withdraw(&self) {
513 self.withdrawn.store(true, Ordering::SeqCst);
514 self.touch();
515 }
516
517 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 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 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
703#[non_exhaustive]
704pub struct NodeServerOptions {
705 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
724pub 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 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 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#[derive(Debug, Clone, PartialEq)]
814#[non_exhaustive]
815pub enum Update {
816 Record(Box<Capability>),
817 Withdrawn,
819}
820
821pub struct Subscription {
823 ch: Channel,
824 node: String,
825 verifier: Verifier,
826 last_seq: u64,
827 done: bool,
828}
829
830impl Subscription {
831 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
867pub 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 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 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 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 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 pub async fn drain(&self, node: &str, on: bool) -> Result<(), RemoteError> {
933 self.done(node, Command::Drain { on }).await
934 }
935
936 pub async fn reserve(&self, node: &str, holder: &str) -> Result<(), RemoteError> {
939 self.done(node, Command::Reserve { holder: holder.into() }).await
940 }
941
942 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}