inference-engine 0.1.0-alpha.13

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::vocabulary::Vocabulary;
use inference_engine::reasoning::{TripleCursor, TripleSource};
use oxigraph::store::{QuadIter, Store};
use oxrdf::{GraphName, GraphNameRef, NamedNode, NamedNodeRef, NamedOrBlankNodeRef, Term};
use std::{io, sync::Arc};
use tokio::task;

pub struct Graph {
    store: Arc<Store>,
    vocabulary: Arc<Vocabulary>,
    name: NamedNode,
}
impl Graph {
    pub fn new(store: &Arc<Store>, vocabulary: &Arc<Vocabulary>, name: &str) -> io::Result<Self> {
        Ok(Self {
            store: store.clone(),
            vocabulary: vocabulary.clone(),
            name: NamedNode::new(name).map_err(io::Error::other)?,
        })
    }
}
pub struct Cursor {
    iter: Option<QuadIter<'static>>,
    vocabulary: Arc<Vocabulary>,
    name: NamedNode,
    pattern: [Option<u64>; 3],
    // Keep the native database alive until this independent reader is released.
    _store: Arc<Store>,
}
impl TripleSource for Graph {
    type Term = u64;
    type Error = io::Error;
    type Cursor = Cursor;
    async fn scan(&self, pattern: [Option<u64>; 3]) -> io::Result<Cursor> {
        let store = self.store.clone();
        let vocabulary = self.vocabulary.clone();
        let name = self.name.clone();
        // Audited async boundary: the synchronous native snapshot/query may read disk.
        task::spawn_blocking(move || {
            let subject: Option<NamedOrBlankNodeRef<'_>> =
                match pattern[0].map(|key| vocabulary.term(key)).transpose()? {
                    None => None,
                    Some(Term::NamedNode(node)) => Some(node.as_ref().into()),
                    Some(Term::BlankNode(node)) => Some(node.as_ref().into()),
                    _ => return Err(io::Error::other("nonstandard subject probe")),
                };
            let predicate: Option<NamedNodeRef<'_>> =
                match pattern[1].map(|key| vocabulary.term(key)).transpose()? {
                    None => None,
                    Some(Term::NamedNode(node)) => Some(node.as_ref()),
                    _ => return Err(io::Error::other("non-IRI predicate probe")),
                };
            let object = pattern[2]
                .map(|key| vocabulary.term(key))
                .transpose()?
                .map(Term::as_ref);
            let iter = store.quads_for_pattern(
                subject,
                predicate,
                object,
                Some(GraphNameRef::NamedNode(name.as_ref())),
            );
            Ok(Cursor {
                iter: Some(iter),
                vocabulary,
                name,
                pattern,
                _store: store,
            })
        })
        .await
        .map_err(io::Error::other)?
    }
}
impl TripleCursor for Cursor {
    type Term = u64;
    type Error = io::Error;
    async fn next(&mut self) -> io::Result<Option<[u64; 3]>> {
        let mut iter = self.iter.take().expect("one exclusive cursor read");
        // Audited async boundary: at most one native quad per blocking read.
        let (iter, row) = task::spawn_blocking(move || {
            let row = iter.next();
            (iter, row)
        })
        .await
        .map_err(io::Error::other)?;
        self.iter = Some(iter);
        let Some(row) = row else {
            return Ok(None);
        };
        let row = row.map_err(io::Error::other)?;
        if row.graph_name != GraphName::NamedNode(self.name.clone()) {
            return Err(io::Error::other("native graph isolation violation"));
        }
        let triple = [
            self.vocabulary.key(&row.subject.into())?,
            self.vocabulary.key(&row.predicate.into())?,
            self.vocabulary.key(&row.object)?,
        ];
        if self
            .pattern
            .iter()
            .zip(triple)
            .any(|(expected, actual)| expected.is_some_and(|key| key != actual))
        {
            return Err(io::Error::other("native probe identity violation"));
        }
        Ok(Some(triple))
    }
}