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