#![cfg(not(target_arch = "wasm32"))]
#![allow(clippy::unwrap_used)]
mod support;
use happenstance_postgres::event_store::PostgresEventStore;
use happenstance_postgres::sqlx::{Row, query};
use happenstance_testkit::concurrency::CONTENDERS;
use happenstance_testkit::{Capability, Fixture};
use support::PostgresFixture;
macro_rules! emit_ignored_tokio {
($($name:ident),* $(,)?) => {
$(
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn $name() {
happenstance_testkit::rules::$name(__conformance_fixture)
.await
.report(::core::stringify!($name));
}
)*
};
}
pub(crate) use emit_ignored_tokio;
macro_rules! emit_ignored_concurrency_tokio {
($($name:ident),* $(,)?) => {
$(
#[tokio::test(flavor = "multi_thread")]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn $name() {
happenstance_testkit::concurrency::rules::$name(__conformance_fixture)
.await
.report(::core::stringify!($name));
}
)*
};
}
pub(crate) use emit_ignored_concurrency_tokio;
macro_rules! emit_ignored_model_tokio {
($($name:ident),* $(,)?) => {
$(
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn $name() {
happenstance_testkit::model::rules::$name(__conformance_fixture)
.await
.report(::core::stringify!($name));
}
)*
};
}
pub(crate) use emit_ignored_model_tokio;
happenstance_testkit::event_store_conformance!(
mod_name = dcb_conformance,
emit = crate::emit_ignored_tokio,
fixture = PostgresFixture::new()
);
happenstance_testkit::event_store_concurrency_conformance!(
mod_name = dcb_concurrency_conformance,
emit = crate::emit_ignored_concurrency_tokio,
fixture = PostgresFixture::new()
);
happenstance_testkit::event_store_model_conformance!(
mod_name = dcb_model_conformance,
emit = crate::emit_ignored_model_tokio,
fixture = PostgresFixture::new()
);
const SETTLED_COLUMNS: &[(&str, &str, bool)] = &[
("position", "bigint", false),
("event_type", "text", false),
("data", "bytea", false),
("metadata", "bytea", true),
("tags", "ARRAY", false),
("origin_store", "bytea", true),
("origin_position", "bigint", true),
("recorded_at", "bigint", false),
("xact_id", "xid8", false),
("write_group", "bigint", true),
("group_guard", "bytea", true),
];
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn migration_1_creates_the_settled_column_set() {
let fixture = PostgresFixture::new();
let store = fixture.connect().await;
let rows = query(
"SELECT column_name, data_type, is_nullable \
FROM information_schema.columns \
WHERE table_schema = $1 AND table_name = 'event' \
ORDER BY ordinal_position",
)
.bind(fixture.schema())
.fetch_all(store.pool())
.await
.expect("the event table should exist after migrations 1 and 3");
let found: Vec<(String, String, bool)> = rows
.iter()
.map(|row| {
(
row.get::<String, _>("column_name"),
row.get::<String, _>("data_type"),
row.get::<String, _>("is_nullable") == "YES",
)
})
.collect();
let expected: Vec<(String, String, bool)> = SETTLED_COLUMNS
.iter()
.map(|(name, ty, nullable)| ((*name).to_owned(), (*ty).to_owned(), *nullable))
.collect();
assert_eq!(
found, expected,
"the event table's column set drifted: a new column is a decision, not a formality"
);
let indexes =
query("SELECT indexname FROM pg_indexes WHERE schemaname = $1 AND tablename = 'event'")
.bind(fixture.schema())
.fetch_all(store.pool())
.await
.expect("pg_indexes should answer");
let names: Vec<String> = indexes
.iter()
.map(|row| row.get::<String, _>("indexname"))
.collect();
let promised = ["event_tags_idx", "event_type_idx", "event_origin_idx"];
for expected in promised.into_iter().chain(["event_write_group_idx"]) {
assert!(
names.iter().any(|name| name == expected),
"index `{expected}` is missing; found {names:?}"
);
}
}
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn migration_1_does_not_preempt_adr_0024() {
let fixture = PostgresFixture::new();
let store = fixture.connect().await;
let row = query(
"SELECT column_default, is_identity \
FROM information_schema.columns \
WHERE table_schema = $1 AND table_name = 'event' AND column_name = 'position'",
)
.bind(fixture.schema())
.fetch_one(store.pool())
.await
.expect("the position column should exist");
assert!(
row.get::<Option<String>, _>("column_default").is_none(),
"`position` has acquired a column default. A default is `nextval()`, and \
`nextval()` allocating outside the transaction is where ES-10 is lost — \
which is the question ADR-0024 exists to answer deliberately."
);
assert_eq!(
row.get::<String, _>("is_identity"),
"NO",
"`position` has become an identity column, which is a sequence by another name"
);
}
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn two_fixture_instances_are_two_backing_stores() {
let left = PostgresFixture::new();
let right = PostgresFixture::new();
assert_ne!(
left.schema(),
right.schema(),
"two instances share a schema, so they are one backing store wearing two names"
);
let left_store = left.connect().await;
let right_store = right.connect().await;
insert_bare_row(&left_store, 1).await;
assert_eq!(count_events(&left_store).await, 1);
assert_eq!(
count_events(&right_store).await,
0,
"the second instance can see the first's row, so the isolation scheme is a lie"
);
}
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn two_handles_from_one_instance_share_a_backing_store() {
let fixture = PostgresFixture::new();
let first = fixture.connect().await;
let second = fixture.connect().await;
insert_bare_row(&first, 1).await;
assert_eq!(
count_events(&second).await,
1,
"the second handle cannot see the first's write, so they are not one store"
);
}
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn a_row_survives_a_reopen() {
let fixture = PostgresFixture::new();
{
let store = fixture.connect().await;
insert_bare_row(&store, 1).await;
}
fixture.reopen().await;
let reopened = fixture.connect().await;
assert_eq!(
count_events(&reopened).await,
1,
"the row did not survive a reopen, so `REOPEN: SUPPORTED` is not true"
);
}
#[tokio::test]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn removal_outside_the_port_deletes_the_row_and_keeps_the_allocator() {
use happenstance_core::{EventStore, Query, ReadOptions, collect};
use happenstance_testkit::fixtures::{query_tagged, tagged_event};
use happenstance_testkit::{Removed, Settled};
let fixture = PostgresFixture::new();
let store = fixture.connect().await;
let mut appended = Vec::new();
for (event_type, tag) in [("Kept", "kept"), ("Middle", "middle"), ("Tail", "tail")] {
let position = store
.append(&[tagged_event(event_type, &[("removal", tag)])], None)
.await
.unwrap();
appended.push(position);
}
let [kept, middle, tail] = appended[..] else {
unreachable!("three appends returned three positions")
};
assert_eq!(
fixture.remove_outside_port(&[middle, tail]).await,
Removed::Deleted
);
assert_eq!(fixture.settle_frontier().await, Settled::Visible);
let held = collect(store.read(&Query::all(), ReadOptions::new()))
.await
.unwrap();
assert_eq!(
held.iter().map(|event| event.position).collect::<Vec<_>>(),
[kept],
"only the event that was not named is left"
);
let survivor = held.first().unwrap();
let by_tag = collect(store.read(&query_tagged(&[("removal", "tail")]), ReadOptions::new()))
.await
.unwrap();
assert!(
by_tag.is_empty(),
"a tag query for a removed event finds nothing"
);
let next = store
.append(&[tagged_event("Next", &[("removal", "next")])], None)
.await
.unwrap();
assert_eq!(fixture.settle_frontier().await, Settled::Visible);
let after = collect(store.read(&Query::all(), ReadOptions::new()))
.await
.unwrap();
let appended_next = after.iter().find(|event| event.position == next).unwrap();
assert_eq!(
appended_next.id.store(),
survivor.id.store(),
"the same incarnation: a removal does not re-mint the StoreId"
);
assert!(
next > tail,
"the next append took {next}, at or below the removed tail at {tail}: \
the sequence rewound"
);
}
#[tokio::test(flavor = "multi_thread")]
#[ignore = "needs a live Postgres; run with `-- --ignored` (starts a container)"]
async fn contenders_handles_open_concurrently_without_deadlock() {
let fixture = PostgresFixture::new();
let mut stores = Vec::with_capacity(CONTENDERS);
for _ in 0..CONTENDERS {
stores.push(fixture.connect().await);
}
let mut handles = Vec::with_capacity(CONTENDERS);
for store in &stores {
let pool = store.pool().clone();
handles.push(tokio::spawn(async move {
query("SELECT 1")
.execute(&pool)
.await
.expect("a live handle should answer a trivial query");
}));
}
for handle in handles {
handle.await.expect("no contender task should panic");
}
assert_eq!(stores.len(), CONTENDERS);
}
struct Defaulted;
impl Fixture for Defaulted {
type Store = PostgresEventStore;
const SECOND_HANDLE: Capability = Capability::SUPPORTED;
const REOPEN: Capability = Capability::SUPPORTED;
async fn connect(&self) -> Self::Store {
unreachable!("`Defaulted` exists to be read, never constructed")
}
}
#[test]
fn capability_constants_are_answered_not_defaulted() {
assert!(PostgresFixture::SECOND_HANDLE.is_supported());
assert!(PostgresFixture::REOPEN.is_supported());
assert!(PostgresFixture::HELD_ABOVE_FRONTIER.is_supported());
assert!(PostgresFixture::REMOVAL.is_supported());
assert!(
PostgresFixture::MID_BATCH_FAULT.is_supported(),
"Postgres can fail between two rows of one batch -- an AFTER INSERT trigger raising on the nth row does it -- so declining is not an honest answer once `append` exists to fault"
);
assert_ne!(
PostgresFixture::MID_BATCH_FAULT.reason(),
Defaulted::MID_BATCH_FAULT.reason(),
"MID_BATCH_FAULT is the trait's silent default on a store that could co-operate"
);
assert_eq!(
PostgresFixture::MAX_EVENT_DATA_LEN,
Some(PostgresEventStore::MAX_EVENT_DATA_LEN)
);
assert_eq!(
PostgresFixture::MAX_TAGS_PER_EVENT,
Some(PostgresEventStore::MAX_TAGS_PER_EVENT)
);
assert_eq!(
PostgresFixture::MAX_EVENTS_PER_BATCH,
Some(PostgresEventStore::MAX_EVENTS_PER_BATCH)
);
}
#[test]
fn the_stated_ceilings_clear_the_specification_floors() {
const {
assert!(
PostgresEventStore::MAX_EVENT_DATA_LEN
>= happenstance_core::MIN_SUPPORTED_EVENT_DATA_LEN
);
assert!(
PostgresEventStore::MAX_TAGS_PER_EVENT
>= happenstance_core::MIN_SUPPORTED_TAGS_PER_EVENT
);
assert!(
PostgresEventStore::MAX_EVENTS_PER_BATCH
>= happenstance_core::MIN_SUPPORTED_EVENTS_PER_BATCH
);
}
}
async fn insert_bare_row(store: &PostgresEventStore, position: i64) {
query(
"INSERT INTO event (position, event_type, data, metadata, tags, recorded_at) \
VALUES ($1, 'probe', '\\x00'::bytea, NULL, ARRAY[]::text[], 0)",
)
.bind(position)
.execute(store.pool())
.await
.expect("a bare insert should succeed against migration 1's table");
}
async fn count_events(store: &PostgresEventStore) -> i64 {
query("SELECT count(*) AS n FROM event")
.fetch_one(store.pool())
.await
.expect("counting rows should succeed")
.get::<i64, _>("n")
}