1pub mod catalog;
32pub mod codec;
33pub mod infer;
34mod memory;
35pub mod pool;
36pub mod pool_model;
37pub mod task;
38
39use async_trait::async_trait;
40use serde::de::DeserializeOwned;
41use serde::{Deserialize, Serialize};
42
43pub use memory::{MemoryDialer, memory_pair};
44
45#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
47#[serde(rename_all = "snake_case", tag = "kind")]
48#[non_exhaustive]
49pub enum RemoteError {
50 #[error("node unreachable: {message}")]
51 Unreachable { message: String },
52 #[error("node busy")]
53 Busy,
54 #[error("node refused: {message}")]
55 Refused { message: String },
56 #[error("model unavailable on the node: {message}")]
57 Unavailable { message: String },
58 #[error("remote run failed: {message}")]
59 Failed { message: String },
60 #[error("protocol error: {message}")]
61 Protocol { message: String },
62 #[error("connection closed")]
63 Closed,
64 #[error("timed out")]
65 Timeout,
66 #[error("not supported by the node: {message}")]
68 Unsupported { message: String },
69 #[error("bad request: {message}")]
71 BadRequest { message: String },
72 #[error("cancelled")]
74 Cancelled,
75 #[error("stalled: no frame for {ms} ms")]
77 Stalled { ms: u64 },
78}
79
80impl RemoteError {
81 pub fn protocol(message: impl Into<String>) -> Self {
82 RemoteError::Protocol { message: message.into() }
83 }
84
85 pub fn refused(message: impl Into<String>) -> Self {
86 RemoteError::Refused { message: message.into() }
87 }
88
89 pub fn unavailable(message: impl Into<String>) -> Self {
90 RemoteError::Unavailable { message: message.into() }
91 }
92
93 pub fn is_request_error(&self) -> bool {
96 matches!(self, RemoteError::BadRequest { .. } | RemoteError::Cancelled)
97 }
98
99 pub fn is_node_answer(&self) -> bool {
103 matches!(self, RemoteError::Unsupported { .. } | RemoteError::Refused { .. } | RemoteError::Unavailable { .. } | RemoteError::Busy)
104 || self.is_request_error()
105 }
106
107 pub(crate) fn for_v1(self) -> Self {
110 match self {
111 e @ (RemoteError::Unsupported { .. } | RemoteError::BadRequest { .. } | RemoteError::Cancelled | RemoteError::Stalled { .. }) => {
112 RemoteError::Failed { message: e.to_string() }
113 }
114 e => e,
115 }
116 }
117}
118
119#[derive(Debug, Clone, PartialEq, Eq, Default)]
125pub struct Caller {
126 pub peer: String,
127 pub cert_bytes: Option<Vec<u8>>,
128}
129
130impl Caller {
131 pub fn new(peer: impl Into<String>) -> Self {
132 Self { peer: peer.into(), cert_bytes: None }
133 }
134
135 pub fn with_cert(mut self, cert_bytes: Vec<u8>) -> Self {
136 self.cert_bytes = Some(cert_bytes);
137 self
138 }
139
140 pub(crate) fn presenting(mut self, cert: Option<Vec<u8>>) -> Self {
142 if self.cert_bytes.is_none() {
143 self.cert_bytes = cert;
144 }
145 self
146 }
147}
148
149#[derive(Debug, Clone, PartialEq, Eq)]
153#[non_exhaustive]
154pub struct Admitted {
155 pub peer: String,
156 pub roles: Option<Vec<String>>,
158}
159
160impl Admitted {
161 pub fn new(peer: impl Into<String>, roles: Option<Vec<String>>) -> Self {
162 Self { peer: peer.into(), roles }
163 }
164
165 pub fn has_role(&self, role: &str) -> bool {
166 self.roles.as_ref().is_some_and(|r| r.iter().any(|x| x == role))
167 }
168}
169
170pub trait Authorize: Send + Sync {
173 fn authorize(&self, caller: &Caller) -> Result<(), RemoteError>;
174
175 fn admit(&self, caller: &Caller) -> Result<Admitted, RemoteError> {
178 self.authorize(caller)?;
179 Ok(Admitted::new(caller.peer.clone(), None))
180 }
181}
182
183impl<F> Authorize for F
184where
185 F: Fn(&Caller) -> Result<(), RemoteError> + Send + Sync,
186{
187 fn authorize(&self, caller: &Caller) -> Result<(), RemoteError> {
188 self(caller)
189 }
190}
191
192#[async_trait]
194pub trait FrameTx: Send {
195 async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError>;
196}
197
198#[async_trait]
202pub trait FrameRx: Send {
203 async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError>;
204}
205
206pub struct Channel {
208 pub tx: Box<dyn FrameTx>,
209 pub rx: Box<dyn FrameRx>,
210}
211
212impl Channel {
213 pub fn new(tx: Box<dyn FrameTx>, rx: Box<dyn FrameRx>) -> Self {
214 Self { tx, rx }
215 }
216
217 pub async fn send<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
219 send_json(self.tx.as_mut(), msg).await
220 }
221
222 pub async fn recv<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
224 recv_json(self.rx.as_mut()).await
225 }
226
227 pub async fn send_cbor<T: Serialize + Sync>(&mut self, msg: &T) -> Result<(), RemoteError> {
229 let bytes = to_cbor(msg)?;
230 self.tx.send(bytes).await
231 }
232
233 pub async fn recv_cbor<T: DeserializeOwned>(&mut self) -> Result<Option<T>, RemoteError> {
235 match self.rx.recv().await? {
236 None => Ok(None),
237 Some(bytes) => from_cbor(&bytes).map(Some),
238 }
239 }
240}
241
242#[async_trait]
246pub trait Dialer: Send + Sync {
247 async fn open(&self, node: &str, protocol: &str) -> Result<Channel, RemoteError>;
248}
249
250pub(crate) async fn send_json<T: Serialize + Sync + ?Sized>(tx: &mut dyn FrameTx, msg: &T) -> Result<(), RemoteError> {
251 let bytes = serde_json::to_vec(msg).map_err(|e| RemoteError::protocol(e.to_string()))?;
252 tx.send(bytes).await
253}
254
255pub(crate) async fn recv_json<T: DeserializeOwned>(rx: &mut dyn FrameRx) -> Result<Option<T>, RemoteError> {
256 match rx.recv().await? {
257 None => Ok(None),
258 Some(bytes) => serde_json::from_slice(&bytes).map(Some).map_err(|e| RemoteError::protocol(e.to_string())),
259 }
260}
261
262pub fn to_cbor<T: Serialize>(msg: &T) -> Result<Vec<u8>, RemoteError> {
264 cbor4ii::serde::to_vec(Vec::new(), msg).map_err(|e| RemoteError::protocol(e.to_string()))
265}
266
267pub fn from_cbor<T: DeserializeOwned>(bytes: &[u8]) -> Result<T, RemoteError> {
269 cbor4ii::serde::from_slice(bytes).map_err(|e| RemoteError::protocol(e.to_string()))
270}
271
272pub(crate) fn request_id() -> String {
274 use std::sync::atomic::{AtomicU64, Ordering};
275 static SEQ: AtomicU64 = AtomicU64::new(0);
276 let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or_default();
277 format!("{nanos:x}-{}", SEQ.fetch_add(1, Ordering::Relaxed))
278}
279
280pub(crate) mod bytes {
282 use serde::de::{self, SeqAccess, Visitor};
283 use serde::{Deserializer, Serializer};
284
285 pub fn serialize<S: Serializer>(v: &[u8], s: S) -> Result<S::Ok, S::Error> {
286 s.serialize_bytes(v)
287 }
288
289 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<u8>, D::Error> {
290 d.deserialize_byte_buf(BytesVisitor)
291 }
292
293 pub(super) struct BytesVisitor;
294
295 impl<'de> Visitor<'de> for BytesVisitor {
296 type Value = Vec<u8>;
297
298 fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
299 f.write_str("a byte string")
300 }
301
302 fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<Vec<u8>, E> {
303 Ok(v.to_vec())
304 }
305
306 fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<Vec<u8>, E> {
307 Ok(v)
308 }
309
310 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Vec<u8>, A::Error> {
311 let mut out = Vec::new();
312 while let Some(b) = seq.next_element::<u8>()? {
313 out.push(b);
314 }
315 Ok(out)
316 }
317 }
318
319 pub mod opt {
321 use serde::{Deserialize, Deserializer, Serializer};
322
323 pub fn serialize<S: Serializer>(v: &Option<Vec<u8>>, s: S) -> Result<S::Ok, S::Error> {
324 match v {
325 Some(b) => s.serialize_some(&Wrap(b)),
326 None => s.serialize_none(),
327 }
328 }
329
330 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<Vec<u8>>, D::Error> {
331 Ok(Option::<Owned>::deserialize(d)?.map(|o| o.0))
332 }
333
334 struct Wrap<'a>(&'a [u8]);
335
336 impl serde::Serialize for Wrap<'_> {
337 fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
338 s.serialize_bytes(self.0)
339 }
340 }
341
342 struct Owned(Vec<u8>);
343
344 impl<'de> Deserialize<'de> for Owned {
345 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
346 d.deserialize_byte_buf(super::BytesVisitor).map(Owned)
347 }
348 }
349 }
350}