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