weirdnet_agent/remote/
mod.rs1pub mod codec;
16pub mod infer;
17mod memory;
18pub mod task;
19
20use async_trait::async_trait;
21use serde::de::DeserializeOwned;
22use serde::{Deserialize, Serialize};
23
24pub use memory::{MemoryDialer, memory_pair};
25
26#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
28#[serde(rename_all = "snake_case", tag = "kind")]
29pub enum RemoteError {
30 #[error("node unreachable: {message}")]
31 Unreachable { message: String },
32 #[error("node busy")]
33 Busy,
34 #[error("node refused: {message}")]
35 Refused { message: String },
36 #[error("model unavailable on the node: {message}")]
37 Unavailable { message: String },
38 #[error("remote run failed: {message}")]
39 Failed { message: String },
40 #[error("protocol error: {message}")]
41 Protocol { message: String },
42 #[error("connection closed")]
43 Closed,
44 #[error("timed out")]
45 Timeout,
46}
47
48impl RemoteError {
49 pub fn protocol(message: impl Into<String>) -> Self {
50 RemoteError::Protocol { message: message.into() }
51 }
52}
53
54#[async_trait]
56pub trait FrameTx: Send {
57 async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError>;
58}
59
60#[async_trait]
64pub trait FrameRx: Send {
65 async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError>;
66}
67
68pub struct Channel {
70 pub tx: Box<dyn FrameTx>,
71 pub rx: Box<dyn FrameRx>,
72}
73
74impl Channel {
75 pub fn new(tx: Box<dyn FrameTx>, rx: Box<dyn FrameRx>) -> Self {
76 Self { tx, rx }
77 }
78
79 pub async fn send<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
80 send_json(self.tx.as_mut(), msg).await
81 }
82
83 pub async fn recv<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
84 recv_json(self.rx.as_mut()).await
85 }
86}
87
88#[async_trait]
91pub trait Dialer: Send + Sync {
92 async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError>;
93}
94
95pub(crate) async fn send_json<T: Serialize + Sync + ?Sized>(tx: &mut dyn FrameTx, msg: &T) -> Result<(), RemoteError> {
96 let bytes = serde_json::to_vec(msg).map_err(|e| RemoteError::protocol(e.to_string()))?;
97 tx.send(bytes).await
98}
99
100pub(crate) async fn recv_json<T: DeserializeOwned>(rx: &mut dyn FrameRx) -> Result<Option<T>, RemoteError> {
101 match rx.recv().await? {
102 None => Ok(None),
103 Some(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| RemoteError::protocol(e.to_string())),
104 }
105}
106
107pub(crate) fn request_id() -> String {
109 use std::sync::atomic::{AtomicU64, Ordering};
110 static SEQ: AtomicU64 = AtomicU64::new(0);
111 let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
112 format!("{nanos:x}-{}", SEQ.fetch_add(1, Ordering::Relaxed))
113}