Skip to main content

weirdnet_net/
app.rs

1//! App calls: request/response exchanges with streamed bodies between nodes, for apps that
2//! speak HTTP-like methods and paths over Weirdnet (Morph's `weirdnet-<app>://` URLs).
3//!
4//! One libp2p stream per call on [`APP_PROTOCOL`]:
5//!
6//! - the caller writes a head, CBOR `{v: 1, app, method, path, headers}` prefixed with its
7//!   unsigned-varint length (at most the header cap), then the body as varint-length frames
8//!   ending with a zero-length frame;
9//! - the server answers with CBOR `{v: 1, status, headers}` the same way, then the response
10//!   body frames and a zero-length frame; on an error, CBOR `{v: 1, error, message}` takes
11//!   the place of the response head (`error` is an [`AppError::code`]);
12//! - either side cancels by closing or resetting the stream. The zero-length frame ends a
13//!   body, so the caller never half-closes: when it drops a call the stream is reset and the
14//!   server's handler and body stop. The server closes its side after its last frame.
15//!
16//! Frames this crate writes are at most [`WRITE_FRAME`] bytes; it reads frames up to
17//! [`MAX_FRAME`]. The caps come from [`NodeConfig`](crate::NodeConfig): `app_header_max`
18//! (16 KiB by default) for each head, `app_body_max` (none by default) for each body, and
19//! `app_idle_timeout` (60 s by default), how long a call may go without a byte. There are no
20//! rate or bandwidth limits; relays forward the bytes under their own circuit limits.
21//!
22//! A node serving app `X` also accepts `/weirdnet/app/1/X`, so identify tells peers which
23//! apps it serves (`app:X` in a [`Sighting`](crate::Sighting)'s caps, and
24//! [`Node::peer_apps`](crate::Node::peer_apps)); nothing is ever sent on that protocol.
25//!
26//! ```no_run
27//! use std::{sync::Arc, time::Duration};
28//! use weirdnet_net::{AppRequest, AppResponse, Node, PeerId};
29//! # fn demo(server: &Node<(), ()>, client: &Node<(), ()>, user_id: &str) -> Result<(), weirdnet_net::AppError> {
30//! server.serve_app("notes", Arc::new(|peer: PeerId, req: AppRequest| async move {
31//!     let body = req.body.collect().await?; // or read it chunk by chunk
32//!     Ok(AppResponse::new(200).header("content-type", "text/plain").body(format!("{peer} sent {} bytes", body.len())))
33//! }))?;
34//!
35//! let peers = client.resolve_app("notes", user_id)?; // a peer id, user id or bound name
36//! let req = AppRequest::new("notes", "POST", "/inbox?draft=1").header("content-type", "text/plain").body("hello");
37//! let resp = futures::executor::block_on(client.app_call(peers[0].0, req, Duration::from_secs(30)))?;
38//! let text = futures::executor::block_on(resp.body.collect())?;
39//! # Ok(()) }
40//! ```
41use crate::stream::transport::{Control, OpenError};
42use futures::channel::mpsc;
43use futures::io::{ReadHalf, WriteHalf};
44use futures::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt, SinkExt, StreamExt};
45use libp2p::{PeerId, StreamProtocol};
46use serde::{Deserialize, Serialize};
47use std::collections::HashMap;
48use std::future::Future;
49use std::pin::Pin;
50use std::sync::{Arc, Mutex, RwLock};
51use std::task::{Context, Poll};
52use std::time::Duration;
53
54/// The protocol app calls run on.
55pub const APP_PROTOCOL: &str = "/weirdnet/app/1";
56/// What a node serving app `X` announces through identify: this prefix and `X`.
57pub const ANNOUNCE_PREFIX: &str = "/weirdnet/app/1/";
58/// The default cap on a request or response head (its CBOR bytes).
59pub const DEFAULT_HEADER_MAX: usize = 16 * 1024;
60/// The default time a call may go without a byte before it is given up.
61pub const DEFAULT_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
62/// The longest body frame a reader accepts (writers send at most [`WRITE_FRAME`]).
63pub const MAX_FRAME: usize = 1 << 20;
64/// The longest body frame this crate writes.
65pub const WRITE_FRAME: usize = 64 * 1024;
66const VERSION: u8 = 1;
67/// Calls a server holds before refusing new streams.
68const BACKLOG: usize = 64;
69/// Body chunks buffered between the network and the app, each way.
70const CHANNEL: usize = 8;
71
72/// Why an app call or lookup failed.
73#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
74pub enum AppError {
75    /// No record, binding or peer for that locator.
76    #[error("not found")]
77    NotFound,
78    /// The peer does not serve that app.
79    #[error("the peer does not serve this app")]
80    NoHandler,
81    /// No path to the peer, or the connection went away.
82    #[error("unreachable: {0}")]
83    Unreachable(String),
84    /// The call took longer than its timeout, or went idle.
85    #[error("timed out")]
86    TimedOut,
87    /// The app said no.
88    #[error("refused: {0}")]
89    Refused(String),
90    /// A head over the header cap, or a body over the body cap.
91    #[error("too large")]
92    TooLarge,
93    /// The peer broke the wire format.
94    #[error("protocol error: {0}")]
95    Protocol(String),
96}
97
98impl AppError {
99    /// Its code on the wire.
100    pub fn code(&self) -> &'static str {
101        match self {
102            AppError::NotFound => "not_found",
103            AppError::NoHandler => "no_handler",
104            AppError::Unreachable(_) => "unreachable",
105            AppError::TimedOut => "timed_out",
106            AppError::Refused(_) => "refused",
107            AppError::TooLarge => "too_large",
108            AppError::Protocol(_) => "protocol",
109        }
110    }
111
112    fn message(&self) -> String {
113        match self {
114            AppError::Unreachable(m) | AppError::Refused(m) | AppError::Protocol(m) => m.clone(),
115            _ => String::new(),
116        }
117    }
118
119    fn from_wire(code: &str, message: String) -> Self {
120        match code {
121            "not_found" => AppError::NotFound,
122            "no_handler" => AppError::NoHandler,
123            "unreachable" => AppError::Unreachable(message),
124            "timed_out" => AppError::TimedOut,
125            "refused" => AppError::Refused(message),
126            "too_large" => AppError::TooLarge,
127            _ => AppError::Protocol(if message.is_empty() { format!("error {code}") } else { message }),
128        }
129    }
130}
131
132fn io_err(e: std::io::Error) -> AppError {
133    match e.kind() {
134        std::io::ErrorKind::UnexpectedEof => AppError::Protocol("the stream ended early".into()),
135        _ => AppError::Unreachable(e.to_string()),
136    }
137}
138
139/// A streamed body: chunks of bytes, or an error that ends it.
140pub struct Body(Pin<Box<dyn futures::Stream<Item = Result<Vec<u8>, AppError>> + Send>>);
141
142impl Body {
143    /// No bytes.
144    pub fn empty() -> Body {
145        Body(Box::pin(futures::stream::empty()))
146    }
147
148    /// These bytes, in one chunk.
149    pub fn bytes(b: impl Into<Vec<u8>>) -> Body {
150        let b = b.into();
151        if b.is_empty() { Body::empty() } else { Body(Box::pin(futures::stream::once(async move { Ok(b) }))) }
152    }
153
154    /// Chunks from a stream (an error ends the body: the peer sees the stream reset).
155    pub fn stream(s: impl futures::Stream<Item = Result<Vec<u8>, AppError>> + Send + 'static) -> Body {
156        Body(Box::pin(s))
157    }
158
159    /// Everything, in one buffer.
160    pub async fn collect(mut self) -> Result<Vec<u8>, AppError> {
161        let mut out = vec![];
162        while let Some(c) = self.0.next().await {
163            out.extend_from_slice(&c?);
164        }
165        Ok(out)
166    }
167}
168
169impl futures::Stream for Body {
170    type Item = Result<Vec<u8>, AppError>;
171    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
172        self.0.as_mut().poll_next(cx)
173    }
174}
175
176impl std::fmt::Debug for Body {
177    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178        f.write_str("Body")
179    }
180}
181
182impl Default for Body {
183    fn default() -> Self {
184        Body::empty()
185    }
186}
187
188impl From<Vec<u8>> for Body {
189    fn from(b: Vec<u8>) -> Self {
190        Body::bytes(b)
191    }
192}
193
194impl From<&str> for Body {
195    fn from(b: &str) -> Self {
196        Body::bytes(b.as_bytes().to_vec())
197    }
198}
199
200impl From<String> for Body {
201    fn from(b: String) -> Self {
202        Body::bytes(b.into_bytes())
203    }
204}
205
206/// A call to an app on a peer.
207#[derive(Debug, Default)]
208pub struct AppRequest {
209    /// The app (`morph`, `muninn`, …), as in `weirdnet-<app>://`.
210    pub app: String,
211    /// `GET`, `POST`, … (the app decides what they mean).
212    pub method: String,
213    /// The path and query, such as `/notes/1?full=1`.
214    pub path_with_query: String,
215    pub headers: Vec<(String, String)>,
216    pub body: Body,
217}
218
219impl AppRequest {
220    pub fn new(app: &str, method: &str, path_with_query: &str) -> AppRequest {
221        AppRequest { app: app.into(), method: method.into(), path_with_query: path_with_query.into(), ..Default::default() }
222    }
223
224    pub fn header(mut self, name: &str, value: &str) -> AppRequest {
225        self.headers.push((name.into(), value.into()));
226        self
227    }
228
229    pub fn body(mut self, body: impl Into<Body>) -> AppRequest {
230        self.body = body.into();
231        self
232    }
233}
234
235/// An app's answer.
236#[derive(Debug)]
237pub struct AppResponse {
238    pub status: u16,
239    pub headers: Vec<(String, String)>,
240    pub body: Body,
241}
242
243impl AppResponse {
244    pub fn new(status: u16) -> AppResponse {
245        AppResponse { status, headers: vec![], body: Body::empty() }
246    }
247
248    pub fn header(mut self, name: &str, value: &str) -> AppResponse {
249        self.headers.push((name.into(), value.into()));
250        self
251    }
252
253    pub fn body(mut self, body: impl Into<Body>) -> AppResponse {
254        self.body = body.into();
255        self
256    }
257
258    /// The first header called `name` (case-insensitive).
259    pub fn header_value(&self, name: &str) -> Option<&str> {
260        self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
261    }
262}
263
264/// What [`AppHandler::handle`] returns.
265pub type HandlerFuture = Pin<Box<dyn Future<Output = Result<AppResponse, AppError>> + Send>>;
266
267/// Serves one app's calls. A closure `Fn(PeerId, AppRequest) -> impl Future<Output =
268/// Result<AppResponse, AppError>>` is one. An `Err` goes back as an error head
269/// (`Refused(why)` for "no").
270pub trait AppHandler: Send + Sync + 'static {
271    fn handle(&self, peer: PeerId, req: AppRequest) -> HandlerFuture;
272}
273
274impl<F, Fut> AppHandler for F
275where
276    F: Fn(PeerId, AppRequest) -> Fut + Send + Sync + 'static,
277    Fut: Future<Output = Result<AppResponse, AppError>> + Send + 'static,
278{
279    fn handle(&self, peer: PeerId, req: AppRequest) -> HandlerFuture {
280        Box::pin(self(peer, req))
281    }
282}
283
284/// The caps of app calls (from [`NodeConfig`](crate::NodeConfig)).
285#[derive(Debug, Clone, Copy)]
286pub(crate) struct AppLimits {
287    pub(crate) header_max: usize,
288    /// 0: no cap.
289    pub(crate) body_max: u64,
290    pub(crate) idle: Duration,
291}
292
293// ---------- wire ----------
294
295#[derive(Debug, Serialize, Deserialize)]
296struct ReqHead {
297    v: u8,
298    app: String,
299    method: String,
300    path: String,
301    #[serde(default)]
302    headers: Vec<(String, String)>,
303}
304
305#[derive(Debug, Default, Serialize, Deserialize)]
306struct RespHead {
307    v: u8,
308    #[serde(default, skip_serializing_if = "Option::is_none")]
309    status: Option<u16>,
310    #[serde(default, skip_serializing_if = "Vec::is_empty")]
311    headers: Vec<(String, String)>,
312    #[serde(default, skip_serializing_if = "Option::is_none")]
313    error: Option<String>,
314    #[serde(default, skip_serializing_if = "Option::is_none")]
315    message: Option<String>,
316}
317
318fn cbor<T: Serialize>(v: &T) -> Result<Vec<u8>, AppError> {
319    cbor4ii::serde::to_vec(Vec::new(), v).map_err(|e| AppError::Protocol(e.to_string()))
320}
321
322fn uncbor<'a, T: Deserialize<'a>>(b: &'a [u8]) -> Result<T, AppError> {
323    cbor4ii::serde::from_slice(b).map_err(|e| AppError::Protocol(format!("bad head: {e}")))
324}
325
326/// Appends `n` as an unsigned varint (LEB128, as multiformats).
327pub(crate) fn put_varint(mut n: u64, out: &mut Vec<u8>) {
328    loop {
329        let b = (n & 0x7f) as u8;
330        n >>= 7;
331        if n == 0 {
332            out.push(b);
333            return;
334        }
335        out.push(b | 0x80);
336    }
337}
338
339/// Reads an unsigned varint; `None` at a clean end before its first byte.
340pub(crate) async fn read_varint<R: AsyncRead + Unpin>(r: &mut R) -> std::io::Result<Option<u64>> {
341    let mut n: u64 = 0;
342    for i in 0..10 {
343        let mut b = [0u8; 1];
344        if r.read(&mut b).await? == 0 {
345            return if i == 0 { Ok(None) } else { Err(std::io::ErrorKind::UnexpectedEof.into()) };
346        }
347        n |= u64::from(b[0] & 0x7f) << (7 * i);
348        if b[0] & 0x80 == 0 {
349            return Ok(Some(n));
350        }
351    }
352    Err(std::io::Error::new(std::io::ErrorKind::InvalidData, "varint too long"))
353}
354
355async fn idle<T>(d: Duration, f: impl Future<Output = Result<T, AppError>>) -> Result<T, AppError> {
356    tokio::time::timeout(d, f).await.map_err(|_| AppError::TimedOut)?
357}
358
359/// A head: its length (at most `max`), then its bytes.
360async fn read_head<R: AsyncRead + Unpin>(r: &mut R, max: usize) -> Result<Vec<u8>, AppError> {
361    let n = read_varint(r).await.map_err(io_err)?.ok_or_else(|| AppError::Protocol("the stream closed before the head".into()))?;
362    if n > max as u64 {
363        return Err(AppError::TooLarge);
364    }
365    let mut b = vec![0u8; n as usize];
366    r.read_exact(&mut b).await.map_err(io_err)?;
367    Ok(b)
368}
369
370async fn write_frame<W: AsyncWrite + Unpin>(w: &mut W, data: &[u8]) -> Result<(), AppError> {
371    let mut b = Vec::with_capacity(data.len() + 4);
372    put_varint(data.len() as u64, &mut b);
373    b.extend_from_slice(data);
374    w.write_all(&b).await.map_err(io_err)
375}
376
377async fn write_error<W: AsyncWrite + Unpin>(w: &mut W, e: &AppError) {
378    let head = RespHead { v: VERSION, error: Some(e.code().into()), message: Some(e.message()).filter(|m| !m.is_empty()), ..Default::default() };
379    if let Ok(b) = cbor(&head) {
380        let _ = write_frame(w, &b).await;
381        let _ = w.close().await;
382    }
383}
384
385/// Sends a body as frames, then the zero-length frame.
386async fn send_body<W: AsyncWrite + Unpin>(w: &mut W, mut body: Body, idle_for: Duration) -> Result<(), AppError> {
387    while let Some(chunk) = body.next().await {
388        let chunk = chunk?;
389        for piece in chunk.chunks(WRITE_FRAME) {
390            idle(idle_for, write_frame(w, piece)).await?;
391        }
392    }
393    idle(idle_for, write_frame(w, &[])).await?;
394    idle(idle_for, async { w.flush().await.map_err(io_err) }).await
395}
396
397/// Aborts a task when dropped.
398pub(crate) struct AbortOnDrop(pub(crate) tokio::task::AbortHandle);
399
400impl Drop for AbortOnDrop {
401    fn drop(&mut self) {
402        self.0.abort();
403    }
404}
405
406/// A body read from `r` frame by frame (on the node's runtime) into a channel. `guard` lives
407/// as long as the reading does: dropping the body stops both.
408fn read_body<R: AsyncRead + Unpin + Send + 'static>(rt: &tokio::runtime::Handle, mut r: R, limits: AppLimits, guard: Option<AbortOnDrop>) -> Body {
409    let (mut tx, rx) = mpsc::channel::<Result<Vec<u8>, AppError>>(CHANNEL);
410    rt.spawn(async move {
411        let _guard = guard;
412        let mut total: u64 = 0;
413        loop {
414            let frame = idle(limits.idle, async {
415                let n =
416                    read_varint(&mut r).await.map_err(io_err)?.ok_or_else(|| AppError::Protocol("the body ended without its last frame".into()))?;
417                if n == 0 {
418                    return Ok(None);
419                }
420                if n > MAX_FRAME as u64 {
421                    return Err(AppError::Protocol(format!("a {n}-byte frame")));
422                }
423                total += n;
424                if limits.body_max > 0 && total > limits.body_max {
425                    return Err(AppError::TooLarge);
426                }
427                let mut b = vec![0u8; n as usize];
428                r.read_exact(&mut b).await.map_err(io_err)?;
429                Ok(Some(b))
430            })
431            .await;
432            match frame {
433                Ok(Some(b)) => {
434                    if tx.send(Ok(b)).await.is_err() {
435                        return; // the app dropped the body: cancel
436                    }
437                }
438                Ok(None) => return,
439                Err(e) => {
440                    let _ = tx.send(Err(e)).await;
441                    return;
442                }
443            }
444        }
445    });
446    Body(Box::pin(rx))
447}
448
449// ---------- calling ----------
450
451async fn within<T>(deadline: tokio::time::Instant, f: impl Future<Output = Result<T, AppError>>) -> Result<T, AppError> {
452    tokio::time::timeout_at(deadline, f).await.map_err(|_| AppError::TimedOut)?
453}
454
455fn split(s: libp2p::Stream) -> (ReadHalf<libp2p::Stream>, WriteHalf<libp2p::Stream>) {
456    s.split()
457}
458
459/// One call on an open connection to `peer`, on the node's runtime; `deadline` covers opening
460/// the stream, sending the head and getting the response head.
461pub(crate) async fn call(
462    rt: tokio::runtime::Handle,
463    control: Control,
464    peer: PeerId,
465    req: AppRequest,
466    limits: AppLimits,
467    deadline: tokio::time::Instant,
468) -> Result<AppResponse, AppError> {
469    let head = cbor(&ReqHead {
470        v: VERSION,
471        app: req.app.clone(),
472        method: req.method.clone(),
473        path: req.path_with_query.clone(),
474        headers: req.headers.clone(),
475    })?;
476    if head.len() > limits.header_max {
477        return Err(AppError::TooLarge);
478    }
479    let (stream, _, _) = within(deadline, async {
480        control.open(peer, StreamProtocol::new(APP_PROTOCOL)).await.map_err(|e| match e {
481            OpenError::Unsupported(_) => AppError::NoHandler,
482            OpenError::Io(e) => AppError::Unreachable(e.to_string()),
483        })
484    })
485    .await?;
486    let (mut r, mut w) = split(stream);
487    within(deadline, write_frame(&mut w, &head)).await?;
488    // the request body goes out while the response comes in
489    let body = req.body;
490    let idle_for = limits.idle;
491    let sender = rt.spawn(async move {
492        // no FIN after the body (its last frame ends it): dropping a stream that is still
493        // open resets it, and a reset is how the server learns the caller went away
494        if send_body(&mut w, body, idle_for).await.is_ok() {
495            // keep the write half until the read side is done with the stream
496            futures::future::pending::<()>().await;
497        }
498    });
499    let guard = AbortOnDrop(sender.abort_handle());
500    let bytes = within(deadline, read_head(&mut r, limits.header_max)).await?;
501    let h: RespHead = uncbor(&bytes)?;
502    if h.v != VERSION {
503        return Err(AppError::Protocol(format!("version {}", h.v)));
504    }
505    if let Some(code) = h.error {
506        return Err(AppError::from_wire(&code, h.message.unwrap_or_default()));
507    }
508    let status = h.status.ok_or_else(|| AppError::Protocol("a head with no status".into()))?;
509    Ok(AppResponse { status, headers: h.headers, body: read_body(&rt, r, limits, Some(guard)) })
510}
511
512// ---------- serving ----------
513
514/// The apps a node serves.
515pub(crate) struct Server {
516    handlers: RwLock<HashMap<String, Arc<dyn AppHandler>>>,
517    /// The announcement acceptors, by app (dropping one stops the announcement).
518    markers: Mutex<HashMap<String, AbortOnDrop>>,
519    started: Mutex<bool>,
520    pub(crate) serving: Arc<std::sync::atomic::AtomicBool>,
521}
522
523impl Server {
524    pub(crate) fn new(serving: Arc<std::sync::atomic::AtomicBool>) -> Server {
525        Server { handlers: RwLock::new(HashMap::new()), markers: Mutex::new(HashMap::new()), started: Mutex::new(false), serving }
526    }
527
528    pub(crate) fn check_app(app: &str) -> Result<(), AppError> {
529        let ok =
530            (1..=64).contains(&app.len()) && app.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') && !app.starts_with('-');
531        if ok { Ok(()) } else { Err(AppError::Protocol(format!("bad app name {app:?} (a-z, 0-9 and -)"))) }
532    }
533
534    pub(crate) fn serve(
535        self: &Arc<Self>,
536        rt: &tokio::runtime::Handle,
537        control: &Control,
538        app: &str,
539        h: Arc<dyn AppHandler>,
540        limits: AppLimits,
541    ) -> Result<(), AppError> {
542        Self::check_app(app)?;
543        {
544            let mut started = self.started.lock().unwrap();
545            if !*started {
546                let mut inc = control
547                    .accept(StreamProtocol::new(APP_PROTOCOL), BACKLOG)
548                    .ok_or_else(|| AppError::Protocol(format!("{APP_PROTOCOL} is accepted elsewhere")))?;
549                let me = self.clone();
550                let rt2 = rt.clone();
551                rt.spawn(async move {
552                    while let Some((peer, stream, _, _)) = inc.next().await {
553                        let me = me.clone();
554                        let rt3 = rt2.clone();
555                        rt2.spawn(async move { me.serve_one(rt3, peer, stream, limits).await });
556                    }
557                });
558                *started = true;
559            }
560        }
561        self.handlers.write().unwrap().insert(app.to_string(), h);
562        let mut markers = self.markers.lock().unwrap();
563        if !markers.contains_key(app) {
564            let p = StreamProtocol::try_from_owned(format!("{ANNOUNCE_PREFIX}{app}")).map_err(|e| AppError::Protocol(e.to_string()))?;
565            let mut rx = control.accept(p, 1).ok_or_else(|| AppError::Protocol(format!("{app} is announced elsewhere")))?;
566            let t = rt.spawn(async move { while rx.next().await.is_some() {} });
567            markers.insert(app.to_string(), AbortOnDrop(t.abort_handle()));
568        }
569        self.serving.store(true, std::sync::atomic::Ordering::SeqCst);
570        Ok(())
571    }
572
573    /// Stop serving `app`; true if it was served.
574    pub(crate) fn unserve(&self, app: &str) -> bool {
575        let had = self.handlers.write().unwrap().remove(app).is_some();
576        self.markers.lock().unwrap().remove(app);
577        if self.handlers.read().unwrap().is_empty() {
578            self.serving.store(false, std::sync::atomic::Ordering::SeqCst);
579        }
580        had
581    }
582
583    pub(crate) fn serves(&self, app: &str) -> bool {
584        self.handlers.read().unwrap().contains_key(app)
585    }
586
587    pub(crate) fn apps(&self) -> Vec<String> {
588        let mut v: Vec<String> = self.handlers.read().unwrap().keys().cloned().collect();
589        v.sort();
590        v
591    }
592
593    async fn serve_one(self: Arc<Self>, rt: tokio::runtime::Handle, peer: PeerId, stream: libp2p::Stream, limits: AppLimits) {
594        let (mut r, mut w) = split(stream);
595        let head = match idle(limits.idle, read_head(&mut r, limits.header_max)).await.and_then(|b| uncbor::<ReqHead>(&b)) {
596            Ok(h) if h.v == VERSION => h,
597            Ok(h) => return write_error(&mut w, &AppError::Protocol(format!("version {}", h.v))).await,
598            Err(e) => return write_error(&mut w, &e).await,
599        };
600        let Some(h) = self.handlers.read().unwrap().get(&head.app).cloned() else {
601            return write_error(&mut w, &AppError::NoHandler).await;
602        };
603        let req = AppRequest {
604            app: head.app,
605            method: head.method,
606            path_with_query: head.path,
607            headers: head.headers,
608            body: read_body(&rt, r, limits, None),
609        };
610        match h.handle(peer, req).await {
611            Err(e) => write_error(&mut w, &e).await,
612            Ok(resp) => {
613                let head = RespHead { v: VERSION, status: Some(resp.status), headers: resp.headers, ..Default::default() };
614                let Ok(b) = cbor(&head) else { return };
615                if b.len() > limits.header_max {
616                    return write_error(&mut w, &AppError::TooLarge).await;
617                }
618                if idle(limits.idle, write_frame(&mut w, &b)).await.is_err() {
619                    return;
620                }
621                if send_body(&mut w, resp.body, limits.idle).await.is_ok() {
622                    let _ = w.close().await;
623                }
624                // on an error the halves drop here and the stream resets
625            }
626        }
627    }
628}
629
630/// An app announced in identify protocols (`/weirdnet/app/1/X` → `X`).
631pub(crate) fn announced(protocol: &str) -> Option<&str> {
632    protocol.strip_prefix(ANNOUNCE_PREFIX).filter(|a| Server::check_app(a).is_ok())
633}
634
635#[cfg(test)]
636mod tests {
637    use super::*;
638
639    #[test]
640    fn varints_round_trip() {
641        for n in [0u64, 1, 127, 128, 300, 16_384, u32::MAX as u64, u64::MAX] {
642            let mut b = vec![];
643            put_varint(n, &mut b);
644            let got = futures::executor::block_on(read_varint(&mut &b[..])).unwrap();
645            assert_eq!(got, Some(n));
646        }
647        let mut b = vec![];
648        put_varint(300, &mut b);
649        assert_eq!(b, [0xac, 0x02]);
650        assert_eq!(futures::executor::block_on(read_varint(&mut &[][..])).unwrap(), None);
651        assert!(futures::executor::block_on(read_varint(&mut &[0x80][..])).is_err(), "cut short");
652        assert!(futures::executor::block_on(read_varint(&mut &[0xff; 11][..])).is_err(), "too long");
653    }
654
655    #[test]
656    fn heads_are_cbor_maps_with_the_spec_keys() {
657        let b =
658            cbor(&ReqHead { v: 1, app: "morph".into(), method: "GET".into(), path: "/a?b=1".into(), headers: vec![("accept".into(), "*/*".into())] })
659                .unwrap();
660        // a map of five entries whose first key is "v"
661        assert_eq!(b[0], 0xa5);
662        assert_eq!(&b[1..3], &[0x61, b'v']);
663        let h: ReqHead = uncbor(&b).unwrap();
664        assert_eq!((h.app.as_str(), h.path.as_str()), ("morph", "/a?b=1"));
665        let e = RespHead { v: 1, error: Some("no_handler".into()), ..Default::default() };
666        let back: RespHead = uncbor(&cbor(&e).unwrap()).unwrap();
667        assert_eq!(back.error.as_deref(), Some("no_handler"));
668        assert!(back.status.is_none());
669        assert!(uncbor::<RespHead>(b"\xff").is_err());
670    }
671
672    #[test]
673    fn error_codes_round_trip() {
674        for e in [
675            AppError::NotFound,
676            AppError::NoHandler,
677            AppError::Unreachable("x".into()),
678            AppError::TimedOut,
679            AppError::Refused("no".into()),
680            AppError::TooLarge,
681            AppError::Protocol("bad".into()),
682        ] {
683            assert_eq!(AppError::from_wire(e.code(), e.message()), e);
684        }
685        assert!(matches!(AppError::from_wire("new_code", String::new()), AppError::Protocol(_)));
686    }
687
688    #[test]
689    fn app_names_and_announcements() {
690        assert!(Server::check_app("morph").is_ok() && Server::check_app("my-app2").is_ok());
691        for bad in ["", "Morph", "a/b", "-x", "a b"] {
692            assert!(Server::check_app(bad).is_err(), "{bad:?}");
693        }
694        assert_eq!(announced("/weirdnet/app/1/morph"), Some("morph"));
695        assert_eq!(announced("/weirdnet/app/1"), None);
696        assert_eq!(announced("/weirdnet/app/1/Bad"), None);
697    }
698
699    #[test]
700    fn bodies_collect_and_frames_are_capped() {
701        let b = Body::stream(futures::stream::iter(vec![Ok(b"ab".to_vec()), Ok(b"cd".to_vec())]));
702        assert_eq!(futures::executor::block_on(b.collect()).unwrap(), b"abcd");
703        let rt = tokio::runtime::Runtime::new().unwrap();
704        let limits = AppLimits { header_max: 16, body_max: 5, idle: Duration::from_secs(5) };
705        let frames = |parts: &[&[u8]]| {
706            let mut v = vec![];
707            for p in parts {
708                put_varint(p.len() as u64, &mut v);
709                v.extend_from_slice(p);
710            }
711            futures::io::Cursor::new(v)
712        };
713        let ok = read_body(rt.handle(), frames(&[b"abc", b"de", b""]), limits, None);
714        assert_eq!(rt.block_on(ok.collect()).unwrap(), b"abcde");
715        let big = read_body(rt.handle(), frames(&[b"abc", b"def", b""]), limits, None);
716        assert_eq!(rt.block_on(big.collect()), Err(AppError::TooLarge));
717        let cut = read_body(rt.handle(), frames(&[b"abc"]), limits, None);
718        assert!(matches!(rt.block_on(cut.collect()), Err(AppError::Protocol(_))));
719        let mut huge = vec![];
720        put_varint(MAX_FRAME as u64 + 1, &mut huge);
721        let huge = read_body(rt.handle(), futures::io::Cursor::new(huge), AppLimits { body_max: 0, ..limits }, None);
722        assert!(matches!(rt.block_on(huge.collect()), Err(AppError::Protocol(_))));
723        let mut head = vec![];
724        put_varint(17, &mut head);
725        assert_eq!(rt.block_on(read_head(&mut futures::io::Cursor::new(head), 16)), Err(AppError::TooLarge));
726    }
727}