use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;
use rocksdb::OptimisticTransactionDB;
use sqlx::sqlite::SqlitePool;
use tracing::debug;
pub mod conf;
mod moonlight;
mod sqlite;
mod transformer;
use conf::Params as ArchiveParams;
pub use moonlight::{MoonlightGroup, Order};
const ARCHIVE_FOLDER_NAME: &str = "archive";
#[derive(Debug, Clone)]
pub struct Archive {
sqlite_writer: SqlitePool,
sqlite_reader: SqlitePool,
moonlight_db: Arc<OptimisticTransactionDB>,
last_finalized_block_height: u64,
}
impl Archive {
fn archive_folder_path<P: AsRef<Path>>(base_path: P) -> PathBuf {
let path = base_path.as_ref().join(ARCHIVE_FOLDER_NAME);
fs::create_dir_all(&path).unwrap_or_else(|_| {
panic!("creating directory in {path:?} should not fail")
});
path
}
pub async fn create_or_open<P: AsRef<Path>>(base_path: P) -> Self {
Self::create_or_open_with_conf(base_path, ArchiveParams::default())
.await
}
pub async fn create_or_open_with_conf<P: AsRef<Path>>(
base_path: P,
params: ArchiveParams,
) -> Self {
let path = Self::archive_folder_path(base_path);
tracing::info!(
"Archive::create_or_open_with_conf with conf {}",
params
);
let sqlite_writer = Self::create_writer_pool(&path).await;
let sqlite_reader =
Self::create_reader_pool(&path, params.reader_max_connections)
.await;
let moonlight_db = Self::create_or_open_moonlight_db(&path, params);
let mut self_archive = Self {
sqlite_writer,
sqlite_reader,
moonlight_db,
last_finalized_block_height: 0,
};
let last_finalized_block_height = match self_archive
.fetch_last_finalized_block()
.await
{
Ok((height, _)) => height,
Err(e) => {
debug!("Error fetching last finalized block height during archive initialization: {e}");
0
}
};
self_archive.last_finalized_block_height = last_finalized_block_height;
self_archive
}
pub fn last_finalized_block_height(&self) -> u64 {
self.last_finalized_block_height
}
}