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