use crate::channels::{Channel, Request, Scoped, Unscoped, payload_shape, payload_stamps};
use crate::errors::{
BusRequestError, BusRequestErrorCode, SemiontError, TransportError, TransportErrorCode,
};
use crate::required::{Fault, fault_of};
use crate::transport::{
ConnectionState, Envelope, Frame, FrameRefusal, Frames, Lagged, ResourceHold, TraceCarrier,
Transport,
};
use crate::types::ResourceId;
use futures_core::Stream;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use std::fmt;
use std::marker::PhantomData;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use tokio::time::Instant;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Operation {
pub request: &'static str,
pub result: &'static str,
pub failure: &'static str,
}
impl Operation {
pub(crate) const fn of<R: Request>() -> Operation {
Operation {
request: R::NAME,
result: <R::Result as Channel>::NAME,
failure: <R::Failure as Channel>::NAME,
}
}
}
include!(concat!(env!("OUT_DIR"), "/operations.rs"));
pub fn operation(request: &str) -> Option<&'static Operation> {
OPERATIONS.iter().find(|op| op.request == request)
}
pub fn reply_names(request: &str) -> &'static [&'static str] {
REPLY_NAMES
.iter()
.find(|(asked, _)| *asked == request)
.map_or(&[][..], |(_, named)| *named)
}
pub fn reply_channels_for(channels: &[&str]) -> Vec<&'static str> {
let mut replies = Vec::new();
for op in channels.iter().filter_map(|channel| operation(channel)) {
for reply in [op.result, op.failure] {
if !replies.contains(&reply) {
replies.push(reply);
}
}
}
replies
}
pub fn payload_of(payload: &impl Serialize) -> Result<Map<String, Value>, TransportError> {
match serde_json::to_value(payload) {
Ok(Value::Object(fields)) => Ok(fields),
Ok(other) => Err(TransportError::without_response(
format!("a payload is a JSON object, not {other}"),
TransportErrorCode::Error,
)),
Err(error) => Err(TransportError::without_response(
format!("a payload that does not serialize: {error}"),
TransportErrorCode::Error,
)),
}
}
#[derive(Clone)]
pub struct Bus {
transport: Arc<dyn Transport>,
}
impl Bus {
pub fn new(transport: Arc<dyn Transport>) -> Bus {
Bus { transport }
}
pub async fn emit_on(
&self,
channel: &str,
payload: Map<String, Value>,
envelope: Envelope,
) -> Result<Option<u64>, TransportError> {
self.transport.emit(channel, payload, envelope).await
}
pub fn frames_on(&self, channel: &str) -> Result<Frames, BusRequestError> {
self.transport.frames(channel)
}
pub async fn request_of(
&self,
operation: &Operation,
payload: Map<String, Value>,
within: Duration,
) -> Result<Option<Value>, SemiontError> {
let mut result = self.result_of(operation, payload, within).await?;
Ok(result.payload.remove("response"))
}
async fn result_of(
&self,
operation: &Operation,
payload: Map<String, Value>,
within: Duration,
) -> Result<Frame, SemiontError> {
let deadline = Instant::now() + within;
for channel in [operation.result, operation.failure] {
if !self.transport.is_subscribed(channel) {
return Err(BusRequestError::new(
BusRequestErrorCode::Unsubscribed,
format!(
"Transport is not subscribed to reply channel {channel}: a reply to {} can never arrive. Add this operation's reply channels to the transport's channels.",
operation.request
),
)
.into());
}
}
let timed_out = || {
BusRequestError::new(
BusRequestErrorCode::Timeout,
format!(
"Bus request timed out after {}ms on {}",
within.as_millis(),
operation.result
),
)
};
let closed_before_emit = || {
BusRequestError::new(
BusRequestErrorCode::Closed,
format!("Bus closed before emit on {}", operation.request),
)
};
let mut state = self.transport.state();
loop {
match *state.borrow_and_update() {
ConnectionState::Open => break,
ConnectionState::Closed => return Err(closed_before_emit().into()),
_ => {}
}
tokio::select! {
changed = state.changed() => {
if changed.is_err() {
return Err(closed_before_emit().into());
}
}
() = tokio::time::sleep_until(deadline) => return Err(timed_out().into()),
}
}
let correlation_id = uuid::Uuid::new_v4().to_string();
let mut pending = self
.transport
.track_reply(&correlation_id, &[operation.result, operation.failure]);
let envelope = Envelope {
correlation_id: Some(correlation_id),
scope: None,
};
self.transport
.emit(operation.request, payload, envelope)
.await?;
let reply = tokio::select! {
biased;
reply = pending.frame() => reply,
() = tokio::time::sleep_until(deadline) => return Err(timed_out().into()),
};
let reply = match reply {
Some(Ok(reply)) => reply,
Some(Err(refusal)) => {
return Err(TransportError::without_response(
refusal.to_string(),
TransportErrorCode::Error,
)
.into());
}
None => {
return Err(BusRequestError::new(
BusRequestErrorCode::Closed,
format!("Bus closed before a reply on {}", operation.result),
)
.into());
}
};
if reply.channel == operation.result {
return Ok(reply);
}
Err(answered(operation.failure, reply.payload))
}
}
#[derive(Deserialize)]
struct Failure {
message: String,
code: Option<String>,
}
fn answered(channel: &str, failure: Map<String, Value>) -> SemiontError {
let fault = match held_to(channel, failure.clone()) {
Err(fault) => fault,
Ok(declared) => match serde_json::from_value::<Failure>(declared) {
Ok(read) => {
return BusRequestError {
code: BusRequestErrorCode::of_wire(read.code.as_deref()),
message: read.message,
failure: Some(failure),
}
.into();
}
Err(_) => Fault::undecoded(),
},
};
TransportError::without_response(
format!("a payload on {channel} is not that channel's: {fault}"),
TransportErrorCode::Error,
)
.into()
}
pub struct Delivered<C: Channel> {
pub payload: C::Payload,
pub correlation_id: Option<String>,
pub scope: Option<ResourceId>,
pub user_id: Option<String>,
pub trace: Option<TraceCarrier>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StreamError {
Lagged(u64),
Refused(Box<FrameRefusal>),
}
impl fmt::Display for StreamError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
StreamError::Lagged(missed) => Lagged(*missed).fmt(f),
StreamError::Refused(refusal) => refusal.fmt(f),
}
}
}
impl std::error::Error for StreamError {}
pub(crate) fn held_to(channel: &str, mut payload: Map<String, Value>) -> Result<Value, Fault> {
let stamps = payload_stamps(channel);
payload.retain(|key, _| !key.starts_with('_') || stamps.contains(&key.as_str()));
let payload = Value::Object(payload);
match fault_of(payload_shape(channel), &payload) {
Some(fault) => Err(fault),
None => Ok(payload),
}
}
pub(crate) fn decoded<C: Channel>(payload: Map<String, Value>) -> Result<C::Payload, Fault> {
serde_json::from_value(held_to(C::NAME, payload)?).map_err(|_| Fault::undecoded())
}
fn delivered<C: Channel, E>(
frame: Frame,
refused: impl FnOnce(Fault, Frame) -> E,
) -> Result<Delivered<C>, E> {
let payload = match decoded::<C>(frame.payload.clone()) {
Ok(payload) => payload,
Err(fault) => return Err(refused(fault, frame)),
};
let user_id = frame
.payload
.get("_userId")
.and_then(Value::as_str)
.map(str::to_owned);
Ok(Delivered {
payload,
correlation_id: frame.correlation_id,
scope: frame.scope,
user_id,
trace: frame.trace,
})
}
fn not_the_channels(fault: Fault, frame: Frame) -> FrameRefusal {
let Fault { member, reason } = fault.within("payload");
FrameRefusal {
channel: frame.channel,
member,
reason,
payload: Some(Value::Object(frame.payload)),
scope: frame.scope,
correlation_id: frame.correlation_id,
}
}
pub struct Typed<C: Channel, F = Frames> {
frames: F,
channel: PhantomData<fn() -> C>,
}
impl<C: Channel, F> Typed<C, F> {
pub(crate) fn of(frames: F) -> Typed<C, F> {
Typed {
frames,
channel: PhantomData,
}
}
}
impl<C: Channel, F: Stream<Item = Result<Result<Frame, FrameRefusal>, Lagged>> + Unpin>
Typed<C, F>
{
pub async fn next(&mut self) -> Option<Result<Delivered<C>, StreamError>> {
std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
}
}
impl<C: Channel, F: Stream<Item = Result<Result<Frame, FrameRefusal>, Lagged>> + Unpin> Stream
for Typed<C, F>
{
type Item = Result<Delivered<C>, StreamError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
Pin::new(&mut self.frames).poll_next(cx).map(|item| {
item.map(|item| match item {
Ok(Ok(frame)) => delivered::<C, _>(frame, |fault, frame| {
StreamError::Refused(Box::new(not_the_channels(fault, frame)))
}),
Ok(Err(refusal)) => Err(StreamError::Refused(Box::new(refusal))),
Err(Lagged(missed)) => Err(StreamError::Lagged(missed)),
})
})
}
}
pub struct ScopedFrames {
frames: Frames,
resource: ResourceId,
_hold: ResourceHold,
}
impl Stream for ScopedFrames {
type Item = Result<Result<Frame, FrameRefusal>, Lagged>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
match Pin::new(&mut self.frames).poll_next(cx) {
Poll::Ready(Some(Ok(Ok(frame))))
if frame.scope.as_ref() != Some(&self.resource) => {}
Poll::Ready(Some(Ok(Err(refusal))))
if refusal.scope.as_ref() != Some(&self.resource) => {}
other => return other,
}
}
}
}
impl Bus {
pub async fn emit<C: Channel>(
&self,
payload: &C::Payload,
envelope: Envelope,
) -> Result<Option<u64>, TransportError> {
self.emit_on(C::NAME, payload_of(payload)?, envelope).await
}
pub fn frames<C: Unscoped>(&self) -> Result<Typed<C>, BusRequestError> {
Ok(Typed::of(self.frames_on(C::NAME)?))
}
pub fn frames_of<C: Scoped>(
&self,
resource: &ResourceId,
) -> Result<Typed<C, ScopedFrames>, BusRequestError> {
let frames = self.frames_on(C::NAME)?;
Ok(Typed::of(ScopedFrames {
frames,
resource: resource.clone(),
_hold: self.transport.subscribe_to_resource(resource),
}))
}
pub async fn request<R: Request>(
&self,
payload: &R::Payload,
within: Duration,
) -> Result<<R::Result as Channel>::Payload, SemiontError> {
Ok(self.result::<R>(payload, within).await?.payload)
}
pub(crate) async fn result<R: Request>(
&self,
payload: &R::Payload,
within: Duration,
) -> Result<Delivered<R::Result>, SemiontError> {
let result = self
.result_of(&Operation::of::<R>(), payload_of(payload)?, within)
.await?;
delivered::<R::Result, _>(result, |fault, _| {
TransportError::without_response(
format!(
"a payload on {} is not that channel's: {fault}",
<R::Result as Channel>::NAME
),
TransportErrorCode::Error,
)
.into()
})
}
}