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 BINDING: async-graphql's `DataLoader` as one provider of [`Batched`], reached from
//! [`AsyncBatchLoad`].
//!
//! ```text
//! AsyncBatchLoad<K>                 ← ingraph's seam: these keys, in one ask
//!     │  AsLoader
//!     ▼
//! dataloader::Loader<K>        ← async-graphql's: the window, the dedup, the fan-out
//!     │  DataLoader::new(…, spawner)
//!     ▼
//! Batched<K, V>                ← ingraph's again: one key, answered
//!     │
//!     ▼
//! BatchDoor<K, V>              ← what the emitted resolver looks up
//! ```
//!
//! # A BINDING, and under a feature of its own
//!
//! *独立 opt-in feature — the dataloader dependency rides its own feature, costing nobody who does
//! not ask.* The ruling named five crates — `futures-channel`, `lru`, and `lru`'s `hashbrown`,
//! `foldhash` and `allocator-api2`. Measured in THIS graph the net add is two: the other three are
//! already here through other edges. Either number is a cost a build serving one root field per
//! document never uses, so the `dataloader` feature is independent of `async-graphql` — a schema
//! builds, every emitted resolver keeps its two lanes, and none of them is compiled. The
//! measurement and the `cargo tree` that took it are written out at the feature's own row in
//! `Cargo.toml`.
//!
//! It is a BINDING and not the seam for the reason the module note states: the engine below is
//! adopted whole — this file builds no window, no dedup and no fan-out — and the seam above names
//! no wire backend, so a second one binds the same [`AsyncBatchLoad`] without touching it.
//!
//! # The SPAWNER never appears here
//!
//! `DataLoader::new` takes one, and this file hands it straight through. Choosing a runtime is an
//! application's act: `ingraph` enables no `runtime-*` feature of sqlx for the same reason, and a
//! framework that spawned on a runtime of its own choosing would be making that choice for every
//! consumer at once.

use std::{collections::HashMap, hash::Hash};

use async_graphql::dataloader::{CacheFactory, DataLoader, Loader};

use super::{AsyncBatchLoad, BatchAnswer, BatchDoor, BatchError, Batched};

/// Any [`AsyncBatchLoad`] as one of async-graphql's `Loader`s.
///
/// A TRANSPARENT wrapper — the `pub` field IS the contract, the [`Reverse`](core::cmp::Reverse)
/// shape — so a mint site reads `AsLoader(SqlRows::new(door))` and nothing has to be looked up to
/// know what is inside.
///
/// # Every engine bound is carried HERE
///
/// [`AsyncBatchLoad`] bounds its key by nothing, because a batch read needs nothing of it. What the
/// COALESCING engine needs is another matter — a key it can hash and compare to dedup, and clone to
/// fan an answer back out — and those are stated at this impl, which is the position that spends
/// them. That placement is what keeps a third-party loader over an un-hashable key legal at the
/// seam while this binding refuses it, at the binding, with the bound named.
pub struct AsLoader<L>(pub L);

impl<K, L> Loader<K> for AsLoader<L>
where
  K: Hash + Eq + Clone + Send + Sync + 'static,
  L: AsyncBatchLoad<K>,
  L::Value: Clone + Send + Sync + 'static,
{
  type Error = BatchError;
  type Value = L::Value;

  // `manual_async_fn`: the explicit `-> impl Future<…> + Send` is deliberate and is the same
  // spelling `AsyncBatchLoad::load` carries. The engine SPAWNS this future, so it has to be provably
  // `Send` from outside, which an `async fn`'s return is not (rustc #100013).
  #[allow(
    clippy::manual_async_fn,
    reason = "the `+ Send` is the point — see the note above"
  )]
  fn load(
    &self,
    keys: &[K],
  ) -> impl core::future::Future<Output = Result<HashMap<K, Self::Value>, Self::Error>> + Send {
    // The seam answers PAIRS and the engine wants a map, which is exactly the neutrality the two
    // shapes were chosen for: the collection and its hasher are the engine's, named here and
    // nowhere in the seam.
    async move { Ok(self.0.load(keys).await?.into_iter().collect()) }
  }
}

/// The engine as a door's provider — the second half of the binding.
///
/// Generic over the CACHE FACTORY rather than fixed at `NoCache`, so an application that wants a
/// request-scoped `LruCache` installs one and the door does not care. `load_one`'s own impl block
/// is bounded that way and this one follows it.
impl<K, L, C> Batched<K, L::Value> for DataLoader<AsLoader<L>, C>
where
  K: Hash + Eq + Clone + Send + Sync + 'static,
  L: AsyncBatchLoad<K>,
  L::Value: Clone + Send + Sync + 'static,
  C: CacheFactory,
{
  #[inline]
  fn one(&self, key: K) -> BatchAnswer<'_, L::Value> {
    Box::pin(self.load_one(key))
  }
}

impl<K, V> BatchDoor<K, V>
where
  K: Hash + Eq + Clone + Send + Sync + 'static,
  V: Clone + Send + Sync + 'static,
{
  /// THE SHIPPED DOOR: batch through async-graphql's coalescing engine, on the application's
  /// spawner.
  ///
  /// ```ignore
  /// let door = BatchDoor::batched(SqlRows::<ReelSqliteRow, Sqlite>::new(read.clone()), tokio::spawn);
  /// schema.execute(Request::new(query).data(door)).await
  /// ```
  ///
  /// `NoCache`, which is `DataLoader::new`'s own default and is the posture rather than an omission:
  /// COALESCING is the win a per-request door is installed for, and a cache is a different facility
  /// with an invalidation problem attached. An application that wants one builds the `DataLoader`
  /// itself — `DataLoader::with_cache(AsLoader(…), spawner, cache)` — and hands it to
  /// [`new`](Self::new), which is the same door with the engine chosen further out.
  ///
  /// The spawner's argument is spelled out rather than named through the library's
  /// `futures_util::future::BoxFuture` alias, so this signature costs no dependency of its own:
  /// the alias IS this type, and an application already writing `tokio::spawn` here never spells
  /// either.
  #[must_use]
  pub fn batched<L, S, R>(loader: L, spawner: S) -> Self
  where
    L: AsyncBatchLoad<K, Value = V>,
    S: Fn(core::pin::Pin<Box<dyn core::future::Future<Output = ()> + Send + 'static>>) -> R
      + Send
      + Sync
      + 'static,
  {
    Self::new(std::sync::Arc::new(DataLoader::new(
      AsLoader(loader),
      spawner,
    )))
  }
}