use crate::record::Header;
use crate::store::{CheckpointedLog, RecordSource};
use crate::substrate::SubstrateError;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexedRecord {
pub record_id: String,
pub seq: u64,
pub record_type: String,
pub subject_ref: Option<String>,
}
pub fn committed_records(
log: &dyn CheckpointedLog,
records: &dyn RecordSource,
) -> Result<Vec<IndexedRecord>, SubstrateError> {
let count = log.leaf_count()?;
let mut out = Vec::new();
for leaf_index in 0..count {
let unreadable = |why: &str| SubstrateError::Record {
leaf_index,
why: why.to_string(),
};
let record = records
.record_at(leaf_index)
.filter(|r| r.leaf_index == leaf_index)
.ok_or_else(|| unreadable("the store holds no record there"))?;
if records.entry_of(&record.body).as_deref() != Some(record.digest.as_str()) {
return Err(unreadable(
"its octets do not recompute its committed entry",
));
}
let value: serde_json::Value = serde_json::from_slice(&record.body)
.map_err(|e| unreadable(&format!("not JSON: {e}")))?;
if crate::padding::is_padding(&value) {
continue;
}
let header: Header =
serde_json::from_value(value).map_err(|e| unreadable(&format!("not a header: {e}")))?;
out.push(IndexedRecord {
record_id: record.digest,
seq: header.seq,
record_type: header.record_type,
subject_ref: header.subject_ref,
});
}
Ok(out)
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Filter {
pub record_type: Option<String>,
pub subject_ref: Option<String>,
pub from_seq: Option<u64>,
pub to_seq: Option<u64>,
}
impl Filter {
pub fn matches(&self, record: &IndexedRecord) -> bool {
self.record_type
.as_ref()
.is_none_or(|t| *t == record.record_type)
&& self
.subject_ref
.as_ref()
.is_none_or(|s| record.subject_ref.as_ref() == Some(s))
&& self.from_seq.is_none_or(|from| record.seq >= from)
&& self.to_seq.is_none_or(|to| record.seq <= to)
}
}
pub trait OperationalIndex {
type Error;
fn insert(&mut self, record: &IndexedRecord) -> Result<(), Self::Error>;
fn query(&self, filter: &Filter) -> Result<Vec<String>, Self::Error>;
fn rebuild(&mut self, records: &[IndexedRecord]) -> Result<(), Self::Error>;
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct IndexRoot {
pub index: String,
pub size: u64,
pub root: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyRange {
pub low: String,
pub high: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct KeyRangeAnswer<P> {
pub root: IndexRoot,
pub range: KeyRange,
pub keys: Vec<String>,
pub proof: P,
}
pub trait AuthenticatedIndex {
type Proof;
type Error;
fn insert(&mut self, key: &str) -> Result<(), Self::Error>;
fn root(&self) -> IndexRoot;
fn prove_key_range(&self, range: &KeyRange)
-> Result<KeyRangeAnswer<Self::Proof>, Self::Error>;
fn verify_key_range(root: &IndexRoot, answer: &KeyRangeAnswer<Self::Proof>) -> bool;
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Candidates {
ids: Vec<String>,
}
impl Candidates {
pub fn new(ids: Vec<String>) -> Self {
Self { ids }
}
pub fn suggestions(&self) -> impl Iterator<Item = &str> {
self.ids.iter().map(String::as_str)
}
pub fn len(&self) -> usize {
self.ids.len()
}
pub fn is_empty(&self) -> bool {
self.ids.is_empty()
}
}
pub trait DiscoveryIndex {
type Error;
fn discover(&self, query: &str) -> Result<Candidates, Self::Error>;
}
#[cfg(test)]
mod tests {
use super::*;
fn rec(seq: u64, record_type: &str, subject: Option<&str>) -> IndexedRecord {
IndexedRecord {
record_id: format!("{seq:064x}"),
seq,
record_type: record_type.into(),
subject_ref: subject.map(str::to_string),
}
}
#[test]
fn filter_matches_every_set_field() {
let r = rec(5, "claim", Some("s1"));
assert!(Filter::default().matches(&r));
assert!(Filter {
record_type: Some("claim".into()),
subject_ref: Some("s1".into()),
from_seq: Some(5),
to_seq: Some(5),
}
.matches(&r));
assert!(!Filter {
record_type: Some("close".into()),
..Filter::default()
}
.matches(&r));
assert!(!Filter {
subject_ref: Some("s2".into()),
..Filter::default()
}
.matches(&r));
assert!(!Filter {
from_seq: Some(6),
..Filter::default()
}
.matches(&r));
assert!(!Filter {
to_seq: Some(4),
..Filter::default()
}
.matches(&r));
assert!(!Filter {
subject_ref: Some("s1".into()),
..Filter::default()
}
.matches(&rec(5, "claim", None)));
}
#[test]
fn candidates_only_expose_suggestions() {
let c = Candidates::new(vec!["a".into(), "b".into()]);
assert_eq!(c.suggestions().collect::<Vec<_>>(), ["a", "b"]);
assert_eq!(c.len(), 2);
assert!(Candidates::default().is_empty());
}
}