use std::path::Path;
use std::sync::Arc;
use galata_vault_client::{Request, Response, Transport, TransportError};
use galata_vault_server_core::data_dir::{DataDir, DataDirError};
use galata_vault_server_core::{CanonicalRequest, Core, FileJournal, Policy, SystemClock};
use galata_vault_store::{SqliteStore, StoreConfig};
use crate::error::{Error, code};
pub struct Embedded {
core: Core,
data: DataDir,
}
impl std::fmt::Debug for Embedded {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Embedded")
.field("data_dir", &self.data.path())
.finish_non_exhaustive()
}
}
pub fn open(data_dir: impl AsRef<Path>) -> Result<Embedded, Error> {
let data = DataDir::open(data_dir.as_ref()).map_err(|e| match e {
DataDirError::InUse(_) => Error::local(code::DATA_DIR_IN_USE, e.to_string()),
DataDirError::Unusable(_) => Error::local(code::INVALID_DATA_DIR, e.to_string()),
})?;
let database = data.database();
let store = SqliteStore::open(StoreConfig::new(&database))
.map_err(|e| Error::other(format!("opening {}: {e}", database.display())))?;
let journal = FileJournal::open(data.journal_root()).map_err(Error::other)?;
let core = Core::open(
Arc::new(store),
Arc::new(journal),
Policy::default(),
Arc::new(SystemClock),
)
.map_err(|e| Error::other(format!("{}: {e}", data.path().display())))?;
Ok(Embedded { core, data })
}
impl Embedded {
pub fn data_dir(&self) -> &Path {
self.data.path()
}
}
impl Transport for Embedded {
fn send(&self, request: Request<'_>) -> Result<Response, TransportError> {
let answer = self.core.call(CanonicalRequest {
method: request.method.as_str(),
path_and_query: request.path_and_query,
authorization: request.authorization,
if_match: request.if_match,
if_none_match: request.if_none_match,
body: request.body.unwrap_or(&[]),
});
let mut response = Response::new(answer.status, answer.body);
if let Some(version) = answer.etag {
response = response.with_etag(format!("\"{version}\""));
}
if let Some(at) = answer.expires_at {
response = response.with_expires_at(at.to_string());
}
Ok(response)
}
}