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;
pub const FALLBACK_SERVICE: &str = "menger";
pub const RECONNECT_MS: i32 = 1_000;
struct Inner {
url: String,
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()>>>,
on_signed_out: RefCell<Vec<Rc<dyn Fn(SignedOut)>>>,
answered: Cell<bool>,
probed: Cell<bool>,
}
impl Inner {
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);
}
}
fn answered(&self) {
if !self.answered.replace(true) {
host_js::signed_in();
}
}
}
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,
}
}
#[derive(Clone)]
pub struct WsWire(Rc<Inner>);
thread_local! {
static METHODS: RefCell<HashMap<String, MethodRef>> = RefCell::new(HashMap::new());
}
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
})
}
fn refused(item: StreamItem) -> WireItem {
let StreamItem::Error { message, error, .. } = &item else { return WireItem::Failed("not an error item".into()) };
let words = message.clone().unwrap_or_else(|| error.to_string());
let mut typed = serde_json::to_value(&item).unwrap_or(Value::Null);
if let Some(o) = typed.as_object_mut() {
o.remove("type");
o.remove("metadata");
}
WireItem::Refused(words, typed)
}
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 {
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),
}))
}
pub fn is_open(&self) -> bool {
self.0.transport.borrow().as_ref().is_some_and(|t| !t.is_closed())
}
pub fn on_reconnect(&self, f: Rc<dyn Fn()>) {
self.0.on_reconnect.borrow_mut().push(f);
}
pub fn on_signed_out(&self, f: Rc<dyn Fn(SignedOut)>) {
self.0.on_signed_out.borrow_mut().push(f);
}
pub async fn run(&self) {
self.connect().await;
self.keep_open();
}
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();
}
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());
if !self.0.probed.replace(true) && host_js::session_gone().await {
self.0.signed_out();
}
false
}
}
}
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(item @ StreamItem::Error { .. }) => (refused(item), true),
Ok(_) => continue,
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);
};
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();
}
}
}