use core::fmt;
use smol_bytes::Utf8Bytes;
use crate::Lane;
use super::{LaneRouter, RoutedProbe};
#[cfg(test)]
mod tests;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LaneFan<T> {
lanes: &'static [Lane],
router: Option<T>,
}
impl<T> LaneFan<T> {
#[inline]
#[must_use]
pub const fn new(lanes: &'static [Lane]) -> Self {
Self {
lanes,
router: None,
}
}
#[inline]
#[must_use]
pub fn with_router(mut self, router: T) -> Self {
self.set_router(Some(router));
self
}
#[inline]
pub fn set_router(&mut self, router: Option<T>) -> &mut Self {
self.router = router;
self
}
#[inline]
#[must_use]
pub const fn router(&self) -> Option<&T> {
self.router.as_ref()
}
#[inline]
#[must_use]
pub const fn lanes(&self) -> &'static [Lane] {
self.lanes
}
pub fn check(&self) -> Result<(), RouterMissing> {
if self.router.is_none() && self.lanes.len() > 1 {
return Err(RouterMissing::new(self.lanes));
}
Ok(())
}
}
impl<T: LaneRouter> LaneFan<T> {
pub fn route(
&self,
question: &T::Question,
) -> Result<Vec<RoutedProbe<T::Routed>>, FanError<T::Error>> {
let Some(router) = self.router.as_ref() else {
return Err(FanError::Missing(RouterMissing::new(self.lanes)));
};
let routed = router.route(question).map_err(FanError::Router)?;
for probe in &routed {
if !self.holds(probe.lane()) {
return Err(FanError::Unroutable(UnroutableLane::new(
probe.lane(),
self.lanes,
)));
}
}
Ok(routed)
}
fn holds(&self, key: &crate::LaneIdent) -> bool {
self.lanes.iter().any(|lane| **lane.key() == **key)
}
}
#[cfg(feature = "runtime")]
impl<T> crate::Serve for LaneFan<T> {
type Options = ();
}
#[cfg(feature = "runtime")]
impl<T> crate::DefaultServe for LaneFan<T>
where
T: LaneRouter,
T::Question: ToOwned,
{
type Question = <T::Question as ToOwned>::Owned;
type Answer = RoutedProbe<T::Routed>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouterMissing {
lanes: &'static [Lane],
}
impl RouterMissing {
#[inline]
#[must_use]
pub const fn new(lanes: &'static [Lane]) -> Self {
Self { lanes }
}
#[inline]
#[must_use]
pub const fn lanes(&self) -> &'static [Lane] {
self.lanes
}
}
impl fmt::Display for RouterMissing {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"this corpus holds {} lanes and no router to choose between them (",
self.lanes.len()
)?;
for (at, lane) in self.lanes.iter().enumerate() {
let separator = if at == 0 { "" } else { ", " };
write!(f, "{separator}`{}`", &**lane.key())?;
}
f.write_str(
"); mount one — `ScriptWeightedFan` asks every lane and leans on the ones the question is \
written in, `FanAll` asks every lane flat",
)
}
}
impl core::error::Error for RouterMissing {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnroutableLane {
lane: Utf8Bytes,
lanes: &'static [Lane],
}
impl UnroutableLane {
#[inline]
#[must_use]
pub fn new(lane: &crate::LaneIdent, lanes: &'static [Lane]) -> Self {
let lane: &str = lane;
Self {
lane: Utf8Bytes::from(lane.to_owned()),
lanes,
}
}
#[inline]
#[must_use]
pub fn lane(&self) -> &str {
self.lane.as_str()
}
#[inline]
#[must_use]
pub const fn lanes(&self) -> &'static [Lane] {
self.lanes
}
}
impl fmt::Display for UnroutableLane {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"the router asked for lane `{}`, which this corpus does not hold; it holds",
self.lane
)?;
if self.lanes.is_empty() {
return f.write_str(" no lanes at all");
}
for (at, lane) in self.lanes.iter().enumerate() {
let separator = if at == 0 { " " } else { ", " };
write!(f, "{separator}`{}`", &**lane.key())?;
}
Ok(())
}
}
impl core::error::Error for UnroutableLane {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FanError<E> {
Missing(RouterMissing),
Unroutable(UnroutableLane),
Router(E),
}
impl<E: fmt::Display> fmt::Display for FanError<E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Missing(missing) => missing.fmt(f),
Self::Unroutable(unroutable) => unroutable.fmt(f),
Self::Router(router) => write!(f, "the lane router refused: {router}"),
}
}
}
impl<E> core::error::Error for FanError<E>
where
E: core::error::Error + 'static,
{
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Missing(missing) => Some(missing),
Self::Unroutable(unroutable) => Some(unroutable),
Self::Router(router) => Some(router),
}
}
}