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
//! DECLARATION-DRIVEN MOUNTING: an origin that enters the arrangement from what it states, and a
//! launch walk that puts it on an engine without being told which one.
//!
//! Two claims here are COMPILE-level. That ONE door serves both faces is proven by the two mounts
//! below type-checking — nothing in either call names `Source` or `AsyncSource`, and the face comes
//! from the declaration's own `Mode` seat. And that an awaited origin is still driven PINNED is
//! proven by `Pinned` holding an `Rc` across two awaits, which no runtime in this file is named to
//! drive.
//!
//! The third claim is a refusal, and it runs: a source nobody listens to is a pure leaf, and the
//! plan says so before anything ignites.
use crate::Context;

use core::convert::Infallible;
use std::{rc::Rc, sync::Arc};

use crate::{
  Async, AsyncSource, Block, Buffered, Control, DeclaredOrigin, Effect, Enablement, Feed, Fin,
  GraphBuilder, LifecycleTap, MutationNode, NodeId, RecordingTap, Refusal, Resources, Source,
  Station, Taps, Upstream,
};

/// A finite BLOCKING origin, declared.
struct Counting {
  remaining: u64,
}

impl Source for Counting {
  type Options = u64;
  type Yield = u64;
  type Mutation = ();
  type Error = Infallible;

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

  fn run(
    mut self,
    ctx: Context,
    giving: Feed<u64>,
    _eating: Control<Infallible>,
  ) -> Result<Fin, Self::Error> {
    while self.remaining > 0 {
      if ctx.shutdown().is_shutdown() {
        return Ok(Fin::Stopped);
      }
      if giving.give(self.remaining).is_err() {
        return Ok(Fin::Stopped);
      }
      self.remaining -= 1;
    }
    Ok(Fin::Spent)
  }
}

/// Its declaration — three lines, exactly what `#[ingraph::source]` emits.
impl DeclaredOrigin for Counting {
  type Mode = Block;
}

/// THE `!Send` AWAITED ORIGIN, declared — the same door, the other face.
struct Pinned {
  seed: u64,
}

impl AsyncSource for Pinned {
  type Options = u64;
  type Yield = u64;
  type Mutation = ();
  type Error = Infallible;

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

  async fn run(
    self,
    _ctx: Context,
    giving: Feed<u64>,
    _eating: Control<Infallible>,
  ) -> Result<Fin, Self::Error> {
    let here = Rc::new(self.seed);
    let _ = giving.give_async(*here).await;
    // Alive ACROSS the await and read after it, which is what makes the whole future `!Send`.
    let _ = giving.give_async(*here + 1).await;
    Ok(Fin::Spent)
  }
}

impl DeclaredOrigin for Pinned {
  type Mode = Async;
  const MOUNTS: Option<&'static str> = Some("crate::Nothing");
}

/// A recorder, and the composite that carries it into a walk.
fn watching() -> (Arc<RecordingTap>, Taps) {
  let tap = Arc::new(RecordingTap::new());
  let taps = Taps::new().with(Arc::clone(&tap) as Arc<dyn LifecycleTap>);
  (tap, taps)
}

/// The consumer an origin publishes to — it exists so an arrangement holding one is not a pure leaf.
struct Keeping;

impl crate::Operator for Keeping {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    _delivery: crate::Delivery<u64>,
    _emitter: &mut crate::Emitter<u64>,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

impl crate::Declared for Keeping {
  const EFFECT: Effect = Effect::Lands;
  const HOLDS_LANE: bool = true;
  const UPSTREAMS: &'static [Upstream] = &[Upstream::of::<Counting>("counting")];
  type Channels = crate::Unchanneled;
  type Mode = Block;
  type Options = ();
  type Pair = Buffered;
  type Wires<O> = crate::Downstream<O>;
  type Attribution<O> = ();
}

/// The AWAITED origin's own consumer — a second one, because a consumer is per upstream and an
/// origin nobody listens to is refused however many other origins the arrangement holds.
struct Watching;

impl crate::Operator for Watching {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

  fn accept(
    &mut self,
    _ctx: &Context,
    _delivery: crate::Delivery<u64>,
    _emitter: &mut crate::Emitter<u64>,
  ) -> Result<(), Self::Error> {
    Ok(())
  }
}

impl crate::Declared for Watching {
  const EFFECT: Effect = Effect::Lands;
  const HOLDS_LANE: bool = true;
  const UPSTREAMS: &'static [Upstream] = &[Upstream::of::<Pinned>("pinned")];
  type Channels = crate::Unchanneled;
  type Mode = Block;
  type Options = ();
  type Pair = Buffered;
  type Wires<O> = crate::Downstream<O>;
  type Attribution<O> = ();
}

/// AN ORIGIN NOBODY LISTENS TO is refused BEFORE anything ignites, by the refusal that was already
/// there.
///
/// The arrangement is one origin and nothing else. It publishes to nobody, polls nothing and answers
/// nobody, so its effect — which is the pure one, an origin landing nothing — makes it a leaf that
/// computes into nothing. `Refusal::PureLeaf` is what says so, and this test is where the ruling that
/// no separate orphan-head family is needed is held to.
#[test]
fn a_source_nobody_listens_to_is_refused_as_a_pure_leaf() {
  let mut blueprint = crate::Blueprint::new();
  let _ = blueprint.origin::<Counting>("counting");
  let plan = blueprint
    .into_plan()
    .expect("one node with no edge is an arrangement")
    .with_enablement(Enablement::new().launching("counting"));

  let refused = plan.validate().expect_err("an origin nobody listens to");
  let crate::LaunchError::Refused(refusals) = refused else {
    panic!("the refusal is a validation refusal");
  };
  assert!(
    refusals
      .iter()
      .any(|refusal| matches!(refusal, Refusal::PureLeaf(_))),
    "{refusals:?}"
  );
  // The SENTENCE names the node, which is what sends an author to the right line.
  assert!(
    refusals
      .iter()
      .any(|refusal| refusal.to_string().contains("counting")),
    "{refusals:?}"
  );
}

/// AN ORIGIN WITH A CONSUMER validates — the same arrangement with somebody at the far end.
///
/// The consumer is DECLARED and not launched, which is the whole shape a deployment with an origin
/// in it can take today: the edge is what keeps the origin from being a leaf that computes into
/// nothing, and launching the far end of one is the dead edge `bridge_tests` refuses.
#[test]
fn an_origin_with_a_consumer_is_an_arrangement() {
  let mut blueprint = crate::Blueprint::new();
  let origin = blueprint.origin::<Counting>("counting");
  let consumer = blueprint.node::<Keeping>("keeping");
  assert_eq!(origin, NodeId::new(0));
  assert_eq!(consumer, NodeId::new(1));

  let plan = blueprint
    .into_plan()
    .expect("the edge joins on the origin's own identity")
    .with_enablement(Enablement::new().launching("counting"));
  let _: crate::Wired = plan.validate().expect("the deployment checks out");
}

/// A CONSUMER NAMING AN ORIGIN THE ROOT DOES NOT MOUNT is the ordinary unknown-upstream refusal —
/// an origin joins the registry by TYPE like anything else.
#[test]
fn an_origin_is_joined_by_its_own_identity() {
  let mut blueprint = crate::Blueprint::new();
  let _ = blueprint.node::<Keeping>("keeping");
  let refused = blueprint
    .into_plan()
    .expect_err("nothing mounts the origin its upstream names");
  let crate::LaunchError::Refused(refusals) = refused else {
    panic!("the refusal is a join refusal");
  };
  assert!(
    refusals
      .iter()
      .any(|refusal| matches!(refusal, Refusal::UnknownUpstream(_))),
    "{refusals:?}"
  );
}

/// An arrangement small enough to ignite, with the origin in it and its consumer left unlaunched —
/// which is the honest shape for a test that reads the feed itself.
fn wired() -> crate::Wired {
  let mut blueprint = crate::Blueprint::new();
  let _ = blueprint.origin::<Counting>("counting");
  let _ = blueprint.origin::<Pinned>("pinned");
  let _ = blueprint.node::<Keeping>("keeping");
  let _ = blueprint.node::<Watching>("watching");
  blueprint
    .into_plan()
    .expect("the edges join")
    // The CONSUMERS are declared and not launched, which is the honest shape for a test that reads
    // the feed itself: the edge exists, so neither origin computes into nothing, and nothing in the
    // graph is running that would expect a message.
    .with_enablement(Enablement::new().launching("counting").launching("pinned"))
    .validate()
    .expect("the deployment checks out")
}

/// ONE DOOR, BOTH FACES — and neither call names a face.
///
/// `Counting` is blocking and `Pinned` is awaited, and the two lines below are the same line with a
/// different type in it. What picks the driver is each declaration's own `Mode` seat, which is what
/// makes the mount declaration-driven rather than caller-driven.
#[test]
fn one_door_mounts_both_faces_and_neither_call_names_one() {
  let (tap, taps) = watching();
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let counting = wiring.enrol("counting");
  let pinned = wiring.enrol("pinned");
  let mut ignition = wiring.into_assembly().ignite();

  let blocking = ignition
    .origin_declared::<Counting>("counting", Counting { remaining: 3 }, 8, counting)
    .expect("its engine");
  // NO RUNTIME is named anywhere in this walk, and `Pinned`'s own future holds an `Rc` across two
  // awaits — which together are the claim: the awaited face is driven by the thread engine, pinned.
  let awaited = ignition
    .origin_declared::<Pinned>("pinned", Pinned { seed: 5 }, 8, pinned)
    .expect("its engine");

  // PARKED FIRST, and the assertions below are why: the shutdown tells every mounted origin to wind
  // down, so a FINITE origin that has not reached its last item yet would end `Stopped` with items
  // it never handed out — an ordinary ending, and not the one this test is about. `until_stopped`
  // waits for both lives to end of their own accord, and the stop after it says the word to two
  // origins that are already gone.
  let app = ignition.into_app::<()>();
  app.until_stopped();
  let stopped = app.shutdown(None);
  assert_eq!(stopped.settled(), 2, "both origins settle their parties");
  assert!(stopped.is_clean());

  assert_eq!(
    blocking.yielded().drain().collect::<Vec<_>>(),
    vec![3, 2, 1]
  );
  assert_eq!(awaited.yielded().drain().collect::<Vec<_>>(), vec![5, 6]);

  // The two threads end independently, so the ORDER a tap sees them in is not a fact — what is one
  // is that each ended, and ended the pure way.
  let seen = tap.seen();
  assert_eq!(seen.len(), 2, "{seen:?}");
  for named in ["counting", "pinned"] {
    assert!(
      seen
        .iter()
        .any(|(node, station)| node == named && *station == Station::Processed),
      "{named}: {seen:?}"
    );
  }
}

/// THE HANDLE IS THE THREE ENDS, and the mount is what minted them — no caller here built a feed, a
/// control line or a stop.
#[test]
fn the_walk_mints_the_lines_and_hands_back_their_ends() {
  let (_tap, taps) = watching();
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let counting = wiring.enrol("counting");
  let mut ignition = wiring.into_assembly().ignite();

  let mounted = ignition
    .origin_declared::<Counting>("counting", Counting { remaining: 2 }, 4, counting)
    .expect("its engine");

  // The command line is keyed by the vocabulary the declaration's own seat resolved to — here the
  // ABSENT seat, whose command type is uninhabited. The annotation is the claim: a line minted for
  // another node's vocabulary would be `E0308` on this line.
  let (commands, yielded, stopper) = mounted.into_parts();
  let _: &crate::Commands<<() as MutationNode>::Command> = &commands;

  // The park is what lets this finite origin reach its own last item — the shutdown would tell it to
  // wind down — and the shutdown after it JOINS the thread, so what the feed holds afterwards is the
  // whole of what it produced. Read after, because reading before would be reading a race.
  let app = ignition.into_app::<()>();
  app.until_stopped();
  let stopped = app.shutdown(None);
  assert!(stopped.is_clean());
  assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![2, 1]);

  // And the stop line's far end is gone with it: an origin that has already finished has nothing
  // left to be told, which is what `announce` answering `false` means.
  assert!(!stopper.announce(), "the origin's life is over");
}

/// THE RECORD is readable, and it is what a walk that never saw the declaration's tokens reads.
#[test]
fn the_declaration_states_its_face_and_the_node_it_mounts() {
  // In `const` blocks, so the claim is made at COMPILE time: the row a declaration's mode selected
  // is a fact about the type and not a value anybody computes.
  const {
    assert!(<Counting as crate::Lived<<Counting as DeclaredOrigin>::Mode>>::SYNC);
  }
  const {
    assert!(!<Pinned as crate::Lived<<Pinned as DeclaredOrigin>::Mode>>::SYNC);
  }
  assert_eq!(Counting::MOUNTS, None);
  assert_eq!(Pinned::MOUNTS, Some("crate::Nothing"));
}

/// An origin enters the builder as a HEAD, exactly as a subscribing-nothing operator does.
#[test]
fn an_origin_enters_the_arrangement_as_a_head() {
  let mut builder = GraphBuilder::new();
  let handle = builder.origin::<Counting>("counting", crate::DriverKind::Thread);
  assert_eq!(handle.id(), NodeId::new(0));
  let graph = builder.validate().expect("one node validates");
  assert!(graph.nodes()[0].is_source(), "an origin is a dataflow head");
}