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 ENGINE SUBSTRATE: where an async body's runtime comes from, and where its clock does.
//!
//! The thread engine needs nothing from this module. It owns an OS thread, parks in a blocking
//! receive and times itself with `recv_timeout` — a machine `std` already ships — which is why it is
//! the default per engine-follows-mobility and why a `!Send` node is an ordinary node on it.
//!
//! The ASYNC engine has no such luck. A task needs a runtime to be spawned onto, and a task that
//! parks in `recv_async` cannot time itself, so its clock has to be somebody's timer. Both were open
//! questions this layer answered by handing work back to the caller: a composed body for whoever
//! held a runtime, and a [`Sweeper`](super::Sweeper) — one thread, one hand-written timer wheel —
//! for the cadences. This module is what closes them.
//!
//! # ONE runtime, named ONCE, at the door
//!
//! [`agnostic_lite`] is the substrate. An app names its runtime at the ignition door
//! ([`Assembly::ignite_on`](super::Assembly::ignite_on)) and nowhere else, and everything downstream
//! of that reads what it needs off the same `R`. What that buys over a launch-time handle is a
//! COMPILE-TIME fact where there was a start-up refusal: a deployment with an async node and no
//! runtime does not build, because the method that spawns one exists only on an
//! [`Ignition`](super::Ignition) whose runtime has been named.
//!
//! # BUNDLE AT THE DOOR, NARROW INSIDE
//!
//! The door's bound is [`RuntimeLite`](agnostic_lite::RuntimeLite) — one name for an app to write.
//! Every organ below it binds exactly what it spends and no more: [`engage`] takes an
//! [`AsyncSpawner`], [`after_clock`] takes an [`AsyncAfterSpawner`]. So this module's own surface
//! says what the async engine actually uses, and a reader of it does not have to take a runtime
//! trait's whole vocabulary on trust to see that the clock spawns nothing but timers.
//!
//! # THE `!Send` LAW
//!
//! The async engine requires `Send` bodies, because [`AsyncSpawner::spawn`] does: a task may be
//! stolen by another worker thread, and a value that cannot cross one cannot be spawned. That is not
//! a restriction this crate adds — it is the mobility the engine choice already declares, and PIN 5's
//! sentence read from the runtime's side.
//!
//! The `!Send` home is the THREAD engine, and it is a first-class one: a model context, an FFI
//! session, anything whose handle is pinned to the thread that made it, is constructed on its own
//! resident thread and never migrates.
//!
//! [`AsyncLocalSpawner`](agnostic_lite::AsyncLocalSpawner) is the named seat for the lane that would
//! change that — a `!Send` body on a thread-pinned executor — and it is REFUSED UNTIL there is
//! something to measure it against. Nothing here writes it: a local spawn needs an ambient
//! thread-local executor that not every runtime has (smol panics, embassy panics, tokio panics
//! outside a `LocalSet`), so a lane built on it would be a lane that works on one backend and
//! panics on the next. The seat is named so the widening has an address, and left empty so nobody
//! mistakes an unmeasured hope for a supported posture.

use core::{any::Any, future::Future, pin::Pin};

use std::sync::{Arc, Mutex, MutexGuard};

use agnostic_lite::{AsyncAfterSpawner, AsyncSpawner};

use super::{Cadence, Recurrence, Rings, Sweeper};

#[cfg(test)]
mod tests;

/// The absence of an async runtime, as a type.
///
/// [`Unpolled`](super::Unpolled)'s sibling one layer up: a marker whose whole job is to be the
/// default nobody writes. An [`Ignition`](super::Ignition) is `Ignition<Unruntimed>` unless a
/// deployment named a runtime, so a THREAD-ONLY graph — the shape most arrangements have — spells
/// nothing at all, and the async-only surface is simply not there to call.
///
/// It is what makes *a missing runtime* a compile-time fact rather than a start-up refusal, and it
/// is why that fact reads well: rustc's *no method named `spawn` found for struct
/// `Ignition<Unruntimed>`* names both halves of what went wrong — what was reached for, and the
/// absence that explains it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Unruntimed;

/// One async body's JOIN, as the launch holds it.
///
/// The handle a spawn answers is `<R::Spawner as AsyncSpawner>::JoinHandle<()>` — a different type
/// per runtime — and the world that has to await it at shutdown is [`App`](super::App), which is
/// generic over the generated root and not over the runtime. So the typed handle is erased HERE, at
/// the one site that knows which runtime spawned it, exactly as the teardown chain's hand-back is
/// boxed by the one party that knows the value's type.
///
/// It stays a FUTURE rather than becoming a `dyn Any`, which is the whole point: the join step can
/// still await it, and dropping one detaches the task the way dropping a thread's handle detaches a
/// thread.
pub(super) type Join = Pin<Box<dyn Future<Output = ()> + Send>>;

/// Spawn `body` on `S`, and hand back the join the shutdown will await.
///
/// The narrow half of the door's bound: spawning is all this does, so [`AsyncSpawner`] is all it
/// asks for.
pub(super) fn engage<S, F>(body: F) -> Join
where
  S: AsyncSpawner,
  F: Future<Output = ()> + Send + 'static,
{
  let handle = S::spawn(body);
  // The `JoinHandle`'s own error is dropped rather than reported, and the reason is what a join
  // error MEANS here: a body that panicked or was aborted. Both are already the shutdown's business
  // — a party that never settles is named in the `Stopped` report by the registry that knew `N`
  // before anything started — so a second, engine-shaped account of the same silence would report
  // one absence twice and under a worse name.
  Box::pin(async move {
    let _ = handle.await;
  })
}

/// How a deployment's cadences are DRIVEN.
///
/// A function pointer rather than a stored closure, because what it carries is a TYPE and not a
/// value: [`after_clock`] instantiated at the runtime the door named, or [`hand_timer`] where no
/// runtime was. Both answer the erased handle that STOPS the clock, which is the same shape every
/// other source's start answers — see [`Ignition::source`](super::Ignition::source).
pub(super) type Clock = fn(Vec<Cadence>) -> Box<dyn Any + Send>;

/// The R-LESS clock: one thread, one hand-written timer wheel.
///
/// What this layer had before it had a runtime, kept as the fallback for the world that still has
/// none — a hand-wired arrangement spawning its own async bodies with
/// [`Ignition::task`](super::Ignition::task) has cadences to ring and nothing to ring them with.
pub(super) fn hand_timer(cadences: Vec<Cadence>) -> Box<dyn Any + Send> {
  Box::new(Sweeper::ticking(cadences))
}

/// The RUNTIME's clock: every cadence on the After family, and not a thread of our own.
pub(super) fn after_clock<S>(cadences: Vec<Cadence>) -> Box<dyn Any + Send>
where
  S: AsyncAfterSpawner,
{
  Box::new(AfterClock::start::<S>(cadences))
}

/// The ASYNC engine's clock: one self-re-arming timer per cadence, on the runtime's own After
/// family.
///
/// [`Sweeper`](super::Sweeper)'s twin, and the reason it has one: a sweeper is a thread running a
/// timer wheel somebody here wrote, which is a runtime this crate built rather than a runtime it
/// was given. Where an app has named one, its `spawn_after` is that machine — Go's `time.AfterFunc`
/// as a trait — and the wheel becomes what it always was, a stand-in.
///
/// # A cadence is a REPEAT and the After family fires ONCE, so the fire re-arms
///
/// [`AsyncAfterSpawner::spawn_after`] runs a future after a duration and is done. A cadence rings
/// forever, so each fire rings and then arms the next one — the interval measured from the fire and
/// never from the deadline it may have missed, which is the same *one look, never a burst of
/// catch-up* posture the sweeper's wheel and the thread engine's arithmetic both spell.
///
/// The cost of that is stated rather than hidden: ONE SPAWN PER FIRE PER CADENCE, which is what a
/// repeat costs on a family whose primitive fires once. `reset` cannot buy it back — it adjusts a
/// delay that has not elapsed, and a fired timer's task has returned — so the alternative would be
/// the runtime's interval family, one task per cadence looping a stream. That is a real option and
/// it is not taken here: what rides this clock is a schedule (a sweep floor, a reaper's ten minutes,
/// a compactor's hour), so the spawn rate is the cadence rate, and the After family is what the
/// design record names. A deployment that ever makes a cadence hot enough for the difference to
/// register is the measurement that would move it.
///
/// # Dropping this must release the ringers AT ONCE, and that is what shapes it
///
/// A ringer holds a full sender into a node's inbox, and that sender is often the last thing keeping
/// a poll-only node alive — so the clock's drop is a step of the shutdown wave rather than
/// housekeeping. An armed timer holding the ringer would release it one interval late, and an
/// interval can be an hour.
///
/// So the timers hold a HAND rather than a ringer: dropping the clock empties every hand — the
/// senders are gone as the drop returns — and the fire that follows finds an empty one and stops
/// re-arming. What is left running is one timer per cadence with nothing in it, for at most one
/// interval, which is a task the runtime reaps and not a sender anybody is waiting on.
#[derive(Debug)]
pub struct AfterClock {
  hands: Vec<Arc<Hand>>,
}

impl AfterClock {
  /// Ring each of `cadences` on its own interval, until this handle is dropped or the ringer's far
  /// end is gone.
  ///
  /// [`Sweeper::ticking`](super::Sweeper::ticking)'s contract verbatim — same cadences, same
  /// per-cadence liveness, same stop-on-drop — over the runtime's timers instead of a thread's.
  #[must_use]
  pub fn start<S>(cadences: Vec<Cadence>) -> Self
  where
    S: AsyncAfterSpawner,
  {
    let hands: Vec<Arc<Hand>> = cadences.into_iter().map(Hand::new).collect();
    for hand in &hands {
      arm::<S>(Arc::clone(hand));
    }
    Self { hands }
  }

  /// How many cadences it rings.
  #[inline]
  #[must_use]
  pub fn hands(&self) -> usize {
    self.hands.len()
  }
}

impl Drop for AfterClock {
  /// Empty every hand, which releases every ringer — and with it every sender a node's inbox is
  /// held open by. See the type's own note for why this cannot wait for the armed timers.
  fn drop(&mut self) {
    for hand in &self.hands {
      hand.stop();
    }
  }
}

/// One cadence as the clock holds it: the interval, and the ringer BEHIND A LATCH the clock's drop
/// can open.
///
/// The latch is what separates the two lifetimes this design has to keep apart — the timer's, which
/// ends at the next fire, and the sender's, which must end when the clock is dropped.
struct Hand {
  recurrence: Recurrence,
  ringer: Mutex<Option<Box<dyn Rings>>>,
}

impl Hand {
  /// The hand for `cadence`, holding its ringer.
  fn new(cadence: Cadence) -> Arc<Self> {
    let (recurrence, ringer) = cadence.into_parts();
    Arc::new(Self {
      recurrence,
      ringer: Mutex::new(Some(ringer)),
    })
  }

  /// Ring it. `false` once there is nothing left to ring — a stopped clock, or a far end that is
  /// gone — which is what tells the fire not to arm another.
  ///
  /// A ringer that answers `false` is DROPPED here rather than kept for a next round that will not
  /// happen: its sender is the thing worth releasing, and the clock may outlive one dead cadence by
  /// however long its liveliest one runs.
  fn ring(&self) -> bool {
    let mut held = self.held();
    let Some(ringer) = held.as_ref() else {
      return false;
    };
    // The ring is a non-blocking `try_send` by contract, so nothing is awaited under this lock and
    // nothing can be blocked behind it.
    if ringer.ring() {
      return true;
    }
    *held = None;
    false
  }

  /// Release the ringer NOW.
  fn stop(&self) {
    *self.held() = None;
  }

  /// The latch, past a poisoned lock.
  ///
  /// A panic under this lock would have to come from a ringer's own `ring`, and what is behind it is
  /// one `Option`: there is no half-updated state for a poisoned guard to protect, so reading
  /// through the poison is the honest recovery rather than a second failure at shutdown time.
  fn held(&self) -> MutexGuard<'_, Option<Box<dyn Rings>>> {
    self.ringer.lock().unwrap_or_else(|held| held.into_inner())
  }
}

impl core::fmt::Debug for Hand {
  /// The recurrence, for [`Cadence`]'s own reason: a ringer is a trait object with no
  /// [`Debug`](core::fmt::Debug) supertrait, and demanding one would bound every app's ringer for
  /// the sake of this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Hand")
      .field("recurrence", &self.recurrence)
      .finish_non_exhaustive()
  }
}

/// Arm `hand`'s next fire.
///
/// Recursive, and it costs nothing: `arm` is an ordinary function called from inside the spawned
/// future rather than awaited by it, so the future's own type never contains itself — what recurses
/// is one call at the end of one timer, which is what a repeating clock IS.
fn arm<S>(hand: Arc<Hand>)
where
  S: AsyncAfterSpawner,
{
  // THE ONE NEXT-DUE CORE, asked here as the other two clocks ask it. A cadence that answers `None`
  // is due never: no timer is armed and the hand is simply left holding its ringer until the clock
  // is dropped, which is the same shape a far end that has gone away already produces.
  let Some(wait) = hand.recurrence.until_next() else {
    return;
  };
  S::spawn_after_detach(wait, async move {
    if hand.ring() {
      arm::<S>(hand);
    }
  });
}