use crate::conversation::{Error, Redaction};
use crate::postgres::PostgresStore;
use crate::remote::RemoteStore;
use crate::state::State;
use crate::state::records::Source;
use crate::store::FileStore;
use crate::store::erasure::TrailAt;
const PAGE: usize = 500;
const CEILING: usize = 500;
pub(super) enum Trail<'a> {
File(&'a FileStore),
Postgres(&'a PostgresStore),
Remote(&'a RemoteStore),
}
type Visit<'v> = dyn FnMut(Vec<Redaction>) -> Result<(), Error> + 'v;
impl<'a> Trail<'a> {
pub(super) fn of(source: &'a Source) -> Self {
match source {
Source::File(store) => Self::File(store),
Source::Postgres(store) => Self::Postgres(store),
Source::Remote(store) => Self::Remote(store),
}
}
pub(super) fn preflight(&self, id: &str) -> Result<(), Error> {
if let Self::Remote(store) = self {
legacy(store, id)?;
}
Ok(())
}
pub(super) fn each_page(&self, id: &str, visit: &mut Visit<'_>) -> Result<(), Error> {
match self {
Self::File(store) => paged(TrailAt::default(), visit, |at| {
store.trail_page(id, at, PAGE)
}),
Self::Postgres(store) => paged(0, visit, |after| store.trail_page(id, after, PAGE)),
Self::Remote(store) => visit(legacy(store, id)?),
}
}
}
fn paged<K>(
mut at: K,
visit: &mut Visit<'_>,
mut page: impl FnMut(K) -> Result<(Vec<Redaction>, Option<K>), Error>,
) -> Result<(), Error> {
loop {
let (acts, next) = page(at)?;
visit(acts)?;
match next {
Some(next) => at = next,
None => return Ok(()),
}
}
}
fn legacy(store: &RemoteStore, id: &str) -> Result<Vec<Redaction>, Error> {
let ids = [id.to_string()];
let mut acts = match store.turn_redactions(Some(&ids), None, CEILING as i64) {
Ok(acts) => acts,
Err(Error::Memory(error)) if error.code == "agent_configuration_error" => Vec::new(),
Err(error) => return Err(error),
};
if acts.len() >= CEILING {
return Err(Error::Value(format!(
"conversation {id} has at least {CEILING} erasure acts on the server, the most its \
audit read answers, so its trail may be longer than the server can show and an \
archive could miss older acts. Export from the store itself instead: --root DIR \
for a FileStore, or NEOSIAN_POSTGRES_DSN for PostgreSQL"
)));
}
acts.reverse();
Ok(acts)
}