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
//! ONE PARTY, ONE CLASS — the settle seat read once, at every schedule a party can keep.
//!
//! The shutdown report has two classes of party: the ones it names as un-settled, and the ones whose
//! goodbye it carries a row for. Both are written from ONE reading of the settle seat, so a party is
//! in exactly one of them however it was scheduled — and the claims below are that fact driven
//! rather than hoped for.
//!
//! # The window these pin
//!
//! The report used to read the seat TWICE: a look, to count who had not settled, and a take further
//! down, to build the teardown chain. A party settling between the two was un-settled by the first
//! reading and holding an un-said goodbye by the second — named in BOTH classes, which is a fact
//! about the reader rather than about the world.
//!
//! # Driving it, rather than racing for it
//!
//! The window had exactly one synchronous hook, and it is what makes these deterministic: the stop
//! lets go of its own TASK handles between the two readings, and a task is a boxed future whose drop
//! runs whatever it captured. So a task that settles a party as it is dropped settles it INSIDE the
//! window, on the stop's own thread, at a point the stop schedules — no thread has to win anything.
//! That is
//! [`a_party_that_settles_inside_the_window_is_named_once_and_not_twice`], and it fails against the
//! two-reading shape.
//!
//! The other schedules a party can keep are driven the same way one step out — a SOURCE whose
//! stopping is a party's settlement lands it after the wave has begun and before the seat is read —
//! and the seat's own two instants are held apart by hand in
//! [`the_seat_is_read_once_so_a_party_that_settles_mid_read_lands_in_one_class`], which is the
//! mechanism under all of them.

use core::{any::Any, error::Error};

use jiff::SignedDuration;

use super::{
  App, Enrolled, Farewell, Stopped, Untorn,
  teardown::{Collected, collected},
};

use crate::{AsyncTeardown, Resources, Shutdown, Taps, drive::engine::Join};

/// THE INVARIANT ITSELF, asserted over a whole report: nobody is named twice.
///
/// The universal the classes' disjointness amounts to, spelled once and spent by every claim below,
/// so a report that started naming a party in both would fail wherever it was built rather than only
/// where a count happened to notice.
fn one_class_each(stopped: &Stopped) {
  let unsettled: Vec<&str> = stopped.unsettled().map(|name| name.as_str()).collect();
  for row in stopped.untorn() {
    assert!(
      !unsettled.contains(&row.name().as_str()),
      "`{}` is named in both classes, which is the report inventing a fact: {stopped}",
      row.name().as_str()
    );
  }
}

fn named(rows: &[Untorn]) -> Vec<&str> {
  rows.iter().map(|row| row.name().as_str()).collect()
}

/// A value with nothing to do on the way out, so a goodbye can be enrolled without a second thing
/// under test.
struct Nothing;

impl AsyncTeardown for Nothing {
  async fn teardown(self) -> Result<(), Box<dyn Error + Send + Sync>> {
    Ok(())
  }
}

fn goodbye(name: &'static str) -> Farewell {
  Farewell::new(name, Nothing)
}

/// A party that settles WHEN THIS IS DROPPED, handing over a goodbye as it goes.
///
/// The whole schedule apparatus below: what decides when the party settles is where the stop lets go
/// of the thing holding it, and the stop lets go of its parts in a fixed order.
struct SettlesAsItGoes(Option<Enrolled>);

impl Drop for SettlesAsItGoes {
  fn drop(&mut self) {
    if let Some(enrolled) = self.0.take() {
      enrolled.settle_saying(Box::pin(async { Ok(()) }));
    }
  }
}

/// A started SOURCE whose stopping is a party's settlement — step 2 of the stop, so the party
/// settles after the wave has begun and before the seat is read.
fn source_that_settles(enrolled: Enrolled) -> Box<dyn Any + Send> {
  Box::new(SettlesAsItGoes(Some(enrolled)))
}

/// A TASK the framework spawned onto the app's own runtime, which settles a party as the stop lets
/// go of it — and that is the ε window's own instant.
///
/// The abort road drops its tasks, and under the two-reading shape that drop sat BETWEEN the look
/// and the take: the look had already written this party into the un-settled class, and the take
/// that followed picked up the goodbye it hands over here, giving it a row as well.
///
/// The future is never polled. What it is for is its DROP, which is where the stop reaches it.
fn task_that_settles(enrolled: Enrolled) -> Join {
  let settling = SettlesAsItGoes(Some(enrolled));
  Box::pin(async move {
    drop(settling);
  })
}

/// A world with no bodies and no edges — what is under test is the REPORT, and a graph would only be
/// a second thing able to decide who settled.
fn world(
  shutdown: Shutdown,
  sources: Vec<Box<dyn Any + Send>>,
  tasks: Vec<Join>,
  teardowns: Vec<Farewell>,
) -> App<()> {
  App::new(
    std::sync::Arc::new(Resources::new()),
    shutdown,
    Taps::new(),
    std::sync::Arc::new(crate::Registries::default()),
    Vec::new(),
    sources,
    // No mounted ORIGIN: what is under test is the report, and an origin would be a second thing
    // able to decide who settled.
    Vec::new(),
    Vec::new(),
    tasks,
    teardowns,
    std::collections::HashMap::new(),
    std::collections::HashMap::new(),
    std::collections::HashMap::new(),
  )
}

/// **THE ε WINDOW, DRIVEN.** A party settles at the one instant that used to be between the report's
/// two readings, and the report names it ONCE.
///
/// The stop's own drop of its task handles is that instant, so this is the window's schedule pinned
/// rather than raced for. Against the two-reading shape `decode` is named as un-settled by the look
/// and given an un-said row by the take, and [`one_class_each`] is what says so.
#[test]
fn a_party_that_settles_inside_the_window_is_named_once_and_not_twice() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let scenes = shutdown.register("scenes");

  let stopped = world(
    shutdown,
    Vec::new(),
    vec![task_that_settles(decode)],
    Vec::new(),
  )
  .abort();

  one_class_each(&stopped);
  let unanswered: Vec<&str> = stopped.unsettled().map(|name| name.as_str()).collect();
  assert_eq!(
    unanswered,
    ["decode", "scenes"],
    "the seat was read before either of them had settled, so both are named: {stopped}"
  );
  assert_eq!(
    stopped.settled() + unanswered.len(),
    2,
    "and the registry's `N` is spent exactly once: {stopped}"
  );
  assert!(
    stopped.untorn().is_empty(),
    "a goodbye handed over after the reading is one nothing collected — and a party already named \
     un-settled does not also get a row: {stopped}"
  );
  drop(scenes);
}

/// **THE WINDOW'S TWO INSTANTS, HELD APART BY HAND.** The mechanism under everything above: the
/// class a party is in is decided by the TAKE, and the look before it is read by nobody.
#[test]
fn the_seat_is_read_once_so_a_party_that_settles_mid_read_lands_in_one_class() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  shutdown.register("scenes").settle();

  // THE LOOK — the window's first instant. `decode` is still running, and this is the reading that
  // used to write its name into the un-settled class.
  assert!(
    !shutdown.parties()[0].settled(),
    "the look finds it still running, which is the window's first instant"
  );

  // THE WINDOW: it settles HERE, after the look and before the collection, handing over a goodbye.
  decode.settle_saying(Box::pin(async { Ok(()) }));

  // THE TAKE — the window's second instant, and now the only one either class is written from.
  let Collected { chain, unsettled } = collected(&shutdown);

  assert!(
    unsettled.is_empty(),
    "the take found the settlement, so the party is ANSWERED — and the look that preceded it names \
     nobody, because nothing reads it"
  );
  let rows: Vec<Untorn> = chain.into_iter().map(Farewell::unsaid).collect();
  assert_eq!(
    named(&rows),
    ["decode"],
    "its goodbye is the one row: the party is in this class INSTEAD of the other, not as well"
  );
}

/// A party that had settled SILENTLY is in neither class, which is what the shipped posture costs —
/// and it is why the row count is not the settled count.
#[test]
fn a_silent_settlement_is_answered_and_in_neither_class() {
  let mut shutdown = Shutdown::new();
  shutdown.register("decode").settle();

  let Collected { chain, unsettled } = collected(&shutdown);

  assert!(unsettled.is_empty(), "it settled, so it is not abandoned");
  assert!(
    chain.is_empty(),
    "and it said nothing, so it is not a row either: no name, no allocation"
  );
}

/// A party that never settled is in the un-settled class ALONE — the seat was empty when it was
/// read, so nothing further down can give it a row.
#[test]
fn a_party_that_never_settles_is_named_once_and_hands_over_no_row() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");

  let stopped = world(shutdown, Vec::new(), Vec::new(), vec![goodbye("pool")]).abort();

  one_class_each(&stopped);
  assert_eq!(stopped.settled(), 0);
  let unanswered: Vec<&str> = stopped.unsettled().map(|name| name.as_str()).collect();
  assert_eq!(unanswered, ["decode"]);
  assert_eq!(
    named(stopped.untorn()),
    ["pool"],
    "the only row is the launch's OWN enrolment — a party that handed nothing over has none"
  );
  drop(decode);
}

/// **THE ABORT, one step earlier in the schedule.** A party settles as the sources stop, and the
/// report answers it once.
///
/// The abort is the road the window lived on: it says no goodbye at all, so every collected
/// settlement becomes an un-said row — which is exactly the class a party that was also named
/// un-settled would have been named in twice.
#[test]
fn a_party_that_settles_during_an_abort_is_answered_and_never_also_abandoned() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  shutdown.register("scenes").settle();

  let stopped = world(
    shutdown,
    vec![source_that_settles(decode)],
    Vec::new(),
    Vec::new(),
  )
  .abort();

  one_class_each(&stopped);
  assert_eq!(
    stopped.settled(),
    2,
    "the mid-stop settler answered, and the registry counts it as answered: {stopped}"
  );
  assert_eq!(
    stopped.unsettled().len(),
    0,
    "so nobody is abandoned: {stopped}"
  );
  assert_eq!(
    named(stopped.untorn()),
    ["decode"],
    "and the goodbye it handed over is its ONE class — the silent party has no row at all"
  );
}

/// **THE OVERRUN, with both kinds of party in one report.**
///
/// A deadline that had already passed waits for nothing, so the schedule is fixed: `decode` settles
/// inside the stop and `scenes` never does. The report answers the first and names the second, and
/// neither of them is in the other's class.
#[test]
fn an_overrun_puts_the_mid_stop_settler_and_the_abandoned_party_in_one_class_each() {
  let mut shutdown = Shutdown::new();
  let decode = shutdown.register("decode");
  let scenes = shutdown.register("scenes");

  let stopped = world(
    shutdown,
    vec![source_that_settles(decode)],
    Vec::new(),
    vec![goodbye("pool")],
  )
  .shutdown(Some(SignedDuration::from_millis(-500)));

  one_class_each(&stopped);
  assert!(
    stopped.overran(),
    "the deadline had passed before it was given"
  );
  let unanswered: Vec<&str> = stopped.unsettled().map(|name| name.as_str()).collect();
  assert_eq!(unanswered, ["scenes"], "only the one that never settled");
  assert_eq!(
    stopped.settled() + unanswered.len(),
    2,
    "and the registry's `N` is spent exactly once: {stopped}"
  );
  assert_eq!(
    named(stopped.untorn()),
    ["decode", "pool"],
    "the settler's goodbye and the launch's own, in enrolment order — and `scenes`, which handed \
     nothing over, is in neither"
  );
  drop(scenes);
}