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
//! What the tower door PROMISES: that a lookup finds the road a deployment installed, that a
//! deployment that installed none is REFUSED by name, that each read gets its OWN road, and that the
//! gate is spent at the install rather than at the question.

use core::{future::Future, pin::Pin, time::Duration};

use std::sync::{
  Arc,
  atomic::{AtomicUsize, Ordering},
};

use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};
use jiff::SignedDuration;

use super::{TowerDoor, installed_road};
use crate::{
  AssembledTower, DeclaredTower, Lane, LaneIdent, RouterMissing, SearchBudget, SearchTower,
  SeatsUnfilled, UnfilledSeat, WalkBudget, WalkClock,
};

/// The corpus the crossing gap's refusal is written about.
static CORPUS: &[Lane] = &[
  Lane::of(LaneIdent::new("en")),
  Lane::of(LaneIdent::new("ja")),
];

/// A tower whose steps COUNT their own mints, so *one road per read* is a number rather than a
/// claim. Written out rather than declared, because what is under test is the citizen and a
/// declaration would put an expansion between the claim and it.
struct Road;

/// Its steps: a shared tally the mint bumps, and the per-road counter a run bumps.
struct RoadSteps {
  minted: Arc<AtomicUsize>,
  walked: usize,
}

impl SearchTower for Road {
  type Question = String;
  type Answer = String;
  type Steps = RoadSteps;
}

impl DeclaredTower for Road {
  type StepOptions = String;
  type SearchOptions = ();
}

impl AssembledTower for Road {
  type Refusal = core::convert::Infallible;

  async fn run(
    steps: &mut Self::Steps,
    question: Self::Question,
    options: Option<&Self::StepOptions>,
    _asked: Option<Self::SearchOptions>,
  ) -> Result<Self::Answer, Self::Refusal> {
    steps.walked += 1;
    Ok(format!(
      "{question}/{walked}/{named}",
      walked = steps.walked,
      named = options.map_or("none", String::as_str),
    ))
  }
}

/// A tower that DECLARED an awaited step, which is the only kind that may carry a budget seat.
struct Awaited;

impl SearchTower for Awaited {
  type Question = String;
  type Answer = String;
  type Steps = ();
}

impl DeclaredTower for Awaited {
  type StepOptions = ();
  type SearchOptions = ();

  const ALL_SYNC: bool = false;
}

impl AssembledTower for Awaited {
  type Refusal = core::convert::Infallible;

  async fn run(
    _steps: &mut Self::Steps,
    question: Self::Question,
    _options: Option<&Self::StepOptions>,
    _asked: Option<Self::SearchOptions>,
  ) -> Result<Self::Answer, Self::Refusal> {
    Ok(question)
  }
}

/// A clock with no patience — every budget is already spent. The seat's own suite races it; this
/// file only needs a value to fill the seat with.
struct Spent;

impl WalkClock for Spent {
  fn elapsed<'a>(&'a self, _budget: Duration) -> Pin<Box<dyn Future<Output = ()> + Send + 'a>> {
    Box::pin(core::future::ready(()))
  }
}

/// A tower whose GATE refuses, standing in for a declaration whose words found no instances.
struct Unfilled;

impl SearchTower for Unfilled {
  type Question = String;
  type Answer = String;
  type Steps = ();
}

impl DeclaredTower for Unfilled {
  type StepOptions = ();
  type SearchOptions = ();
}

impl AssembledTower for Unfilled {
  type Refusal = core::convert::Infallible;

  fn check(_steps: &Self::Steps) -> Result<(), SeatsUnfilled> {
    SeatsUnfilled::checked(
      "Unfilled",
      vec![
        UnfilledSeat::widening("widen", "Synonyms"),
        UnfilledSeat::crossing("fan", RouterMissing::new(CORPUS)),
      ],
    )
  }

  async fn run(
    _steps: &mut Self::Steps,
    question: Self::Question,
    _options: Option<&Self::StepOptions>,
    _asked: Option<Self::SearchOptions>,
  ) -> Result<Self::Answer, Self::Refusal> {
    Ok(question)
  }
}

/// The root that reads the door back, so every claim is made through the same lookup an emitted
/// resolver makes.
struct Root;

#[Object]
impl Root {
  /// The tower's answer for `asked`, looked up and run exactly as an emitted resolver does.
  async fn walked(&self, ctx: &Context<'_>, asked: String) -> async_graphql::Result<String> {
    let (mut steps, options, _wall) = installed_road::<Road>(ctx, "walked")?;
    Ok(
      Road::run(&mut steps, asked, options, None)
        .await
        .expect("this road refuses nothing"),
    )
  }
}

fn schema(door: Option<TowerDoor<Road>>) -> Schema<Root, EmptyMutation, EmptySubscription> {
  let builder = Schema::build(Root, EmptyMutation, EmptySubscription);
  match door {
    Some(door) => door.install(builder).finish(),
    None => builder.finish(),
  }
}

fn road(minted: &Arc<AtomicUsize>) -> TowerDoor<Road> {
  let tally = Arc::clone(minted);
  TowerDoor::<Road>::installed(move || {
    tally.fetch_add(1, Ordering::Relaxed);
    RoadSteps {
      minted: Arc::clone(&tally),
      walked: 0,
    }
  })
  .expect("this road declares nothing that could be missing")
}

async fn asked(schema: &Schema<Root, EmptyMutation, EmptySubscription>) -> async_graphql::Response {
  schema.execute("{ walked(asked: \"harbour\") }").await
}

/// **A DEPLOYMENT THAT INSTALLED NO ROAD IS REFUSED BY NAME**, and the sentence names the field that
/// went looking, the tower it wanted, and the line that is missing.
#[tokio::test]
async fn an_uninstalled_tower_refuses_and_names_the_install_line() {
  let answer = asked(&schema(None)).await;

  let said = answer
    .errors
    .first()
    .map(|refusal| refusal.message.clone())
    .expect("a road nobody installed cannot be walked");

  assert!(said.contains("`walked`"), "{said}");
  assert!(said.contains("Road"), "{said}");
  assert!(said.contains("TowerDoor::<"), "{said}");
  assert!(said.contains("installed"), "{said}");
}

/// **THE LOOKUP FINDS THE ROAD, AND THE RUN IS THE ANSWER** — the whole of lookup-and-run, through a
/// real schema.
#[tokio::test]
async fn an_installed_road_is_looked_up_and_run() {
  let minted = Arc::new(AtomicUsize::new(0));
  let answer = asked(&schema(Some(road(&minted)))).await;

  assert!(answer.errors.is_empty(), "{:?}", answer.errors);
  assert!(answer.data.to_string().contains("harbour/1/none"));
}

/// **ONE ROAD PER READ** — the mint is called once per question, and no read ever sees another
/// read's steps.
#[tokio::test]
async fn every_read_mints_its_own_road() {
  let minted = Arc::new(AtomicUsize::new(0));
  let schema = schema(Some(road(&minted)));

  for _ in 0..3 {
    let answer = asked(&schema).await;
    assert!(answer.errors.is_empty(), "{:?}", answer.errors);
    // `walked` is 1 EVERY TIME: a road that were shared would count up.
    assert!(answer.data.to_string().contains("harbour/1/none"));
  }

  // Three reads, plus the one the gate itself minted at install.
  assert_eq!(minted.load(Ordering::Relaxed), 4);
}

/// **TIER TWO RIDES THE DOOR** — the knobs a launch named once reach the run beside the steps, out of
/// ONE lookup.
#[tokio::test]
async fn the_deployments_own_knobs_arrive_with_the_road() {
  let minted = Arc::new(AtomicUsize::new(0));
  let door = road(&minted).with_step_options("launch".to_owned());
  let answer = asked(&schema(Some(door))).await;

  assert!(answer.errors.is_empty(), "{:?}", answer.errors);
  assert!(answer.data.to_string().contains("harbour/1/launch"));
}

/// **THE GATE RUNS AT INSTALL** — a declaration whose words found no instances never reaches a
/// schema, and the refusal names every gap.
#[test]
fn the_gate_refuses_at_the_install_and_names_every_gap() {
  let refused =
    TowerDoor::<Unfilled>::installed(|| ()).expect_err("two declared words, two empty seats");

  let said = refused.to_string();
  assert_eq!(refused.unfilled().len(), 2);
  assert!(said.contains("`widen`"), "{said}");
  assert!(said.contains("`fan`"), "{said}");
}

/// The DEBUG line names which tower's road it is and whether a launch named knobs — the two facts an
/// erased mint leaves it able to state.
#[test]
fn the_debug_line_names_the_tower_and_whether_knobs_were_named() {
  let minted = Arc::new(AtomicUsize::new(0));
  let rendered = format!("{:?}", road(&minted).with_step_options("launch".to_owned()));

  assert!(rendered.contains("TowerDoor"), "{rendered}");
  assert!(rendered.contains("Road"), "{rendered}");
  assert!(rendered.contains("options: true"), "{rendered}");
  // A DOOR THAT NAMED NO BUDGET SAYS SO, which is the absence this seat rests on.
  assert!(rendered.contains("budget: None"), "{rendered}");
}

/// **TIER TWO'S PROTECTIVE NUMBER RIDES THE SAME DOOR** — named beside the mint, handed back beside
/// the steps, and printed as the numbers rather than as the erased clock.
#[test]
fn the_budget_seat_holds_what_the_launch_named() {
  let wall = SignedDuration::from_secs(30);
  let door = TowerDoor::<Awaited>::installed(|| ())
    .expect("this tower declares nothing that could be missing")
    .with_budget(WalkBudget::new(Spent, SearchBudget::new().with_walk(wall)));

  assert_eq!(
    door.budget().map(|seat| seat.budget().walk()),
    Some(Some(wall)),
  );

  let rendered = format!("{door:?}");
  assert!(rendered.contains("WalkBudget"), "{rendered}");
  assert!(rendered.contains("30s"), "{rendered}");
}

/// **AND BACK TO NOTHING** — the in-place form takes an [`Option`] so a holder narrowing a door it
/// was handed can clear the seat, exactly as it can clear the knobs.
#[test]
fn a_budget_seat_can_be_cleared_after_construction() {
  let mut door = TowerDoor::<Awaited>::installed(|| ())
    .expect("this tower declares nothing that could be missing")
    .with_budget(WalkBudget::new(Spent, SearchBudget::new()));

  assert!(door.budget().is_some());
  door.set_budget(None);
  assert!(door.budget().is_none());
}

/// The steps a mint hands out carry the tally they were built from, which is what makes the count
/// above a fact about the road rather than about the closure alone.
#[test]
fn a_minted_road_holds_what_its_deployment_gave_it() {
  let minted = Arc::new(AtomicUsize::new(0));
  let door = road(&minted);
  let steps = door.mint();

  assert!(Arc::ptr_eq(&steps.minted, &minted));
  assert_eq!(steps.walked, 0);
}