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
//! **AN INFINITE ORIGIN WINDS DOWN WHEN THE WORLD DOES** — the origin's stop, joined to the
//! shutdown chain.
//!
//! An origin's body is inside `run` for its whole life, so it never reads the party announcement
//! [`App::shutdown`](super::App::shutdown) broadcasts: its [`ShutdownSignal`] is the one road it listens to.
//! The mount therefore keeps a half of that line, and the wind-down says the word through it. Every
//! test here is bounded by a DEADLINE rather than by `None`, because the failure this pins is a
//! shutdown that never returns — and a hanging test reports nothing.
//!
//! Three lives, which is the whole of what an origin can be doing when the word arrives:
//!
//! | toy | what it is doing | which door hears the stop |
//! |---|---|---|
//! | [`Parking`] | nothing at all, blocked | [`ShutdownSignal::heard`] |
//! | [`Looking`] | work of its own, between passes | [`ShutdownSignal::is_shutdown`] |
//! | [`Awaiting`] | nothing at all, parked on a runtime | [`ShutdownSignal::heard_async`] |
//!
//! And the road that was there before is pinned beside them: LETTING GO of the handle stops the
//! origin too, while the world is still running. Both halves say the stop as they go, so the one a
//! deployment holds is still the one that stops it early.
use crate::Context;

use core::{convert::Infallible, sync::atomic::Ordering, time::Duration};

use std::sync::{Arc, atomic::AtomicBool};

use jiff::SignedDuration;

use crate::{
  Async, AsyncSource, Block, Buffered, Control, Declared, DeclaredOrigin, Delivery, Effect,
  Emitter, Enablement, Feed, Fin, Operator, Resources, Source, Unchanneled, Upstream,
};

/// How long a bounded wait in this file is given. Generous, because what it bounds is a HANG: a
/// stop that reaches an origin does so in microseconds, and a stop that does not would never
/// arrive at all.
const PATIENCE: Duration = Duration::from_secs(30);

/// What each toy sets on the way out, so a test can say the ending was reached rather than merely
/// that the party settled.
type Wound = Arc<AtomicBool>;

/// AN ORIGIN THAT NEVER ENDS OF ITSELF, parked on the stop with nothing else to do.
struct Parking {
  wound: Wound,
}

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

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

  fn run(
    self,
    ctx: Context,
    _giving: Feed<u64>,
    _eating: Control<Infallible>,
  ) -> Result<Fin, Self::Error> {
    ctx.shutdown().heard();
    self.wound.store(true, Ordering::Release);
    Ok(Fin::Stopped)
  }
}

impl DeclaredOrigin for Parking {
  type Mode = Block;
}

/// THE SAME LIFE THROUGH THE OTHER DOOR: an origin with work of its own, looking at the stop once
/// per pass.
///
/// The pass sleeps rather than spinning, and one millisecond is what a poller's own pass would be:
/// what is under test is that the LOOK answers, not how quickly a busy loop can ask.
struct Looking {
  wound: Wound,
}

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

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

  fn run(
    self,
    ctx: Context,
    _giving: Feed<u64>,
    _eating: Control<Infallible>,
  ) -> Result<Fin, Self::Error> {
    while !ctx.shutdown().is_shutdown() {
      std::thread::sleep(Duration::from_millis(1));
    }
    self.wound.store(true, Ordering::Release);
    Ok(Fin::Stopped)
  }
}

impl DeclaredOrigin for Looking {
  type Mode = Block;
}

/// THE AWAITED FACE, parked on the same fact through the future its own door mints.
struct Awaiting {
  wound: Wound,
}

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

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

  async fn run(
    self,
    ctx: Context,
    _giving: Feed<u64>,
    _eating: Control<Infallible>,
  ) -> Result<Fin, Self::Error> {
    ctx.shutdown().heard_async().await;
    self.wound.store(true, Ordering::Release);
    Ok(Fin::Stopped)
  }
}

impl DeclaredOrigin for Awaiting {
  type Mode = Async;
}

/// The consumer all three name — declared and never launched, which is what keeps each origin from
/// being a leaf that computes into nothing without opening an edge nothing bridges.
struct Ledger;

impl Operator for Ledger {
  type Error = Infallible;
  type In = u64;
  type Out = u64;

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

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

/// The three origins launched and their consumer dark — the only shape a deployment with an origin
/// in it takes today, and the one `bridge_tests` refuses the other half of.
fn wired() -> crate::Wired {
  let mut blueprint = crate::Blueprint::new();
  let _ = blueprint.origin::<Parking>("parking");
  let _ = blueprint.origin::<Looking>("looking");
  let _ = blueprint.origin::<Awaiting>("awaiting");
  let _ = blueprint.node::<Ledger>("ledger");
  blueprint
    .into_plan()
    .expect("the edges join on the origins' own identities")
    .with_enablement(
      Enablement::new()
        .launching("parking")
        .launching("looking")
        .launching("awaiting"),
    )
    .validate()
    .expect("the deployment checks out")
}

/// A flag nobody has set.
fn flag() -> Wound {
  Arc::new(AtomicBool::new(false))
}

/// **THE WHOLE CLAIM**: three origins that never end of themselves, their handles HELD, and a
/// shutdown that returns.
///
/// The handles are the subject. A deployment that dropped them would be stopping the origins itself
/// — that road was always there — so they are kept alive past the stop, which is exactly the case
/// that used to wait forever: three parties that had been told nothing, on a wait no deadline of a
/// caller's would have been able to end cleanly.
#[test]
fn an_infinite_origin_is_wound_down_by_the_worlds_own_shutdown() {
  let (parked, looked, awaited) = (flag(), flag(), flag());

  let plan = wired();
  let mut wiring = plan.create().wire();
  let (one, two, three) = (
    wiring.enrol("parking"),
    wiring.enrol("looking"),
    wiring.enrol("awaiting"),
  );
  let mut ignition = wiring.into_assembly().ignite();

  let parking = ignition
    .origin_declared::<Parking>(
      "parking",
      Parking {
        wound: Arc::clone(&parked),
      },
      4,
      one,
    )
    .expect("its engine");
  let looking = ignition
    .origin_declared::<Looking>(
      "looking",
      Looking {
        wound: Arc::clone(&looked),
      },
      4,
      two,
    )
    .expect("its engine");
  let awaiting = ignition
    .origin_declared::<Awaiting>(
      "awaiting",
      Awaiting {
        wound: Arc::clone(&awaited),
      },
      4,
      three,
    )
    .expect("its engine");

  let stopped = ignition.into_app::<()>().shutdown(Some(
    SignedDuration::try_from(PATIENCE).expect("a bounded wait"),
  ));

  assert!(
    !stopped.overran(),
    "the wind-down reached every origin: {stopped}"
  );
  assert!(stopped.is_clean(), "{stopped}");
  assert_eq!(stopped.settled(), 3, "{stopped}");

  // EACH LIFE REACHED ITS OWN ENDING, which is a stronger claim than the party settling: a body
  // that had been killed rather than told would have settled too.
  assert!(parked.load(Ordering::Acquire), "the park was released");
  assert!(looked.load(Ordering::Acquire), "the look answered");
  assert!(
    awaited.load(Ordering::Acquire),
    "the awaited park was released"
  );

  // HELD UNTIL HERE. Written as a use rather than left to the end of the function, because that is
  // the whole test: a deployment holding these across the stop is the case the join exists for.
  assert!(!parking.stopper().announce(), "its life is over");
  assert!(!looking.stopper().announce(), "its life is over");
  assert!(!awaiting.stopper().announce(), "its life is over");
}

/// **AND LETTING GO STILL STOPS IT**, while the world is still running.
///
/// The road the mount had before the join, and the one a second half could have silently taken away:
/// with the launch holding a sender of its own, *every sender is gone* is not something the
/// deployment's handle can bring about by itself. So the drop SAYS the stop — and this is the test
/// that would fail if it stopped saying it, because nothing else here would.
///
/// The party is watched rather than waited on, so a regression is a failed assertion after
/// [`PATIENCE`] rather than a test that never returns.
#[test]
fn dropping_the_handle_stops_an_origin_while_the_world_runs() {
  let wound = flag();

  let plan = wired();
  let mut wiring = plan.create().wire();
  let enrolled = wiring.enrol("parking");
  let mut ignition = wiring.into_assembly().ignite();
  let parking = ignition
    .origin_declared::<Parking>(
      "parking",
      Parking {
        wound: Arc::clone(&wound),
      },
      4,
      enrolled,
    )
    .expect("its engine");
  let app = ignition.into_app::<()>();

  // The deployment lets go, and nothing else does anything.
  drop(parking);

  let end = std::time::Instant::now() + PATIENCE;
  while !app.parties()[0].finished() {
    assert!(
      std::time::Instant::now() < end,
      "the handle's own drop is what stops an origin the world has not stopped"
    );
    std::thread::sleep(Duration::from_millis(1));
  }
  assert!(wound.load(Ordering::Acquire), "the park was released");

  let stopped = app.shutdown(Some(
    SignedDuration::try_from(PATIENCE).expect("a bounded wait"),
  ));
  assert!(stopped.is_clean(), "{stopped}");
}