use std::cell::RefCell;
use happenstance_core::{Event, EventStore, RecordedAt};
use happenstance_sync::{IngestError, IngestGroup, IngestStore, ReplicatedEvent, 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)]
struct Backup {
last_value: i64,
is_called: bool,
identity: [u8; 16],
removed: (Vec<Vec<u8>>, Vec<i64>),
}
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: RefCell<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: RefCell::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()),
)
})?;
let removed: Vec<(Vec<u8>, i64)> =
sqlx::query_as("SELECT origin_store, origin_position FROM event_removed")
.fetch_all(pool)
.await
.map_err(|error| arranging("read the removal record", &error))?;
*self.backup.borrow_mut() = Some(Backup {
last_value,
is_called,
identity,
removed: removed.into_iter().unzip(),
});
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))?;
sqlx::query("DELETE FROM event_removed")
.execute(&mut *restore)
.await
.map_err(|error| arranging("clear the removal record", &error))?;
sqlx::query(
"INSERT INTO event_removed (origin_store, origin_position) \
SELECT * FROM unnest($1::bytea[], $2::bigint[])",
)
.bind(&backup.removed.0)
.bind(&backup.removed.1)
.execute(&mut *restore)
.await
.map_err(|error| arranging("put the removal record 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_rolls_the_removal_record_back_with_the_allocator() {
for after_restore in [AfterRestore::Remint, AfterRestore::NothingMore] {
let fixture = PostgresRestoreFixture::with(after_restore);
let store = fixture.store().await;
let old = PostgresEventStore::store_id(&store)
.await
.expect("a migrated store has an identity");
let kept = Event::new("Kept", b"kept".to_vec()).expect("a valid event type");
let lost = Event::new("Lost", b"lost".to_vec()).expect("a valid event type");
fixture
.append_local(core::slice::from_ref(&kept))
.await
.expect("the kept event lands");
fixture.back_up().await.expect("the backup is taken");
let lost_at = EventStore::append(&store, core::slice::from_ref(&lost), None)
.await
.expect("the lost event lands");
fixture.restore().await.expect("the restore runs");
let removed: i64 = sqlx::query_scalar("SELECT count(*) FROM event_removed")
.fetch_one(store.pool())
.await
.expect("the record reads");
assert_eq!(
removed, 0,
"the restore kept a record the backup did not have"
);
let lost_id = happenstance_core::EventId::new(old, lost_at);
let offered = [ReplicatedEvent::new(
lost_id,
RecordedAt::from_millis(0),
lost,
)];
let ingested =
IngestStore::ingest(&fixture.store().await, &[IngestGroup::new(&offered, &[])]).await;
match after_restore {
AfterRestore::Remint => {
let landed = ingested.expect("after the re-mint the lost event is foreign");
assert_eq!(
(landed.appended, landed.skipped),
(1, 0),
"the lost event was skipped as removed"
);
}
AfterRestore::NothingMore => assert!(
matches!(ingested, Err(IngestError::UnheldOwnIdentity { id, .. }) if id == lost_id),
"without the re-mint the claim is SY-38's refusal: {ingested:?}"
),
}
}
}
#[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}"
);
}