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
//! ASSEMBLY — what a DEPLOYMENT fills a declared tower's seats with, the gate that reads the filling
//! at boot, and the ONE call a resolver makes over the result.
//!
//! ```text
//! #[ingraph::tower]  ──▶  the WORDS   expand = "Synonyms" · route(router = …, slot = …) · annotate
//!                             │
//! the deployment     ──▶  the SEATS   Expansion::with_expander(…) · LaneFan::with_router(…) · a Door
//!                             │
//! TowerDoor::installed  ──▶  the GATE  every declared word must have found an instance  ← AT BOOT
//!                             │
//! the resolver       ──▶  the RUN     AssembledTower::run(&mut steps, question, options, asked)
//! ```
//!
//! [`tower`](super::tower) states what a tower IS ([`SearchTower`](super::SearchTower)) and what one
//! DECLARED ([`DeclaredTower`](super::DeclaredTower)). This module is the third row and it is about
//! neither a type nor a declaration: it is about a VALUE whose seats a deployment has filled.
//!
//! # THE THREE PARTIES, verbatim from the fold door
//!
//! The governance is [`FoldDoor`](crate::FoldDoor)'s, word for word, because it is the same question
//! asked one layer up — *who chooses what a search runs through*:
//!
//! - **the REQUEST never chooses an implementation.** Which expander widens a question and which
//!   router cuts it are facts about what the answer MEANS, and a client able to swap them per query
//!   is a client able to make two answers of one corpus that cannot be compared. Knobs are a
//!   different family and ride all three tiers — see the three-tier law at
//!   [`route_depth`](super::route_depth).
//! - **the DECLARATION chooses the DEFAULT**, through the words it writes: `expand = "Synonyms"`
//!   names the expander a deployment gets unless it names another, and `route(router = …)` names
//!   the router.
//! - **the DEPLOYMENT overrides at launch**, which is what this module is. It fills each seat with
//!   the instance it wants — the declared one or its own — and the same act that installs the tower
//!   installs the knobs it runs under.
//!
//! # THE GATE: a declared word whose seat is EMPTY is refused AT BOOT
//!
//! [`LaneFan::check`](crate::LaneFan::check)'s own guardrail, generalised to every word a tower
//! writes. A declaration that wrote `expand = "Synonyms"` and an assembly that mounted nothing
//! answers the UNWIDENED result, silently and for ever: the search is simply a little worse than the
//! declaration says it is, which is the hardest defect class there is to trace. So the assembly is
//! read once, at install, and every word that found no instance NAMES ITSELF — see
//! [`SeatsUnfilled`].
//!
//! **AND AN UNMOUNTED SEAT IS STILL THE IDENTITY ROAD**, which is not a contradiction of the above.
//! [`Expansion`](super::Expansion)'s absent expander is a real, supported state: a road with nothing
//! mounted answers `[the original]` and a tower walked over it is walked with the very question it
//! was handed. What the gate refuses is not that state — it is a state that DISAGREES WITH A
//! DECLARATION. A hand-written road that never wrote the word has nothing to disagree with and is
//! gated by nothing.
//!
//! **A TOWER THAT DECLARED NO WORD NEEDS NOTHING.** [`AssembledTower::check`] defaults to the honest
//! nothing, an unfanned tower's emitted gate answers `Ok(())` without reading a field, and the road
//! such a deployment walks is the road it always walked — the amendment's degenerate case, kept
//! degenerate at the assembly too.
//!
//! # THE RUN: one call, whatever the step count
//!
//! A tower's `walk` is an INHERENT fn whose arity is its step count, and a search recipe's expansion
//! has never seen the steps — so a resolver could not write the call, and until this row landed no
//! resolver did. [`AssembledTower::run`] is that call at a FIXED arity: the steps as one value, the
//! question, the DEPLOYMENT's knobs and the REQUEST's. The arity stays the tower macro's own
//! business, on the far side of a trait the macro implements.
//!
//! It is AWAITED whatever the walk's own face is. The caller is a resolver and a resolver is already
//! async, so a blocking tower's `run` wraps its blocking walk rather than making every caller ask
//! [`DeclaredTower::ALL_SYNC`](super::DeclaredTower::ALL_SYNC) which shape it is about to get — the
//! same one-call-seat division [`AsyncQueryExpander`](super::AsyncQueryExpander) already makes over
//! its blocking half. `ALL_SYNC` still answers the HAND-CALL road, where a caller spelling `walk`
//! itself needs to know.

use core::{fmt, future::Future};

use crate::route::RouterMissing;

use super::DeclaredTower;

#[cfg(test)]
mod tests;

/// **A TOWER WHOSE SEATS ARE FILLED** — the gate a deployment's assembly is read by, and the ONE
/// call a resolver makes over it.
///
/// Emitted by `#[ingraph::tower]` off the declaration's own words, and hand-writable by anybody: a
/// hand-written tower states its refusal type and calls its own walk, and inherits a gate that
/// refuses nothing.
///
/// # It is stated over the TOWER and spends the STEPS
///
/// Every method here takes [`Steps`](super::SearchTower::Steps) rather than `self`, which is
/// [`walk`]'s own shape one seam over: a tower is a TYPE that names a road and the steps are the
/// VALUE that walks it, and the two are only the same thing because today's declaration is its own
/// steps carrier. A deployment holding its steps somewhere else says so at that seat and every row
/// here follows it without moving.
///
/// [`walk`]: super::tower
#[diagnostic::on_unimplemented(
  message = "`{Self}` is not an assembled tower",
  label = "no assembly row",
  note = "`#[ingraph::tower]` emits this row beside the declaration's walk; a hand-written tower \
          writes `impl AssembledTower for {Self}` with its refusal type and a `run` that calls its \
          own walk"
)]
pub trait AssembledTower: DeclaredTower {
  /// **WHAT THIS TOWER REFUSES WITH** — the emitted `<Tower>Error` sum, one arm per step.
  ///
  /// Bound-free, per [`Serves::Error`](crate::Serves::Error)'s discipline: nothing is demanded of it
  /// here, and a caller that renders one demands what rendering needs where it renders. The emitted
  /// sum carries each step's own error unerased, so a `match` on an arm reaches the very type that
  /// step declared.
  type Refusal;

  /// **THE GATE** — every word this declaration wrote, read against the instance the assembly put in
  /// its seat.
  ///
  /// Spent at [`TowerDoor::installed`](crate::TowerDoor::installed), which is the one act a
  /// deployment performs for a tower, so the refusal lands at BOOT and names every gap at once
  /// rather than the first one.
  ///
  /// # It defaults to the honest nothing
  ///
  /// A tower that declared no fan word has no seat that could be empty, and a hand-written road has
  /// no declaration to disagree with. Both take this body and pay the gate nothing.
  ///
  /// # Errors
  ///
  /// [`SeatsUnfilled`], naming the tower and every declared word whose seat is empty.
  #[inline]
  fn check(steps: &Self::Steps) -> Result<(), SeatsUnfilled> {
    let _ = steps;
    Ok(())
  }

  /// **THE UNIFORM RUN** — the whole tower, at an arity that does not move with the step count.
  ///
  /// What a resolver calls, and the reason this trait exists: `walk` takes one `&mut` per step and a
  /// recipe's expansion cannot see the steps, so the walk's own face is unspellable across the
  /// expansion wall and this one is not.
  ///
  /// `options` is [`None`] where this call names nothing, at which every step runs at its own floor
  /// — the walk's own reading, unchanged.
  ///
  /// # `asked` IS TIER THREE, and composition happens INSIDE
  ///
  /// The DEPLOYMENT's knobs and the REQUEST's arrive as two parameters rather than one composed
  /// value, because composing them is the tower's own business and the tiers compose differently per
  /// knob: a PREFERENCE is request-supreme ([`ArmWeights::over`](crate::ArmWeights::over)) and a
  /// PROTECTIVE number may only tighten ([`tightened_budget`](crate::tightened_budget)). A caller
  /// that had to compose them would be a caller writing one of those laws a second time.
  ///
  /// [`None`] is *this request named nothing*, under which the deployment's own value stands
  /// unchanged — the defer-never-default law, at the outermost tier.
  ///
  /// It is taken BY VALUE where `options` is a borrow, and the asymmetry is the two clocks': the
  /// deployment's package is installed once and lent to every read, and a request's is built for
  /// this question and has nowhere else to be.
  ///
  /// # It is the ONE awaited seat in this crate that does NOT write `+ Send`, and that is MEASURED
  ///
  /// [`AsyncServes::serve`](crate::AsyncServes::serve) writes it, and so does every hook seam here
  /// that answers a boxed future. This one does not, because of WHO calls it: a recipe binds a tower
  /// by its TYPE PATH, so every call site in this framework names a CONCRETE tower and auto-trait
  /// leakage answers `Send` exactly where it is true — `ingraph/tests/tower_assembly.rs` runs one
  /// inside a real resolver, whose own future async-graphql demands be `Send`.
  ///
  /// What the bound would cost is a tower that has every right to exist: the `!Send` EXCLUSIVE MODEL
  /// this framework's own resident-hop chapter is about, held directly in a blocking tower's step
  /// rather than behind a door. Its walk compiles today, and a `Send` demand written at this seat
  /// would refuse its assembly row for a property no caller of it needs. Such a tower keeps both, and
  /// is refused only where it is asked to cross a resolver — which is where the demand genuinely is.
  fn run(
    steps: &mut Self::Steps,
    question: Self::Question,
    options: Option<&Self::StepOptions>,
    asked: Option<Self::SearchOptions>,
  ) -> impl Future<Output = Result<Self::Answer, Self::Refusal>>;

  /// **THE ONE ROW OF A REQUEST'S PACKAGE THAT IS SPENT OUTSIDE THE WALK** — how long this request
  /// is willing to wait, or [`None`] where it named nothing.
  ///
  /// Every other row of [`SearchOptions`](super::DeclaredTower::SearchOptions) composes INSIDE
  /// [`run`](Self::run), where the deployment's own value is in hand. The walk budget cannot: it is
  /// enforced by racing the whole run against a clock, so the number has to be read BEFORE the run
  /// is built. [`walk_within`](super::walk_within) is that race and this is the projection it is fed
  /// through — the composition itself stays [`tightened_budget`](super::tightened_budget)'s, spent
  /// there and nowhere else.
  ///
  /// # It defaults to the honest nothing, exactly as [`check`](Self::check) does
  ///
  /// A hand-written tower whose request face carries no budget — `()`, or a package of its own —
  /// takes this body and publishes no budget road. Nothing is lost by it: a request that cannot name
  /// a budget is a request the deployment's own wall stands alone for, which is what every road did
  /// before this seat existed.
  #[inline]
  fn asked_budget(asked: Option<&Self::SearchOptions>) -> Option<jiff::SignedDuration> {
    let _ = asked;
    None
  }
}

/// **WHAT A DECLARATION ASKED FOR AND AN ASSEMBLY DID NOT PROVIDE** — the boot refusal, naming every
/// gap at once.
///
/// [`RouterMissing`]'s twin at the tower's grain, and it carries that refusal whole wherever the gap
/// is a crossing's: a vocabulary a seat already publishes is never restated here, which is the
/// [`FanError`](crate::FanError) discipline the tower's own refusal sum already keeps.
///
/// # EVERY gap, and never the first
///
/// A deployment fixing an assembly wants the whole list: a tower with an unmounted expander AND an
/// unmounted router is two lines in one launch rather than two launches. So the gate collects and
/// this type holds a roster.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SeatsUnfilled {
  /// The tower whose assembly this is about, as its own declaration spells it.
  tower: &'static str,
  /// The declared words that found no instance, in declaration order.
  unfilled: Vec<UnfilledSeat>,
}

impl SeatsUnfilled {
  /// **THE GATE'S ONE AUTHORITY**: an empty roster is an assembly that answered every word, and
  /// anything else is this refusal.
  ///
  /// A constructor that answers a [`Result`] rather than a value, because *nothing unfilled is not a
  /// refusal* is the law itself and a law spelled at each emitted gate is a law each gate could get
  /// wrong.
  ///
  /// # Errors
  ///
  /// Where `unfilled` names anything at all.
  #[inline]
  pub fn checked(tower: &'static str, unfilled: Vec<UnfilledSeat>) -> Result<(), Self> {
    if unfilled.is_empty() {
      return Ok(());
    }
    Err(Self { tower, unfilled })
  }

  /// The tower whose assembly was read.
  #[inline]
  #[must_use]
  pub const fn tower(&self) -> &'static str {
    self.tower
  }

  /// Every declared word that found no instance, in declaration order — NEVER EMPTY, by
  /// [`checked`](Self::checked)'s own construction.
  #[inline]
  #[must_use]
  pub fn unfilled(&self) -> &[UnfilledSeat] {
    &self.unfilled
  }
}

impl fmt::Display for SeatsUnfilled {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    write!(
      f,
      "`{tower}` declares {count} stage {word} its assembly left unfilled",
      tower = self.tower,
      count = self.unfilled.len(),
      word = if self.unfilled.len() == 1 {
        "seat"
      } else {
        "seats"
      },
    )?;
    for (at, seat) in self.unfilled.iter().enumerate() {
      let separator = if at == 0 { ": " } else { "; " };
      write!(f, "{separator}{seat}")?;
    }
    Ok(())
  }
}

impl core::error::Error for SeatsUnfilled {}

/// **ONE DECLARED WORD WHOSE SEAT IS EMPTY** — which step, which word, and what the assembly owed
/// it.
///
/// # There are TWO arms and the third stage has none, which is an ANSWER
///
/// ⟂ `annotate` mounts an ORDINARY SERVER at an ordinary field, so a deployment that left it out
/// wrote a struct literal missing a field: `E0063`, at the assembly, before anything boots. A gate
/// arm for it would be a runtime check standing behind a compile error that has already fired. ②
/// and ④ are here because their seats are TYPES THAT HOLD AN OPTION — a road with no expander and a
/// fan with no router are both perfectly constructible values — so the compiler has nothing to say
/// about them and this does.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum UnfilledSeat {
  /// ② A `expand = "…"` word whose [`Expansion`](super::Expansion) mounts nothing.
  Widening {
    /// The step that declared it — the field a deployment fills.
    step: &'static str,
    /// The expander the declaration named, as it was written.
    expander: &'static str,
  },
  /// ④ A `route(…)` word whose [`LaneFan`](crate::LaneFan) has a choice and nothing to make it
  /// with.
  Crossing {
    /// The step that declared it.
    step: &'static str,
    /// The fan's own refusal, carried whole — the roster and both escapes, in the sentence
    /// [`LaneFan::check`](crate::LaneFan::check) already writes.
    missing: RouterMissing,
  },
}

impl UnfilledSeat {
  /// ② The widening gap at `step`, whose declaration named `expander`.
  #[inline]
  #[must_use]
  pub const fn widening(step: &'static str, expander: &'static str) -> Self {
    Self::Widening { step, expander }
  }

  /// ④ The crossing gap at `step`, carrying the fan's own refusal.
  #[inline]
  #[must_use]
  pub const fn crossing(step: &'static str, missing: RouterMissing) -> Self {
    Self::Crossing { step, missing }
  }

  /// The STEP this gap is about — the field a deployment fills to close it.
  #[inline]
  #[must_use]
  pub const fn step(&self) -> &'static str {
    match self {
      Self::Widening { step, .. } | Self::Crossing { step, .. } => step,
    }
  }

  /// The WORD the declaration wrote at that step — the stage's own spelling.
  #[inline]
  #[must_use]
  pub const fn word(&self) -> &'static str {
    match self {
      Self::Widening { .. } => "expand",
      Self::Crossing { .. } => "route",
    }
  }
}

impl fmt::Display for UnfilledSeat {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    match self {
      Self::Widening { step, expander } => write!(
        f,
        "the `{step}` step declares `expand = \"{expander}\"` and its seat mounts nothing; a \
         deployment fills it — `Expansion::new().with_expander(Box::new({expander}))`",
      ),
      Self::Crossing { step, missing } => {
        write!(f, "the `{step}` step declares `route(…)` and {missing}")
      }
    }
  }
}