use std::sync::Arc;
use super::{Keeper, Kept, Records};
use crate::conversation::Error;
use crate::limits;
use crate::postgres::PostgresStore;
use crate::profile::HistoryRecords;
use crate::remote::RemoteStore;
use crate::remote::selection::Selection;
use crate::state::State;
use crate::store::FileStore;
use crate::store::error::Error as StoreError;
pub enum HistoryReader {
File(Arc<FileStore>),
Postgres(Arc<PostgresStore>),
Remote(Arc<RemoteStore>),
Profile(HistoryRecords),
Whole(Arc<dyn State>),
}
impl HistoryReader {
pub fn open(selection: &Selection) -> Result<Self, StoreError> {
Ok(match selection {
Selection::File(root) => Self::File(Arc::new(FileStore::open(root)?)),
Selection::Postgres { dsn, schema } => {
Self::Postgres(Arc::new(PostgresStore::open(dsn, schema)?))
}
Selection::Remote { url, token } => {
Self::Remote(Arc::new(RemoteStore::connect(url, token)?))
}
Selection::Profile(resolved) if resolved.profile.history.is_some() => {
Self::Profile(resolved.open_history()?)
}
Selection::Profile(resolved) => Self::Whole(resolved.open()?),
})
}
pub fn state(&self) -> Arc<dyn State> {
match self {
Self::File(store) => store.clone(),
Self::Postgres(store) => store.clone(),
Self::Remote(store) => store.clone(),
Self::Profile(history) => history.shared(),
Self::Whole(state) => state.clone(),
}
}
pub fn records(&self) -> Result<Option<Box<dyn Records + '_>>, Error> {
fn boxed<'a>(records: impl Records + 'a) -> Box<dyn Records + 'a> {
Box::new(records)
}
Ok(match self {
Self::File(store) => file(store)?.map(boxed),
Self::Postgres(store) => postgres(store)?.map(boxed),
Self::Remote(store) => remote(store).map(boxed),
Self::Profile(history) => history.records()?.map(boxed),
Self::Whole(_) => None,
})
}
}
pub(super) fn file(store: &FileStore) -> Result<Option<Keeper<'_>>, Error> {
if !store.records_enabled()? {
return Ok(None);
}
let kept = Kept::File(store, limits::Records::load()?);
Ok(Some(Keeper { kept }))
}
pub(super) fn postgres(store: &PostgresStore) -> Result<Option<Keeper<'_>>, Error> {
if !store.supports_records()? {
return Ok(None);
}
let kept = Kept::Postgres(store, limits::Records::load()?);
Ok(Some(Keeper { kept }))
}
pub(super) fn remote(store: &RemoteStore) -> Option<Keeper<'_>> {
store.supports_records().then_some(Keeper {
kept: Kept::Remote(store),
})
}