use crate::Resources;
use std::sync::{
Arc,
atomic::{AtomicUsize, Ordering},
};
use async_graphql::{EmptyMutation, EmptySubscription, Object, Schema};
use super::{search_slot, vector_slot};
use crate::{
AsyncResource, NoColumns, Shared, SlotName,
store::{FulltextEngine, FulltextMount, SlotHandle},
};
struct Shots;
struct Subs;
const TITLE: &SlotName = SlotName::new("shots__title__lexical");
const BODY: &SlotName = SlotName::new("shots__body__lexical");
#[derive(Clone, Debug, PartialEq, Eq)]
struct Corpus {
slot: String,
}
impl FulltextEngine for Corpus {
type Options = ();
type SearchOptions = ();
type Error = NoColumns;
type Score = f32;
type Address = ();
type Connection = Manager;
type WriteBuffer = ();
type ReadBuffer = ();
fn buffer() -> Self::WriteBuffer {}
fn finalize(_buf: Self::WriteBuffer) -> Self::Address {}
fn open(_address: Self::Address) -> Self::ReadBuffer {}
}
#[derive(Debug)]
struct Manager {
opened: &'static str,
}
struct Ft {
manager: Manager,
minted: Arc<AtomicUsize>,
}
impl AsyncResource for Ft {
type Options = &'static str;
type Error = core::convert::Infallible;
fn build(
_ctx: &Resources,
options: Self::Options,
) -> impl core::future::Future<Output = Result<Self, Self::Error>> + Send {
core::future::ready(Ok(Self {
manager: Manager { opened: options },
minted: Arc::new(AtomicUsize::new(0)),
}))
}
}
impl FulltextMount for Ft {
type Handle = Corpus;
fn corpus(&self, slot: impl Into<smol_bytes::Utf8Bytes>) -> Self::Handle {
self.minted.fetch_add(1, Ordering::Relaxed);
Corpus {
slot: slot.into().to_string(),
}
}
fn connection(&self) -> &Manager {
&self.manager
}
}
struct Other {
manager: Manager,
}
impl AsyncResource for Other {
type Options = ();
type Error = core::convert::Infallible;
fn build(
_ctx: &Resources,
_options: Self::Options,
) -> impl core::future::Future<Output = Result<Self, Self::Error>> + Send {
core::future::ready(Ok(Self {
manager: Manager { opened: "other" },
}))
}
}
fn mounted() -> Shared<Ft> {
Shared::new(Ft {
manager: Manager { opened: "root" },
minted: Arc::new(AtomicUsize::new(0)),
})
}
struct Query;
#[Object]
impl Query {
async fn searched(&self, ctx: &async_graphql::Context<'_>) -> async_graphql::Result<String> {
let (mut slot, connection) = search_slot::<Ft, Shots>(ctx, "searched", TITLE)?;
let handle: &mut SlotHandle<Corpus, Shots> = &mut slot;
let held = core::future::ready(handle.engine().slot.clone()).await;
Ok(format!("{held}@{}", connection.opened))
}
async fn other(&self, ctx: &async_graphql::Context<'_>) -> async_graphql::Result<String> {
let (slot, _) = search_slot::<Ft, Shots>(ctx, "other", BODY)?;
Ok(slot.engine().slot.clone())
}
}
fn schema(installed: bool) -> Schema<Query, EmptyMutation, EmptySubscription> {
let builder = Schema::build(Query, EmptyMutation, EmptySubscription);
let builder = if installed {
builder.data(mounted())
} else {
builder
};
builder.finish()
}
#[tokio::test]
async fn a_read_owns_the_handle_it_was_minted() {
let answered = schema(true).execute("{ searched }").await;
assert!(answered.errors.is_empty(), "{:?}", answered.errors);
assert_eq!(
answered.data.to_string(),
"{searched: \"shots__title__lexical@root\"}",
"the resolver did not reach its corpus, or did not reach its manager",
);
}
#[test]
fn one_lookup_answers_with_the_corpus_and_the_manager() {
let ft = Ft {
manager: Manager { opened: "root" },
minted: Arc::new(AtomicUsize::new(0)),
};
let handle = FulltextMount::corpus(&ft, TITLE.as_ref());
assert_eq!(handle.slot, "shots__title__lexical");
assert_eq!(FulltextMount::connection(&ft).opened, "root");
}
#[tokio::test]
async fn one_mount_holds_a_corpus_per_election() {
let answered = schema(true).execute("{ searched other }").await;
assert!(answered.errors.is_empty(), "{:?}", answered.errors);
let answer = answered.data.to_string();
assert!(answer.contains("shots__title__lexical"), "{answer}");
assert!(answer.contains("shots__body__lexical"), "{answer}");
}
#[test]
fn each_read_mints_its_own_corpus() {
let minted = Arc::new(AtomicUsize::new(0));
let ft = Ft {
manager: Manager { opened: "root" },
minted: Arc::clone(&minted),
};
let mut one = SlotHandle::<_, Shots>::mint(FulltextMount::corpus(&ft, TITLE.as_ref()));
let mut two = SlotHandle::<_, Shots>::mint(FulltextMount::corpus(&ft, TITLE.as_ref()));
let _: (
&mut SlotHandle<Corpus, Shots>,
&mut SlotHandle<Corpus, Shots>,
) = (&mut one, &mut two);
assert_eq!(minted.load(Ordering::Relaxed), 2);
}
#[tokio::test]
async fn a_missing_resource_names_the_field_the_corpus_and_the_resource() {
let answered = schema(false).execute("{ searched }").await;
let refusal = answered
.errors
.first()
.map(|refusal| refusal.message.clone())
.expect("an uninstalled resource refuses");
assert!(refusal.contains("`searched`"), "{refusal}");
assert!(refusal.contains("shots__title__lexical"), "{refusal}");
assert!(refusal.contains("Ft"), "{refusal}");
assert!(refusal.contains("Shared::<"), "{refusal}");
}
#[test]
fn two_resources_of_one_kind_are_two_citizens() {
use core::any::TypeId;
assert_ne!(
TypeId::of::<Shared<Ft>>(),
TypeId::of::<Shared<Other>>(),
"two resources shared one context key",
);
}
#[test]
fn the_brand_still_names_the_declaration() {
use core::any::TypeId;
assert_ne!(
TypeId::of::<SlotHandle<Corpus, Shots>>(),
TypeId::of::<SlotHandle<Corpus, Subs>>(),
"two declarations shared one brand",
);
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Coordinates {
slot: String,
dim: usize,
}
impl crate::store::VectorEngine for Coordinates {
type Options = ();
type SearchOptions = ();
type Error = NoColumns;
type Score = f32;
type Element = f32;
type Address = ();
type Connection = Manager;
type WriteBuffer = ();
type ReadBuffer = ();
fn buffer() -> Self::WriteBuffer {}
fn finalize(_buf: Self::WriteBuffer) -> Self::Address {}
fn open(_address: Self::Address) -> Self::ReadBuffer {}
}
impl crate::store::VectorMount for Other {
type Handle = Coordinates;
fn corpus(&self, slot: impl Into<smol_bytes::Utf8Bytes>, dim: usize) -> Self::Handle {
Coordinates {
slot: slot.into().to_string(),
dim,
}
}
fn connection(&self) -> &Manager {
&self.manager
}
}
#[tokio::test]
async fn the_vector_twin_carries_the_width_to_the_mint() {
struct VQuery;
#[Object]
impl VQuery {
async fn near(&self, ctx: &async_graphql::Context<'_>) -> async_graphql::Result<String> {
let (slot, connection) = vector_slot::<Other, Shots>(ctx, "near", BODY, 768)?;
Ok(format!(
"{}/{}@{}",
slot.engine().slot,
slot.engine().dim,
connection.opened
))
}
}
let answered = Schema::build(VQuery, EmptyMutation, EmptySubscription)
.data(Shared::new(Other {
manager: Manager { opened: "lance" },
}))
.finish()
.execute("{ near }")
.await;
assert!(answered.errors.is_empty(), "{:?}", answered.errors);
assert_eq!(
answered.data.to_string(),
"{near: \"shots__body__lexical/768@lance\"}",
);
}