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
//! What the fold door PROMISES: that a lookup finds the fold a deployment installed, that it finds
//! NOTHING where none was installed — which is the answer the emitted resolver's fallback hangs on —
//! and that the pairing is the routing.

use core::{future::Future, num::NonZeroUsize};

use async_graphql::{Context, EmptyMutation, EmptySubscription, Object, Schema};

use super::{FoldDoor, installed_fold};
use crate::{
  AsyncVectorRead, AsyncVectorWrite, Connected, FoldSemantics, Hits, Max, Sum, VectorColumn,
  store::{
    VectorEngine,
    column::testkit::{Col, Fallback, FallbackRead, Refusal},
  },
};

/// Two engines that never search — the door is keyed by the engine TYPE, and nothing in this file
/// asks one a question. Written out rather than reached for through a declaration, because what is
/// under test is a lookup and a declaration would put an expansion between the claim and it.
macro_rules! scoring_engine {
  ($engine:ident) => {
    #[derive(Clone, Default)]
    struct $engine;

    impl VectorEngine for $engine {
      type Address = Vec<Col>;
      type Connection = ();
      type Element = f32;
      type Error = Refusal;
      type Options = ();
      type Score = f32;
      type SearchOptions = ();
      type WriteBuffer = Fallback;
      type ReadBuffer = FallbackRead;

      fn buffer() -> Self::WriteBuffer {
        Fallback::default()
      }

      fn finalize(buf: Self::WriteBuffer) -> Self::Address {
        buf.0
      }

      fn open(address: Self::Address) -> Self::ReadBuffer {
        Fallback(address).read()
      }
    }

    impl AsyncVectorWrite for $engine {
      type Doc = ();
      type WriteContext<'a> = ();

      fn upsert(
        &self,
        _ctx: Connected<'_, Self::Connection, Self::WriteContext<'_>>,
        _doc: Self::Doc,
      ) -> impl Future<Output = Result<(), Self::Error>> + Send {
        core::future::ready(Ok(()))
      }
    }

    impl AsyncVectorRead for $engine {
      type ReadContext<'a> = ();

      fn knn(
        &self,
        _ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
        _column: VectorColumn,
        _query: &[Self::Element],
        _k: NonZeroUsize,
        _options: Option<&Self::SearchOptions>,
      ) -> impl Future<Output = Result<Hits<Self::Address, Self::Score>, Self::Error>> + Send {
        core::future::ready(Ok(Vec::new()))
      }

      fn get(
        &self,
        _ctx: Connected<'_, Self::Connection, Self::ReadContext<'_>>,
        _column: VectorColumn,
        _address: &Self::Address,
      ) -> impl Future<Output = Result<Vec<Vec<Self::Element>>, Self::Error>> + Send {
        core::future::ready(Ok(Vec::new()))
      }
    }
  };
}

scoring_engine!(Toy);
scoring_engine!(Other);

/// One election marker's stand-in — what an emitted `<Index>By<Field>` is at this seat.
struct FramesByClip;

/// A second, so two elections of one engine can be shown not to share a fold.
struct FramesByCaption;

/// A fold nobody ships, so *any `FoldSemantics`* is not proved by a citizen.
struct Leading;

impl FoldSemantics<f32> for Leading {
  fn score(&self, bests: &[Option<f32>]) -> f32 {
    bests.iter().flatten().copied().next().unwrap_or_default()
  }

  fn name(&self) -> &str {
    "leading"
  }
}

/// The root that reads the doors back, so every claim is made through the same lookup an emitted
/// resolver makes.
struct Root;

#[Object]
impl Root {
  /// The name of whatever `(Toy × FramesByClip)` folds by, or `none` where nothing is installed.
  async fn clip_fold(&self, ctx: &Context<'_>) -> String {
    installed_fold::<Toy, FramesByClip>(ctx)
      .map_or_else(|| "none".to_owned(), |door| FoldDoor::name(door).to_owned())
  }

  async fn caption_fold(&self, ctx: &Context<'_>) -> String {
    installed_fold::<Toy, FramesByCaption>(ctx)
      .map_or_else(|| "none".to_owned(), |door| FoldDoor::name(door).to_owned())
  }

  async fn other_engine_fold(&self, ctx: &Context<'_>) -> String {
    installed_fold::<Other, FramesByClip>(ctx)
      .map_or_else(|| "none".to_owned(), |door| FoldDoor::name(door).to_owned())
  }
}

async fn asked(schema: &Schema<Root, EmptyMutation, EmptySubscription>, field: &str) -> String {
  let answer = schema.execute(format!("{{ {field} }}")).await;
  assert!(answer.errors.is_empty(), "{:?}", answer.errors);
  answer.data.to_string()
}

/// **A DEPLOYMENT THAT INSTALLS NOTHING IS FOUND TO HAVE INSTALLED NOTHING**, and that is the whole
/// contract the emitted fallback rests on: `None` here is what makes the election's own fold the
/// answer, rather than a `Sum` this module would have had to invent.
#[tokio::test]
async fn an_uninstalled_pairing_answers_nothing() {
  let schema = Schema::build(Root, EmptyMutation, EmptySubscription).finish();
  assert!(asked(&schema, "clipFold").await.contains("none"));
}

/// **ANY `FoldSemantics` INSTALLS**, including one this crate has never heard of — the openness is
/// at the Rust seam and there is no wire vocabulary to close.
#[tokio::test]
async fn a_downstream_fold_installs_and_names_itself() {
  let schema = FoldDoor::<Toy, FramesByClip>::installed(Leading)
    .install(Schema::build(Root, EmptyMutation, EmptySubscription))
    .finish();
  assert!(asked(&schema, "clipFold").await.contains("leading"));
}

/// **THE PAIRING IS THE ROUTING** — two elections of one engine, and one engine's election against
/// another's, each reaching its own door and never a neighbour's.
#[tokio::test]
async fn each_pairing_reaches_its_own_fold_and_no_other() {
  let schema = FoldDoor::<Toy, FramesByClip>::installed(Max::new())
    .install(
      FoldDoor::<Toy, FramesByCaption>::installed(Sum::new()).install(Schema::build(
        Root,
        EmptyMutation,
        EmptySubscription,
      )),
    )
    .finish();

  assert!(asked(&schema, "clipFold").await.contains("max"));
  assert!(asked(&schema, "captionFold").await.contains("sum"));
  // The SAME election marker under a DIFFERENT engine is a different door, and nothing was installed
  // at that pairing.
  assert!(asked(&schema, "otherEngineFold").await.contains("none"));
}

/// The DEBUG line names what is installed, which is the third place the fold's own name is spent.
#[test]
fn the_debug_line_names_the_installed_fold() {
  let door = FoldDoor::<Toy, FramesByClip>::installed(Max::new());
  let rendered = format!("{door:?}");
  assert!(rendered.contains("max"), "{rendered}");
  assert!(rendered.contains("FoldDoor"), "{rendered}");
}