use super::traits::{DeRecTransport, TransportFuture};
use derec_proto::TransportProtocol;
pub trait SendOne {
fn send_one(&self, endpoint: &TransportProtocol, message: Vec<u8>) -> TransportFuture<'_>;
}
#[derive(Clone, Copy, Debug, Default)]
pub struct SequentialFailover<T>(T);
impl<T> SequentialFailover<T> {
pub fn new(dialer: T) -> Self {
Self(dialer)
}
pub fn inner(&self) -> &T {
&self.0
}
pub fn into_inner(self) -> T {
self.0
}
}
macro_rules! impl_adapters {
($($bound:tt)*) => {
impl<T: SendOne $($bound)*> DeRecTransport for SequentialFailover<T> {
fn send(
&self,
endpoints: &[TransportProtocol],
message: Vec<u8>,
) -> TransportFuture<'_> {
let endpoints = endpoints.to_vec();
Box::pin(async move {
let mut last: Option<crate::Error> = None;
for endpoint in &endpoints {
match self.0.send_one(endpoint, message.clone()).await {
Ok(()) => return Ok(()),
Err(e) => last = Some(e),
}
}
Err(last.unwrap_or(crate::Error::NoUsableEndpoint { offered: 0 }))
})
}
}
impl<T: SendOne $($bound)*> DeRecTransport for SingleEndpointTransport<T> {
fn send(
&self,
endpoints: &[TransportProtocol],
message: Vec<u8>,
) -> TransportFuture<'_> {
let first = endpoints.first().cloned();
Box::pin(async move {
match first {
Some(endpoint) => self.0.send_one(&endpoint, message).await,
None => Err(crate::Error::NoUsableEndpoint { offered: 0 }),
}
})
}
}
};
}
#[cfg(not(target_arch = "wasm32"))]
impl_adapters!(+ Send + Sync);
#[cfg(target_arch = "wasm32")]
impl_adapters!();
#[derive(Clone, Copy, Debug, Default)]
pub struct SingleEndpointTransport<T>(T);
impl<T> SingleEndpointTransport<T> {
pub fn new(dialer: T) -> Self {
Self(dialer)
}
pub fn inner(&self) -> &T {
&self.0
}
pub fn into_inner(self) -> T {
self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Error;
use derec_proto::Protocol;
use std::pin::Pin;
use std::sync::Mutex;
fn endpoint(uri: &str) -> TransportProtocol {
TransportProtocol {
uri: uri.to_owned(),
protocol: Protocol::Https as i32,
}
}
#[derive(Default)]
struct Recorder {
attempted: Mutex<Vec<String>>,
fail: Vec<String>,
}
impl Recorder {
fn failing(fail: &[&str]) -> Self {
Self {
attempted: Mutex::new(Vec::new()),
fail: fail.iter().map(|s| (*s).to_owned()).collect(),
}
}
fn attempted(&self) -> Vec<String> {
self.attempted.lock().unwrap().clone()
}
}
impl SendOne for Recorder {
fn send_one(&self, endpoint: &TransportProtocol, _message: Vec<u8>) -> TransportFuture<'_> {
self.attempted.lock().unwrap().push(endpoint.uri.clone());
let refused = self.fail.contains(&endpoint.uri);
Box::pin(async move {
if refused {
Err(Error::InvalidInput("endpoint refused"))
} else {
Ok(())
}
})
}
}
fn block_on<F: Future>(mut f: F) -> F::Output {
use std::task::{Context, Poll, Waker};
let waker = Waker::noop();
let mut cx = Context::from_waker(waker);
let mut f = unsafe { Pin::new_unchecked(&mut f) };
loop {
match f.as_mut().poll(&mut cx) {
Poll::Ready(v) => return v,
Poll::Pending => continue,
}
}
}
#[test]
fn failover_stops_at_the_first_success() {
let t = SequentialFailover::new(Recorder::default());
let endpoints = [endpoint("https://a.example"), endpoint("https://b.example")];
block_on(t.send(&endpoints, vec![1])).expect("the first endpoint answers");
assert_eq!(
t.inner().attempted(),
["https://a.example"],
"a message delivered to the first endpoint must not also go to the second"
);
}
#[test]
fn failover_advances_past_a_failing_endpoint() {
let t = SequentialFailover::new(Recorder::failing(&["https://a.example"]));
let endpoints = [endpoint("https://a.example"), endpoint("https://b.example")];
block_on(t.send(&endpoints, vec![1])).expect("the second endpoint answers");
assert_eq!(
t.inner().attempted(),
["https://a.example", "https://b.example"],
"the peer offered a working endpoint and it has to be tried"
);
}
#[test]
fn failover_tries_the_peers_order_not_its_own() {
let t = SequentialFailover::new(Recorder::failing(&["https://first.example"]));
let endpoints = [
endpoint("https://first.example"),
endpoint("https://second.example"),
endpoint("https://third.example"),
];
block_on(t.send(&endpoints, vec![1])).expect("the second endpoint answers");
assert_eq!(
t.inner().attempted(),
["https://first.example", "https://second.example"],
"the order is the peer's and is not reinterpreted"
);
}
#[test]
fn failover_fails_only_when_every_endpoint_did() {
let t = SequentialFailover::new(Recorder::failing(&[
"https://a.example",
"https://b.example",
]));
let endpoints = [endpoint("https://a.example"), endpoint("https://b.example")];
block_on(t.send(&endpoints, vec![1])).expect_err("no endpoint accepted the message");
assert_eq!(
t.inner().attempted(),
["https://a.example", "https://b.example"],
"every endpoint must be tried before the send is called a failure"
);
}
#[test]
fn single_endpoint_ignores_the_rest() {
let t = SingleEndpointTransport::new(Recorder::default());
let endpoints = [endpoint("https://a.example"), endpoint("https://b.example")];
block_on(t.send(&endpoints, vec![1])).expect("the first endpoint answers");
assert_eq!(t.inner().attempted(), ["https://a.example"]);
}
#[test]
fn single_endpoint_does_not_fall_back() {
let t = SingleEndpointTransport::new(Recorder::failing(&["https://a.example"]));
let endpoints = [endpoint("https://a.example"), endpoint("https://b.example")];
block_on(t.send(&endpoints, vec![1])).expect_err("the only endpoint tried was refused");
assert_eq!(
t.inner().attempted(),
["https://a.example"],
"the second endpoint is deliberately never tried"
);
}
}