use std::collections::HashMap;
use std::pin::Pin;
use std::task::{Context, Poll};
use rkyv::api::high::to_bytes_in;
use rkyv::util::AlignedVec;
use crate::types::{Event, EventKind, Observable, RpcError, RpcHeader, ServiceRef, WireEvent};
pub trait ResponseEmitter {
fn emit(&mut self, kind: EventKind, payload: &[u8]) -> bool;
}
#[derive(Default)]
pub struct CollectEmitter {
samples: Vec<(EventKind, Vec<u8>)>,
}
impl CollectEmitter {
pub fn new() -> Self {
Self::default()
}
pub fn take(&mut self) -> Vec<(EventKind, Vec<u8>)> {
std::mem::take(&mut self.samples)
}
}
impl ResponseEmitter for CollectEmitter {
fn emit(&mut self, kind: EventKind, payload: &[u8]) -> bool {
self.samples.push((kind, payload.to_vec()));
true
}
}
pin_project_lite::pin_project! {
struct WireFolding<T, E> {
#[pin]
source: Observable<T, E>,
pending: Option<Event<T, E>>,
}
}
impl<T, E> WireFolding<T, E> {
fn new(source: Observable<T, E>) -> Self {
Self {
source,
pending: None,
}
}
async fn next_wire(mut self: Pin<&mut Self>) -> Option<WireEvent<T, E>> {
futures_lite::future::poll_fn(|cx| futures_lite::Stream::poll_next(self.as_mut(), cx)).await
}
}
impl<T, E> futures_lite::Stream for WireFolding<T, E> {
type Item = WireEvent<T, E>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
let mut this = self.project();
let event = match this.pending.take() {
Some(event) => event,
None => match futures_lite::Stream::poll_next(this.source.as_mut(), cx) {
Poll::Ready(Some(event)) => event,
Poll::Ready(None) => return Poll::Ready(None),
Poll::Pending => return Poll::Pending,
},
};
match event {
Event::Next(value) => {
match futures_lite::Stream::poll_next(this.source.as_mut(), cx) {
Poll::Ready(Some(Event::Complete)) => {
Poll::Ready(Some(WireEvent::CompleteWith(value)))
}
Poll::Ready(other) => {
*this.pending = other;
Poll::Ready(Some(WireEvent::Next(value)))
}
Poll::Pending => Poll::Ready(Some(WireEvent::Next(value))),
}
}
other => Poll::Ready(Some(other.into())),
}
}
}
pub async fn observable_to_responses<T, E, S>(observable: Observable<T, E>, emitter: &mut S)
where
S: ResponseEmitter + ?Sized,
T: Send + 'static,
E: Send + 'static,
for<'a> WireEvent<T, E>: rkyv::Serialize<
rkyv::rancor::Strategy<
rkyv::ser::Serializer<
rkyv::util::AlignedVec,
rkyv::ser::allocator::ArenaHandle<'a>,
rkyv::ser::sharing::Share,
>,
rkyv::rancor::Error,
>,
>,
{
let mut scratch = AlignedVec::<16>::with_capacity(256);
let mut stream = std::pin::pin!(WireFolding::new(observable));
loop {
let wire = match stream.as_mut().next_wire().await {
Some(wire) => wire,
None => return,
};
scratch.clear();
let framed: (EventKind, Result<AlignedVec<16>, rkyv::rancor::Error>) = match &wire {
WireEvent::RpcError(err) => (EventKind::RpcError, to_bytes_in(err, scratch)),
_ => (wire.kind(), to_bytes_in(&wire, scratch)),
};
let (kind, result) = framed;
match result {
Ok(bytes) => {
if !emitter.emit(kind, &bytes) {
return;
}
scratch = bytes;
}
Err(e) => {
log::error!("[bridge] response serialization failed: {e:?}");
return;
}
}
}
}
pub type OwnedEmitter = Box<dyn ResponseEmitter + Send>;
pub type MethodHandler =
Box<dyn Fn(RpcHeader, Vec<u8>, OwnedEmitter) -> BoxResponseFuture + Send + Sync>;
pub type BoxResponseFuture = crate::types::BoxResponseFuture;
#[derive(Default)]
pub struct ServiceDispatcher {
service: ServiceRef,
handlers: HashMap<&'static str, MethodHandler>,
}
impl ServiceDispatcher {
pub fn new(service: ServiceRef) -> Self {
Self {
service,
handlers: HashMap::new(),
}
}
pub fn service(&self) -> ServiceRef {
self.service
}
pub fn method<F>(&mut self, name: &'static str, handler: F) -> &mut Self
where
F: Fn(RpcHeader, Vec<u8>, OwnedEmitter) -> BoxResponseFuture + Send + Sync + 'static,
{
self.handlers.insert(name, Box::new(handler));
self
}
pub fn dispatch(
&self,
method: &str,
header: RpcHeader,
payload: Vec<u8>,
emitter: OwnedEmitter,
) -> Option<BoxResponseFuture> {
self.handlers
.get(method)
.map(|handler| handler(header, payload, emitter))
}
}
pub fn emit_rpc_error(err: RpcError, emitter: &mut dyn ResponseEmitter) -> bool {
let scratch = AlignedVec::<16>::with_capacity(256);
let encoded: Result<AlignedVec<16>, rkyv::rancor::Error> = to_bytes_in(&err, scratch);
match encoded {
Ok(bytes) => emitter.emit(EventKind::RpcError, &bytes),
Err(e) => {
log::error!("[bridge] rpc error serialization failed: {e:?}");
false
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::types::ObservableError;
use std::time::Duration;
fn encode(observable: Observable<i32, String>) -> Vec<(EventKind, Vec<u8>)> {
let mut emitter = CollectEmitter::new();
crate::rt::block_on(observable_to_responses(observable, &mut emitter));
emitter.take()
}
fn fold(observable: Observable<i32, String>) -> Vec<(EventKind, WireEvent<i32, String>)> {
encode(observable)
.into_iter()
.map(|(kind, payload)| {
let event =
rkyv::from_bytes::<WireEvent<i32, String>, rkyv::rancor::Error>(&payload)
.expect("the payload of a service response is a WireEvent");
(kind, event)
})
.collect()
}
#[test]
fn a_single_value_response_travels_as_one_sample() {
let samples = fold(Observable::from_events([Event::Next(42), Event::Complete]));
assert_eq!(samples.len(), 1, "the pair must fold into one sample");
assert_eq!(samples[0].0, EventKind::Complete);
assert_eq!(samples[0].1, WireEvent::CompleteWith(42));
}
#[test]
fn intermediate_values_keep_their_own_sample() {
let samples = fold(Observable::from_events([
Event::Next(1),
Event::Next(2),
Event::Complete,
]));
assert_eq!(samples.len(), 2);
assert_eq!(samples[0], (EventKind::Next, WireEvent::Next(1)));
assert_eq!(
samples[1],
(EventKind::Complete, WireEvent::CompleteWith(2))
);
}
#[test]
fn a_pipeline_single_value_keeps_one_wire_sample() {
let samples = fold(
Observable::<i32, String>::from_events([Event::Next(7), Event::Complete])
.map(|v| v * 6),
);
assert_eq!(samples.len(), 1);
assert_eq!(
samples[0],
(EventKind::Complete, WireEvent::CompleteWith(42))
);
}
#[test]
fn a_technical_error_is_framed_as_a_bare_rpc_error() {
let samples = encode(Observable::from_events([Event::Error(
ObservableError::Technical(RpcError::Timeout),
)]));
assert_eq!(samples.len(), 1);
assert_eq!(samples[0].0, EventKind::RpcError);
assert!(
rkyv::from_bytes::<WireEvent<i32, String>, rkyv::rancor::Error>(&samples[0].1).is_err()
);
let error = rkyv::from_bytes::<RpcError, rkyv::rancor::Error>(&samples[0].1)
.expect("a technical error carries a bare RpcError");
assert_eq!(error, RpcError::Timeout);
}
#[test]
fn a_business_error_keeps_the_service_framing() {
let samples = fold(Observable::from_events([Event::Error(
ObservableError::Business("boom".into()),
)]));
assert_eq!(samples.len(), 1);
assert_eq!(
samples[0],
(EventKind::Error, WireEvent::Error("boom".into()))
);
}
#[test]
fn a_value_followed_by_silence_is_published_at_once() {
let (tx, rx) = crate::types::unbounded_channel::<i32, String>();
tx.try_send_next(1).expect("the channel is unbounded");
let mut stream = std::pin::pin!(WireFolding::new(rx));
let wire = crate::rt::test_block_on(crate::rt::timeout(
Duration::from_millis(500),
stream.as_mut().next_wire(),
));
assert_eq!(
wire.expect("a value must not wait for the event that follows it"),
Some(WireEvent::Next(1))
);
}
#[test]
fn send_complete_with_folds_on_a_two_slot_channel() {
let (tx, rx) = crate::types::channel::<i32, String>(2);
crate::rt::block_on(tx.send_complete_with(42)).expect("two slots are enough");
drop(tx);
let mut stream = std::pin::pin!(WireFolding::new(rx));
assert_eq!(
crate::rt::block_on(stream.as_mut().next_wire()),
Some(WireEvent::CompleteWith(42))
);
assert_eq!(crate::rt::block_on(stream.as_mut().next_wire()), None);
}
}