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
//! WHO RUNS A TICK, AND WHERE: the handler citizens a poll entry mounts, the executors a detached
//! entry runs on, and the cell that keeps a slow clock from piling up.
//!
//! A `poll(…)` entry says WHEN. Everything here answers the other two questions the declaration can
//! ask — WHAT runs and IN WHICH WORLD — and the words that select them live on the entry:
//!
//!   * `handler = "app::PromScraper"` MOUNTS a citizen — a value the deployment built and the node
//!     never sees — and `light` runs the node's OWN `<Node>Sweeps` method instead. Exactly one of
//!     the two on every entry: WHO runs a tick is declared rather than left to a silence.
//!   * `block` · `spawn` · `rayon` · `async(inline)` · `async(spawn)` say WHERE. The word is
//!     MANDATORY — a role is declared rather than inferred — and it decides which of the two citizen
//!     traits the mount's bound demands, so a `block` entry mounting an async-only handler is
//!     `E0277` at the word.
//!
//! # TWO CITIZENS, ONE SHAPE — the dual-mode law at this seam
//!
//! [`AsyncTick`] is the async face and [`Tick`] the blocking one, and they differ in exactly one
//! thing: whether the answer is a future. Same receiver, same lent context, same `Info` and `Error`.
//!
//! # THE NAMING AXIS, framework-wide and permanent
//!
//! **`Async*` is the asynchronous face; the BARE name is the blocking one.** There is no
//! `Blocking*` prefix anywhere in this framework — it was retired outright rather than deprecated,
//! because two spellings of one axis is the drift a reader has to hold in their head. The pairs
//! read the same way at every seam: [`AsyncTick`] / [`Tick`] here,
//! [`AsyncLands`](super::AsyncLands) / [`Lands`](super::Lands) one lane over,
//! [`AsyncSpawn`] / [`Spawn`] below, and
//! [`AsyncBlobEngine`](crate::AsyncBlobEngine) / [`BlobEngine`](crate::BlobEngine),
//! [`AsyncLocate`](crate::AsyncLocate) / [`Locate`](crate::Locate),
//! [`AsyncBlobStore`](crate::AsyncBlobStore) / [`BlobStore`](crate::BlobStore) in the store layer.
//!
//! A trait carrying NEITHER prefix nor a twin is a marker or an assoc-only face: it has no mode to
//! carry, so it is not named on this axis at all.
//!
//! # THE ONE EXEMPTION: a framework-internal engine seam, where dual VERBS are the faithful shape
//!
//! The pair-of-traits law governs AUTHOR-IMPLEMENTABLE contract faces — the ones a declaration or a
//! deployment writes an impl for. A FRAMEWORK-INTERNAL seam whose implementor must serve BOTH
//! engines at once is exempt, and the criterion is exactly that: an emitted subscribe container's
//! intake cannot know which engine will drive it, so ONE BODY has to hold TWO ENGINE DOORS. Two
//! verbs on one trait is the faithful spelling of that; a mode PAIR would be two types for one
//! implementor and would push the choice back onto a party that has no way to make it.
//!
//! The exempt family, on the record: [`Intake::park`](super::Intake::park) /
//! [`park_async`](super::Intake::park_async), [`Inbox`](super::Inbox)'s same pair,
//! [`Outbox`](super::Outbox)'s `deliver` / `deliver_async`, and the lane's own `block_on` driver.
//! Nothing else is exempt, and a new `*_async` verb beside a bare one is a claim that has to answer
//! this criterion first.
//!
//! A handler may implement BOTH citizen traits, and nothing here objects: which one is called is
//! decided by the word on the entry, not by what the type happens to offer.
//!
//! # ONE `Info` AND ONE `Error` PER NODE, and that law reaches the citizens
//!
//! A resident has one observation stream and one effect table, which is why `<Node>Sweeps` carries
//! one `Info` and one `Error` for a whole node. A mounted handler joins that same answer: the
//! emitted route states the node's pair and BINDS each INLINE citizen to it, so two handlers that
//! disagree are `E0271` at the deployment naming both types.
//!
//! DETACHED citizens are exempt, and structurally so — their answer never reaches the seat, so
//! there is nothing for it to agree with. See [`Spawn`] for what does happen to it.
//!
//! # THE EXECUTORS ARE A SEAM, AND THE WORDS ARE SUGAR FOR THE SHIPPED ONES
//!
//! [`Spawn`] and [`AsyncSpawn`] are open capability traits; [`Thread`], [`Rayon`] and
//! [`Tasks`] are the citizens this crate ships for them. `spawn` selects [`Thread`], `rayon` selects
//! [`Rayon`], `async(spawn)` selects whatever [`AsyncSpawn`] the deployment installed. A third-party
//! pool implements the seam and is installed into `<Node>Polling` deployment-side, displacing the
//! shipped default — and no vocabulary word is minted per engine, which is the framework-open law
//! read one axis over from the store engines.
//!
//! # WHAT THIS IS NOT: a deployment with no runtime at all
//!
//! `block` runs a sync body on the driver's own thread, and the thread engine already needs no
//! runtime — but the driver itself is still a driver, and a `Seats` seating is still an async call
//! it blocks on. A graph whose every seam is synchronous, with no future anywhere, is a DIFFERENT
//! and larger thing: it is about the shape of every seam in the tree rather than about where one
//! tick runs.
//!
//! It is RECORDED SCOPE rather than a gap here. The dual-mode law is about seam FACES — a blocking
//! twin beside an async one, so a sync body has somewhere to stand — and never about removing the
//! driver. The all-sync deployment is the R-line's own arc, and it opens with an inventory of every
//! execution seam in this crate rather than with a widening of this one.

use core::future::Future;

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

/// WHAT A MOUNTED CLOCK RUNS — the async citizen a `poll(…)` entry names with `handler = "…"`.
///
/// `Ctx` is what the clock LENDS the tick, and it defaults to `()`: an entry that granted nothing
/// lends nothing, and a handler for it writes `impl AsyncTick for Scraper` with no context named. An
/// entry that wrote `write = "…"` lends its own emitted grants context, so its handler names that
/// type — `impl AsyncTick<ExporterScrapeGrants<Rows>> for Scraper` — and the write sockets it reaches are
/// exactly the grants that entry wrote.
///
/// # Why the citizen is not the operator
///
/// Because a node's clocks and a node's data path are two different concerns wearing one struct. A
/// `light` entry is a method on the operator and stays the road for a sweep that works
/// through the node's own state; a mounted handler is a value the DEPLOYMENT built and handed over,
/// which is what makes a scraper, an exporter or a health probe reusable across declarations and
/// testable without a resident. Both roads stay open, entry by entry, which is what the presence
/// split buys.
///
/// # The answer is a `Send` future, spelled rather than hoped for
///
/// [`AsyncLands::land`](super::AsyncLands)' reason verbatim: a resident is a task on somebody's runtime, so a
/// body it awaits has to cross threads. Writing the bound into the signature makes it part of the
/// contract instead of something each caller discovers.
pub trait AsyncTick<Ctx = ()> {
  /// What one tick has to say about itself — the info the observation it becomes carries.
  ///
  /// Bound-free here, as [`Seats::Info`](super::Seats) is: the erasure a tap needs costs
  /// `Any + Send + Sync`, and the driver asks for it at its own call site.
  type Info;

  /// What a tick can fail with. Bound-free for [`Info`](Self::Info)'s reason.
  type Error;

  /// Run one tick, through what this clock was lent.
  fn tick(
    &mut self,
    grants: &mut Ctx,
  ) -> impl Future<Output = Result<Self::Info, Self::Error>> + Send;
}

/// [`AsyncTick`]'s BLOCKING twin — what a `block`, `spawn` or `rayon` entry's mount implements.
///
/// The whole difference is the answer: a `Result` rather than a future. Everything else — the
/// receiver, the lent context and its default, the two associated types — is [`AsyncTick`]'s, because the
/// two faces are one seam seen from two worlds rather than two seams.
///
/// # It is not a lesser face
///
/// A scan over a directory tree, a `rusqlite` sweep, an FFI session's compaction: these are natively
/// blocking, and wrapping them in an async signature to satisfy a seam would put an await point
/// where no yield happens. The word on the entry says which world the body lives in, and the driver
/// spends it accordingly — `block` on its own thread, `spawn`/`rayon` on an executor.
pub trait Tick<Ctx = ()> {
  /// What one tick has to say about itself — [`AsyncTick::Info`]'s twin.
  type Info;

  /// What a tick can fail with — [`AsyncTick::Error`]'s twin.
  type Error;

  /// Run one tick, through what this clock was lent.
  fn tick(&mut self, grants: &mut Ctx) -> Result<Self::Info, Self::Error>;
}

/// WHERE A DETACHED BLOCKING TICK RUNS: the open executor seam behind the `spawn` and `rayon` words.
///
/// # The word is sugar and this is the door
///
/// `spawn` selects [`Thread`] and `rayon` selects [`Rayon`], and both are ordinary implementations
/// of this trait with no privilege the seam does not give them. A deployment holding a pool of its
/// own implements this and installs the value into `<Node>Polling`, displacing the shipped citizen
/// at the field the declaration's word typed — so a third-party executor costs no vocabulary word,
/// which is the framework-open law: the enum-shaped alternative would make every new pool a change
/// to this crate's grammar.
///
/// # It DETACHES, and that is the whole contract
///
/// There is no handle, no join and no answer. A detached tick's `Result` is dropped where it is
/// produced, because the party that could report it — the resident, which holds the taps — has
/// already moved on: the seat answered [`Swept::Dispatched`](super::Swept) the moment the work was
/// handed over. A body whose outcome must be observed writes `block` or `async(inline)`, where the
/// answer travels back through the seat and reaches the taps.
pub trait Spawn {
  /// Run `work` somewhere that is not the caller's thread, and do not wait for it.
  fn spawn(&self, work: impl FnOnce() + Send + 'static);
}

/// The `spawn` word's engine: ONE OS THREAD PER TICK.
///
/// The shipped default, and the ignition door's own precedent — a resident that names no runtime is
/// a thread too. A thread per tick is the honest cost of the plainest detachment: no pool to size,
/// no queue to fill, and a clock whose interval is minutes pays for a thread every minute.
///
/// A cadence fast enough for that to matter is a cadence that wants [`Rayon`] or a pool of the
/// deployment's own, which is why this is a default rather than a policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Thread(());

impl Thread {
  /// The shipped thread executor.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self(())
  }
}

impl Spawn for Thread {
  /// Spawn, and DROP the join handle — which is what detaches the thread.
  #[inline]
  fn spawn(&self, work: impl FnOnce() + Send + 'static) {
    drop(std::thread::spawn(work));
  }
}

/// The `rayon` word's engine: rayon's own global pool.
///
/// A sibling of [`Thread`] rather than a replacement: the pool is sized once for the process and a
/// tick joins the work already queued there, so a fast clock costs a task instead of a thread. What
/// it buys over the plain spawn is what a pool always buys, and what it costs is the dependency —
/// which is why it rides the optional `rayon` feature and nothing else in this crate names it.
#[cfg(feature = "rayon")]
#[cfg_attr(docsrs, doc(cfg(feature = "rayon")))]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Rayon(());

#[cfg(feature = "rayon")]
impl Rayon {
  /// The shipped rayon executor.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self(())
  }
}

#[cfg(feature = "rayon")]
impl Spawn for Rayon {
  #[inline]
  fn spawn(&self, work: impl FnOnce() + Send + 'static) {
    rayon::spawn(work);
  }
}

/// [`Spawn`]'s async twin: WHERE A DETACHED ASYNC TICK RUNS.
///
/// The `async(spawn)` word's seam, and the same layering one world over — the shipped citizen
/// ([`Tasks`]) binds it to whichever runtime a deployment already named, and a third-party executor
/// implements it directly.
///
/// # Why a value at all, when the runtime seam is a TYPE
///
/// [`AsyncSpawner`](agnostic_lite::AsyncSpawner)'s methods are static, so a task could in principle
/// be spawned by naming the type alone. Naming it alone is the problem: the lending is built by the
/// deployment, which would then have to spell the runtime in a turbofish on a constructor whose
/// every other argument is inferred. A value is what makes the executor an ordinary constructor
/// argument, told apart from its neighbours by the type it carries.
///
/// A blanket `impl<S: AsyncSpawner> AsyncSpawn for S` would remove the wrapper and CLOSE the seam:
/// no downstream type could then implement this trait, because coherence cannot rule out that type
/// implementing `AsyncSpawner` later. The wrapper is what keeps the door open.
pub trait AsyncSpawn {
  /// Run `work` as a task, and do not wait for it.
  ///
  /// [`Spawn::spawn`]'s contract verbatim, futures instead of closures: no handle, no join,
  /// and the answer is dropped where it is produced.
  fn spawn(&self, work: impl Future<Output = ()> + Send + 'static);
}

/// The `async(spawn)` word's shipped engine: the runtime the deployment already named.
///
/// It holds the spawner rather than only its type so that `Tasks::new(TokioSpawner)` infers `R` —
/// the constructor argument's whole reason, argued at [`AsyncSpawn`]. The value costs nothing: an
/// [`AsyncSpawner`](agnostic_lite::AsyncSpawner) is `Copy + Send + Sync + 'static` and every shipped
/// one is a unit struct.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Tasks<R>(R);

// Hand-written so `R` need not be `Debug`. A runtime marker is somebody else's unit struct and
// `AsyncSpawner` asks nothing of it here, so a derive would put a bound on the LENDING's own `Debug`
// — the value this wraps is printed by parties that never spawn anything.
impl<R> core::fmt::Debug for Tasks<R> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Tasks")
      .field("runtime", &core::any::type_name::<R>())
      .finish()
  }
}

impl<R> Tasks<R> {
  /// Spawn onto `spawner`.
  #[inline]
  #[must_use]
  pub const fn new(spawner: R) -> Self {
    Self(spawner)
  }
}

impl<R> AsyncSpawn for Tasks<R>
where
  R: agnostic_lite::AsyncSpawner,
{
  #[inline]
  fn spawn(&self, work: impl Future<Output = ()> + Send + 'static) {
    R::spawn_detach(work);
  }
}

/// AT MOST ONE IN FLIGHT: the cell a detached SYNC clock claims per tick.
///
/// The default posture of `spawn` and `rayon`, and the `concurrent` word is what turns it off. The
/// asymmetry with `async(spawn)` is the ruling's, and it is about what a pile-up COSTS: a task that
/// waits is cheap and a runtime multiplexes them, while a thread that waits is a stack — so an
/// unbounded pile of blocking ticks is the failure mode a default has to stand against.
///
/// # A skip is not a loss and it SPEAKS
///
/// A tick that finds the cell claimed is a tick whose predecessor is still working, and the next
/// interval asks the same question again — which is the same coalescing posture
/// [`Ticker`](super::Ticker)'s own cell spells about the inbox. The seat answers
/// [`Swept::Lapped`](super::Swept) and the resident says
/// [`Observation::Lapped`](super::Observation) at INFO: configured behaviour working, not an alarm.
///
/// # The cell is freed by DROP
///
/// [`InFlight`] is a guard the work owns, so a body that panicked, unwound or was cancelled leaves
/// the cell as it found it. A cell nobody freed is a clock that never ticks again, which is exactly
/// the shape [`Tick`](super::Ticked)'s own `Drop` exists to prevent one layer over.
#[derive(Debug, Clone, Default)]
pub struct AtMostOne(Arc<AtomicBool>);

impl AtMostOne {
  /// A free cell.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self::default()
  }

  /// Claim it for one tick, or `None` where the previous tick still holds it.
  #[inline]
  #[must_use]
  pub fn claim(&self) -> Option<InFlight> {
    (!self.0.swap(true, Ordering::AcqRel)).then(|| InFlight(self.0.clone()))
  }

  /// Whether a tick holds it right now.
  #[inline]
  #[must_use]
  pub fn claimed(&self) -> bool {
    self.0.load(Ordering::Acquire)
  }
}

/// One claim on an [`AtMostOne`], released when it drops.
///
/// It carries no method: the whole of what it is for is being alive, and the work it travels with is
/// what keeps it so.
#[derive(Debug)]
pub struct InFlight(Arc<AtomicBool>);

impl Drop for InFlight {
  #[inline]
  fn drop(&mut self) {
    self.0.store(false, Ordering::Release);
  }
}

#[cfg(test)]
mod tests;