use inference_engine::reasoning::{TripleCursor, TripleSource};
use std::{
io,
sync::{
Arc,
atomic::{AtomicBool, AtomicUsize, Ordering},
},
};
pub struct SecondScanFailure<S> {
inner: S,
scans: AtomicUsize,
}
pub struct SignalSource<S> {
inner: S,
scans: AtomicUsize,
active: Arc<AtomicBool>,
}
impl<S> SignalSource<S> {
pub fn new(inner: S, active: Arc<AtomicBool>) -> Self {
Self {
inner,
scans: AtomicUsize::new(0),
active,
}
}
}
impl<S: TripleSource<Term = u64, Error = io::Error>> TripleSource for SignalSource<S> {
type Term = u64;
type Error = io::Error;
type Cursor = S::Cursor;
async fn scan(&self, pattern: [Option<u64>; 3]) -> io::Result<Self::Cursor> {
if self.scans.fetch_add(1, Ordering::SeqCst) == 1 {
self.active.store(true, Ordering::SeqCst);
}
self.inner.scan(pattern).await
}
}
pub enum MetadataFault {
Storage,
Missing,
OverCap,
}
pub struct FaultAccess<'a, A> {
pub inner: &'a A,
pub active: Arc<AtomicBool>,
pub fault: MetadataFault,
}
use inference_engine::entailment::{EntailmentTerms, IriTermAccess};
impl<A: EntailmentTerms<Term = u64, Error = io::Error>> EntailmentTerms for FaultAccess<'_, A> {
type Term = u64;
type Error = io::Error;
async fn is_blank(&self, term: &u64) -> io::Result<bool> {
self.inner.is_blank(term).await
}
async fn triple_term(&self, term: &u64) -> io::Result<Option<[u64; 3]>> {
self.inner.triple_term(term).await
}
fn is_cancelled(&self) -> bool {
self.inner.is_cancelled()
}
}
impl<A: IriTermAccess<Term = u64, Error = io::Error>> IriTermAccess for FaultAccess<'_, A> {
type Iri<'a>
= Arc<str>
where
Self: 'a;
async fn iri<'a>(
&'a self,
term: &'a u64,
maximum: std::num::NonZeroU32,
) -> io::Result<Option<Arc<str>>> {
if self.active.load(Ordering::SeqCst) {
return match self.fault {
MetadataFault::Storage => Err(io::Error::other("projection metadata unavailable")),
MetadataFault::Missing => Ok(None),
MetadataFault::OverCap => Ok(Some(Arc::from("x".repeat(4097)))),
};
}
self.inner
.iri(term, maximum)
.await
.map(|v| v.map(|v| Arc::from(v.as_ref())))
}
}
impl<S> SecondScanFailure<S> {
pub fn new(inner: S) -> Self {
Self {
inner,
scans: AtomicUsize::new(0),
}
}
}
pub struct Cursor<C> {
inner: C,
fail_eof: bool,
}
impl<S: TripleSource<Term = u64, Error = io::Error>> TripleSource for SecondScanFailure<S> {
type Term = u64;
type Error = io::Error;
type Cursor = Cursor<S::Cursor>;
async fn scan(&self, pattern: [Option<u64>; 3]) -> io::Result<Self::Cursor> {
let fail_eof = self.scans.fetch_add(1, Ordering::SeqCst) == 1;
Ok(Cursor {
inner: self.inner.scan(pattern).await?,
fail_eof,
})
}
}
impl<C: TripleCursor<Term = u64, Error = io::Error>> TripleCursor for Cursor<C> {
type Term = u64;
type Error = io::Error;
async fn next(&mut self) -> io::Result<Option<[u64; 3]>> {
let row = self.inner.next().await?;
if row.is_none() && self.fail_eof {
return Err(io::Error::other("projection EOF failed"));
}
Ok(row)
}
}