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 RESOURCES: the type-erased map a deployment reaches its shared handles through.
//!
//! ONE map, and `Resources` is its whole name. It held the word `Context` while it was the only
//! thing a construction was handed; that word now names the PER-NODE window
//! ([`Context`](crate::Context)) — a node's own wind-down line, its own name, and a handle onto
//! this map — and the map kept the plural noun that says what it is. A body reaches a resource
//! through `ctx.shared::<R>()`, which is this map's own [`shared`](Resources::shared) one seat out.
//!
//! [`AsyncResource`]s are built ONCE, by the launch, before any node is constructed — a model context is
//! loaded on nobody's behalf in particular, and every node that declared `Shared<R>` gets a clone of
//! the same handle. What carries them from the resource pass to the node pass is this: one
//! framework-owned map, keyed by the resource's own type, handed to each construction as `&Resources`.
//!
//! # Why ERASED, when every lookup is typed
//!
//! The map holds resources of types this crate cannot name — a deployment's resources are its own —
//! so the storage is `dyn Any` and the DOOR is typed: [`shared`](Resources::shared) takes `R` as a
//! parameter and hands back a [`Shared<R>`], with the downcast the map's business and never a
//! caller's. It is `async-graphql`'s `Resources` shape, taken deliberately: a construction reaches for
//! what it needs by type, and nothing threads a per-node tuple of handles through a walk that cannot
//! know their arity.
//!
//! # The ONE honest tooth
//!
//! A lookup for a resource the DECLARATION never demanded is a launch-time refusal naming the type,
//! not a silent `None`. The demand scan reads a node's declared `Shared<R>` FIELDS; it cannot see
//! inside a hand-written [`AsyncConstructor`](super::AsyncConstructor) body, so a body that reaches past its
//! own declaration is a mistake the map has to report rather than one the walk can prevent. The
//! context pattern accepts that gap in exchange for its ergonomics, exactly as `async-graphql` does,
//! and [`MissingResourceError`] is the record of the trade.
//!
//! # THE RELEASE, which is the mirror of everything above
//!
//! ResourceCatalog are built FIRST, so they are released LAST — after every node that was handed a clone
//! has said its own goodbye and gone. [`release`](Resources::release) is that step, and what makes it
//! honest is [`Arc::into_inner`](std::sync::Arc::into_inner): a [`Shared<R>`] is a handle among
//! handles, so the map's own is the LAST one only when every borrower has finished, and unsealing it
//! is a question rather than an assertion.
//!
//! A resource whose last handle is not the map's is LEAKED — an application kept a clone of its own
//! — and the answer to that is to say so and move on. Its goodbye is skipped, the taps are told
//! under its name and the report carries the row. Waiting would be the alternative, and waiting for
//! a handle somebody else forgot to drop is a shutdown that never returns.

use core::any::{Any, TypeId};

use std::{collections::HashMap, sync::Arc};

use crate::{
  drive::Taps,
  resource::{AsyncResource, ResourceName, Shared},
};

use super::teardown::{Farewell, Parting, Untorn, farewell};

#[cfg(test)]
mod tests;

/// The shared resources a launch built, reachable by type.
///
/// Populated by the launch walk — resources first, then nodes, so a construction always finds what
/// the pass before it built — and handed to every [`AsyncConstructor`](super::AsyncConstructor) as `&Resources`.
/// A hand-wired arrangement builds one with [`with`](Self::with) and gets the same doors.
///
/// # `Send + Sync`, and it costs nothing to promise
///
/// The values are [`Shared<R>`] handles and [`AsyncResource`] is `Send + Sync` by supertrait, so the map
/// crosses threads because everything in it already does. That is what lets one context be borrowed
/// by constructions running wherever the launch runs.
///
/// # Examples
///
/// ```
/// use ingraph::{Resources, AsyncResource, Shared};
///
/// 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 ctx = Resources::new().with(Shared::new(Egemma { dim: 768 }));
///
/// // The door is typed: the map holds `dyn Any`, and a caller never downcasts.
/// let model = ctx.shared::<Egemma>().expect("the launch built it");
/// assert_eq!(model.dim, 768);
///
/// // A resource nothing built is a refusal that NAMES the type, never a silent `None`.
/// struct Whisper;
/// # impl AsyncResource for Whisper {
/// #   type Options = ();
/// #   type Error = core::convert::Infallible;
/// #   async fn build(_ctx: &Resources, _: ()) -> Result<Self, Self::Error> { Ok(Self) }
/// # }
/// let refusal = ctx.shared::<Whisper>().expect_err("nothing built one");
/// assert!(refusal.to_string().contains("Whisper"));
/// ```
#[derive(Default)]
pub struct Resources {
  shared: HashMap<TypeId, Box<dyn Any + Send + Sync>>,
  // The resources that enrolled a GOODBYE, in the order they were built — walked backwards at
  // release. A list beside the map rather than a second map, because what the release needs is an
  // ORDER and a map has none.
  releases: Vec<Release>,
}

impl Resources {
  /// Nothing built yet.
  #[inline]
  #[must_use]
  pub fn new() -> Self {
    Self {
      shared: HashMap::new(),
      releases: Vec::new(),
    }
  }

  /// Put `resource` in, and hand the context back — the door a hand-wired arrangement builds one
  /// through.
  ///
  /// A second handle for a type already in REPLACES it, which is the only answer a map can give and
  /// the one the walk never needs: a resource is built once per type, so a second insertion is a
  /// hand-written context stating its own last word.
  #[inline]
  #[must_use]
  pub fn with<R: AsyncResource + 'static>(mut self, resource: Shared<R>) -> Self {
    self.insert(resource);
    self
  }

  /// [`with`](Self::with), in place — what the launch walk spends, one call per resource it built.
  #[inline]
  pub fn insert<R: AsyncResource + 'static>(&mut self, resource: Shared<R>) -> &mut Self {
    self.shared.insert(TypeId::of::<R>(), Box::new(resource));
    self
  }

  /// Put `resource` in AND enrol its goodbye — where the `#[ingraph(resource(teardown))]` word
  /// routes.
  ///
  /// [`with`](Self::with) for a resource that has something to say before the process leaves it: a
  /// pool to drain, a lock to remove, a device to release politely. It is released LAST of
  /// everything the launch built, and only where the map's handle turns out to be the last one —
  /// see the module note.
  ///
  /// What gets SAID is [`AsyncResource::goodbye`], whose default drops. That is the word's whole
  /// economy read from this end: one door for every resource a declaration enrolled, no
  /// [`AsyncTeardown`] bound anywhere on the road, and a resource that overrode nothing enrolling a
  /// goodbye that costs one row and says nothing.
  #[inline]
  #[must_use]
  pub fn with_goodbye<R: AsyncResource + 'static>(mut self, resource: Shared<R>) -> Self {
    self.insert_goodbye(resource);
    self
  }

  /// [`with_goodbye`](Self::with_goodbye), in place.
  ///
  /// A second handle for a type already in replaces the HANDLE, exactly as [`insert`](Self::insert)
  /// does, and enrols a second goodbye for it — which is the only honest answer: the release walks
  /// its own list, and the first enrolment would otherwise be a goodbye for a value the map no
  /// longer holds.
  pub fn insert_goodbye<R: AsyncResource + 'static>(&mut self, resource: Shared<R>) -> &mut Self {
    self.insert(resource);
    self.releases.push(Release {
      resource: ResourceName::of::<R>(),
      id: TypeId::of::<R>(),
      unseal: unseal::<R>,
    });
    self
  }

  /// The handle to `R`, cloned — a cheap `Arc` bump, and the whole of what a construction reaches
  /// for.
  ///
  /// # Errors
  ///
  /// [`MissingResourceError`] where nothing built an `R`. See the module note for why that is a
  /// refusal and not a `None`.
  #[inline]
  pub fn shared<R: AsyncResource + 'static>(&self) -> Result<Shared<R>, MissingResourceError> {
    self
      .shared
      .get(&TypeId::of::<R>())
      .and_then(|resource| resource.downcast_ref::<Shared<R>>())
      .cloned()
      .ok_or_else(MissingResourceError::of::<R>)
  }

  /// Whether an `R` is in — the question a check asks without wanting the handle.
  #[inline]
  #[must_use]
  pub fn holds<R: AsyncResource + 'static>(&self) -> bool {
    self.shared.contains_key(&TypeId::of::<R>())
  }

  /// How many resources the launch built.
  #[inline]
  #[must_use]
  pub fn len(&self) -> usize {
    self.shared.len()
  }

  /// Whether none was.
  #[inline]
  #[must_use]
  pub fn is_empty(&self) -> bool {
    self.shared.is_empty()
  }

  /// How many resources enrolled a goodbye.
  #[inline]
  #[must_use]
  pub fn goodbyes(&self) -> usize {
    self.releases.len()
  }

  /// RELEASE every resource that enrolled a goodbye, LAST BUILT FIRST, and never stop for a
  /// refusal.
  ///
  /// The chain's last step and the mirror of the launch's first: what was built before anything
  /// else is let go of after everything else. It spends the same walk the nodes' own goodbyes went
  /// through — one mechanism, one order, one report — so a refusal here is tapped and named exactly
  /// as a node's is, and a resource that could not be unsealed is a row rather than a wait.
  ///
  /// Whatever enrolled nothing is dropped as this returns, which is the shipped posture: a pool
  /// closes its connections on the way out, and a value with nothing to await never needed a seat
  /// here.
  pub(super) async fn release(mut self, taps: &Taps) -> Vec<Untorn> {
    let farewells: Vec<Farewell> = self
      .releases
      .drain(..)
      .filter_map(|release| {
        // The handle comes OUT of the map, so the goodbye owns the very thing it is saying goodbye
        // to. A release whose type is no longer in the map is one a later `insert` replaced, and
        // there is nothing left of it to say anything to.
        let handle = self.shared.remove(&release.id)?;
        let unseal = release.unseal;
        Some(Farewell::held(release.resource.as_str(), move || {
          unseal(handle)
        }))
      })
      .collect();
    let untorn = farewell(farewells, taps).await;
    // Everything that enrolled nothing, released the shipped way, and only now: a resource with no
    // goodbye may still be the one another resource's goodbye was reaching for.
    drop(self);
    untorn
  }

  /// The names of the resources that enrolled a goodbye, in the order they were built.
  ///
  /// What an ABORT reports with. Nothing is unsealed and nothing is said — see
  /// [`App::abort`](super::App::abort) — so all the report can carry is who was enrolled, and this
  /// is the list.
  pub(super) fn enrolled(&self) -> impl Iterator<Item = &'static ResourceName> {
    self.releases.iter().map(|release| release.resource)
  }
}

/// RELEASE the deployment's resources — the chain's last step, over the map behind `ctx`.
///
/// [`Resources::release`] needs the map by value, and what a running world holds is an
/// [`Arc`] of one. So this is the unsealing one layer up, and it is
/// [`Arc::into_inner`](std::sync::Arc::into_inner) for the same reason it is inside: whether this
/// handle is the last is a question rather than an assumption.
///
/// Where it is NOT the last, every enrolled resource is unreachable — the map holding it is still
/// somebody's — so each is reported as held rather than silently skipped. The count such a row
/// carries is the MAP's remaining holders, which is the honest number for the fact being reported:
/// how many parties can still reach the resource.
pub(super) async fn released(ctx: Arc<Resources>, taps: &Taps) -> Vec<Untorn> {
  let enrolled: Vec<&'static ResourceName> = ctx.enrolled().collect();
  let holders = Arc::strong_count(&ctx);
  match Arc::into_inner(ctx) {
    Some(ctx) => ctx.release(taps).await,
    None => {
      let stranded = enrolled
        .into_iter()
        .map(|resource| {
          Farewell::held(resource.as_str(), move || {
            Parting::Held(holders.saturating_sub(1))
          })
        })
        .collect();
      farewell(stranded, taps).await
    }
  }
}

/// One resource's enrolled goodbye: whose it is, which entry of the map holds it, and how to unseal
/// it.
///
/// `unseal` is a plain function POINTER rather than a boxed closure, and it can be because the
/// monomorphised function item below is the whole of what has to be remembered: the value itself
/// stays in the map until the release pulls it out, so nothing is captured and nothing is allocated
/// for an enrolment that may never be spent.
struct Release {
  resource: &'static ResourceName,
  id: TypeId,
  unseal: fn(Box<dyn Any + Send + Sync>) -> Parting,
}

/// Take `R` back out of its handle, and answer the goodbye — or the leak.
///
/// The one place [`Arc::into_inner`](std::sync::Arc::into_inner) is spent, and it is spent rather
/// than `try_unwrap` for the reason the two differ: `into_inner` promises that exactly one of
/// several concurrent callers wins, so a resource whose last two handles are dropped at once is
/// still torn down once rather than by neither of them.
///
/// The goodbye it answers with is [`AsyncResource::goodbye`] — the resource-side seat, defaulted to a
/// drop — so this function is monomorphised for every enrolled resource without any of them owing a
/// [`AsyncTeardown`] impl.
fn unseal<R: AsyncResource + 'static>(handle: Box<dyn Any + Send + Sync>) -> Parting {
  let shared = handle
    .downcast::<Shared<R>>()
    .expect("the map entry was keyed by the very type this release was minted at");
  // Read BEFORE the unseal, which consumes: what a leak report wants is how many are still out, and
  // `into_inner` lets go of ours whether it wins or loses.
  let holders = shared.holders();
  match shared.unseal() {
    Some(resource) => Parting::Say(resource.goodbye()),
    None => Parting::Held(holders.saturating_sub(1)),
  }
}

impl core::fmt::Debug for Resources {
  /// The ARITY, for [`Taps`](crate::Taps)' own reason: a resource is somebody else's type with no
  /// useful [`Debug`](core::fmt::Debug), and demanding one would bound every author's type for the
  /// benefit of this line.
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Resources")
      .field("resources", &self.shared.len())
      .field("goodbyes", &self.releases.len())
      .finish()
  }
}

/// A construction reached for a resource nothing built — the resource map's one honest refusal.
///
/// It names the TYPE, which is the whole of what a reader needs: the fix is either declaring the
/// resource with `#[ingraph::resource]` or spelling the `Shared<R>` field that would have made the
/// demand scan build it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, derive_more::Display)]
#[display(
  "the resource `{}` is not in this deployment's resources — nothing built one, so either its \
   declaration is missing (`#[ingraph::resource]`) or this construction reached past the \
   `Shared<…>` fields its own declaration states",
  self.resource.as_str()
)]
pub struct MissingResourceError {
  resource: &'static ResourceName,
}

impl MissingResourceError {
  /// The refusal a lookup for `R` gives.
  #[inline]
  #[must_use]
  pub fn of<R: AsyncResource>() -> Self {
    Self {
      resource: ResourceName::of::<R>(),
    }
  }

  /// The resource nothing built — the compiler's own path for the type, so a reader can find it.
  #[inline]
  #[must_use]
  pub const fn resource(&self) -> &'static ResourceName {
    self.resource
  }
}

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