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 TYPE WALK: [`TypeVisitor`], one visitor applied to every node a graph declares.
//!
//! # Ownership is INVERTED from the reference implementation, and that is the whole shape
//!
//! Legacy pairs a walk with an `InGraph` back-pointer: an entity names the graph it belongs to, the
//! visitor is parameterised by that graph, and the pairing is what keeps one indexer's visitor from
//! being handed another indexer's entity. The wall is real and it is bought with a bounded slot on
//! every entity's binding.
//!
//! Here the GRAPH ROOT lists its types — a user-authored struct whose fields are the nodes, and
//! `#[ingraph::graph]` writes the walk over them. So the list is the root's, there is no registry a
//! node registers itself into, and nothing on [`Transformer`](super::Transformer) points back at a
//! graph. What legacy's wall protected against is unrepresentable for a different reason: a walk is
//! written by the root that owns the list, and there is no second list for a type to be borrowed
//! from.
//!
//! # It hands TYPES, and it is not an [`Iterator`]
//!
//! An `Iterator` names ONE `Item` for the whole traversal. Here each step is a different type with
//! different associated types, so no `Item` could name them — the only common supertype is an erased
//! one, which is exactly what this shape exists to avoid. Inverting control is what buys the
//! difference: the WALK calls the visitor, so each call gets its own `E`, statically, and every call
//! monomorphises. There is no `dyn`, no registry to populate first, and no runtime reflection.
//!
//! A value list was measured against the same question and withdrawn: a `&[&dyn …]` erases the one
//! thing a visitor came for.
//!
//! # The capability bound is DECLARED on `next_type`, and that is the extension point
//!
//! An impl may not ADD a where clause to a trait method, but the TRAIT may declare one — and then
//! every impl inherits it and every walk site must PROVE it. So the bound on
//! [`next_type`](TypeVisitor::next_type) is what a visitor body may assume about `E`, it is paid by
//! every visitor, and it is added one real requirement at a time.
//!
//! It is exactly one and it always was: [`Describe<Self::Db>`](crate::Describe) — this node's home
//! in the TARGET the visitor works against.
//!
//! # A second node KIND joined THROUGH it, and the earlier reading is the record of what changed
//!
//! This note used to say that an engine-backed slot — a full-text index, a vector index, a family
//! of blobs — is a node with no table and a descriptor of its own, and that a kind would therefore
//! join as a TRAIT of its own beside this bound rather than widening it. The argument against
//! widening still stands and is the reference implementation's own: a per-family face exists to
//! reach ONE family's slot, so folding several into one trait makes the bound set the UNION of every
//! family's, paid by every visitor whether or not it has that face.
//!
//! What was wrong was the premise that a per-kind DESCRIPTOR needs a per-kind TRAIT.
//! [`Habitat`](crate::Habitat) is what took that apart: the TARGET says what a home looks like, so
//! `Describe` is one trait whose descriptor differs per kind and the bound set is still ONE
//! predicate. A slot maker's visitor is bounded exactly as a DDL visitor is, and neither pays for
//! the other's vocabulary. [`next_type`](TypeVisitor::next_type)'s signature is untouched, which is
//! the half of the earlier reading that survived.
//!
//! # THE PAIR: one walk COLLECTS and the other CANNOT
//!
//! [`TypeVisitor`] is synchronous, and both DDL visitors are: the walk collects — statements to run,
//! descriptors to audit — and the I/O runs after it, once, against one connection. That is the write
//! lane's own discipline (every statement renders before any executes, so a plan that will not render
//! leaves nothing half-written) applied to a boot sequence.
//!
//! [`AsyncTypeVisitor`] is its twin, and the record of a REFUSAL OVERTURNED. The pair was measured
//! once and declined — *nothing here runs I/O per type* — and the second initialization layer is
//! what made that untrue: a slot maker CREATES the corpus it is shown, an index, a bucket, a
//! directory, and half the engines it does that against answer with a future. There is no collecting
//! version of *create this* to postpone, so the awaited face is not a convenience here; it is the
//! only face an async engine has.
//!
//! # NO BLANKET BETWEEN THEM, and the reason is a type that wears both
//!
//! `impl<V: TypeVisitor> AsyncTypeVisitor for V` is spellable and is refused. A visitor is free to
//! wear BOTH faces with DIFFERENT [`Db`](TypeVisitor::Db)s — one machine that creates a SQL table
//! synchronously and a remote corpus asynchronously is one struct with two impls — and a blanket
//! would collide with the second of them (`E0119`) and would silently give every blocking visitor an
//! awaited face pinned to the wrong target. So the glue that drives a walk names the face it means,
//! per (target × mode), and makes no single-face assumption.

use core::future::Future;

use crate::{Describe, Habitat};

/// A visitor applied once per node the graph declares.
///
/// # What a visitor may assume about a node
///
/// [`Describe<Self::Db>`](crate::Describe), which [`next_type`](Self::next_type) declares — so a
/// body reads `<E as Describe<Self::Db>>::BLUEPRINT` and not merely the node's identity. A node that
/// describes no storage in this target is `E0277` where the WALK is written, which is where the
/// graph's field list can be fixed.
///
/// # The database is the VISITOR's, not the walk's
///
/// [`Db`](Self::Db) is an associated type rather than a parameter on the trait, because a visitor is
/// built for one database and the walk that drives it takes no side: `App::type_iter` is generic
/// over `V` alone, so the same emitted walk serves a SQLite create, a PostgreSQL create and a
/// validate against either. Putting the database on the trait would make a graph's walk name a
/// database, which is a fact about a deployment rather than about a declaration.
///
/// # Examples
///
/// A graph written by hand, and a visitor that counts the columns its nodes declare:
///
/// ```
/// use ingraph::{Column, Describe, FieldName, Habitat, RecordAddress, Table, TypeVisitor};
///
/// struct Sqlite;
///
/// impl Habitat for Sqlite {
///   type Blueprint = Table;
/// }
///
/// struct Media;
/// struct Clip;
///
/// impl Describe<Sqlite> for Media {
///   const BLUEPRINT: Table = Table::new(
///     RecordAddress::new(FieldName::new("media"), &[FieldName::new("id")]),
///     &[Column::new(FieldName::new("id"), "INTEGER", false)],
///   );
/// }
///
/// impl Describe<Sqlite> for Clip {
///   const BLUEPRINT: Table = Table::new(
///     RecordAddress::new(FieldName::new("clip"), &[FieldName::new("id")]),
///     &[
///       Column::new(FieldName::new("id"), "INTEGER", false),
///       Column::new(FieldName::new("title"), "TEXT", true),
///     ],
///   );
/// }
///
/// /// What `#[ingraph::graph]` writes for a root whose fields are `Media` and `Clip`.
/// struct App;
///
/// impl App {
///   fn type_iter<V>(v: &mut V) -> Result<(), V::Error>
///   where
///     V: TypeVisitor,
///     Media: Describe<V::Db>,
///     Clip: Describe<V::Db>,
///   {
///     v.next_type::<Media>()?;
///     v.next_type::<Clip>()
///   }
/// }
///
/// #[derive(Default)]
/// struct Widths(Vec<usize>);
///
/// impl TypeVisitor for Widths {
///   type Db = Sqlite;
///   type Error = core::convert::Infallible;
///
///   fn next_type<E: Describe<Sqlite>>(&mut self) -> Result<(), Self::Error> {
///     self.0.push(E::BLUEPRINT.columns().width());
///     Ok(())
///   }
/// }
///
/// let mut widths = Widths::default();
/// App::type_iter(&mut widths).unwrap();
/// assert_eq!(widths.0, vec![1, 2]);
/// ```
///
/// A node this database does not store is refused where the WALK names it, and the refusal is the
/// bound's own sentence:
///
/// ```compile_fail,E0277
/// use ingraph::{Describe, TypeVisitor};
///
/// struct Sqlite;
/// struct Cue;
///
/// fn walk<V: TypeVisitor>(v: &mut V) -> Result<(), V::Error> {
///   v.next_type::<Cue>()
/// }
/// ```
pub trait TypeVisitor {
  /// The TARGET this visitor describes nodes for — a database, a full-text mount, a vector store, a
  /// family of buckets.
  ///
  /// # [`Habitat`] and nothing else, and that ONE bound is what the second layer bought
  ///
  /// The member was bound by NOTHING while every visitor here worked against a SQL dialect: what a
  /// database had to satisfy was the visitor's own question, so it was asked where the visitor was
  /// written. The initialization layer is what changed it — a walk now hands over a BLUEPRINT, and a
  /// target that has not said what a blueprint IS has nothing to hand. So the floor is exactly the
  /// vocabulary that answers that, and the rest is still the visitor's: a create visitor asks for a
  /// dialect beside it, a slot maker asks for a mount.
  type Db: Habitat;

  /// This visitor's failure.
  ///
  /// Bound-free, per [`Operator::Error`](crate::Operator::Error)'s discipline: a visitor reports in
  /// its own currency, and a caller bounds it where it must render or propagate one.
  type Error;

  /// Observe one node of the graph.
  ///
  /// # Errors
  ///
  /// Whatever this visitor's per-node work fails with. Returning `Err` ENDS the walk — the nodes
  /// after it are not visited — which is what makes a walk's refusal name the first node it could
  /// not serve rather than a list.
  fn next_type<E: Describe<Self::Db>>(&mut self) -> Result<(), Self::Error>;
}

/// [`TypeVisitor`]'s AWAITED twin — the face a walk takes when the per-node work is I/O that cannot
/// be postponed.
///
/// # Why it exists now, having been measured and declined once
///
/// The refusal was recorded in as many words: *no async face is here, because legacy carries
/// `walk_async` beside its walk because its visitors run I/O per type, and nothing here does*. That
/// was true of the two DDL visitors, which COLLECT statements and send them afterwards. It is not
/// true of the second initialization layer: a slot maker CREATES the corpus it is shown — an index,
/// a bucket, a remote collection — and there is no collecting version of *create this* to postpone.
/// Half the engines a deployment mounts answer with a future, so the awaited face is the only face
/// those targets have.
///
/// # It is a TWIN and not a supertrait, and nothing bridges the two
///
/// The dual-mode law, at the walk's own grain: a blocking visitor implements this trait not at all,
/// an awaited one implements [`TypeVisitor`] not at all, and a machine that does both work items
/// implements BOTH — with different [`Db`](Self::Db)s, which is the whole reason no blanket may
/// stand between them. See the module note.
///
/// # `Send` is NOT asked for
///
/// The returned future is bound by nothing beyond the trait's own output, which is the posture the
/// framework keeps everywhere an AUTHOR's body is the thing being awaited —
/// [`AsyncOperator::accept`](crate::AsyncOperator::accept) and
/// [`AsyncSource::run`](crate::AsyncSource::run) take it too. A slot maker holding a thread-affine
/// client stays expressible, and the glue that drives one pins rather than demands.
///
/// # Examples
///
/// A visitor that creates each corpus its target describes, awaited:
///
/// ```
/// use ingraph::{AsyncTypeVisitor, Describe, Habitat, SlotColumn, SlotName, SlotSchema};
///
/// struct Remote;
///
/// impl Habitat for Remote {
///   type Blueprint = &'static [SlotSchema];
/// }
///
/// struct Media;
///
/// impl Describe<Remote> for Media {
///   const BLUEPRINT: &'static [SlotSchema] = &[SlotSchema::new(
///     SlotName::new("media__title__lexical"),
///     &[SlotColumn::text("title")],
///   )];
/// }
///
/// #[derive(Default)]
/// struct Made(Vec<&'static str>);
///
/// impl AsyncTypeVisitor for Made {
///   type Db = Remote;
///   type Error = core::convert::Infallible;
///
///   async fn next_type<E: Describe<Remote>>(&mut self) -> Result<(), Self::Error> {
///     for corpus in E::BLUEPRINT {
///       self.0.push(corpus.slot().as_ref());
///     }
///     Ok(())
///   }
/// }
///
/// # tokio::runtime::Builder::new_current_thread().build().unwrap().block_on(async {
/// let mut made = Made::default();
/// made.next_type::<Media>().await.unwrap();
/// assert_eq!(made.0, ["media__title__lexical"]);
/// # });
/// ```
pub trait AsyncTypeVisitor {
  /// The TARGET this visitor makes homes in — [`TypeVisitor::Db`]'s member, and the same bound for
  /// the same reason.
  type Db: Habitat;

  /// This visitor's failure — bound-free, per its twin's.
  type Error;

  /// Make one node's home, awaited.
  ///
  /// # Errors
  ///
  /// Whatever this visitor's per-node work fails with. Returning `Err` ENDS the walk, exactly as it
  /// does on the blocking face: the nodes after it are not visited, so a refusal names the first
  /// home it could not make rather than a list.
  fn next_type<E: Describe<Self::Db>>(&mut self) -> impl Future<Output = Result<(), Self::Error>>;
}

#[cfg(test)]
mod tests;