use std::{
process,
sync::atomic::{AtomicU64, Ordering},
};
use ed25519_dalek::VerifyingKey;
use eventsourcingdb::{Client, container::Container};
use crate::{Store, StoreBuilder};
pub(super) const SOURCE: &str = "https://thenativeweb.io";
pub(super) struct Database {
container: Container,
}
impl Database {
pub(super) async fn start() -> Self {
let image_tag =
std::env::var("EVENTSOURCINGDB_IMAGE_TAG").unwrap_or_else(|_| "latest".to_owned());
let container = Container::builder()
.with_image_tag(&image_tag)
.with_signing_key()
.start()
.await
.expect("the database starts");
Self { container }
}
pub(super) async fn client(&self) -> Client {
self.container
.get_client()
.await
.expect("the database has a client")
}
pub(super) fn verification_key(&self) -> VerifyingKey {
*self
.container
.get_verification_key()
.expect("the database has a signing key")
}
pub(super) async fn store(&self) -> Store {
self.store_with(|builder| builder).await
}
pub(super) async fn store_with(
&self,
build: impl FnOnce(StoreBuilder) -> StoreBuilder,
) -> Store {
build(Store::builder(self.client().await, SOURCE)).build()
}
}
pub(super) fn subject_for(name: &str) -> String {
static NEXT: AtomicU64 = AtomicU64::new(0);
format!(
"/test/{name}/{}-{}",
process::id(),
NEXT.fetch_add(1, Ordering::Relaxed),
)
}