ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! [`LaneFan`] — where a router mounts, and where the three guardrails are enforced.

use core::fmt;

use smol_bytes::Utf8Bytes;

use crate::Lane;

use super::{LaneRouter, RoutedProbe};

#[cfg(test)]
mod tests;

/// **THE ROUTER'S SEAT** — a roster, the router that chooses between its lanes, and the guardrails
/// that stand between them.
///
/// ```
/// use ingraph::{Lane, LaneFan, LaneIdent, ScriptRouter};
///
/// static CORPUS: &[Lane] = &[
///   Lane::of(LaneIdent::new("en")).accepting(&[LaneIdent::new("latn")]),
///   Lane::of(LaneIdent::new("zh")).accepting(&[LaneIdent::new("hani")]),
/// ];
///
/// let fan = LaneFan::new(CORPUS).with_router(ScriptRouter::new(CORPUS));
/// fan.check().expect("a fanned corpus with a router mounted");
///
/// let dispatches = fan.route("hello 世界").expect("both scripts reach a lane");
/// assert_eq!(dispatches.len(), 2);
/// ```
///
/// # THE SEAT IS TYPED, and there is no `Box` at the door
///
/// A router is a CAPABILITY rather than a policy — what it is wired to is checked by equality at the
/// declaration, so erasing it would delete the very check the shape exists for. That is the whole of
/// what separates this mount from the expand step's, which is assembled from a deployment's words
/// and therefore erased. Two seams, two dispositions, and the taxonomy is written down so that
/// neither follows the other.
///
/// The [`with_`](Self::with_router) / [`set_`](Self::set_router) pair is the house's, and
/// [`set_router`](Self::set_router) takes an [`Option`] so that *mount nothing* stays sayable after
/// construction — [`Flow::set_limit`](crate::Flow::set_limit)'s own law.
///
/// # AN UNFANNED CORPUS HAS NO FAN
///
/// A corpus with one lane needs nothing to choose between, so it does not mount one of these at all
/// — it reads its one lane exactly as it did before lanes existed. What this type is for is the
/// corpus that HAS a choice, and [`check`](Self::check) is what refuses one that has a choice and
/// nothing to make it with.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct LaneFan<T> {
  /// The lanes a question may be routed into.
  lanes: &'static [Lane],
  /// The router that chooses between them, where one is mounted.
  router: Option<T>,
}

impl<T> LaneFan<T> {
  /// A fan over `lanes`, with nothing mounted.
  #[inline]
  #[must_use]
  pub const fn new(lanes: &'static [Lane]) -> Self {
    Self {
      lanes,
      router: None,
    }
  }

  /// The same fan, routed by `router`.
  #[inline]
  #[must_use]
  pub fn with_router(mut self, router: T) -> Self {
    self.set_router(Some(router));
    self
  }

  /// [`with_router`](Self::with_router), in place — INCLUDING back to nothing.
  #[inline]
  pub fn set_router(&mut self, router: Option<T>) -> &mut Self {
    self.router = router;
    self
  }

  /// The mounted router, or [`None`].
  #[inline]
  #[must_use]
  pub const fn router(&self) -> Option<&T> {
    self.router.as_ref()
  }

  /// The lanes this fan routes into.
  #[inline]
  #[must_use]
  pub const fn lanes(&self) -> &'static [Lane] {
    self.lanes
  }

  /// **GUARDRAIL ①, AT BOOT: a corpus with a choice must have something to make it with.**
  ///
  /// Several lanes and no router is refused, and the refusal happens at boot rather than at the
  /// first question — because the failure it prevents is silent. A fan that answered anyway would
  /// have to pick a lane, every choice available to it is arbitrary, and the result is a search that
  /// quietly misses whatever lives in the lanes it did not ask. Months later that reads as *our
  /// search is bad*, which is the hardest kind of defect to trace.
  ///
  /// A corpus with ONE lane passes with nothing mounted: there is no choice to make, so there is
  /// nothing to refuse for the want of.
  ///
  /// # The refusal names BOTH escapes
  ///
  /// [`ScriptWeightedFan`](crate::ScriptWeightedFan) is the recommended one — every lane asked, the
  /// question's own lanes weighted — and [`FanAll`](crate::FanAll) is the flat one. Naming them both
  /// is what keeps this a guardrail rather than an obstacle: a reader who hits it is told the two
  /// answers, not merely that the arrangement is wrong.
  ///
  /// # It is a FUNCTION, spent at three vantages
  ///
  /// [`lane_collisions`](crate::lane_collisions)' own posture: a declaration's expansion may spend
  /// it, a boot walk spends it over the slots it is about to make, and a downstream's test spends it
  /// over a fan built by hand. One implementation, no second opinion.
  ///
  /// # Errors
  ///
  /// [`RouterMissing`] naming the roster and the built-in that answers it.
  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> {
  /// **SPLIT `question` INTO ONE DISPATCH PER LANE**, with every guardrail applied.
  ///
  /// The router does the choosing; this checks its work against the roster it was declared beside,
  /// because the two are written by different parties and can drift.
  ///
  /// # What each answer means
  ///
  /// - **A non-empty `Vec`** — one independent dispatch each, in the router's own order. The order
  ///   does not enter any score; it is the stable tie order the fold's sort preserves.
  /// - **An EMPTY `Vec`** — guardrail ③. A question with nothing in it for this corpus reached no
  ///   lane, which is the empty set and not a refusal: no streams, an empty answer, and nothing
  ///   invented to fill the silence.
  /// - **[`FanError::Unroutable`]** — guardrail ②. A probe named a lane this corpus does not hold.
  /// - **[`FanError::Missing`]** — nothing is mounted. A corpus that never had a choice does not
  ///   call this at all; one that does and did not mount a router should have been refused by
  ///   [`check`](Self::check) at boot, and this is the same refusal reaching the question it would
  ///   otherwise have answered wrongly.
  /// - **[`FanError::Router`]** — the router's own refusal, carried whole.
  ///
  /// # Errors
  ///
  /// [`FanError`], one arm per cause.
  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)?;

    // GUARDRAIL ②, checked here rather than trusted: a router is a third party's type and the
    // roster is the declaration's, so a probe naming a lane nobody declared is caught where both are
    // in hand — instead of as a read against an index that does not exist.
    for probe in &routed {
      if !self.holds(probe.lane()) {
        return Err(FanError::Unroutable(UnroutableLane::new(
          probe.lane(),
          self.lanes,
        )));
      }
    }

    Ok(routed)
  }

  /// Whether this corpus holds a lane by that key.
  fn holds(&self, key: &crate::LaneIdent) -> bool {
    self.lanes.iter().any(|lane| **lane.key() == **key)
  }
}

/// **THE ④ SEGMENT TAKES NO KNOBS**, and the empty seat is a CENSUS ANSWER rather than a gap.
///
/// The crossing's one number is the LANE EMPHASIS, and the router already owns it:
/// [`ScriptWeightedFan::with_emphasis`](crate::ScriptWeightedFan::with_emphasis) sets it and every
/// dispatch carries it out on [`RoutedProbe::weight`]. A row here would be a second home for a
/// number that has one, and two homes for one fact is what the fold would then have to pick between.
///
/// So a crossing step's row in a tower's emitted options is zero-sized and read by nobody — which is
/// what `()` means at this seat everywhere else in this crate.
#[cfg(feature = "runtime")]
impl<T> crate::Serve for LaneFan<T> {
  type Options = ();
}

/// **THE CROSSING, STATED ONCE AT THE SEAT** — a question in, ONE DISPATCH out, so a tower's
/// `answer = "…"` is omissible at a ④ step.
///
/// # The answer is the whole [`RoutedProbe`] and never the bare probe
///
/// A lane's read is scoped BY THE LANE — the shipped full-text emission keys one column per lane, so
/// a routed read reaches its corpus through `FulltextSubset::These(&[the lane's column])` — and a
/// step handed the probe alone would have to guess which lane it was cut for. So the dispatch
/// crosses whole: the lane, the probe and the weight, in the carrier the router already answered in.
///
/// # The question is the router's, OWNED
///
/// A router may be asked through an unsized borrow ([`ScriptRouter`](crate::ScriptRouter) takes
/// `str`), and a tower's steps hand VALUES along, so the canonical question here is the owned form —
/// which is exactly what the step before a crossing can produce. The borrow back down to the
/// router's own question type costs nothing and cannot fail: [`ToOwned`] already guarantees
/// `Owned: Borrow<Self>`.
#[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>;
}

/// **A CORPUS WITH A CHOICE AND NOTHING TO MAKE IT WITH** — guardrail ①'s refusal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RouterMissing {
  /// The lanes that had nothing to choose between them.
  lanes: &'static [Lane],
}

impl RouterMissing {
  /// The refusal for a fan over `lanes` with nothing mounted.
  #[inline]
  #[must_use]
  pub const fn new(lanes: &'static [Lane]) -> Self {
    Self { lanes }
  }

  /// The lanes that had nothing to choose between them.
  #[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 {}

/// **A PROBE NAMED A LANE THIS CORPUS DOES NOT HOLD** — guardrail ②'s refusal.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnroutableLane {
  /// The key the router asked for — OWNED, because a refusal outlives the borrow that produced it.
  lane: Utf8Bytes,
  /// The roster it was not in.
  lanes: &'static [Lane],
}

impl UnroutableLane {
  /// The refusal for `lane` against `lanes`.
  #[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,
    }
  }

  /// The key the router asked for.
  #[inline]
  #[must_use]
  pub fn lane(&self) -> &str {
    self.lane.as_str()
  }

  /// The roster it was not in.
  #[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 {}

/// **HOW A FAN REFUSES** — one arm per cause, carrying each whole.
///
/// The emitted `<Tower>Error`'s own shape one road over: a walk with several ways to fail answers a
/// sum rather than an erasure, so a caller may match on which of them happened and reach the router's
/// own error type without a downcast.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum FanError<E> {
  /// Nothing was mounted — guardrail ①, reaching a question.
  Missing(RouterMissing),
  /// The router named a lane this corpus does not hold — guardrail ②.
  Unroutable(UnroutableLane),
  /// The router's own refusal, carried whole.
  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),
    }
  }
}