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 READ DOOR: where an emitted resolver's engine call gets the connection it runs on.
//!
//! ```text
//! Schema::build(root, …).data(SqlDoor::pooled(pool))   // the application, once
//!         │
//!         ▼
//! ctx.data::<SqlDoor<Sqlite>>()?  →  door.pool()  →  Reel::find_sqlite(pool)…  // every resolver
//! ```
//!
//! # It exists because of a MEASUREMENT, and the measurement is `Send`'s rather than async-graphql's
//!
//! `ingraph/tests/wire_trio.rs` put five shapes to the compiler and every one of them that reached a
//! borrowed CONNECTION failed the same way — *implementation of `sqlx::Acquire` is not general
//! enough* — inside a resolver, behind a free `async fn`, with owned arguments, and boxed. The
//! identical calls awaited from an ordinary test compile and run. What refuses is the `Send` bound
//! async-graphql demands of every resolver future: sqlx implements `Acquire<'c>` for
//! `&'c mut Connection`, and a `Send`-bounded future asks for that at two independent lifetimes,
//! which no impl answers.
//!
//! `&Pool<Db>` is the surface that passes — it is `Acquire` and it is `Send` by construction, the
//! pool being `Sync` and shared rather than uniquely borrowed. So the door's whole job is to hand a
//! resolver one of those, and everything else about it follows from that one fact.
//!
//! # The seam is [`SqlSource`] and the KEY is [`SqlDoor`], and the split is what `ctx.data` forces
//!
//! `Context::data::<T>` is keyed on a CONCRETE type — it is a `TypeId` lookup — so an emitted
//! resolver has to name one. A trait cannot be that name, and an emitted unit cannot be generic over
//! the application's own provider either: the unit is what
//! [`Graphql::Query`](crate::Graphql::Query) binds, and a binding is a type rather than a family.
//!
//! So the type a resolver looks up is this crate's, parameterised by the DATABASE — which the
//! emission knows, the record's own `persist(…)` block having named it — and the OPENNESS lives
//! inside it: a `SqlDoor<Db>` holds any [`SqlSource<Db>`] an application wrote. The shipped provider
//! is `sqlx::Pool<Db>` itself, through the blanket impl below, and that is what
//! [`pooled`](SqlDoor::pooled) mints.
//!
//! # ONE DOOR PER STORE TYPE, and the keying is what makes several stores legal
//!
//! `SqlDoor<Sqlite>` and `SqlDoor<Postgres>` are two types, so a schema serving records from two
//! databases installs two doors and every resolver reaches the one its own record is stored in. No
//! registry, no name, and no way for a record to read the wrong store: the parameter IS the routing.
//!
//! # The RUNTIME stays the application's
//!
//! `ingraph` enables no `runtime-*` feature of sqlx — picking a runtime is an application's act —
//! so this module compiles the pool's TYPE and never builds one. An application serving GraphQL
//! already has a runtime and already enables that feature; `Pool::connect` panics without it, which
//! is sqlx's own answer and not this crate's to intercept. This crate's own end-to-end test enables
//! it as a DEV-dependency feature, which is the same posture one tier down.

use std::sync::Arc;

/// WHERE a read runs — the seam an application answers with its own pool.
///
/// # Object-safe on purpose, and the return type is the measurement
///
/// `&Pool<Db>` rather than an associated `Acquire` surface, and the reason is the module note's
/// measurement rather than a simplification: inside a `Send` resolver future, the pool borrow is the
/// only surface sqlx's `Acquire` answers for. An associated type would have widened the seam to
/// forms that cannot be spent at the one position the seam exists for — and it would have cost the
/// object safety this trait's whole purpose rests on, `ctx.data` being a lookup on a concrete type.
///
/// What the seam DOES open is who owns the pool and how it is reached: an application holding its
/// pool inside a larger handle, behind its own accessor, or beside a tenant's routing table
/// implements this for that type and hands it to [`SqlDoor::new`]. The shipped provider is the pool
/// itself.
pub trait SqlSource<Db>: Send + Sync + 'static
where
  Db: sqlx::Database,
{
  /// The pool this source's reads run through.
  fn pool(&self) -> &sqlx::Pool<Db>;
}

/// The SHIPPED provider: a pool is its own source.
///
/// A blanket over the concrete pool rather than a wrapper type, so `SqlDoor::pooled(pool)` stores
/// what the application already holds and no second handle exists to go out of step with it.
impl<Db> SqlSource<Db> for sqlx::Pool<Db>
where
  Db: sqlx::Database,
{
  #[inline]
  fn pool(&self) -> &sqlx::Pool<Db> {
    self
  }
}

/// The DOOR a resolver takes from a request's context — one per database a schema serves.
///
/// Cloneable and cheap: the source is behind an [`Arc`], as `sqlx::Pool` is internally, so
/// installing a door costs a refcount rather than a connection.
pub struct SqlDoor<Db>
where
  Db: sqlx::Database,
{
  source: Arc<dyn SqlSource<Db>>,
}

impl<Db> SqlDoor<Db>
where
  Db: sqlx::Database,
{
  /// The SHIPPED door: read through this pool.
  #[must_use]
  #[inline]
  pub fn pooled(pool: sqlx::Pool<Db>) -> Self {
    Self::new(Arc::new(pool))
  }

  /// A door onto an application's own source.
  #[must_use]
  #[inline]
  pub const fn new(source: Arc<dyn SqlSource<Db>>) -> Self {
    Self { source }
  }

  /// The pool one read runs through — what an emitted resolver hands the engine.
  #[must_use]
  #[inline]
  pub fn pool(&self) -> &sqlx::Pool<Db> {
    self.source.pool()
  }
}

/// Written out rather than derived, for the reason every `Db`-parameterised type in this crate
/// writes its own: a derive would bound `Db: Clone`, which a database marker never is and never
/// needs to be — what is cloned is the handle inside.
impl<Db> Clone for SqlDoor<Db>
where
  Db: sqlx::Database,
{
  #[inline]
  fn clone(&self) -> Self {
    Self {
      source: Arc::clone(&self.source),
    }
  }
}

/// Written out because a trait object carries no [`Debug`](core::fmt::Debug), and the pool behind it
/// is a connection manager rather than a value worth printing. What a reader wants from this line is
/// WHICH door it is, which the database's own name answers.
impl<Db> core::fmt::Debug for SqlDoor<Db>
where
  Db: sqlx::Database,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("SqlDoor")
      .field("database", &core::any::type_name::<Db>())
      .finish()
  }
}

#[cfg(feature = "async-graphql")]
impl<Db> SqlDoor<Db>
where
  Db: sqlx::Database,
{
  /// INSTALL this door on a schema being built — the one act an application performs for it.
  ///
  /// ```ignore
  /// let schema = SqlDoor::pooled(pool)
  ///   .install(Schema::build(MediaQuery::default(), EmptyMutation, EmptySubscription))
  ///   .finish();
  /// ```
  ///
  /// A named act rather than a bare `.data(door)`, because the KEYING is the contract: the door is
  /// found by its own type, so a schema serving two databases calls this twice and each resolver
  /// reaches the store its record declared. A method here is where that sentence has a home.
  #[must_use]
  pub fn install<Q, M, S>(
    self,
    builder: async_graphql::SchemaBuilder<Q, M, S>,
  ) -> async_graphql::SchemaBuilder<Q, M, S>
  where
    Q: async_graphql::ObjectType + 'static,
    M: async_graphql::ObjectType + 'static,
    S: async_graphql::SubscriptionType + 'static,
  {
    builder.data(self)
  }
}