1use std::collections::{HashMap, VecDeque};
22use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
23use std::sync::{Arc, Mutex};
24use std::time::{Duration, Instant};
25
26use async_trait::async_trait;
27use serde::{Deserialize, Serialize};
28use tokio::sync::watch;
29use weirdnet_agent::remote::infer::{Admission, InferHost};
30use weirdnet_agent::remote::{Authorize, Caller, Channel, Dialer, RemoteError, from_cbor, to_cbor};
31use weirdnet_agent::serve::{Server, Serving, channel, stream_limits};
32use weirdnet_model::hw::{Budget, Hardware};
33use weirdnet_net::node::{Message, Node};
34use weirdnet_net::profile::Profile;
35use weirdnet_net::user::NodeCert;
36use weirdnet_net::{AppBody, AppResponse, Keypair, PeerId, PublicKey};
37
38use crate::engine::EngineKind;
39use crate::host::{ModelHost, RAW_INFER_PROTOCOL, Speed};
40pub use crate::link::{AddrClass, LinkInfo, LinkMeasure};
41use crate::supervisor::{ModelState, ModelStatus, SupervisorEvent};
42use weirdnet_agent::serve::RosterView;
43
44pub const PROTOCOL: &str = "/weirdnet-backends/node/1";
46pub const MODEL_NODE_APP: &str = "weirdnet-backends-node";
49pub const RECORD_TTL: Duration = Duration::from_secs(90);
51pub const REFRESH: Duration = Duration::from_secs(15);
53const SKEW_MS: i64 = 60_000;
55const DOMAIN: &[u8] = b"weirdnet-backends/node/1 capability record\n";
57const RECENT: usize = 32;
59
60fn now_ms() -> i64 {
61 weirdnet_net::now_ms()
62}
63
64#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
66#[non_exhaustive]
67pub struct Capability {
68 pub peer: String,
70 pub seq: u64,
72 pub issued_ms: i64,
73 pub expires_ms: i64,
74 pub hardware: Option<Hardware>,
76 pub budget: Option<Budget>,
78 pub engines: Vec<EngineKind>,
80 pub models: Vec<ModelEntry>,
82 pub load: Load,
83 pub warm_prefixes: Vec<String>,
85 pub groups: Vec<String>,
87 pub draining: bool,
89 pub group_jobs: bool,
91 #[serde(default, skip_serializing_if = "Vec::is_empty")]
94 pub links: Vec<LinkInfo>,
95}
96
97#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
99#[non_exhaustive]
100pub struct ModelEntry {
101 pub status: ModelStatus,
102 pub revision: Option<String>,
103 pub quant: Option<String>,
104 pub load_secs_estimate: Option<f32>,
106 pub speed: Speed,
107}
108
109#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
111#[non_exhaustive]
112pub struct Load {
113 pub queued: u32,
115 pub active: u32,
117 pub slots: u32,
119 pub in_flight: u32,
121}
122
123#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
125pub struct SignedRecord {
126 #[serde(with = "serde_bytes")]
128 pub record: Vec<u8>,
129 #[serde(with = "serde_bytes")]
131 pub public_key: Vec<u8>,
132 #[serde(with = "serde_bytes")]
133 pub signature: Vec<u8>,
134 pub cert: Option<NodeCert>,
136}
137
138fn signed_bytes(record: &[u8]) -> Vec<u8> {
139 [DOMAIN, record].concat()
140}
141
142impl SignedRecord {
143 pub fn sign(keypair: &Keypair, cap: &Capability, cert: Option<NodeCert>) -> Result<Self, RemoteError> {
145 let record = to_cbor(cap)?;
146 let signature = keypair.sign(&signed_bytes(&record)).map_err(|e| RemoteError::Failed { message: format!("signing: {e}") })?;
147 Ok(Self { record, public_key: keypair.public().encode_protobuf(), signature, cert })
148 }
149
150 pub fn verify(&self, from_peer: &str, now_ms: i64) -> Result<Capability, RemoteError> {
153 let bad = |why: &str| RemoteError::protocol(format!("capability record: {why}"));
154 let key = PublicKey::try_decode_protobuf(&self.public_key).map_err(|_| bad("bad public key"))?;
155 if PeerId::from_public_key(&key).to_string() != from_peer {
156 return Err(bad("signed by another node"));
157 }
158 if !key.verify(&signed_bytes(&self.record), &self.signature) {
159 return Err(bad("bad signature"));
160 }
161 let cap: Capability = from_cbor(&self.record)?;
162 if cap.peer != from_peer {
163 return Err(bad("names another node"));
164 }
165 if cap.expires_ms <= now_ms {
166 return Err(bad("expired"));
167 }
168 if cap.issued_ms > now_ms + SKEW_MS {
169 return Err(bad("issued in the future"));
170 }
171 Ok(cap)
172 }
173}
174
175#[derive(Clone)]
180pub struct Verifier {
181 profile: &'static Profile,
182 user: Option<PublicKey>,
183 roster: Option<RosterView>,
184}
185
186impl Verifier {
187 pub fn new(profile: &'static Profile, user: PublicKey) -> Self {
188 Self { profile, user: Some(user), roster: None }
189 }
190
191 pub fn signature_only(profile: &'static Profile) -> Self {
193 Self { profile, user: None, roster: None }
194 }
195
196 pub fn with_roster(mut self, roster: RosterView) -> Self {
199 self.roster = Some(roster);
200 self
201 }
202
203 pub fn verify(&self, record: &SignedRecord, from_peer: &str, now_ms: i64) -> Result<Capability, RemoteError> {
204 let cap = record.verify(from_peer, now_ms)?;
205 if let Some(user) = &self.user {
206 let ok = match &record.cert {
207 Some(c) => c.peer_id == from_peer && c.active() && self.profile.verify_cert(user, c),
208 None => false,
209 };
210 if !ok {
211 return Err(RemoteError::refused("capability record: no valid certificate from the user"));
212 }
213 if let Some(roster) = &self.roster {
214 use weirdnet_sync::CallerCheck;
215 match roster().check_caller(self.profile, user, from_peer, record.cert.as_ref()) {
216 CallerCheck::Linked | CallerCheck::NotAdmitted => {}
217 other => {
218 let reason = other.reason().unwrap_or("unknown-device");
219 return Err(RemoteError::refused(format!("capability record: {reason}")));
220 }
221 }
222 }
223 }
224 Ok(cap)
225 }
226}
227
228#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
230#[non_exhaustive]
231pub struct GroupPlan {
232 pub group: String,
233 pub leader: String,
235 pub members: Vec<String>,
236 pub drop: Vec<String>,
238 pub model: Option<String>,
240 pub link: Option<String>,
242 pub worker: Option<String>,
244 pub extra: HashMap<String, String>,
246}
247
248impl GroupPlan {
249 pub fn new(group: impl Into<String>, leader: impl Into<String>) -> Self {
250 Self { group: group.into(), leader: leader.into(), ..Default::default() }
251 }
252
253 pub fn with_members(mut self, members: Vec<String>) -> Self {
254 self.members = members;
255 self
256 }
257
258 pub fn with_drop(mut self, drop: Vec<String>) -> Self {
259 self.drop = drop;
260 self
261 }
262
263 pub fn with_model(mut self, model: impl Into<String>) -> Self {
264 self.model = Some(model.into());
265 self
266 }
267
268 pub fn with_link(mut self, link: impl Into<String>) -> Self {
269 self.link = Some(link.into());
270 self
271 }
272
273 pub fn with_worker(mut self, worker: impl Into<String>) -> Self {
274 self.worker = Some(worker.into());
275 self
276 }
277}
278
279#[async_trait]
282pub trait GroupWorkers: Send + Sync {
283 async fn up(&self, me: &str, plan: &GroupPlan) -> Result<(), RemoteError>;
285 async fn down(&self, group: &str) -> Result<(), RemoteError>;
286}
287
288#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
290#[non_exhaustive]
291pub enum Command {
292 Subscribe,
294 Record,
296 Load {
297 model: String,
298 force: bool,
299 },
300 Unload {
301 model: String,
302 },
303 Drain {
305 on: bool,
306 },
307 GroupUp {
308 plan: GroupPlan,
309 },
310 GroupDown {
311 group: String,
312 },
313 Health,
314}
315
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
318pub struct ClientMsg {
319 #[serde(default, with = "serde_bytes")]
321 pub cert: Option<Vec<u8>>,
322 pub command: Command,
323}
324
325#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
327#[non_exhaustive]
328pub enum ServerMsg {
329 Record(SignedRecord),
330 Done,
332 Health(Health),
333 Failed(RemoteError),
334 Withdrawn {
336 peer: String,
337 seq: u64,
338 },
339}
340
341#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
343#[non_exhaustive]
344pub struct Health {
345 pub peer: String,
346 pub at_ms: i64,
347 pub ok: bool,
349 pub draining: bool,
350 pub in_flight: u32,
351 pub uptime_secs: u64,
352 pub models: Vec<ModelHealth>,
353 pub events: Vec<SupervisorEvent>,
355}
356
357#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
358#[non_exhaustive]
359pub struct ModelHealth {
360 pub id: String,
361 pub state: ModelState,
362 pub crashes: usize,
363}
364
365type ModelInfo = (Option<String>, Option<String>);
367
368pub struct NodeService {
372 host: Arc<ModelHost>,
373 admission: Admission,
374 slots: usize,
375 keypair: Keypair,
376 peer: String,
377 cert: Option<NodeCert>,
378 auth: Arc<dyn Authorize>,
379 hardware: Option<Hardware>,
380 budget: Option<Budget>,
381 engines: Vec<EngineKind>,
382 workers: Option<Arc<dyn GroupWorkers>>,
383 drain_timeout: Duration,
384 info: Mutex<HashMap<String, ModelInfo>>,
385 warm: Mutex<Vec<String>>,
386 groups: Mutex<Vec<String>>,
387 links: Mutex<Vec<LinkInfo>>,
388 recent: Mutex<VecDeque<SupervisorEvent>>,
389 seq: AtomicU64,
390 withdrawn: AtomicBool,
391 changed: watch::Sender<u64>,
392 started: Instant,
393}
394
395impl NodeService {
396 pub fn new(host: Arc<ModelHost>, keypair: Keypair, cert: Option<NodeCert>, auth: Arc<dyn Authorize>) -> Self {
399 let peer = keypair.public().to_peer_id().to_string();
400 let engines = host.supervisor().status().iter().map(|m| m.engine).fold(Vec::new(), |mut v, e| {
401 if !v.contains(&e) {
402 v.push(e);
403 }
404 v
405 });
406 Self {
407 host,
408 admission: Admission::new(4),
409 slots: 4,
410 keypair,
411 peer,
412 cert,
413 auth,
414 hardware: None,
415 budget: None,
416 engines,
417 workers: None,
418 drain_timeout: Duration::from_secs(60),
419 info: Mutex::default(),
420 warm: Mutex::default(),
421 groups: Mutex::default(),
422 links: Mutex::default(),
423 recent: Mutex::default(),
424 seq: AtomicU64::new(now_ms().max(0) as u64),
425 withdrawn: AtomicBool::new(false),
426 changed: watch::Sender::new(0),
427 started: Instant::now(),
428 }
429 }
430
431 pub fn with_admission(mut self, slots: usize, queue: usize) -> Self {
433 self.admission = Admission::with_queue(slots, queue);
434 self.slots = slots;
435 self
436 }
437
438 pub fn with_hardware(mut self, hardware: Hardware, budget: Budget) -> Self {
440 self.hardware = Some(hardware);
441 self.budget = Some(budget);
442 self
443 }
444
445 pub fn with_group_workers(mut self, workers: Arc<dyn GroupWorkers>) -> Self {
446 self.workers = Some(workers);
447 self
448 }
449
450 pub fn with_drain_timeout(mut self, d: Duration) -> Self {
452 self.drain_timeout = d;
453 self
454 }
455
456 pub fn peer(&self) -> &str {
457 &self.peer
458 }
459
460 pub fn host(&self) -> &Arc<ModelHost> {
461 &self.host
462 }
463
464 pub fn admission(&self) -> &Admission {
465 &self.admission
466 }
467
468 pub fn set_model_info(&self, model: &str, revision: Option<String>, quant: Option<String>) {
470 self.info.lock().unwrap_or_else(|e| e.into_inner()).insert(model.into(), (revision, quant));
471 self.touch();
472 }
473
474 pub fn set_links(&self, links: Vec<LinkInfo>) {
477 *self.links.lock().unwrap_or_else(|e| e.into_inner()) = crate::link::advertised(links);
478 self.touch();
479 }
480
481 pub fn set_warm_prefixes(&self, hashes: Vec<String>) {
483 *self.warm.lock().unwrap_or_else(|e| e.into_inner()) = hashes;
484 self.touch();
485 }
486
487 pub fn touch(&self) {
489 self.changed.send_modify(|v| *v += 1);
490 }
491
492 pub fn withdraw(&self) {
494 self.withdrawn.store(true, Ordering::SeqCst);
495 self.touch();
496 }
497
498 pub fn capability(&self) -> Capability {
500 let issued_ms = now_ms();
501 let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
502 let info = self.info.lock().unwrap_or_else(|e| e.into_inner()).clone();
503 let models = self
504 .host
505 .supervisor()
506 .status()
507 .into_iter()
508 .map(|status| {
509 let (revision, quant) = info.get(&status.id).cloned().unwrap_or_default();
510 let load_secs_estimate = status.last_load_secs.or(status.size_bytes.map(|b| b as f32 / 1e9 + 3.0));
512 let speed = self.host.speed(&status.id);
513 ModelEntry { status, revision, quant, load_secs_estimate, speed }
514 })
515 .collect::<Vec<_>>();
516 let in_flight = self.host.supervisor().in_flight() as u32;
517 let free = self.admission.free();
518 let load =
519 Load { queued: self.admission.waiting() as u32, active: self.slots.saturating_sub(free) as u32, slots: self.slots as u32, in_flight };
520 Capability {
521 peer: self.peer.clone(),
522 seq,
523 issued_ms,
524 expires_ms: issued_ms + RECORD_TTL.as_millis() as i64,
525 hardware: self.hardware.clone(),
526 budget: self.budget,
527 engines: self.engines.clone(),
528 models,
529 load,
530 warm_prefixes: self.warm.lock().unwrap_or_else(|e| e.into_inner()).clone(),
531 groups: self.groups.lock().unwrap_or_else(|e| e.into_inner()).clone(),
532 draining: self.host.draining(),
533 group_jobs: self.workers.is_some(),
534 links: self.links.lock().unwrap_or_else(|e| e.into_inner()).clone(),
535 }
536 }
537
538 pub fn record(&self) -> Result<SignedRecord, RemoteError> {
540 SignedRecord::sign(&self.keypair, &self.capability(), self.cert.clone())
541 }
542
543 pub fn health(&self) -> Health {
544 let status = self.host.supervisor().status();
545 let ok = status.iter().all(|m| !matches!(m.state, ModelState::Failed(_)));
546 Health {
547 peer: self.peer.clone(),
548 at_ms: now_ms(),
549 ok,
550 draining: self.host.draining(),
551 in_flight: self.host.supervisor().in_flight() as u32,
552 uptime_secs: self.started.elapsed().as_secs(),
553 models: status.into_iter().map(|m| ModelHealth { id: m.id, state: m.state, crashes: m.crashes }).collect(),
554 events: self.recent.lock().unwrap_or_else(|e| e.into_inner()).iter().cloned().collect(),
555 }
556 }
557
558 pub fn watch(self: &Arc<Self>) -> tokio::task::JoinHandle<()> {
560 let me = self.clone();
561 let mut events = self.host.supervisor().subscribe();
562 tokio::spawn(async move {
563 loop {
564 match events.recv().await {
565 Ok(ev) => {
566 let mut recent = me.recent.lock().unwrap_or_else(|e| e.into_inner());
567 if recent.len() == RECENT {
568 recent.pop_front();
569 }
570 recent.push_back(ev);
571 }
572 Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => {}
573 Err(tokio::sync::broadcast::error::RecvError::Closed) => return,
574 }
575 me.touch();
576 }
577 })
578 }
579
580 async fn run(&self, command: Command) -> Result<ServerMsg, RemoteError> {
581 let sup = self.host.supervisor();
582 let done = match command {
583 Command::Record => return Ok(ServerMsg::Record(self.record()?)),
584 Command::Health => return Ok(ServerMsg::Health(self.health())),
585 Command::Load { model, force } => {
586 if self.host.draining() {
587 return Err(RemoteError::unavailable("this node is draining"));
588 }
589 sup.load_with(&model, force).await
590 }
591 Command::Unload { model } => sup.unload(&model).await,
592 Command::Drain { on } => {
593 self.host.set_draining(on);
594 self.touch();
595 if on {
596 let deadline = Instant::now() + self.drain_timeout;
597 while sup.in_flight() > 0 || self.admission.free() < self.slots {
598 if Instant::now() >= deadline {
599 return Err(RemoteError::Timeout);
600 }
601 tokio::time::sleep(Duration::from_millis(50)).await;
602 }
603 }
604 Ok(())
605 }
606 Command::GroupUp { plan } => {
607 let workers = self.workers.as_ref().ok_or_else(|| RemoteError::Unsupported { message: "this node takes no group jobs".into() })?;
608 for model in &plan.drop {
609 sup.unload(model).await?;
610 }
611 workers.up(&self.peer, &plan).await?;
612 let mut groups = self.groups.lock().unwrap_or_else(|e| e.into_inner());
613 if !groups.contains(&plan.group) {
614 groups.push(plan.group.clone());
615 }
616 Ok(())
617 }
618 Command::GroupDown { group } => {
619 let workers = self.workers.as_ref().ok_or_else(|| RemoteError::Unsupported { message: "this node takes no group jobs".into() })?;
620 workers.down(&group).await?;
621 self.groups.lock().unwrap_or_else(|e| e.into_inner()).retain(|g| *g != group);
622 Ok(())
623 }
624 Command::Subscribe => unreachable!("handled by serve"),
625 };
626 self.touch();
627 done.map(|()| ServerMsg::Done)
628 }
629
630 pub async fn serve(&self, mut ch: Channel, caller: Caller) -> Result<(), RemoteError> {
632 let Some(msg) = ch.recv_cbor::<ClientMsg>().await? else { return Ok(()) };
633 let caller = match (caller.cert_bytes.is_some(), msg.cert) {
634 (false, Some(cert)) => caller.with_cert(cert),
635 (_, _) => caller,
636 };
637 if let Err(e) = self.auth.authorize(&caller) {
638 return ch.send_cbor(&ServerMsg::Failed(e)).await;
639 }
640 if msg.command != Command::Subscribe {
641 let answer = self.run(msg.command).await.unwrap_or_else(ServerMsg::Failed);
642 return ch.send_cbor(&answer).await;
643 }
644 let mut changed = self.changed.subscribe();
645 loop {
646 if self.withdrawn.load(Ordering::SeqCst) {
647 let seq = self.seq.fetch_add(1, Ordering::SeqCst) + 1;
648 return ch.send_cbor(&ServerMsg::Withdrawn { peer: self.peer.clone(), seq }).await;
649 }
650 ch.send_cbor(&ServerMsg::Record(self.record()?)).await?;
651 changed.mark_unchanged();
652 tokio::select! {
653 r = changed.changed() => if r.is_err() { return Ok(()) },
654 _ = tokio::time::sleep(REFRESH) => {}
655 r = ch.rx.recv() => match r {
656 Ok(None) | Err(_) => return Ok(()),
657 Ok(Some(_)) => return Err(RemoteError::protocol("unexpected message on a subscription")),
658 },
659 }
660 }
661 }
662}
663
664#[derive(Debug, Clone, Copy, PartialEq, Eq)]
666#[non_exhaustive]
667pub struct NodeServerOptions {
668 pub legacy_infer2: bool,
672}
673
674impl Default for NodeServerOptions {
675 fn default() -> Self {
676 Self { legacy_infer2: true }
677 }
678}
679
680impl NodeServerOptions {
681 pub fn with_legacy_infer2(mut self, on: bool) -> Self {
682 self.legacy_infer2 = on;
683 self
684 }
685}
686
687pub struct NodeServer {
692 _infer: Option<Server>,
693 tasks: Vec<tokio::task::JoinHandle<()>>,
694 stop_app: Box<dyn Fn() + Send + Sync>,
695}
696
697impl NodeServer {
698 pub fn start<Q: Message, R: Message>(node: &Arc<Node<Q, R>>, service: Arc<NodeService>) -> Result<NodeServer, RemoteError> {
701 Self::start_with(node, service, NodeServerOptions::default())
702 }
703
704 pub fn start_with<Q: Message, R: Message>(
706 node: &Arc<Node<Q, R>>,
707 service: Arc<NodeService>,
708 options: NodeServerOptions,
709 ) -> Result<NodeServer, RemoteError> {
710 let net = |e: weirdnet_net::NetError| RemoteError::Failed { message: e.to_string() };
711 if node.peer_id().to_string() != service.peer {
712 return Err(RemoteError::Failed { message: "the service's keypair is not this node's".into() });
713 }
714 let host: Arc<dyn InferHost> = service.host.clone();
715 let mut raw = node.accept_streams(RAW_INFER_PROTOCOL, stream_limits()).map_err(net)?;
716 let (h, a) = (host.clone(), service.admission.clone());
717 let raw_accept = tokio::spawn(async move {
718 while let Some(stream) = futures::StreamExt::next(&mut raw).await {
719 let caller = Caller::new(stream.peer().to_string());
720 let (h, a) = (h.clone(), a.clone());
721 tokio::spawn(async move {
722 let _ = weirdnet_agent::remote::infer::v2::serve(channel(stream), caller, h.as_ref(), &a).await;
723 });
724 }
725 });
726 let infer = if options.legacy_infer2 {
727 Some(Server::start(node, Serving { infer: Some((host, service.admission.clone())), catalog: None, announce: false })?)
728 } else {
729 None
730 };
731 let mut incoming = node.accept_streams(PROTOCOL, stream_limits()).map_err(net)?;
732 let svc = service.clone();
733 let accept = tokio::spawn(async move {
734 while let Some(stream) = futures::StreamExt::next(&mut incoming).await {
735 let caller = Caller::new(stream.peer().to_string());
736 let svc = svc.clone();
737 tokio::spawn(async move {
738 let _ = svc.serve(channel(stream), caller).await;
739 });
740 }
741 });
742 let mut protocols = vec![PROTOCOL, RAW_INFER_PROTOCOL];
743 if options.legacy_infer2 {
744 protocols.push(weirdnet_agent::remote::infer::v2::PROTOCOL);
745 }
746 let body = to_cbor(&protocols)?;
747 node.serve_app(
748 MODEL_NODE_APP,
749 Arc::new(move |_peer, _req| {
750 let body = body.clone();
751 async move { Ok(AppResponse::new(200).header("content-type", "application/cbor").body(AppBody::bytes(body))) }
752 }),
753 )
754 .map_err(|e| RemoteError::Failed { message: e.to_string() })?;
755 let n = node.clone();
756 Ok(NodeServer {
757 _infer: infer,
758 tasks: vec![accept, raw_accept, service.watch()],
759 stop_app: Box::new(move || {
760 n.stop_serving_app(MODEL_NODE_APP);
761 }),
762 })
763 }
764}
765
766impl Drop for NodeServer {
767 fn drop(&mut self) {
768 for t in &self.tasks {
769 t.abort();
770 }
771 (self.stop_app)();
772 }
773}
774
775#[derive(Debug, Clone, PartialEq)]
777#[non_exhaustive]
778pub enum Update {
779 Record(Box<Capability>),
780 Withdrawn,
782}
783
784pub struct Subscription {
786 ch: Channel,
787 node: String,
788 verifier: Verifier,
789 last_seq: u64,
790 done: bool,
791}
792
793impl Subscription {
794 pub async fn next(&mut self) -> Option<Result<Update, RemoteError>> {
797 if self.done {
798 return None;
799 }
800 let msg = match self.ch.recv_cbor::<ServerMsg>().await {
801 Ok(Some(m)) => m,
802 Ok(None) => {
803 self.done = true;
804 return None;
805 }
806 Err(e) => {
807 self.done = true;
808 return Some(Err(e));
809 }
810 };
811 let out = match msg {
812 ServerMsg::Record(r) => self.verifier.verify(&r, &self.node, now_ms()).and_then(|cap| {
813 if cap.seq <= self.last_seq {
814 return Err(RemoteError::protocol("capability record: sequence went backwards"));
815 }
816 self.last_seq = cap.seq;
817 Ok(Update::Record(Box::new(cap)))
818 }),
819 ServerMsg::Withdrawn { seq, .. } if seq > self.last_seq => Ok(Update::Withdrawn),
820 ServerMsg::Failed(e) => Err(e),
821 other => Err(RemoteError::protocol(format!("unexpected {other:?} on a subscription"))),
822 };
823 if !matches!(out, Ok(Update::Record(_))) {
824 self.done = true;
825 }
826 Some(out)
827 }
828}
829
830pub struct NodeClient {
833 dialer: Arc<dyn Dialer>,
834 verifier: Verifier,
835 cert: Option<Vec<u8>>,
836}
837
838impl NodeClient {
839 pub fn new(dialer: Arc<dyn Dialer>, verifier: Verifier) -> Self {
840 Self { dialer, verifier, cert: None }
841 }
842
843 pub fn with_cert(mut self, cert: Option<Vec<u8>>) -> Self {
845 self.cert = cert;
846 self
847 }
848
849 async fn open(&self, node: &str, command: Command) -> Result<Channel, RemoteError> {
850 let mut ch = self.dialer.open(node, PROTOCOL).await?;
851 ch.send_cbor(&ClientMsg { cert: self.cert.clone(), command }).await?;
852 Ok(ch)
853 }
854
855 async fn call(&self, node: &str, command: Command) -> Result<ServerMsg, RemoteError> {
856 let mut ch = self.open(node, command).await?;
857 match ch.recv_cbor::<ServerMsg>().await? {
858 Some(ServerMsg::Failed(e)) => Err(e),
859 Some(m) => Ok(m),
860 None => Err(RemoteError::Closed),
861 }
862 }
863
864 async fn done(&self, node: &str, command: Command) -> Result<(), RemoteError> {
865 match self.call(node, command).await? {
866 ServerMsg::Done => Ok(()),
867 other => Err(RemoteError::protocol(format!("expected done, got {other:?}"))),
868 }
869 }
870
871 pub async fn record(&self, node: &str) -> Result<Capability, RemoteError> {
873 match self.call(node, Command::Record).await? {
874 ServerMsg::Record(r) => self.verifier.verify(&r, node, now_ms()),
875 other => Err(RemoteError::protocol(format!("expected a record, got {other:?}"))),
876 }
877 }
878
879 pub async fn subscribe(&self, node: &str) -> Result<Subscription, RemoteError> {
881 let ch = self.open(node, Command::Subscribe).await?;
882 Ok(Subscription { ch, node: node.into(), verifier: self.verifier.clone(), last_seq: 0, done: false })
883 }
884
885 pub async fn load(&self, node: &str, model: &str, force: bool) -> Result<(), RemoteError> {
887 self.done(node, Command::Load { model: model.into(), force }).await
888 }
889
890 pub async fn unload(&self, node: &str, model: &str) -> Result<(), RemoteError> {
891 self.done(node, Command::Unload { model: model.into() }).await
892 }
893
894 pub async fn drain(&self, node: &str, on: bool) -> Result<(), RemoteError> {
896 self.done(node, Command::Drain { on }).await
897 }
898
899 pub async fn group_up(&self, node: &str, plan: GroupPlan) -> Result<(), RemoteError> {
900 self.done(node, Command::GroupUp { plan }).await
901 }
902
903 pub async fn group_down(&self, node: &str, group: &str) -> Result<(), RemoteError> {
904 self.done(node, Command::GroupDown { group: group.into() }).await
905 }
906
907 pub async fn health(&self, node: &str) -> Result<Health, RemoteError> {
908 match self.call(node, Command::Health).await? {
909 ServerMsg::Health(h) => Ok(h),
910 other => Err(RemoteError::protocol(format!("expected health, got {other:?}"))),
911 }
912 }
913}
914
915#[cfg(test)]
916mod tests {
917 use super::*;
918 use crate::supervisor::{Supervisor, SupervisorOptions};
919 use weirdnet_net::WEIRDNET;
920
921 fn service() -> (NodeService, Keypair) {
922 let sup = Supervisor::new(vec![], vec![], SupervisorOptions::default());
923 let auth: Arc<dyn Authorize> = Arc::new(|_: &Caller| Ok(()));
924 let host = Arc::new(ModelHost::new(sup, auth.clone()));
925 let kp = Keypair::generate_ed25519();
926 (NodeService::new(host, kp.clone(), None, auth), kp)
927 }
928
929 #[test]
930 fn records_verify_and_tampering_fails() {
931 let (svc, _) = service();
932 let rec = svc.record().unwrap();
933 let v = Verifier::signature_only(&WEIRDNET);
934 let cap = v.verify(&rec, svc.peer(), now_ms()).unwrap();
935 assert_eq!((cap.peer.as_str(), cap.draining, cap.group_jobs), (svc.peer(), false, false));
936 assert!(cap.expires_ms - cap.issued_ms == 90_000);
937 let mut bad = rec.clone();
938 let mid = bad.record.len() / 2;
939 bad.record[mid] ^= 1;
940 assert!(v.verify(&bad, svc.peer(), now_ms()).is_err());
941 assert!(v.verify(&rec, &PeerId::random().to_string(), now_ms()).is_err(), "another peer's record");
942 assert!(v.verify(&rec, svc.peer(), cap.expires_ms).is_err(), "expired");
943 let user = Keypair::generate_ed25519();
944 assert!(Verifier::new(&WEIRDNET, user.public()).verify(&rec, svc.peer(), now_ms()).is_err(), "no certificate");
945 assert!(svc.record().unwrap().verify(svc.peer(), now_ms()).unwrap().seq > cap.seq);
946 }
947}