Skip to main content

weirdnet_agent/
net.rs

1//! Weirdnet glue shared by the `pool` and `serve` features: [`Channel`]s over
2//! `weirdnet-net` streams, and certificate bytes.
3
4use futures::io::{AsyncReadExt, AsyncWriteExt};
5use tokio::sync::mpsc;
6use weirdnet_net::user::NodeCert;
7use weirdnet_net::{Limits, Stream};
8
9use crate::remote::codec::{FrameDecoder, encode_frame};
10use crate::remote::{Channel, FrameRx, FrameTx, RemoteError, from_cbor, to_cbor};
11
12/// The app name inference nodes announce (`Node::serve_app`), so the pool can find them among
13/// the user's linked devices. Model nodes do not announce it: apps never call them.
14pub const INFERENCE_APP: &str = "weirdnet-agent-infer";
15
16/// Stream limits for the agent protocols: `weirdnet-net` defaults (30 s resume window), no
17/// idle reset (a queued request can be quiet for a while; `Queued` keepalives come every 3 s).
18pub fn stream_limits() -> Limits {
19    Limits { idle: None, ..Limits::default() }
20}
21
22/// A certificate as presented with a request (`Caller::cert_bytes`, `PoolOptions::cert`).
23pub fn encode_cert(cert: &NodeCert) -> Vec<u8> {
24    to_cbor(cert).unwrap_or_default()
25}
26
27pub fn decode_cert(bytes: &[u8]) -> Result<NodeCert, RemoteError> {
28    from_cbor(bytes)
29}
30
31/// A guest credential (since 0.5.9): this device's certificate plus its user's public key
32/// (protobuf), so a node of a *different* user can check the certificate (a [`NodeCert`]
33/// names its user only by id). Present it with requests to a shared pool
34/// (`pool::connect_shared` does). Public: it holds no secret.
35///
36/// Wire: CBOR map `{"guest": 1, "key": <bytes>, "cert": <NodeCert>}`. Hosts before 0.5.9 can't
37/// read it as a certificate and refuse the caller (`wrong-user`), so it never widens access.
38pub fn encode_credential(user_key: &weirdnet_net::PublicKey, cert: &NodeCert) -> Vec<u8> {
39    to_cbor(&CredentialOut { guest: 1, key: &user_key.encode_protobuf(), cert }).unwrap_or_default()
40}
41
42/// What a caller presented: a certificate, and its user's public key when it sent a guest
43/// credential ([`encode_credential`]). Nothing here is checked yet.
44#[derive(Debug, Clone, PartialEq)]
45#[non_exhaustive]
46pub struct Presented {
47    pub cert: NodeCert,
48    /// The user's public key (protobuf), from a guest credential.
49    pub user_key: Option<Vec<u8>>,
50}
51
52/// Reads presented bytes: a guest credential or a bare certificate ([`encode_cert`]).
53pub fn decode_presented(bytes: &[u8]) -> Result<Presented, RemoteError> {
54    if let Ok(c) = from_cbor::<CredentialIn>(bytes) {
55        if c.guest != 1 {
56            return Err(RemoteError::protocol(format!("guest credential version {} is not supported", c.guest)));
57        }
58        return Ok(Presented { cert: c.cert, user_key: Some(c.key) });
59    }
60    Ok(Presented { cert: decode_cert(bytes)?, user_key: None })
61}
62
63#[derive(serde::Serialize)]
64struct CredentialOut<'a> {
65    guest: u32,
66    #[serde(with = "crate::remote::bytes")]
67    key: &'a [u8],
68    cert: &'a NodeCert,
69}
70
71#[derive(serde::Deserialize)]
72struct CredentialIn {
73    guest: u32,
74    #[serde(with = "crate::remote::bytes")]
75    key: Vec<u8>,
76    cert: NodeCert,
77}
78
79struct Tx(mpsc::Sender<Vec<u8>>);
80struct Rx(mpsc::Receiver<Result<Vec<u8>, RemoteError>>);
81
82#[async_trait::async_trait]
83impl FrameTx for Tx {
84    async fn send(&mut self, message: Vec<u8>) -> Result<(), RemoteError> {
85        self.0.send(message).await.map_err(|_| RemoteError::Closed)
86    }
87}
88
89#[async_trait::async_trait]
90impl FrameRx for Rx {
91    async fn recv(&mut self) -> Result<Option<Vec<u8>>, RemoteError> {
92        match self.0.recv().await {
93            Some(Ok(m)) => Ok(Some(m)),
94            Some(Err(e)) => Err(e),
95            None => Ok(None),
96        }
97    }
98}
99
100/// A [`Channel`] over a stream: length-prefixed messages ([`crate::remote::codec`]). A task
101/// drives the stream; dropping the channel closes our side, and once both sides are done the
102/// stream is dropped. Call from a Tokio runtime.
103pub fn channel(stream: Stream) -> Channel {
104    let (out_tx, mut out_rx) = mpsc::channel::<Vec<u8>>(16);
105    let (in_tx, in_rx) = mpsc::channel::<Result<Vec<u8>, RemoteError>>(64);
106    tokio::spawn(async move {
107        let (mut r, mut w) = stream.split();
108        let mut decoder = FrameDecoder::new();
109        let mut buf = vec![0u8; 64 * 1024];
110        let mut writing = true;
111        let mut reader = Some(in_tx);
112        loop {
113            if !writing && reader.as_ref().is_none_or(|t| t.is_closed()) {
114                break;
115            }
116            tokio::select! {
117                m = out_rx.recv(), if writing => match m {
118                    Some(message) => {
119                        let ok = match encode_frame(&message) {
120                            Ok(bytes) => w.write_all(&bytes).await.is_ok() && w.flush().await.is_ok(),
121                            Err(_) => false,
122                        };
123                        if !ok {
124                            writing = false;
125                            if let Some(t) = reader.take() {
126                                let _ = t.send(Err(RemoteError::Closed)).await;
127                            }
128                        }
129                    }
130                    None => {
131                        writing = false;
132                        let _ = w.close().await;
133                    }
134                },
135                n = r.read(&mut buf), if reader.is_some() => match n {
136                    Ok(0) => reader = None,
137                    Ok(n) => {
138                        decoder.push(&buf[..n]);
139                        loop {
140                            match decoder.next_frame() {
141                                Ok(Some(m)) => {
142                                    if let Some(t) = &reader && t.send(Ok(m)).await.is_err() {
143                                        reader = None;
144                                        break;
145                                    }
146                                }
147                                Ok(None) => break,
148                                Err(e) => {
149                                    if let Some(t) = reader.take() {
150                                        let _ = t.send(Err(e)).await;
151                                    }
152                                    break;
153                                }
154                            }
155                        }
156                    }
157                    Err(e) => {
158                        if let Some(t) = reader.take() {
159                            let _ = t.send(Err(RemoteError::Unreachable { message: e.to_string() })).await;
160                        }
161                    }
162                },
163                _ = async { match &reader { Some(t) => t.closed().await, None => std::future::pending().await } }, if !writing => {
164                    reader = None;
165                }
166            }
167        }
168    });
169    Channel::new(Box::new(Tx(out_tx)), Box::new(Rx(in_rx)))
170}
171
172/// Maps a stream open error: a peer that does not accept the protocol is
173/// [`RemoteError::Unsupported`], anything else unreachable.
174#[cfg(feature = "pool")]
175pub(crate) fn open_error(e: weirdnet_net::NetError) -> RemoteError {
176    let message = e.to_string();
177    if message.contains("does not accept") { RemoteError::Unsupported { message } } else { RemoteError::Unreachable { message } }
178}