plexus-client 0.10.0

wasm-safe client runtime for Plexus RPC: the wire envelope, the Transport trait, and typed event decoding
Documentation
//! The `ws-native` backend: a `tokio-tungstenite` socket, a writer task and
//! a reader task.
//!
//! Why not jsonrpsee's ws-client, which already speaks subscriptions? Two
//! reasons, both about this ticket's contract. Its subscription plumbing is
//! opaque, so "a notification arriving under `menger.call` routes exactly
//! like one under `result`" could not be *pinned by a test* — and it does
//! not build for `wasm32-unknown-unknown`, so the browser half would have
//! been a second, unshared protocol implementation instead of a second
//! socket under [the same routing code](super::registry).

use super::registry::Registry;
use crate::error::TransportError;
use futures_channel::mpsc;
use futures_util::{SinkExt, StreamExt};
use std::sync::Arc;
use tokio_tungstenite::tungstenite::Message;

/// What the writer task accepts.
#[derive(Debug)]
enum Out {
    Frame(String),
    /// BIDIR-17: a binary input frame.
    Binary(Vec<u8>),
    /// The last `WsTransport` handle went away: shut the socket down rather
    /// than leave a connection open until the process exits.
    Close,
}

/// A handle on the writer task's queue.
///
/// Writes are queued rather than awaited so that [`Drop`] can send the
/// unsubscribe frame — a destructor cannot await.
#[derive(Debug, Clone)]
pub(crate) struct Conn {
    outbound: mpsc::UnboundedSender<Out>,
}

impl Conn {
    pub(crate) fn send(&self, text: String) -> Result<(), TransportError> {
        self.outbound
            .unbounded_send(Out::Frame(text))
            .map_err(|_| TransportError::closed("websocket connection is closed"))
    }

    pub(crate) fn send_binary(&self, frame: Vec<u8>) -> Result<(), TransportError> {
        self.outbound
            .unbounded_send(Out::Binary(frame))
            .map_err(|_| TransportError::closed("websocket connection is closed"))
    }

    pub(crate) fn close(&self) {
        let _ = self.outbound.unbounded_send(Out::Close);
    }
}

pub(crate) async fn connect(url: &str, registry: Arc<Registry>) -> Result<Conn, TransportError> {
    connect_with_headers(url, &[], registry).await
}

/// [`connect`], with headers on the upgrade request (an `Authorization`
/// carrying a key proof, as synapse signs in).
pub(crate) async fn connect_with_headers(
    url: &str,
    headers: &[(String, String)],
    registry: Arc<Registry>,
) -> Result<Conn, TransportError> {
    use tokio_tungstenite::tungstenite::client::IntoClientRequest;
    use tokio_tungstenite::tungstenite::http::{HeaderName, HeaderValue};

    let mut request = url
        .into_client_request()
        .map_err(|e| TransportError::connect(format!("{url}: {e}")))?;
    for (name, value) in headers {
        let name = HeaderName::from_bytes(name.as_bytes())
            .map_err(|e| TransportError::connect(format!("header {name}: {e}")))?;
        // The value is never said back: it may be a credential.
        let value = HeaderValue::from_str(value)
            .map_err(|_| TransportError::connect(format!("header {name}: not a header value")))?;
        request.headers_mut().insert(name, value);
    }
    // TRANSPORT-16: a refused upgrade keeps its status — a 401 is how a
    // bridge in front of this socket learns to challenge its own caller.
    let (socket, _response) = tokio_tungstenite::connect_async(request).await.map_err(|e| match e {
        tokio_tungstenite::tungstenite::Error::Http(response) => {
            let status = response.status();
            TransportError::http(status.as_u16(), format!("{url}: the upgrade was refused with {status}"))
        }
        e => TransportError::connect(format!("{url}: {e}")),
    })?;

    let (mut sink, mut source) = socket.split();
    let (outbound, mut queue) = mpsc::unbounded::<Out>();

    tokio::spawn(async move {
        while let Some(out) = queue.next().await {
            match out {
                Out::Frame(text) => {
                    if sink.send(Message::text(text)).await.is_err() {
                        break;
                    }
                }
                Out::Binary(frame) => {
                    if sink.send(Message::binary(frame)).await.is_err() {
                        break;
                    }
                }
                Out::Close => break,
            }
        }
        let _ = sink.close().await;
    });

    // The reader writes too: a call whose stream was dropped before the
    // acknowledgement arrived is cancelled here, because this task is where
    // the subscription id first becomes known.
    let reader_outbound = outbound.clone();
    tokio::spawn(async move {
        let write_back = |frame: Option<String>| {
            if let Some(frame) = frame {
                super::trace("→", &frame);
                let _ = reader_outbound.unbounded_send(Out::Frame(frame));
            }
        };
        loop {
            match source.next().await {
                Some(Ok(Message::Text(text))) => {
                    super::trace("←", text.as_str());
                    write_back(registry.on_text(text.as_str()));
                }
                // A server is free to frame JSON as binary; jsonrpsee does
                // not, but accepting it costs nothing and a silent drop
                // would be very hard to diagnose.
                Some(Ok(Message::Binary(bytes))) => {
                    if let Ok(text) = std::str::from_utf8(&bytes) {
                        super::trace("←", text);
                        write_back(registry.on_text(text));
                    }
                }
                Some(Ok(Message::Close(_))) | None => {
                    registry.on_close("websocket closed by the peer");
                    return;
                }
                Some(Ok(_)) => {}
                Some(Err(e)) => {
                    registry.on_close(format!("websocket read failed: {e}"));
                    return;
                }
            }
        }
    });

    Ok(Conn { outbound })
}