use std::cell::Cell;
use happenstance_core::{Event, EventStore};
use happenstance_sync::StoreSyncPeer;
use happenstance_sync_testkit::{RestoreFixture, Violation, restore_rules};
use sqlx::PgPool;
use tokio::sync::OnceCell;
use super::server;
use crate::event_store::PostgresEventStore;
const VT_6: &str = "VT-6";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AfterRestore {
Remint,
NothingMore,
}
#[derive(Debug, Clone, Copy)]
struct Backup {
last_value: i64,
is_called: bool,
identity: [u8; 16],
}
impl Backup {
const fn highest_kept(self) -> i64 {
if self.is_called { self.last_value } else { 0 }
}
}
#[derive(Debug)]
struct PostgresRestoreFixture {
pool: OnceCell<PgPool>,
backup: Cell<Option<Backup>>,
after_restore: AfterRestore,
}
impl PostgresRestoreFixture {
fn new() -> Self {
Self::with(AfterRestore::Remint)
}
fn with(after_restore: AfterRestore) -> Self {
Self {
pool: OnceCell::new(),
backup: Cell::new(None),
after_restore,
}
}
async fn pool(&self) -> &PgPool {
self.pool.get_or_init(server::fresh_pool).await
}
async fn store(&self) -> PostgresEventStore {
PostgresEventStore::new(self.pool().await.clone())
}
}
fn arranging(step: &str, error: &sqlx::Error) -> Violation {
Violation::new(VT_6, format!("the fixture could not {step}: {error}"))
}
impl RestoreFixture for PostgresRestoreFixture {
type Peer = StoreSyncPeer<PostgresEventStore, PostgresEventStore>;
async fn connect(&self) -> Self::Peer {
StoreSyncPeer::new(self.store().await, self.store().await)
}
async fn append_local(&self, events: &[Event]) -> Result<(), Violation> {
EventStore::append(&self.store().await, events, None)
.await
.map(drop)
.map_err(|error| Violation::new(VT_6, format!("a local append was refused: {error}")))
}
async fn back_up(&self) -> Result<(), Violation> {
let pool = self.pool().await;
let (last_value, is_called): (i64, bool) =
sqlx::query_as("SELECT last_value, is_called FROM event_position_seq")
.fetch_one(pool)
.await
.map_err(|error| arranging("read the position sequence", &error))?;
let identity: Vec<u8> = sqlx::query_scalar("SELECT v FROM store_meta WHERE k = 'store_id'")
.fetch_one(pool)
.await
.map_err(|error| arranging("read the identity row", &error))?;
let identity = <[u8; 16]>::try_from(identity).map_err(|row| {
Violation::new(
VT_6,
format!("the identity row holds {} bytes, not 16", row.len()),
)
})?;
self.backup.set(Some(Backup {
last_value,
is_called,
identity,
}));
Ok(())
}
async fn restore(&self) -> Result<(), Violation> {
let backup = self
.backup
.take()
.ok_or_else(|| Violation::new(VT_6, "the fixture restored before any backup"))?;
let pool = self.pool().await;
let mut restore = pool
.begin()
.await
.map_err(|error| arranging("open the restore", &error))?;
sqlx::query("DELETE FROM event WHERE position > $1")
.bind(backup.highest_kept())
.execute(&mut *restore)
.await
.map_err(|error| arranging("delete the rows written since the backup", &error))?;
sqlx::query("SELECT setval('event_position_seq', $1, $2)")
.bind(backup.last_value)
.bind(backup.is_called)
.execute(&mut *restore)
.await
.map_err(|error| arranging("set the position sequence back", &error))?;
sqlx::query("UPDATE store_meta SET v = $1 WHERE k = 'store_id'")
.bind(backup.identity.as_slice())
.execute(&mut *restore)
.await
.map_err(|error| arranging("put the identity row back", &error))?;
restore
.commit()
.await
.map_err(|error| arranging("commit the restore", &error))?;
match self.after_restore {
AfterRestore::Remint => self
.store()
.await
.remint_identity()
.await
.map(drop)
.map_err(|error| {
Violation::new(VT_6, format!("the documented re-mint failed: {error}"))
}),
AfterRestore::NothingMore => Ok(()),
}
}
}
macro_rules! emit_ignored_restore_tokio {
($($name:ident),* $(,)?) => {
$(
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container, or set HAPPENSTANCE_POSTGRES_URL)"]
async fn $name() -> ::core::result::Result<(), ::happenstance_sync_testkit::Violation> {
::happenstance_sync_testkit::restore_rules::$name(__restore_fixture)
.await?
.report(::core::stringify!($name));
Ok(())
}
)*
};
}
pub(crate) use emit_ignored_restore_tokio;
happenstance_sync_testkit::restore_conformance!(
mod_name = restore_conformance,
emit = super::emit_ignored_restore_tokio,
fixture = super::PostgresRestoreFixture::new()
);
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container, or set HAPPENSTANCE_POSTGRES_URL)"]
async fn a_restore_without_the_re_mint_reissues_an_identity() {
let verdict = restore_rules::restored_peer_does_not_reissue_identities(async || {
PostgresRestoreFixture::with(AfterRestore::NothingMore)
})
.await;
let violation = verdict.expect_err("a restore left un-reminted must reissue an identity");
assert_eq!(violation.clause(), "VT-6", "{violation}");
assert!(
violation
.message()
.contains("reissued an identity it had already given away"),
"the control failed for another reason: {violation}"
);
}