mod registry;
#[cfg(all(
feature = "ws-web",
not(feature = "ws-native"),
not(target_arch = "wasm32")
))]
compile_error!(
"plexus-client: feature `ws-web` is the wasm32 browser backend. Off \
wasm32-unknown-unknown, enable `ws-native` instead (both features \
expose the same `WsTransport`)."
);
#[cfg(feature = "ws-native")]
#[path = "native.rs"]
mod backend;
#[cfg(all(feature = "ws-web", not(feature = "ws-native")))]
#[path = "web.rs"]
mod backend;
use crate::envelope::StreamItem;
use crate::error::TransportError;
use crate::transport::{ItemStream, MethodRef, Transport};
use futures_util::{stream, StreamExt};
use registry::{subscribe_frame, Items, Registry, SubSlot};
use serde_json::Value;
use std::sync::Arc;
fn trace(direction: &str, frame: &str) {
use std::sync::OnceLock;
static ON: OnceLock<bool> = OnceLock::new();
if *ON.get_or_init(|| std::env::var("PLEXUS_WS_TRACE").is_ok()) {
eprintln!("ws {direction} {frame}");
}
}
#[derive(Debug, Clone)]
pub struct WsTransport {
conn: backend::Conn,
registry: Arc<Registry>,
_closer: Arc<Closer>,
}
#[derive(Debug)]
struct Closer {
conn: backend::Conn,
}
impl Drop for Closer {
fn drop(&mut self) {
self.conn.close();
}
}
impl WsTransport {
pub async fn connect(url: &str, hub_namespace: &str) -> Result<Self, TransportError> {
let registry = Arc::new(Registry::new(Arc::from(hub_namespace)));
let conn = backend::connect(url, registry.clone()).await?;
Ok(Self {
_closer: Arc::new(Closer { conn: conn.clone() }),
conn,
registry,
})
}
#[cfg(all(feature = "ws-web", not(feature = "ws-native")))]
pub async fn adopt(socket: web_sys::WebSocket, hub_namespace: &str) -> Result<Self, TransportError> {
let registry = Arc::new(Registry::new(Arc::from(hub_namespace)));
let conn = backend::adopt(socket, registry.clone()).await?;
Ok(Self {
_closer: Arc::new(Closer { conn: conn.clone() }),
conn,
registry,
})
}
#[cfg(feature = "ws-native")]
pub async fn connect_with_headers(
url: &str,
hub_namespace: &str,
headers: &[(String, String)],
) -> Result<Self, TransportError> {
let registry = Arc::new(Registry::new(Arc::from(hub_namespace)));
let conn = backend::connect_with_headers(url, headers, registry.clone()).await?;
Ok(Self {
_closer: Arc::new(Closer { conn: conn.clone() }),
conn,
registry,
})
}
pub fn hub_namespace(&self) -> &str {
self.registry.hub_namespace()
}
pub fn is_closed(&self) -> bool {
self.registry.is_closed()
}
fn subscribe(&self, method: MethodRef, params: Value) -> Result<Awaiting, TransportError> {
let request_id = self.registry.next_request_id();
let slot = SubSlot::new();
let reply = self.registry.register_pending(request_id, slot.clone())?;
let frame = subscribe_frame(
request_id,
self.registry.hub_namespace(),
&method.qualified(),
¶ms,
);
trace("→", &frame);
if let Err(e) = self.conn.send(frame) {
self.registry.forget_pending(request_id);
return Err(e);
}
Ok(Awaiting {
reply,
guard: SubGuard {
conn: self.conn.clone(),
registry: self.registry.clone(),
slot,
},
})
}
}
impl Transport for WsTransport {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
let start = match self.subscribe(method, params) {
Ok(awaiting) => CallState::Awaiting(awaiting),
Err(e) => return Box::pin(stream::once(async move { Err(e) })),
};
Box::pin(stream::unfold(start, |state| async move {
match state {
CallState::Awaiting(awaiting) => match awaiting.established().await {
Err(e) => Some((Err(e), CallState::Ended)),
Ok(mut active) => active
.next_item()
.await
.map(|item| (item, CallState::Active(active))),
},
CallState::Active(mut active) => active
.next_item()
.await
.map(|item| (item, CallState::Active(active))),
CallState::Ended => None,
}
}))
}
}
enum CallState {
Awaiting(Awaiting),
Active(Active),
Ended,
}
struct Awaiting {
reply: futures_channel::oneshot::Receiver<Result<Items, TransportError>>,
guard: SubGuard,
}
impl Awaiting {
async fn established(self) -> Result<Active, TransportError> {
match self.reply.await {
Ok(Ok(items)) => Ok(Active {
items,
guard: self.guard,
}),
Ok(Err(e)) => Err(e),
Err(_) => Err(TransportError::closed(
"connection closed before the subscription was acknowledged",
)),
}
}
}
struct Active {
guard: SubGuard,
items: Items,
}
impl Active {
async fn next_item(&mut self) -> Option<Result<StreamItem, TransportError>> {
match self.items.next().await {
Some(Ok(item)) => {
if item.is_terminal() {
self.guard.slot.mark_finished();
}
Some(Ok(item))
}
Some(Err(e)) => Some(Err(e)),
None => None,
}
}
}
struct SubGuard {
conn: backend::Conn,
registry: Arc<Registry>,
slot: Arc<SubSlot>,
}
impl Drop for SubGuard {
fn drop(&mut self) {
let Some(subscription) = self.slot.on_dropped() else {
return;
};
self.registry.forget_sub(&subscription);
let frame = self.registry.unsubscribe(&subscription);
trace("→", &frame);
let _ = self.conn.send(frame);
}
}