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
//! The origin drivers, driven — and the launch door that puts a thread under one.
//!
//! Two claims here are COMPILE-level and one is not, and it is worth saying which is which. That an
//! origin whose future cannot cross threads is drivable at all is proven by this file COMPILING —
//! `Pinned` holds an `Rc` across two awaits, so a `+ Send` anywhere on that road would make the
//! declaration itself the error. What the tests then run is everything that would otherwise have
//! been traded away to get there: the ending, the death, the party, the taps.
use crate::Context;

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

use super::{drive_awaited_origin, drive_origin, observed};
use crate::{
  AsyncSource, Control, Enablement, Feed, Fin, GraphBuilder, LifecycleTap, NodeId, NodeName,
  NodeWiring, Plan, RecordingTap, Resources, Source, Station, Taps, Wired, control, feed,
  shutdown_signal,
};

/// A finite BLOCKING origin, which hands out `remaining` numbers and is spent.
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)
  }
}

/// What a line that DIED reports.
#[derive(Debug)]
struct SocketGone;

impl core::fmt::Display for SocketGone {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str("the socket went away")
  }
}

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

/// A BLOCKING origin that dies rather than ending — it hands out one item and then refuses.
struct Dying;

impl Source for Dying {
  type Options = ();
  type Yield = u64;
  type Mutation = ();
  type Error = SocketGone;

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

  fn run(
    self,
    _ctx: Context,
    giving: Feed<u64>,
    _eating: Control<Infallible>,
  ) -> Result<Fin, Self::Error> {
    let _ = giving.give(1);
    Err(SocketGone)
  }
}

/// THE `!Send` AWAITED ORIGIN — the whole point of the pinned road.
///
/// Its VALUE crosses onto the driving thread, which is what a launch needs of it; what does not
/// cross is the `Rc` its life holds between two awaits, which is what makes the FUTURE `!Send` and
/// what a `spawn` door would have refused.
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;
    // The `Rc` is alive ACROSS the await above and read again after it, which is what makes the
    // whole future `!Send` rather than merely this type.
    let _ = giving.give_async(*here + 1).await;
    Ok(Fin::Spent)
  }
}

/// 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)
}

#[test]
fn a_blocking_origin_is_driven_to_its_ending() {
  let (giving, yielded) = feed(8);
  let (_commands, eating) = control(1);
  let (_stopper, halt) = shutdown_signal();

  let counting = Counting::build(&Resources::new(), 3).expect("nothing refuses");
  let ctx = Context::new("counting").halting(halt);
  assert_eq!(drive_origin(counting, ctx, giving, eating), Ok(Fin::Spent));
  assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![3, 2, 1]);
}

#[test]
fn a_pinned_origin_is_driven_where_it_was_built() {
  let (giving, yielded) = feed(4);
  let (_commands, eating) = control(1);
  let (_stopper, halt) = shutdown_signal();

  // No runtime anywhere in this test: the future is pinned on THIS thread's stack and polled by a
  // waker made of `park`/`unpark`, which is the whole of what the pinned road is.
  let pinned = drive_awaited_origin(
    Pinned { seed: 5 },
    Context::new("pinned").halting(halt),
    giving,
    eating,
  );
  assert_eq!(pinned, Ok(Fin::Spent));
  assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![5, 6]);
}

#[test]
fn an_ordinary_ending_reaches_the_taps_as_the_pure_station() {
  let (tap, taps) = watching();
  observed::<Infallible>(&taps, NodeName::new("walk"), Ok(Fin::Spent));
  observed::<Infallible>(&taps, NodeName::new("watch"), Ok(Fin::Stopped));

  assert_eq!(
    tap.seen(),
    vec![
      ("walk".to_owned(), Station::Processed),
      ("watch".to_owned(), Station::Processed),
    ]
  );
}

#[test]
fn a_death_reaches_the_taps_as_a_failure() {
  let (tap, taps) = watching();
  observed(&taps, NodeName::new("watch"), Err(SocketGone));

  assert_eq!(tap.seen(), vec![("watch".to_owned(), Station::Failed)]);
}

/// An arrangement small enough to ignite: one node, wired to land, so nothing here is a pure leaf.
fn wired() -> Wired {
  let mut builder = GraphBuilder::new();
  let _ = builder.source::<Keeping>("keeping", crate::DriverKind::Thread);
  let graph = builder.validate().expect("one node validates");
  Plan::new(graph)
    .with_enablement(Enablement::new().launching("keeping"))
    .wiring(
      NodeId::new(0),
      NodeWiring::new(crate::Effect::Lands).landing(),
    )
    .validate()
    .expect("the deployment checks out")
}

/// The one node the arrangement above holds — it exists so the walk has something to validate, and
/// nothing here ever gives it an engine.
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: crate::Effect = crate::Effect::Lands;
  type Channels = crate::Unchanneled;
  type Mode = crate::Block;
  type Options = ();
  type Pair = crate::Buffered;
  type Wires<O> = crate::Downstream<O>;
  type Attribution<O> = ();
}

#[test]
fn a_launched_origin_lives_on_its_own_thread_and_settles_its_party() {
  let (tap, taps) = watching();
  // The plan is BOUND, because a wiring borrows it: the whole walk below lives inside one
  // deployment's lifetime.
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let enrolled = wiring.enrol("counting");
  let mut ignition = wiring.into_assembly().ignite();

  let (giving, yielded) = feed(8);
  let (_commands, eating) = control(1);
  let (_stopper, halt) = shutdown_signal();
  ignition
    .origin(
      "counting",
      Counting { remaining: 3 },
      giving,
      eating,
      halt,
      enrolled,
    )
    .expect("its engine");

  let stopped = ignition.into_app::<()>().shutdown(None);
  assert_eq!(stopped.settled(), 1, "a finished origin settles its party");
  assert!(stopped.is_clean());
  assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![3, 2, 1]);
  assert_eq!(
    tap.seen(),
    vec![("counting".to_owned(), Station::Processed)]
  );
}

#[test]
fn a_launched_origin_that_dies_is_observed_and_settles_anyway() {
  let (tap, taps) = watching();
  // The plan is BOUND, because a wiring borrows it: the whole walk below lives inside one
  // deployment's lifetime.
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let enrolled = wiring.enrol("dying");
  let mut ignition = wiring.into_assembly().ignite();

  let (giving, yielded) = feed(8);
  let (_commands, eating) = control(1);
  let (_stopper, halt) = shutdown_signal();
  ignition
    .origin("dying", Dying, giving, eating, halt, enrolled)
    .expect("its engine");

  let stopped = ignition.into_app::<()>().shutdown(None);
  // A DEAD body is a FINISHED body: a launch that left it unsettled would hold the shutdown open on
  // a thread that had already returned.
  assert_eq!(stopped.settled(), 1);
  assert!(stopped.is_clean());
  assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![1]);
  assert_eq!(tap.seen(), vec![("dying".to_owned(), Station::Failed)]);
}

#[test]
fn an_awaited_origin_is_launched_pinned_on_a_thread_of_its_own() {
  let (tap, taps) = watching();
  // The plan is BOUND, because a wiring borrows it: the whole walk below lives inside one
  // deployment's lifetime.
  let plan = wired();
  let mut wiring = plan.create().with_taps(taps).wire();
  let enrolled = wiring.enrol("pinned");
  let mut ignition = wiring.into_assembly().ignite();

  let (giving, yielded) = feed(4);
  let (_commands, eating) = control(1);
  let (_stopper, halt) = shutdown_signal();
  // NO RUNTIME is named anywhere in this walk, and the origin's own future cannot cross threads —
  // which together are the claim: the awaited face is driven by the thread engine, pinned.
  ignition
    .awaited_origin("pinned", Pinned { seed: 5 }, giving, eating, halt, enrolled)
    .expect("its engine");

  let stopped = ignition.into_app::<()>().shutdown(None);
  assert_eq!(stopped.settled(), 1);
  assert_eq!(yielded.drain().collect::<Vec<_>>(), vec![5, 6]);
  assert_eq!(tap.seen(), vec![("pinned".to_owned(), Station::Processed)]);
}