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