mod args;
mod db;
mod input;
mod output;
mod quota;
mod source;
use crate::reasoning::{Reasoner, RunLimits};
use args::Args;
use clap::Parser;
use std::{
ffi::OsString,
io,
sync::{Arc, Mutex},
};
pub fn run(args: Vec<OsString>) -> u8 {
let cli =
match Args::try_parse_from(std::iter::once(OsString::from("inference-engine")).chain(args))
{
Ok(cli) => cli,
Err(error) => {
let status = if error.use_stderr() { 2 } else { 0 };
return if error.print().is_ok() { status } else { 1 };
}
};
let worker = std::thread::Builder::new()
.name("inference-engine-cli".into())
.spawn(move || {
let runtime = tokio::runtime::Builder::new_current_thread().build()?;
runtime.block_on(execute(cli))
});
let result = match worker {
Ok(worker) => worker
.join()
.unwrap_or_else(|_| Err(io::Error::other("native CLI worker panicked").into())),
Err(error) => Err(error.into()),
};
match result {
Ok(()) => 0,
Err(error) => {
eprintln!("inference-engine: {error:#}");
1
}
}
}
async fn execute(args: Args) -> anyhow::Result<()> {
args.validate()?;
let work = Arc::new(db::Work::new(args.max_steps.get()));
let work_for_load = work.clone();
let loaded = tokio::task::spawn_blocking(move || -> anyhow::Result<_> {
let directory = match &args.scratch_dir {
Some(parent) => tempfile::tempdir_in(parent)?,
None => tempfile::tempdir()?,
};
let mut state = db::State::create(&directory.path().join("reasoning.redb"), &args)?;
input::load(&mut state, &args, &work_for_load)?;
Ok((directory, Arc::new(Mutex::new(state)), args))
})
.await??;
let (directory, state, args) = loaded;
let mut after = None;
while let Some(graph) = source::next_graph(&state, after).await? {
let mut store = source::Store {
state: state.clone(),
graph,
work: work.clone(),
};
Reasoner::new(
args.profile,
RunLimits::new(args.max_rounds, args.max_inferred, args.max_steps),
)
.run(&mut store)
.await?;
after = Some(graph);
}
tokio::task::spawn_blocking(move||->anyhow::Result<()> {
let mut state=Arc::try_unwrap(state).map_err(|_|io::Error::other("scratch readers outlived reasoning"))?.into_inner().map_err(|_|io::Error::other("scratch state poisoned"))?;
let(emitted,omitted)=output::publish(&mut state,&args,&work,directory.path())?;
if !args.quiet {eprintln!("profile={}; asserted={}; inferred={}; emitted={}; restricted profile, not full RDFS",args.profile.name(),state.asserted,state.inferred,emitted);eprintln!("profile exclusions: {:?}",args.profile.exclusions());}
if omitted>0 {eprintln!("RDF projection omitted {omitted} generalized tuples after reasoning");}
drop(state);directory.close()?;Ok(())
}).await??;
Ok(())
}