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 three facts a stored [`Rate`] states about itself — [`Timebase`](super::super::Timebase)'s
//! storage face over the other reading, and the one place the reciprocal is deliberately NOT taken.
//!
//! ```text
//!   fps_num   i32   ┐  the RATE's own pair: 30000/1001 for NTSC video
//!   fps_den   i32   ┘  and NOT 1001/30000, which is the timebase of it
//! ```
//!
//! # The columns hold the reading the field is named for
//!
//! `mediatime::Rate::to_timebase` swaps the pair, so a rate and its timebase are one value in two
//! readings and either could in principle be what a column holds. This citizen stores the RATE, and
//! the reason is that any other rule needs something in the schema to carry it:
//!
//! - A client sends `30000/1001` and the column holds `30000/1001`, so a query is the number that
//!   was sent rather than a division away from it.
//! - Two `INTEGER` columns look the same whichever convention filled them, so a table storing the
//!   reciprocal would be indistinguishable from one storing the value, and the only place the
//!   difference could live is a comment.
//! - A stream declaring both a rate and a timebase stores both, in two fields, each in its own
//!   reading — which is what the two citizens' rosters already say by mirroring each other entry for
//!   entry rather than by one being the other's storage form.
//!
//! Everything else here is the timebase's storage face verbatim, because the shape is: two `i32`s
//! reduced through one function, bound as two placeholders, read back by name, and carried in a
//! cursor as eight big-endian bytes. See [`Rate::reduced`] for the reduction and
//! [`Timebase`](super::super::Timebase)'s own storage module for the argument that a silent
//! reduction mismatch is the failure worth guarding.
//!
//! # The second bite: `record` retires `ColumnKind`/`Carrier`/`Assemble`
//!
//! [`Rate`] now carries `record(write = "Rate::head_reduced")` (ingraph#380, door (a) of
//! ingraph#377): the fragment HEAD took a whole-value transform seat, `fn(&Self) -> Self`, spent at
//! the bind and the cursor's write alike — the shape a per-field `fn(&T) -> T` could never spell,
//! a gcd reduction reading BOTH halves. [`Rate::head_reduced`] fills it, and its own body is
//! [`Rate::reduced`] rebuilt into a [`Rate`], so the emitted `Carrier` now pushes the identical pair
//! the hand one used to. The emitted `ColumnKind` names the same two columns this module's own
//! [`SEGMENTS`] does — pinned by a test that reads `<Rate as ColumnKind>::SEGMENTS` through the
//! trait rather than by naming the constant, so it now reads the EMITTED impl unmodified.
//!
//! # The third bite: the cursor byte form becomes a MOUNT
//!
//! The parallel hand kit is gone. `record(<db>(cursor = "RateCursor"))` (ingraph#387, door (d) of
//! ingraph#377) names a codec per dialect and the emission's cursor row delegates to it instead of
//! framing, so the eight flat bytes this citizen has always written are now the DECLARED byte form
//! rather than an impl hung beside the declaration. [`RateCursor`] is that codec and the bytes are
//! unchanged — outstanding page tokens keep resuming, which is the one property a migration of a
//! byte form owes.
//!
//! Two facts made the mount legal here, and neither is the comparison door:
//!
//! - **The cursor seam names no driver.** It is keyed on `crate::dialect`'s markers, which ship
//!   ungated, so naming three dialects costs this crate no feature wall — where
//!   `record(<db>(comparison = "…"))` is keyed on `sqlx`'s own backend types and would gate this
//!   citizen's lowering behind features the manifest deliberately does not have. That door stays
//!   shut and [`comparison`](super::comparison) stays hand-written; see it for the full argument.
//! - **A mounted read raises nothing** (ingraph#394). The framed read rebuilds through the
//!   construction protocol, so `builder(fallible)` had nowhere to put an `Err` and the pair was
//!   refused by name; a codec hands back a built value and the emission applies only the head `read`
//!   mirror, so the protocol is never consulted. The exemption holds for exactly as long as EVERY
//!   declared dialect mounts — which is why all three name [`RateCursor`] rather than some riding
//!   the framed default.
//!
//! What this leaves for THIS module to write by hand:
//!
//! - [`RateColumnError`] and [`assembled`] — the one decode rule, unmoved, because [`RateCursor`]
//!   still needs it directly and the emitted raise now reaches it too, through [`CheckedFps`] below.
//! - [`RateCursor`] — the codec the declaration names. A TYPE rather than an impl on [`Rate`]: the
//!   seat takes one implementor because `encode` and `decode` are duals, and a value that mounts per
//!   dialect has no `CursorValue` row at all, the two being `E0119` against the framework's blanket.
//! - [`CheckedFps`] — the raise's OWN remaining question, independent of `write`/`read` AND, it
//!   turns out, of `sqlx` itself (mediagraph#86): a wrapped fragment's raise rebuilds through the
//!   remote's own constructor, and `mediatime::Rate` has none of the infallible shape `builder`'s
//!   default expects. See its own doc for why a trait was the answer and not a new `mediatime`
//!   constructor. Its error is [`RateColumnError`] — the same one [`assembled`] already answers —
//!   so the trait and its impl stand UNGATED beside their neighbours here; the one seat that is
//!   actually `sqlx`'s is the separate, gated `impl From<RateColumnError> for sqlx::Error` right
//!   after it, which is what discharges the `From<E> for sqlx::Error` a fallible protocol owes.

use core::{fmt, num::NonZeroI32};

use crate::CursorCodec;
#[cfg(feature = "sqlx")]
use crate::{ColumnName, ColumnShape, FieldName};
use mediatime as mt;

use super::Rate;

#[cfg(test)]
mod tests;

/// The numerator's segment — the name [`comparison`](super::comparison) frames its predicate at.
///
/// `record`'s own emission now names the columns for the width, the bind and the raise — this pair
/// is what is LEFT to hand-name, because the hand crossing in [`comparison`](super::comparison) is
/// the one face `record` was not asked to mount (door (d), the family-generic feature reason). Gated
/// with that module, its one remaining reader.
#[cfg(feature = "sqlx")]
pub(super) const NUM: &FieldName = FieldName::new("num");

/// The denominator's segment.
#[cfg(feature = "sqlx")]
pub(super) const DEN: &FieldName = FieldName::new("den");

/// **The two columns a rate spans, in [`comparison`](super::comparison)'s own reading** — the same
/// two names the emitted `ColumnKind` gives them, restated here because the hand crossing frames its
/// predicate by NAME rather than by reading the trait.
///
/// The same two SHORT names the timebase citizen uses, and the collision is only apparent: a field
/// lends its own name to its segments, so a `fps: Rate` beside a `timebase: Timebase` renders
/// `fps_num`/`fps_den` and `timebase_num`/`timebase_den` — four columns, no shared spelling. What
/// the short names cost is that a `flattened` rate and a `flattened` timebase in one row would
/// collide, which the framework refuses BY NAME at the declaration rather than silently prefixing
/// one away.
#[cfg(feature = "sqlx")]
pub(super) const SEGMENTS: &[ColumnShape] = &[
  ColumnShape::Plain(ColumnName::of(NUM)),
  ColumnShape::Plain(ColumnName::of(DEN)),
];

/// A pair of columns does not hold a rate, and this says which invariant they broke.
///
/// A decode error rather than a parse error, and a separate type from
/// [`ParseRateError`](super::ParseRateError): nothing here was spelled, so there is no separator to
/// be missing and no half that failed to be an integer. What is left is exactly the two domain
/// rules, met on the way in from a database rather than from a client.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum RateColumnError {
  /// The denominator column holds zero, which [`NonZeroI32`] forbids.
  ZeroDenominator,
  /// A column holds a negative value, which `mediatime`'s constructor refuses.
  NegativeHalf,
}

impl fmt::Display for RateColumnError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    let reason = match self {
      Self::ZeroDenominator => "the stored denominator must not be zero",
      Self::NegativeHalf => "neither stored half may be negative",
    };

    f.write_str(reason)
  }
}

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

/// The two columns as one value, or the invariant they broke — shared by the row decode and the
/// cursor, so a rate arriving from a database and one arriving from a page token are admitted by the
/// same rule.
fn assembled(num: i32, den: i32) -> Result<Rate, RateColumnError> {
  let den = NonZeroI32::new(den).ok_or(RateColumnError::ZeroDenominator)?;

  mt::Rate::try_fps(num, den)
    .map(Rate::new)
    .ok_or(RateColumnError::NegativeHalf)
}

/// A [`Result`]-shaped mirror of [`mt::Rate::try_fps`] — the shape the declaration's
/// `builder(entry = "checked_fps", fallible)` needs at ITS entry, reachable as
/// `mt::Rate::checked_fps` once this trait is in scope.
///
/// # Why a trait over a foreign type
///
/// The construction protocol's `fallible` word appends a bare `?` to the entry call, and that only
/// type-checks against a [`Result`] — an `Option` and a `Result` share no `FromResidual` for one to
/// answer through the other, so naming `try_fps` there directly is `E0277` at the raise.
/// `mediatime::Rate` has no constructor of the `Result` shape on its own: [`mt::Rate::fps`] panics on
/// the rows this citizen exists to refuse gracefully, which a raise reading untrusted columns cannot
/// risk, and [`mt::Rate::try_fps`] answers the `Option` this trait converts. A LOCAL trait over the
/// FOREIGN type is the orphan rule's own answer to closing that gap without asking `mediatime` to
/// grow a constructor only this crate would call.
///
/// # One validation, not two
///
/// [`checked_fps`](Self::checked_fps) is [`assembled`] called again rather than
/// [`mt::Rate::try_fps`] called afresh: the domain rules a stored pair can break are exactly
/// [`assembled`]'s two, and by the time this seat runs, the column read has already crossed `den`
/// into a [`NonZeroI32`] — so only [`RateColumnError::NegativeHalf`] is left to answer. Reusing
/// [`assembled`] is what keeps the emitted raise and [`CursorValue::read_cursor`] admitting a stored
/// pair by one rule rather than by two an editor has to keep in step.
#[cfg(feature = "sqlx")]
pub(super) trait CheckedFps {
  /// Builds from an already-typed pair, refusing exactly what [`assembled`] would.
  fn checked_fps(num: i32, den: NonZeroI32) -> Result<Self, RateColumnError>
  where
    Self: Sized;
}

#[cfg(feature = "sqlx")]
impl CheckedFps for mt::Rate {
  fn checked_fps(num: i32, den: NonZeroI32) -> Result<Self, RateColumnError> {
    assembled(num, den.get()).map(|rate| rate.get())
  }
}

/// **THE ONE SEAT THAT IS ACTUALLY `sqlx`'s.** [`CheckedFps::checked_fps`] answers
/// [`RateColumnError`], unconditionally, but the emitted raise's bare `?` needs [`sqlx::Error`]:
/// [`Assemble::assemble`]'s return type names it directly, a framework-level fact rather than a
/// per-declaration choice. [`sqlx::Error`] has no blanket [`From`] for an arbitrary
/// [`core::error::Error`] — only for [`sqlx::error::DatabaseError`], which a column-invariant
/// refusal is not — so this impl writes the boxed [`sqlx::Error::Decode`] by hand, the same one the
/// trait's own impl used to write inline before the error type moved. Gated because the type it
/// names is: the one place in this file that still has to know `sqlx::Error` by name.
///
/// **The gate is `feature = "sqlx"`, and it USED TO BE `any(feature = "sqlx", test)`** — the second
/// half was load-bearing while this house lived one crate out, and the move is what dissolved it.
///
/// The raise this discharges is the FRAMEWORK's to emit, so it fires whenever the linked `ingraph`
/// was built with `ingraph`'s own `sqlx` feature. In the declaring crate those were TWO features:
/// its `[dev-dependencies]` asked for `ingraph`'s `postgres` and `sqlite` unconditionally — a
/// dev-dependency cannot be optional — so `cargo test --lib` with its own `sqlx` off still compiled
/// the raise with no bridge for it, an `E0277` on a build nobody asked to touch `sqlx` at all. `test`
/// was the honest other half of that predicate: true on exactly the builds where the unconditional
/// pull had already put `sqlx` in the graph.
///
/// Here there is one crate and therefore one feature. `feature = "sqlx"` decides whether
/// [`crate::Assemble`] exists AND whether this bridge does, in the same build, so the two can no
/// longer disagree and the `test` arm has no gap left to cover. Keeping it would have been a gate
/// that reads as a hedge against a configuration this crate cannot be in.
///
#[cfg(feature = "sqlx")]
impl From<RateColumnError> for sqlx::Error {
  fn from(refused: RateColumnError) -> Self {
    Self::Decode(Box::new(refused))
  }
}

/// **The KEYSET position's CODEC**: eight bytes, two big-endian `i32`s, in the order [`SEGMENTS`]
/// names — the byte form this citizen has always written, mounted at every dialect it declares.
///
/// What is written is what the COLUMNS hold — the reduced pair — so a boundary compares against
/// values a row can actually have. The width is checked on the way back and so is the DOMAIN: a
/// forged `den` of zero is refused rather than turned into a rate whose type says it cannot exist.
/// The seat leaves that judgement to the codec — a mounted read never reaches the construction
/// protocol — so [`assembled`] is called here rather than relied on one layer out.
///
/// # It reduces, and the reduction is not the seat's
///
/// `record(write = "Rate::head_reduced")` already hands this codec the canonical value, so the
/// [`Rate::reduced`] call below is idempotent rather than load-bearing. It stays because it makes
/// the bytes a function of the VALUE alone: the pin that an old hand-kit token still decodes here
/// is then a statement about this codec, not about the prologue that ran before it.
///
/// # ONE codec at three dialects, and that is what keeps `builder(fallible)` legal
///
/// The byte form does not vary per store — this household never had a second one — but the seat is
/// per dialect and the fallible exemption requires EVERY declared dialect to mount. A dialect left
/// bare would ride the framed default, which raises, and would bring the refusal back for all of
/// them.
pub struct RateCursor;

impl CursorCodec<Rate> for RateCursor {
  fn encode(value: &Rate, out: &mut Vec<u8>) {
    let (num, den) = value.reduced();
    out.extend_from_slice(&num.to_be_bytes());
    out.extend_from_slice(&den.get().to_be_bytes());
  }

  fn decode(bytes: &[u8]) -> Option<Rate> {
    let (num, den) = bytes.split_at_checked(size_of::<i32>())?;
    let num = i32::from_be_bytes(num.try_into().ok()?);
    let den = i32::from_be_bytes(den.try_into().ok()?);

    assembled(num, den).ok()
  }
}