inference-engine 0.1.0-alpha.14

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::{
    args::{Args, Format},
    db::Work,
    db::{Id, State},
};
use oxrdf::{BlankNode, GraphName, NamedOrBlankNode, Quad, Term};
use oxrdfio::RdfParser;
use std::{
    fmt::{self, Write as _},
    fs::File,
    io::{self, Read},
    path::Path,
};
struct LimitedReader<'a> {
    inner: Box<dyn Read>,
    document: u64,
    total: &'a mut u64,
}
impl Read for LimitedReader<'_> {
    fn read(&mut self, out: &mut [u8]) -> io::Result<usize> {
        if out.is_empty() {
            return Ok(0);
        }
        let max = (out.len() as u64).min(self.document).min(*self.total) as usize;
        if max == 0 {
            let mut byte = [0];
            return if self.inner.read(&mut byte)? == 0 {
                Ok(0)
            } else {
                Err(io::Error::other("input/document byte limit exceeded"))
            };
        }
        let n = self.inner.read(&mut out[..max])?;
        self.document -= n as u64;
        *self.total -= n as u64;
        Ok(n)
    }
}
struct Text {
    text: String,
    cap: usize,
}
impl fmt::Write for Text {
    fn write_str(&mut self, s: &str) -> fmt::Result {
        if s.len() > self.cap.saturating_sub(self.text.len()) {
            return Err(fmt::Error);
        }
        self.text.push_str(s);
        Ok(())
    }
}
fn encode(term: &Term, cap: usize) -> io::Result<(u8, String)> {
    let kind = match term {
        Term::NamedNode(_) => 1,
        Term::BlankNode(_) => 2,
        Term::Literal(_) => 3,
        Term::Triple(_) => 4,
    };
    let mut text = Text {
        text: String::new(),
        cap,
    };
    write!(text, "{term}").map_err(|_| io::Error::other("term byte limit exceeded"))?;
    Ok((kind, text.text))
}
fn blank(b: BlankNode, scope: usize) -> io::Result<BlankNode> {
    BlankNode::new(format!("input{scope}_{}", b.as_str())).map_err(io::Error::other)
}
fn subject(s: NamedOrBlankNode, scope: usize) -> io::Result<NamedOrBlankNode> {
    Ok(match s {
        NamedOrBlankNode::NamedNode(n) => n.into(),
        NamedOrBlankNode::BlankNode(b) => blank(b, scope)?.into(),
    })
}
fn object(t: Term, scope: usize, depth: u32, max: u32) -> io::Result<Term> {
    Ok(match t {
        Term::BlankNode(b) => blank(b, scope)?.into(),
        Term::Triple(mut t) => {
            if depth == max {
                return Err(io::Error::other("triple-term depth limit exceeded"));
            }
            t.subject = subject(t.subject, scope)?;
            t.object = object(t.object, scope, depth + 1, max)?;
            Term::Triple(t)
        }
        t => t,
    })
}
fn scoped(mut q: Quad, scope: usize, max: u32) -> io::Result<Quad> {
    q.subject = subject(q.subject, scope)?;
    q.object = object(q.object, scope, 0, max)?;
    if let GraphName::BlankNode(b) = q.graph_name {
        q.graph_name = blank(b, scope)?.into();
    }
    Ok(q)
}
fn load_one(
    state: &mut State,
    path: &Path,
    scope: usize,
    args: &Args,
    total: &mut u64,
    work: &Work,
) -> anyhow::Result<()> {
    let stdin = path == Path::new("-");
    let format = match args.input_format {
        Some(f) => f,
        None if stdin => anyhow::bail!("stdin requires --input-format"),
        None => Format::from_path(path)?,
    };
    let reader: Box<dyn Read> = if stdin {
        Box::new(io::stdin())
    } else {
        Box::new(File::open(path)?)
    };
    let mut parser = RdfParser::from_format(format.rdf());
    if !stdin {
        let absolute = path.canonicalize()?;
        let base = url::Url::from_file_path(absolute)
            .map_err(|_| io::Error::other("input path cannot be represented as a file IRI"))?;
        parser = parser.with_base_iri(base.to_string())?;
    }
    // No rename_blank_nodes HashMap: scope labels directly, including nested/graph blanks.
    let reader = LimitedReader {
        inner: reader,
        document: args.max_document_bytes.get(),
        total,
    };
    for quad in parser.for_reader(reader) {
        work.step()?;
        let q = scoped(quad?, scope, args.max_depth.get())?;
        let graph = match q.graph_name {
            GraphName::DefaultGraph => None,
            GraphName::NamedNode(n) => Some(Term::from(n)),
            GraphName::BlankNode(b) => Some(Term::from(b)),
        };
        let terms = [Term::from(q.subject), Term::from(q.predicate), q.object];
        // bounded: three terms and at most one graph label, each capped before encoding growth.
        let encoded = terms
            .iter()
            .map(|t| encode(t, args.max_term_bytes.get()))
            .collect::<io::Result<Vec<_>>>()?;
        let graph = graph
            .as_ref()
            .map(|g| encode(g, args.max_term_bytes.get()))
            .transpose()?;
        let bytes = encoded.iter().map(|(_, s)| s.len()).sum::<usize>()
            + graph.as_ref().map_or(0, |(_, s)| s.len());
        state.add_bytes(bytes)?;
        let mut ids = [Id(0); 3];
        for (i, (kind, text)) in encoded.iter().enumerate() {
            ids[i] = state.resolve(text, *kind)?;
        }
        let g = match graph {
            Some((kind, text)) => state.resolve(&text, kind)?.0,
            None => 0,
        };
        state.insert(g, ids, None)?;
    }
    Ok(())
}
pub(super) fn load(state: &mut State, args: &Args, work: &Work) -> anyhow::Result<()> {
    if args.inputs.len() > 1024 {
        anyhow::bail!("input file count exceeds 1024");
    }
    if args.inputs.iter().filter(|p| p.as_os_str() == "-").count() > 1 {
        anyhow::bail!("stdin can be read only once");
    }
    let mut total = args.max_input_bytes.get();
    for (scope, path) in args.inputs.iter().enumerate() {
        use anyhow::Context;
        load_one(state, path, scope, args, &mut total, work)
            .with_context(|| format!("reading {}", path.display()))?;
    }
    state.flush()?;
    Ok(())
}