plexus-ui-engine 0.2.7

The plexus-ui engine — signals, live() over Plexus streams, the view tree over a renderer, Rhai folds, sections, hot-swap
Documentation
//! UI-6: **the page's socket** (wasm32) — v1's `WsTransport` (tag
//! v0.0.1, `frontend/src/session.rs`) over plexus-client's `ws-web`: one
//! socket, signed in by the session's cookie, checked every second and
//! opened again when it has gone (the reconnect loop), each reconnect
//! announced so the engine asks again for what it holds.
//!
//! STUDIO-32: a call answered plexus-core's `-32001` "Authentication
//! required" (a subscribe refused, or an error item), or a socket that
//! cannot be opened while the page itself wants a sign-in, is a session
//! that has ended: the page goes to the sign-in it names
//! ([`crate::host_js::signed_out`]), once, and the hooks of
//! [`WsWire::on_signed_out`] hear what was done.

use super::{CallId, Sink, Wire, WireItem};
use futures::future::{AbortHandle, Abortable};
use futures::StreamExt;
use std::future::Future;
use crate::host_js::{self, SignedOut};
use plexus_client::{MethodRef, RemoteError, StreamItem, Transport, TransportError, TransportErrorKind, WsTransport};
use serde_json::Value;
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::rc::Rc;

/// FRAME-6: the service a page speaks to when it names none (a page
/// without `<meta name="plexus-service">`, every bundle built before the
/// metas): its socket's `<service>.call` is `menger.call`, as it was.
pub const FALLBACK_SERVICE: &str = "menger";

/// How often the loop looks at the socket, in milliseconds.
pub const RECONNECT_MS: i32 = 1_000;

struct Inner {
    url: String,
    /// The service the socket speaks to — its frames' `<service>.call`
    /// (plexus-client's namespace argument).
    service: String,
    transport: RefCell<Option<Rc<WsTransport>>>,
    calls: RefCell<HashMap<u64, AbortHandle>>,
    next: Cell<u64>,
    connects: Cell<u32>,
    on_reconnect: RefCell<Vec<Rc<dyn Fn()>>>,
    /// STUDIO-32: what hears a signed-out page's fate.
    on_signed_out: RefCell<Vec<Rc<dyn Fn(SignedOut)>>>,
    /// STUDIO-32: a call was answered since the last signed-out word.
    answered: Cell<bool>,
    /// STUDIO-32: the page was asked whether it wants a sign-in since the
    /// socket was last open.
    probed: Cell<bool>,
}

impl Inner {
    /// STUDIO-32: the session has ended — the page to its sign-in, once.
    fn signed_out(&self) {
        self.answered.set(false);
        let how = host_js::signed_out();
        if how == SignedOut::None {
            return;
        }
        let hooks: Vec<Rc<dyn Fn(SignedOut)>> = self.on_signed_out.borrow().clone();
        for h in hooks {
            h(how);
        }
    }

    /// STUDIO-32: a call was answered — the page is signed in.
    fn answered(&self) {
        if !self.answered.replace(true) {
            host_js::signed_in();
        }
    }
}

/// STUDIO-32: whether a call's item is plexus-core's `-32001` — an error
/// item typed unauthenticated (or carrying the code), or the subscribe
/// refused with it (plexus-client's "subscribe rejected: {error}").
fn unauthenticated(item: &Result<StreamItem, TransportError>) -> bool {
    match item {
        Ok(StreamItem::Error { error, code, .. }) => matches!(error, RemoteError::Unauthenticated) || code.as_deref() == Some("-32001"),
        Err(e) => matches!(e.kind, TransportErrorKind::Protocol) && e.message.contains("\"code\":-32001"),
        Ok(_) => false,
    }
}

/// The one socket.
#[derive(Clone)]
pub struct WsWire(Rc<Inner>);

thread_local! {
    static METHODS: RefCell<HashMap<String, MethodRef>> = RefCell::new(HashMap::new());
}

/// `tickets.list` → its reference (interned: a page names few methods; a
/// `MethodRef` is `Clone`, not `Copy`, since plexus-client 0.8).
fn method_ref(method: &str) -> MethodRef {
    METHODS.with(|m| {
        if let Some(r) = m.borrow().get(method) {
            return r.clone();
        }
        let (path, name) = method.rsplit_once('.').unwrap_or(("", method));
        let path: &'static str = Box::leak(path.to_string().into_boxed_str());
        let name: &'static str = Box::leak(name.to_string().into_boxed_str());
        let ns: &'static str = path.rsplit('.').next().unwrap_or(path);
        let r = MethodRef::new(ns, name).at(path);
        m.borrow_mut().insert(method.to_string(), r.clone());
        r
    })
}

/// Waits `ms` milliseconds.
pub async fn sleep(ms: i32) {
    let p = js_sys::Promise::new(&mut |resolve, _| {
        let _ = web_sys::window().expect("a window").set_timeout_with_callback_and_timeout_and_arguments_0(&resolve, ms);
    });
    let _ = wasm_bindgen_futures::JsFuture::from(p).await;
}

impl WsWire {
    /// The socket at `url` to `service`, not yet open: [`Self::run`] opens it.
    pub fn new(url: &str, service: &str) -> Self {
        Self(Rc::new(Inner {
            url: url.into(),
            service: service.into(),
            transport: RefCell::new(None),
            calls: RefCell::new(HashMap::new()),
            next: Cell::new(0),
            connects: Cell::new(0),
            on_reconnect: RefCell::new(Vec::new()),
            on_signed_out: RefCell::new(Vec::new()),
            answered: Cell::new(false),
            probed: Cell::new(false),
        }))
    }

    /// Whether the socket is open.
    pub fn is_open(&self) -> bool {
        self.0.transport.borrow().as_ref().is_some_and(|t| !t.is_closed())
    }

    /// Called after every reconnect (not the first connect).
    pub fn on_reconnect(&self, f: Rc<dyn Fn()>) {
        self.0.on_reconnect.borrow_mut().push(f);
    }

    /// STUDIO-32: called when the session has ended and the page names a
    /// sign-in — [`SignedOut::Sent`] on its way there, [`SignedOut::Said`]
    /// back from it still signed out.
    pub fn on_signed_out(&self, f: Rc<dyn Fn(SignedOut)>) {
        self.0.on_signed_out.borrow_mut().push(f);
    }

    /// Opens the socket, then keeps it open: every second, a socket gone
    /// is opened again. Resolves once the first is open.
    pub async fn run(&self) {
        self.connect().await;
        self.keep_open();
    }

    /// FRAME-16: [`Self::run`] over a socket the page made before the wasm
    /// was instantiated (host.js's `start`), adopted — opened again as
    /// `run` does if it closed before it could be.
    pub async fn run_adopting(&self, socket: web_sys::WebSocket) {
        match WsTransport::adopt(socket, &self.0.service).await {
            Ok(t) => {
                *self.0.transport.borrow_mut() = Some(Rc::new(t));
                self.0.connects.set(self.0.connects.get() + 1);
            }
            Err(e) => {
                web_sys::console::warn_1(&format!("the socket host.js opened: {e}; opening another").into());
                self.connect().await;
            }
        }
        self.keep_open();
    }

    /// Every second, a socket gone is opened again.
    fn keep_open(&self) {
        let me = self.clone();
        wasm_bindgen_futures::spawn_local(async move {
            loop {
                sleep(RECONNECT_MS).await;
                if !me.is_open() {
                    *me.0.transport.borrow_mut() = None;
                    if me.try_connect().await {
                        let hooks: Vec<Rc<dyn Fn()>> = me.0.on_reconnect.borrow().clone();
                        for h in hooks {
                            h();
                        }
                    }
                }
            }
        });
    }

    async fn connect(&self) {
        while !self.try_connect().await {
            sleep(RECONNECT_MS).await;
        }
    }

    async fn try_connect(&self) -> bool {
        match WsTransport::connect(&self.0.url, &self.0.service).await {
            Ok(t) => {
                *self.0.transport.borrow_mut() = Some(Rc::new(t));
                self.0.connects.set(self.0.connects.get() + 1);
                self.0.probed.set(false);
                true
            }
            Err(e) => {
                web_sys::console::warn_1(&format!("the socket {}: {e}; again in 1 s", self.0.url).into());
                // STUDIO-32: a refused upgrade is only a failure here; once
                // per outage, the page is asked whether it wants a sign-in.
                if !self.0.probed.replace(true) && host_js::session_gone().await {
                    self.0.signed_out();
                }
                false
            }
        }
    }

    /// One call to its end: its data events, or the refusal / failure.
    pub async fn ask(&self, method: &str, params: Value) -> Result<Vec<Value>, String> {
        let (tx, rx) = futures::channel::oneshot::channel();
        let tx = RefCell::new(Some(tx));
        let got = Rc::new(RefCell::new(Vec::new()));
        let g = got.clone();
        self.open(method, params, Box::new(move |item| {
            let end = match item {
                WireItem::Data(v) => {
                    g.borrow_mut().push(v);
                    return;
                }
                WireItem::Done => Ok(std::mem::take(&mut *g.borrow_mut())),
                WireItem::Refused(m) | WireItem::Failed(m) => Err(m),
                WireItem::Dropped => Err(crate::bus::DISCONNECTED.into()),
            };
            if let Some(tx) = tx.borrow_mut().take() {
                let _ = tx.send(end);
            }
        }));
        rx.await.unwrap_or_else(|_| Err("the call was dropped".into()))
    }
}

impl Wire for WsWire {
    fn open(&self, method: &str, params: Value, mut sink: Sink) -> CallId {
        let id = self.0.next.get() + 1;
        self.0.next.set(id);
        let Some(t) = self.0.transport.borrow().clone().filter(|t| !t.is_closed()) else {
            sink(WireItem::Failed("the socket is not open".into()));
            return CallId(id);
        };
        let mref = method_ref(method);
        let (handle, reg) = AbortHandle::new_pair();
        self.0.calls.borrow_mut().insert(id, handle);
        let inner = self.0.clone();
        let work = async move {
            let mut items = t.call(mref, params);
            while let Some(item) = items.next().await {
                if unauthenticated(&item) {
                    inner.signed_out();
                } else if matches!(item, Ok(StreamItem::Data { .. } | StreamItem::Done { .. })) {
                    inner.answered();
                }
                let (wire, end) = match item {
                    Ok(StreamItem::Data { content, .. }) => (WireItem::Data(content), false),
                    Ok(StreamItem::Done { .. }) => (WireItem::Done, true),
                    Ok(StreamItem::Error { message, error, .. }) => (WireItem::Refused(message.unwrap_or_else(|| error.to_string())), true),
                    Ok(_) => continue,
                    // FRAME-37: the socket closing under the call is a drop;
                    // any other failure keeps plexus-client's words.
                    Err(e) if matches!(e.kind, TransportErrorKind::Closed) => (WireItem::Dropped, true),
                    Err(e) => (WireItem::Failed(e.to_string()), true),
                };
                sink(wire);
                if end {
                    break;
                }
            }
            inner.calls.borrow_mut().remove(&id);
        };
        // FRAME-17: polled once now, so the call's frame leaves in this
        // turn (plexus-client writes it when asked) — not after whatever
        // the page does synchronously next (a whole mount); then handed to
        // the executor, whose waker the stream holds from its next poll.
        // Nothing can arrive between the two: the socket's messages are
        // later turns.
        let mut work = Box::pin(Abortable::new(work, reg));
        let waker = futures::task::noop_waker();
        if work.as_mut().poll(&mut std::task::Context::from_waker(&waker)).is_pending() {
            wasm_bindgen_futures::spawn_local(async move {
                let _ = work.await;
            });
        }
        CallId(id)
    }

    fn close(&self, call: CallId) {
        if let Some(h) = self.0.calls.borrow_mut().remove(&call.0) {
            h.abort();
        }
    }
}