pub mod codec;
pub mod infer;
mod memory;
pub mod task;
use async_trait::async_trait;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
pub use memory::{MemoryDialer, memory_pair};
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
#[serde(rename_all = "snake_case", tag = "kind")]
pub enum RemoteError {
#[error("node unreachable: {message}")]
Unreachable { message: String },
#[error("node busy")]
Busy,
#[error("node refused: {message}")]
Refused { message: String },
#[error("model unavailable on the node: {message}")]
Unavailable { message: String },
#[error("remote run failed: {message}")]
Failed { message: String },
#[error("protocol error: {message}")]
Protocol { message: String },
#[error("connection closed")]
Closed,
#[error("timed out")]
Timeout,
}
impl RemoteError {
pub fn protocol(message: impl Into<String>) -> Self {
RemoteError::Protocol { message: message.into() }
}
}
#[async_trait]
pub trait FrameTx: Send {
async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError>;
}
#[async_trait]
pub trait FrameRx: Send {
async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError>;
}
pub struct Channel {
pub tx: Box<dyn FrameTx>,
pub rx: Box<dyn FrameRx>,
}
impl Channel {
pub fn new(tx: Box<dyn FrameTx>, rx: Box<dyn FrameRx>) -> Self {
Self { tx, rx }
}
pub async fn send<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
send_json(self.tx.as_mut(), msg).await
}
pub async fn recv<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
recv_json(self.rx.as_mut()).await
}
}
#[async_trait]
pub trait Dialer: Send + Sync {
async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError>;
}
pub(crate) async fn send_json<T: Serialize + Sync + ?Sized>(tx: &mut dyn FrameTx, msg: &T) -> Result<(), RemoteError> {
let bytes = serde_json::to_vec(msg).map_err(|e| RemoteError::protocol(e.to_string()))?;
tx.send(bytes).await
}
pub(crate) async fn recv_json<T: DeserializeOwned>(rx: &mut dyn FrameRx) -> Result<Option<T>, RemoteError> {
match rx.recv().await? {
None => Ok(None),
Some(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| RemoteError::protocol(e.to_string())),
}
}
pub(crate) fn request_id() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static SEQ: AtomicU64 = AtomicU64::new(0);
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
format!("{nanos:x}-{}", SEQ.fetch_add(1, Ordering::Relaxed))
}