use std::sync::Arc;
use futures::StreamExt;
use plexus_client::{ItemStream, MethodRef, StreamItem, Transport, TransportError};
use serde_json::Value;
use super::auth::AuthContext;
use super::in_process::to_client_item;
use super::plexus::{error_item, DynamicHub, PlexusError};
#[derive(Clone)]
pub struct HubTransport {
hub: Arc<DynamicHub>,
auth: Option<AuthContext>,
}
impl std::fmt::Debug for HubTransport {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("HubTransport")
.field("hub", &self.hub.runtime_namespace())
.field("caller", &self.auth.as_ref().map(|a| a.user_id.as_str()))
.finish()
}
}
impl HubTransport {
pub fn as_(hub: Arc<DynamicHub>, caller: AuthContext) -> Self {
Self { hub, auth: Some(caller) }
}
pub(crate) fn with(hub: Arc<DynamicHub>, caller: Option<AuthContext>) -> Self {
Self { hub, auth: caller }
}
pub fn anonymous(hub: Arc<DynamicHub>) -> Self {
Self { hub, auth: None }
}
pub fn hub(&self) -> &Arc<DynamicHub> {
&self.hub
}
pub fn caller(&self) -> Option<&AuthContext> {
self.auth.as_ref()
}
}
fn refused(ns: &str, e: &PlexusError) -> StreamItem {
serde_json::from_value(error_item(ns, e)).unwrap_or_else(|_| StreamItem::Error {
metadata: None,
recoverable: false,
message: Some(e.to_string()),
code: None,
error: plexus_client::RemoteError::from(e),
fields: Default::default(),
})
}
impl Transport for HubTransport {
fn call(&self, method: MethodRef, params: Value) -> ItemStream<'_> {
let hub = self.hub.clone();
let auth = self.auth.clone();
Box::pin(
futures::stream::once(async move {
match hub.route_with_ctx(&method.qualified(), params, auth.as_ref(), None).await {
Ok(stream) => stream.map(|item| Ok::<_, TransportError>(to_client_item(item))).left_stream(),
Err(e) => {
let item = refused(hub.runtime_namespace(), &e);
futures::stream::once(async move { Ok(item) }).right_stream()
}
}
})
.flatten(),
)
}
}