inference-engine 0.1.0-alpha.13

Native Rust RDF inference engine with a shared command-line interface
Documentation
use super::{
    args::{Args, Emit, Format},
    db::{ASSERTED, INDEX, PROOFS, State, TERMS, Work},
};
use redb::{ReadTransaction, ReadableDatabase, ReadableTable};
use std::{
    io::{self, BufWriter, Seek, SeekFrom, Write},
    path::Path,
};
use tempfile::NamedTempFile;
struct LimitedWriter<W> {
    inner: W,
    remaining: u64,
}
impl<W: Write> Write for LimitedWriter<W> {
    fn write(&mut self, data: &[u8]) -> io::Result<usize> {
        if data.len() as u64 > self.remaining {
            return Err(io::Error::other("output byte limit exceeded"));
        }
        let n = self.inner.write(data)?;
        self.remaining -= n as u64;
        Ok(n)
    }
    fn flush(&mut self) -> io::Result<()> {
        self.inner.flush()
    }
}
fn term(read: &ReadTransaction, id: u64) -> io::Result<(u8, String)> {
    let table = read.open_table(TERMS).map_err(io::Error::other)?;
    let value = table
        .get(id)
        .map_err(io::Error::other)?
        .ok_or_else(|| io::Error::other("unknown scratch term ID"))?;
    let (kind, text) = value.value();
    Ok((kind, text.to_owned()))
}
fn serialize(
    state: &State,
    args: &Args,
    work: &Work,
    format: Format,
    output: &mut dyn Write,
) -> anyhow::Result<(u64, u64)> {
    let read = state.db.begin_read()?;
    let union = read.open_table(INDEX[0])?;
    let asserted = read.open_table(ASSERTED)?;
    let proofs = read.open_table(PROOFS)?;
    let (mut emitted, mut omitted) = (0_u64, 0_u64);
    for row in union.iter()? {
        work.step()?;
        let (key, _) = row?;
        let k = key.value();
        if args.emit == Emit::Asserted && asserted.get(k)?.is_none()
            || args.emit == Emit::Inferred && proofs.get(k)?.is_none()
        {
            continue;
        }
        let (g, s, p, o) = k;
        let (sk, s) = term(&read, s)?;
        let (pk, p) = term(&read, p)?;
        let (_, o) = term(&read, o)?;
        if !matches!(sk, 1 | 2) || pk != 1 {
            if !args.rdf_only {
                anyhow::bail!(
                    "profile derived a generalized tuple that standard RDF cannot serialize; --rdf-only explicitly emits its RDF projection"
                );
            }
            omitted += 1;
            continue;
        }
        if g != 0 && matches!(format, Format::Nt | Format::Ttl) {
            anyhow::bail!("triple output cannot preserve named graphs; use nq or trig");
        }
        if g == 0 {
            writeln!(output, "{s} {p} {o} .")?;
        } else {
            let (kind, g) = term(&read, g)?;
            if !matches!(kind, 1 | 2) {
                anyhow::bail!("invalid graph label in scratch");
            }
            if format == Format::Trig {
                writeln!(output, "{g} {{ {s} {p} {o} . }}")?;
            } else {
                writeln!(output, "{s} {p} {o} {g} .")?;
            }
        }
        emitted = emitted
            .checked_add(1)
            .ok_or_else(|| io::Error::other("output count overflow"))?;
    }
    Ok((emitted, omitted))
}
pub(super) fn publish(
    state: &mut State,
    args: &Args,
    work: &Work,
    scratch: &Path,
) -> anyhow::Result<(u64, u64)> {
    state.flush()?;
    let destination = args.output.as_deref().filter(|p| *p != Path::new("-"));
    let format = match args.output_format {
        Some(f) => f,
        None => destination.map_or(Ok(Format::Nq), Format::from_path)?,
    };
    if let Some(path) = destination
        && path.exists()
    {
        let target = path.canonicalize()?;
        for input in &args.inputs {
            if input.as_os_str() != "-" && input.canonicalize()? == target {
                anyhow::bail!("output must not replace an input file");
            }
        }
    }
    let mut file = match destination {
        Some(path) => NamedTempFile::new_in(
            path.parent()
                .filter(|p| !p.as_os_str().is_empty())
                .unwrap_or(Path::new(".")),
        )?,
        None => NamedTempFile::new_in(scratch)?,
    };
    let counts = {
        let mut writer = LimitedWriter {
            inner: BufWriter::with_capacity(64 * 1024, file.as_file_mut()),
            remaining: args.max_output_bytes.get(),
        };
        let result = serialize(state, args, work, format, &mut writer)?;
        writer.flush()?;
        result
    };
    file.as_file().sync_all()?;
    if let Some(path) = destination {
        file.persist(path).map_err(|e| e.error)?;
    } else {
        file.as_file_mut().seek(SeekFrom::Start(0))?;
        let mut stdout = io::stdout().lock();
        io::copy(file.as_file_mut(), &mut stdout)?;
        stdout.flush()?;
    }
    Ok(counts)
}