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 CONTEXT: what ONE NODE is handed for its working life — the deployment it belongs to, the
//! wind-down line it hears on, and its own name.
//!
//! Every compute face in this crate takes one, first after `self`, and it is the same value at every
//! kind: [`Operator::accept`](crate::Operator::accept) borrows it once per delivery,
//! [`StreamOperator::run`](crate::StreamOperator::run) borrows it for one delivery's whole life, and
//! [`AutonomousOperator::run`](crate::AutonomousOperator::run) and
//! [`Source::run`](crate::Source::run) — the two kinds whose `run` IS the node's whole life — take it
//! BY VALUE for the same reason they take `self` that way: there is nothing after them.
//!
//! # It is a WINDOW and not a bag
//!
//! Three doors and no more:
//!
//! | door | what it answers |
//! |---|---|
//! | [`shutdown`](Context::shutdown) | the node's own wind-down line — *stop taking new work* |
//! | [`shared`](Context::shared) | a resource the deployment built, by type |
//! | [`node`](Context::node) | who this is, which is what a body's own logs and errors want |
//!
//! Nothing else belongs here. A per-item fact rides the [`Delivery`](crate::Delivery); a per-emission
//! one rides the [`Emitter`](crate::Emitter); a per-CLOCK least-privilege handle rides the
//! [grants](crate::Grant) a declaration wrote. See [`shared`](Context::shared) for the two-roads note
//! that keeps this window and those grants apart on purpose.
//!
//! # ONE LINE covers three ways of being told
//!
//! A node's [`ShutdownSignal`] is not a second announcement beside the deployment's; it is the road
//! every wind-down arrives by. [`App::shutdown`](crate::App::shutdown)'s first step announces on
//! every [`Stopper`](crate::Stopper) the launch kept, a caller that wants ONE node stopped announces
//! on that node's own, and a source registered through
//! [`App::halt_on`](crate::App::halt_on) reaches the same walk. So a body that reads
//! `ctx.shutdown()` mid-item hears all three through one door, and no deployment-wide tenant had to
//! be minted beside the per-node lines to make it so.
//!
//! # The RESOURCES are `Option`, and that is the hand-wired case rather than a defect
//!
//! A deployment always shares its map. A hand-driven test — an `accept` called directly, a lane a
//! test drives itself — has no launch and therefore no map, and the honest answer to
//! `ctx.shared::<R>()` there is the same refusal a launch gives for a resource nothing built:
//! [`MissingResourceError`] naming `R`. It is never a panic, which is what
//! [`Emitter::shared`]'s own note used to say one organ over — the door moved here and the reading
//! came with it.

use std::sync::Arc;

use smol_bytes::Utf8Bytes;

use crate::{
  drive::NodeName,
  resource::{AsyncResource, Shared},
  source::{ShutdownSignal, Stopper, shutdown_signal},
};

use super::resources::{MissingResourceError, Resources};

#[cfg(test)]
mod tests;

/// ONE NODE's window onto the world it runs in.
///
/// Built by the framework at the mount — one per node, carrying that node's own wind-down line —
/// and by [`new`](Self::new) where a test drives a body by hand.
///
/// # `Send + Sync`, and it costs nothing to promise
///
/// A name, a handle onto a map that is already `Send + Sync`, and two halves of a channel that is.
/// The whole value crosses onto whatever engine the node was placed on, which is what a seat handed
/// to a body has to be able to do.
///
/// # Examples
///
/// ```
/// use ingraph::{AsyncResource, Context, Resources, Shared};
/// use std::sync::Arc;
///
/// struct Egemma {
///   dim: usize,
/// }
///
/// impl AsyncResource for Egemma {
///   type Options = usize;
///   type Error = core::convert::Infallible;
///
///   async fn build(_ctx: &Resources, dim: usize) -> Result<Self, Self::Error> {
///     Ok(Self { dim })
///   }
/// }
///
/// let resources = Resources::new().with(Shared::new(Egemma { dim: 768 }));
/// let ctx = Context::new("embed").sharing(Arc::new(resources));
///
/// assert_eq!(ctx.node().as_str(), "embed");
/// assert_eq!(ctx.shared::<Egemma>().expect("the launch built it").dim, 768);
///
/// // A context nobody else holds a line onto never reads as stopping.
/// assert!(!ctx.shutdown().is_shutdown());
/// ```
pub struct Context {
  node: Utf8Bytes,
  // An `Option` because a hand-wired body needs no map to run, and `Arc` because the map is ONE and
  // every node that can reach it holds the same one: a borrow would put a lifetime on a value that
  // is moved onto an engine.
  resources: Option<Arc<Resources>>,
  shutdown: ShutdownSignal,
  // The OTHER half of a line nobody else holds — see `new`. `None` for a framework-built context,
  // whose half is the launch's and is said through by `App::shutdown`.
  own: Option<Stopper>,
}

impl Context {
  /// A context for the node called `node`, WIRED TO NOTHING: no resource map, and a wind-down line
  /// whose other half is held here and therefore can never be said on.
  ///
  /// What the DRIVER hands a body is this with both facts filled in — see
  /// [`sharing`](Self::sharing) and [`halting`](Self::halting), which are also how an author drives
  /// their own body in a test. [`Emitter::new`](crate::Emitter::new)'s shape exactly, one seat over.
  ///
  /// The line is held rather than left dangling because the two are not the same claim: a
  /// [`ShutdownSignal`] whose framework half is GONE reads as stopped — that is the type's own law
  /// — so a context that dropped its half would hand every hand-driven body an immediate wind-down.
  #[must_use]
  pub fn new(node: impl Into<Utf8Bytes>) -> Self {
    let (own, shutdown) = shutdown_signal();
    Self {
      node: node.into(),
      resources: None,
      shutdown,
      own: Some(own),
    }
  }

  /// Reach `resources` from inside this node — the RUNTIME DOOR onto the deployment's map.
  #[inline]
  #[must_use]
  pub fn sharing(mut self, resources: Arc<Resources>) -> Self {
    self.resources = Some(resources);
    self
  }

  /// Hear the wind-down on `shutdown` — the line the framework says *stop taking new work* over.
  ///
  /// It REPLACES the private line [`new`](Self::new) minted, and lets go of that line's other half
  /// as it does: a context hears on exactly one line, and a held half for a line nothing reads any
  /// more is a sender kept alive for nobody.
  #[inline]
  #[must_use]
  pub fn halting(mut self, shutdown: ShutdownSignal) -> Self {
    self.shutdown = shutdown;
    self.own = None;
    self
  }

  /// The SAME window onto a NEW wind-down line — what a driver that runs a node's deliveries one
  /// at a time hands each run.
  ///
  /// A [`StreamLane`](crate::StreamLane) mints a line PER DELIVERY, because that face's seat is
  /// taken by value and one delivery is one whole life; the node facts either side of it — the map
  /// and the name — are the same at every run, so they are carried across rather than re-derived.
  #[inline]
  #[must_use]
  pub(crate) fn reopened(&self, shutdown: ShutdownSignal) -> Self {
    Self {
      node: self.node.clone(),
      resources: self.resources.clone(),
      shutdown,
      own: None,
    }
  }

  /// The node's name AS THE CRATE HOLDS IT — what a settle or a tap that wants an owned copy takes.
  #[inline]
  pub(crate) const fn named(&self) -> &Utf8Bytes {
    &self.node
  }

  /// [`sharing`](Self::sharing), in place — what a driver that already holds a context spends.
  #[inline]
  pub(crate) fn set_resources(&mut self, resources: Arc<Resources>) {
    self.resources = Some(resources);
  }

  /// [`halting`](Self::halting), in place.
  #[inline]
  pub(crate) fn set_shutdown(&mut self, shutdown: ShutdownSignal) {
    self.shutdown = shutdown;
    self.own = None;
  }

  /// WHO THIS IS — the name the deployment mounted this node under, which is what a body's own logs
  /// and errors want and what a shutdown report prints.
  #[inline]
  #[must_use]
  pub fn node(&self) -> &NodeName {
    NodeName::new(&self.node)
  }

  /// **THE WIND-DOWN LINE** — the one thing the framework ever says to a running body.
  ///
  /// Its three doors are [`ShutdownSignal`]'s own: a LOOK a loop takes once per pass, a PARK for a
  /// body with nothing else to do, and an ARM for one that waits on its own edges beside it. See the
  /// module note for why one line carries the deployment's broadcast, a targeted stop and an
  /// [`App::halt_on`](crate::App::halt_on) registration alike.
  #[inline]
  #[must_use]
  pub const fn shutdown(&self) -> &ShutdownSignal {
    &self.shutdown
  }

  /// The shared `R` this deployment built — the RUNTIME DOOR onto the [`Resources`] map.
  ///
  /// # The economics, which decide which door to use
  ///
  /// A resource on the HOT PATH is grabbed at CONSTRUCTION and held as a field: a per-item lookup by
  /// [`TypeId`](core::any::TypeId) is money for nothing when the answer is the same handle every
  /// time. This door is for the occasional need — a resource one branch in a thousand reaches for, a
  /// handle a sweep wants and the steady path does not — where a field would be a demand the
  /// declaration has to carry for a case that rarely happens.
  ///
  /// # TWO ROADS to a handle, and they are deliberately separate
  ///
  /// This one is DEPLOYMENT-WIDE and reached by TYPE: whatever the launch built is here, and a body
  /// asks for what it wants when it wants it. The other is the per-clock
  /// [grant](crate::Grant) — the `context(resource("…"))` word a declaration writes beside a poll or
  /// a mutation handler — which is NAMED, LEAST-PRIVILEGE and checked at start-up: a handler is
  /// handed exactly the handles its own declaration asked for, and reaching for a fifth is a
  /// refusal rather than a runtime `Err`.
  ///
  /// Neither subsumes the other. Take the grant where the set is knowable at the declaration and the
  /// audit is worth having; take this door where it is not — see [`Grant`](crate::Grant), which
  /// carries the same paragraph from its side.
  ///
  /// # Errors
  ///
  /// [`MissingResourceError`] naming `R` where nothing built one — and equally where this context
  /// was handed no map at all, which is the same fact from the body's side: no `R` is reachable from
  /// here.
  #[inline]
  pub fn shared<R>(&self) -> Result<Shared<R>, MissingResourceError>
  where
    R: AsyncResource + 'static,
  {
    self
      .resources
      .as_deref()
      .ok_or_else(MissingResourceError::of::<R>)
      .and_then(Resources::shared::<R>)
  }

  /// The deployment's map itself, where one was shared — the borrow behind
  /// [`shared`](Self::shared), for a caller that wants to ask it more than one question.
  #[inline]
  #[must_use]
  pub fn resources(&self) -> Option<&Resources> {
    self.resources.as_deref()
  }
}

impl core::fmt::Debug for Context {
  /// WHO, HOW MUCH and WHETHER — [`Resources`]' own reason for printing arity rather than contents,
  /// and [`ShutdownSignal`]'s for printing the one fact it holds.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Context")
      .field("node", &self.node.as_str())
      .field("resources", &self.resources.as_deref().map(Resources::len))
      .field("shutdown", &self.shutdown.is_shutdown())
      .finish()
  }
}