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 `generations` SEAT: the engine word a declaration wrote, and the retention a deployment
//! writes beside it.
//!
//! ```ignore
//! #[ingraph::graph(generations(sqlite))]   // the ENGINE — an application's decision
//! pub struct Media { … }
//! ```
//!
//! ```ignore
//! [generations]                            # WHERE, and HOW MANY — a deployment's decisions
//! dsn = "sqlite://var/findit/generations.db"
//! keep = 2
//! ```
//!
//! # WHY THE WORD AND THE NUMBERS ARE ON DIFFERENT SIDES
//!
//! An engine decides what the framework has to COMPILE — a feature, a driver, a dialect — and that
//! is a fact about the program rather than about the machine it runs on, so it is written where the
//! program is: in the declaration, as a word. A DSN is a path on somebody's disk; a retention depth
//! is how much history one operator's disk can afford. Both change per deployment, and both are
//! exactly what a configuration file is for.
//!
//! # `keep` IS A THREE-TIER KNOB, and the third tier is the one that costs disk
//!
//! Every numeric knob in this framework is readable at three grains: a shipped DEFAULT
//! ([`DEFAULT_KEEP`]), a deployment's DOCUMENT (`[generations] keep`), and a REQUEST that turns the
//! dial on a running deployment ([`GenerationsOverride`], folded through
//! [`Curator::apply_knobs`](super::Curator::apply_knobs)). The third tier earns its place here more
//! plainly than at most seats: raising `keep` before a risky re-analysis and lowering it afterwards
//! is a deployment keeping one generation of evidence, which is a decision somebody makes at the
//! moment they make it and not one they restart a process to state.

use core::num::NonZeroUsize;

use smol_bytes::Utf8Bytes;

/// **HOW MANY GENERATIONS A CLOSURE KEEPS** when a document says nothing — ONE, the current.
///
/// The default is the sealed reading of what a superseded generation IS: a DRAFT. A re-analysis that
/// finished replaced the answer, and the answer it replaced is not content a deployment is holding
/// on somebody's behalf — it is the previous attempt. So the shipped posture is to keep the answer
/// and collect the attempt, and a deployment that wants the attempt kept says so.
///
/// It is [`NonZeroUsize`] and not [`usize`] for the reason the type exists: `keep = 0` is *delete the
/// generation every reader is on*, which is not a retention policy but a truncation, and a knob whose
/// zero is a catastrophe is a knob whose zero should not parse.
pub const DEFAULT_KEEP: NonZeroUsize = NonZeroUsize::new(1).expect("1 is not zero");

/// **WHICH ENGINE A FAMILY'S CURRENT POINTERS RUN ON** — the `generations(<engine>)` word, as a
/// value.
///
/// # A CLOSED vocabulary over an OPEN seam, and the two are not in tension
///
/// [`GenerationsStore`](super::GenerationsStore) is a trait anybody may implement; this is the list
/// of engines the framework can build UNAIDED, from a word and a DSN, with no type from the
/// deployment. Each arm is a driver this crate ships behind its own feature and a dialect it knows
/// how to render.
///
/// # WHY MONGODB IS NOT AN ARM, and why that is a statement rather than a gap
///
/// The retirement ledger's own word takes four engines, this one takes three, and the difference is
/// the RETENTION DUTY. A pointer is a row anywhere; a sweep is an anchored `DELETE` whose bound is a
/// correlated subquery over a table's own distinct runs, and that is a SQL shape. A document store
/// sweeps the same closure by MEMBERSHIP instead — read the run set, delete what is not in it — which
/// is a second implementation of [`GenerationsStore`](super::GenerationsStore) rather than a third
/// rendering of these statements. Adding it adds an arm here and changes nothing about the seam,
/// which is what makes the absence a scope line rather than a design limit.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GenerationsEngine {
  /// SQLite — `generations(sqlite)`, under `feature = "sqlite"`.
  Sqlite,
  /// PostgreSQL — `generations(postgres)`, under `feature = "postgres"`.
  Postgres,
  /// MySQL — `generations(mysql)`, under `feature = "mysql"`.
  Mysql,
}

impl GenerationsEngine {
  /// Every engine, in the order a refusal lists them.
  pub const ALL: [Self; 3] = [Self::Sqlite, Self::Postgres, Self::Mysql];

  /// The word a declaration writes: `sqlite`, `postgres`, `mysql`.
  ///
  /// The SAME spellings a record's `persist(…)` takes, and that is a requirement rather than a
  /// convenience: a deployment writing `generations(postgres)` beside `persist(postgres)` has
  /// written one word twice about one database, and two vocabularies for one set of engines is how
  /// the two come to disagree.
  #[inline]
  #[must_use]
  pub const fn as_str(self) -> &'static str {
    match self {
      Self::Sqlite => "sqlite",
      Self::Postgres => "postgres",
      Self::Mysql => "mysql",
    }
  }

  /// The feature a build needs for this engine's store to exist.
  #[inline]
  #[must_use]
  pub const fn feature(self) -> &'static str {
    self.as_str()
  }
}

impl core::str::FromStr for GenerationsEngine {
  type Err = UnknownGenerationsEngine;

  fn from_str(word: &str) -> Result<Self, Self::Err> {
    Self::ALL
      .into_iter()
      .find(|engine| engine.as_str() == word)
      .ok_or_else(|| UnknownGenerationsEngine {
        word: Utf8Bytes::from(word),
      })
  }
}

impl core::fmt::Display for GenerationsEngine {
  #[inline]
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.write_str(self.as_str())
  }
}

/// A word that is not one of the three engines the framework builds.
///
/// It names the three, because a closed vocabulary owes a reader its whole content at the point of
/// refusal — the same posture every other word-shaped refusal in this crate takes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnknownGenerationsEngine {
  /// What was written.
  word: Utf8Bytes,
}

impl UnknownGenerationsEngine {
  /// What was written.
  #[inline]
  #[must_use]
  pub fn word(&self) -> &str {
    self.word.as_str()
  }
}

impl core::fmt::Display for UnknownGenerationsEngine {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "`{word}` is not an engine the generations seat builds — it takes `sqlite`, `postgres` or \
       `mysql`. A document store sweeps by membership rather than by an anchored `DELETE`, so it is \
       a `GenerationsStore` of your own handed to `Curator::new` rather than a word here",
      word = self.word,
    )
  }
}

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

/// **WHERE THIS DEPLOYMENT KEEPS ITS POINTERS, AND HOW DEEP ITS HISTORY GOES** — the `[generations]`
/// section.
///
/// Two knobs, and the shape of the section is what makes it two: the ENGINE is the declaration's
/// (see [`GenerationsEngine`]), the TABLE NAME is the family's (`__ig_current_<family>`, minted
/// rather than configured), and what is left for a document to say is the connection and the depth.
///
/// # THE FRAMEWORK OPENS NOTHING, and `dsn` is a deployment's own statement of WHERE
///
/// `<Root>::init` takes the connection it runs on; a blob store is opened by its author; the options
/// spine's own note says the framework does no file I/O. This seat keeps that law: a store is handed
/// a pool it did not open, and this field is what a deployment READS — through [`dsn`](Self::dsn),
/// off its own options — to decide which pool to open and hand over.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct GenerationsOptions {
  /// The connection the pointers are opened on — a SQLite path (`sqlite://var/x.db`), a PostgreSQL
  /// or MySQL URL.
  ///
  /// One word for all three, because one word is what the engines' own drivers take: every one of
  /// them opens from a string, and a second field per engine would be three ways to say the thing
  /// the declaration already decided.
  #[cfg_attr(feature = "serde", serde(default))]
  dsn: Option<Utf8Bytes>,
  /// How many generations a closure keeps — see [`DEFAULT_KEEP`] for why the shipped answer is one.
  #[cfg_attr(feature = "serde", serde(default = "default_keep"))]
  keep: NonZeroUsize,
}

impl GenerationsOptions {
  /// No connection named, and the shipped retention.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self {
      dsn: None,
      keep: DEFAULT_KEEP,
    }
  }

  /// The connection this deployment named, or [`None`] where it named none.
  #[inline]
  #[must_use]
  pub fn dsn(&self) -> Option<&str> {
    self.dsn.as_ref().map(Utf8Bytes::as_str)
  }

  /// Keep the pointers at `dsn` — a statement, not an act; see the type note.
  #[inline]
  #[must_use]
  pub fn with_dsn(mut self, dsn: impl Into<Utf8Bytes>) -> Self {
    self.set_dsn(Some(dsn.into()));
    self
  }

  /// [`with_dsn`](Self::with_dsn), in place — INCLUDING back to [`None`], which is what lets a
  /// holder narrowing a value parsed off a document say so.
  #[inline]
  pub fn set_dsn(&mut self, dsn: Option<Utf8Bytes>) -> &mut Self {
    self.dsn = dsn;
    self
  }

  /// How many generations a closure keeps.
  #[inline]
  #[must_use]
  pub const fn keep(&self) -> NonZeroUsize {
    self.keep
  }

  /// Keep `keep` generations.
  #[inline]
  #[must_use]
  pub const fn with_keep(mut self, keep: NonZeroUsize) -> Self {
    self.keep = keep;
    self
  }

  /// [`with_keep`](Self::with_keep), in place.
  #[inline]
  pub const fn set_keep(&mut self, keep: NonZeroUsize) -> &mut Self {
    self.keep = keep;
    self
  }
}

impl Default for GenerationsOptions {
  /// The shipped posture — no connection named, one generation kept.
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

/// serde's own door onto [`DEFAULT_KEEP`], for a document that writes the section and not the knob.
fn default_keep() -> NonZeroUsize {
  DEFAULT_KEEP
}

/// **THE LIVE DIAL**: whichever knobs a request named, and no statement at all about the rest.
///
/// [`GenerationsOptions`]'s partial twin, and the difference between them is what an absent field
/// MEANS. On the options a missing knob is the shipped default; here it is *say nothing about this
/// one*, so a request that raises `keep` before a risky re-analysis leaves the connection exactly as
/// the document left it.
#[derive(Debug, Clone, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(deny_unknown_fields))]
pub struct GenerationsOverride {
  /// How many generations to keep from now on, or [`None`] to leave the depth where it was.
  #[cfg_attr(feature = "serde", serde(default))]
  keep: Option<NonZeroUsize>,
}

impl GenerationsOverride {
  /// Nothing named.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self { keep: None }
  }

  /// The depth this override names, or [`None`].
  #[inline]
  #[must_use]
  pub const fn keep(&self) -> Option<NonZeroUsize> {
    self.keep
  }

  /// Name `keep` as the new depth.
  #[inline]
  #[must_use]
  pub const fn with_keep(mut self, keep: NonZeroUsize) -> Self {
    self.keep = Some(keep);
    self
  }

  /// [`with_keep`](Self::with_keep), in place — including back to [`None`], which un-names it.
  #[inline]
  pub const fn set_keep(&mut self, keep: Option<NonZeroUsize>) -> &mut Self {
    self.keep = keep;
    self
  }
}