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
use crate::Resources;
use std::sync::{
  Arc,
  atomic::{AtomicUsize, Ordering},
};

use super::{
  AsyncResource, DeclaredResource, ResourceCatalog, ResourceDemand, ResourceName, ResourceSource,
  ResourceVisitor,
};

/// How many times `Egemma` was BUILT — the lifecycle claim, counted.
///
/// One test drives it, and that is load-bearing: a `static` is shared by every test in the binary
/// and they run at once, so a second builder of this type would make the count race. Every other
/// test here reaches an `Egemma` through [`Shared::new`](super::Shared::new), which builds nothing.
static BUILDS: AtomicUsize = AtomicUsize::new(0);

/// A model handle, as an author writes one: expensive to build, cheap to hold, and shareable
/// because the author said so.
#[derive(Debug)]
struct Egemma {
  dim: usize,
}

impl AsyncResource for Egemma {
  type Options = usize;
  type Error = core::convert::Infallible;

  async fn build(_ctx: &Resources, dim: usize) -> Result<Self, Self::Error> {
    BUILDS.fetch_add(1, Ordering::Relaxed);
    Ok(Self { dim })
  }
}

// What `#[ingraph::resource]` emits.
impl DeclaredResource for Egemma {}

/// A resource whose construction can refuse — the typed error half of the contract.
#[derive(Debug)]
struct Whisper;

#[derive(Debug, derive_more::Display)]
#[display("no such checkpoint: {_0}")]
struct MissingCheckpoint(String);

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

impl AsyncResource for Whisper {
  type Options = String;
  type Error = MissingCheckpoint;

  async fn build(_ctx: &Resources, path: String) -> Result<Self, Self::Error> {
    if path.is_empty() {
      return Err(MissingCheckpoint(path));
    }
    Ok(Self)
  }
}

impl DeclaredResource for Whisper {}

/// A resource that satisfies the CONTRACT and never joined the walk.
///
/// It is the gap the start-up cross-check exists for, and it is reachable exactly because
/// [`AsyncResource`] is hand-implemented — see the module note.
struct Undeclared;

impl AsyncResource for Undeclared {
  type Options = ();
  type Error = core::convert::Infallible;

  async fn build(_ctx: &Resources, (): ()) -> Result<Self, Self::Error> {
    Ok(Self)
  }
}

/// Drive `future` to completion — the launch's own act, since `build` is async.
///
/// A dev-dependency runtime rather than the drive layer's own `block_on`, which is private to that
/// module: what is under test here is the resource tier, and reaching through a neighbour's driver
/// to exercise it would widen a seam for a test's convenience.
fn ready<F: core::future::Future>(future: F) -> F::Output {
  tokio::runtime::Builder::new_current_thread()
    .build()
    .expect("a current-thread runtime")
    .block_on(future)
}

#[test]
fn one_build_and_the_handle_is_what_travels() {
  // THE LIFECYCLE CLAIM: a resource is constructed ONCE and the handle is cloned to its members. A
  // mutation that built per member — a `Shared::build` call inside a per-unit loop — moves this
  // count and nothing else in the crate would notice.
  let before = BUILDS.load(Ordering::Relaxed);
  let shared =
    ready(super::Shared::<Egemma>::build(&Resources::new(), 768)).expect("the model loads");
  assert_eq!(BUILDS.load(Ordering::Relaxed), before + 1);

  let members: Vec<_> = (0..4).map(|_| shared.clone()).collect();
  assert_eq!(BUILDS.load(Ordering::Relaxed), before + 1);
  assert_eq!(shared.holders(), 5);
  for member in &members {
    // Every member reaches the SAME value, which is what construction-sharing means.
    assert_eq!(member.dim, 768);
    assert!(core::ptr::eq(member.get(), shared.get()));
  }
  drop(members);
  assert_eq!(shared.holders(), 1);
}

#[test]
fn a_refused_construction_reports_in_the_authors_own_currency() {
  let refused = ready(super::Shared::<Whisper>::build(
    &Resources::new(),
    String::new(),
  ))
  .expect_err("an empty checkpoint path");
  assert_eq!(refused.to_string(), "no such checkpoint: ");
  assert!(
    ready(super::Shared::<Whisper>::build(
      &Resources::new(),
      "base.en".to_owned()
    ))
    .is_ok()
  );
}

#[test]
fn a_handle_derefs_to_the_resource_and_borrows_it_three_ways() {
  let shared = super::Shared::new(Egemma { dim: 384 });
  assert_eq!(shared.dim, 384);
  assert_eq!(shared.get().dim, 384);
  assert_eq!(AsRef::<Egemma>::as_ref(&shared).dim, 384);
}

#[test]
fn a_handles_debug_names_the_resource_rather_than_dumping_it() {
  // A model context has no useful `Debug`, and demanding one would bound every author's type for
  // the benefit of one line.
  let shared = super::Shared::new(Egemma { dim: 8 });
  let rendered = format!("{shared:?}");
  assert!(rendered.contains("Shared"), "{rendered}");
  assert!(rendered.contains("Egemma"), "{rendered}");
  assert!(rendered.contains("holders"), "{rendered}");
}

#[test]
fn a_handle_crosses_threads_because_the_supertraits_say_it_does() {
  fn shareable<T: Send + Sync>(_: &T) {}
  let shared = super::Shared::new(Egemma { dim: 1 });
  shareable(&shared);

  let second = shared.clone();
  let elsewhere = std::thread::spawn(move || second.dim);
  assert_eq!(elsewhere.join().expect("the thread"), 1);
}

#[test]
fn a_resource_name_is_the_compilers_own_path_and_both_sides_derive_it_once() {
  // THE MUTATION this pins: give the citizenship a name of its own — the bare ident, say — and the
  // cross-check starts refusing resources that are really there. One call, two readers.
  let declared = <Egemma as DeclaredResource>::resource();
  let demanded = ResourceDemand::of::<Egemma>().resource();
  assert_eq!(declared, demanded);
  assert!(
    declared.as_str().ends_with("Egemma"),
    "{}",
    declared.as_str()
  );
  assert_ne!(declared, <Whisper as DeclaredResource>::resource());
  assert_eq!(ResourceName::of::<Egemma>(), declared);
  assert_eq!(
    ResourceDemand::of::<Egemma>().to_string(),
    declared.as_str()
  );
}

#[test]
fn a_resource_name_views_a_str_and_keys_a_map_as_one() {
  use std::collections::HashMap;

  let mut held: HashMap<&ResourceName, usize> = HashMap::new();
  held.insert(ResourceName::new("egemma"), 3);
  assert_eq!(held.get(ResourceName::new("egemma")), Some(&3));
  assert_eq!(ResourceName::new("egemma").as_str(), "egemma");
}

#[test]
fn the_walk_collects_citizens_and_answers_about_them_by_name() {
  let mut declared = ResourceCatalog::new();
  assert!(declared.is_empty());
  declared
    .next_resource::<Egemma>("egemma", ResourceSource::Section)
    .expect("infallible");
  declared
    .next_resource::<Whisper>("whisper", ResourceSource::Prepare)
    .expect("infallible");
  // Walked twice under one mount: the catalog is keyed by the TYPE, so a second visit to a citizen
  // already in it states the same thing again rather than adding a second entry.
  declared
    .next_resource::<Egemma>("egemma", ResourceSource::Section)
    .expect("infallible");

  assert_eq!(declared.len(), 2);
  assert!(declared.declares(<Egemma as DeclaredResource>::resource()));
  assert!(declared.declares(<Whisper as DeclaredResource>::resource()));
  assert!(!declared.declares(ResourceDemand::of::<Undeclared>().resource()));
  assert_eq!(declared.names().count(), 2);
}

#[test]
fn the_hand_written_door_and_the_walk_agree() {
  // `with::<R>()` is what a test and a hand-written launch wire with; `next_resource` is what a
  // walk drives. Two spellings of one act, so they must produce one set.
  let mut walked = ResourceCatalog::new();
  walked
    .next_resource::<Egemma>("egemma", ResourceSource::Section)
    .expect("infallible");
  assert_eq!(
    walked,
    ResourceCatalog::new().with::<Egemma>("egemma", ResourceSource::Section)
  );
}

#[test]
fn a_demand_is_recordable_for_a_resource_nobody_declared() {
  // The refusal has to be REACHABLE: a door that could only be spelled for a citizen would make the
  // start-up cross-check unreachable, which is the one thing it must not be.
  let demand = ResourceDemand::of::<Undeclared>();
  assert!(demand.resource().as_str().ends_with("Undeclared"));
  assert!(
    !ResourceCatalog::new()
      .with::<Egemma>("egemma", ResourceSource::Section)
      .declares(demand.resource())
  );
}

#[test]
fn several_units_hold_one_model_and_the_framework_never_locks_it() {
  // Construction-sharing, end to end: one build, four holders on four threads, every one reading
  // the same value. What the framework adds is an `Arc` and nothing else — whether the protocol
  // underneath is safe to drive concurrently is the author's assertion, which the declaration
  // records.
  let shared = super::Shared::new(Egemma { dim: 1024 });
  let seen = Arc::new(AtomicUsize::new(0));
  let mut units = Vec::new();
  for _ in 0..4 {
    let held = shared.clone();
    let seen = Arc::clone(&seen);
    units.push(std::thread::spawn(move || {
      seen.fetch_add(held.dim, Ordering::Relaxed);
    }));
  }
  for unit in units {
    unit.join().expect("a unit thread");
  }
  assert_eq!(seen.load(Ordering::Relaxed), 4 * 1024);
  assert_eq!(shared.holders(), 1);
}