use happenstance_core::{EventId, EventStore, SequencePosition};
use happenstance_sync::{FailureClass, IngestError, IngestGroup};
use super::{TempFile, carrying, event, id, ingest, log, peer, shipped};
use crate::event_store::SqliteEventStore;
use happenstance_sync::Classify;
pub(super) fn remove(file: &TempFile, positions: &[SequencePosition]) {
let mut operator = file.inspect();
operator
.pragma_update(None, "foreign_keys", "ON")
.expect("the operator's connection enforces foreign keys");
let transaction = operator
.transaction_with_behavior(rusqlite::TransactionBehavior::Immediate)
.expect("the removal takes the write lock");
for position in positions {
let position = i64::try_from(position.get()).expect("a SQLite position fits i64");
transaction
.execute(
"UPDATE tag_cardinality SET events = events - 1 \
WHERE tag IN (SELECT tag FROM event_tag WHERE position = ?1)",
[position],
)
.expect("the tag statistic is decremented");
transaction
.execute("DELETE FROM event_tag WHERE position = ?1", [position])
.expect("the tag rows go");
let deleted = transaction
.execute("DELETE FROM event WHERE position = ?1", [position])
.expect("the event row goes");
assert_eq!(deleted, 1, "position {position} was held");
}
transaction.commit().expect("the removal commits");
}
async fn position_of(store: &SqliteEventStore, id: EventId) -> SequencePosition {
carrying(&log(store).await, id).position
}
fn counts(ingested: happenstance_sync::Ingested) -> (usize, usize, usize) {
(ingested.appended, ingested.skipped, ingested.compensated)
}
#[tokio::test]
async fn a_removed_foreign_event_is_skipped_on_redelivery() {
let file = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let from = peer(0x61);
let batch = [
shipped(id(from, 1), 1, event("Shipped", "a")),
shipped(id(from, 2), 2, event("Shipped", "b")),
shipped(id(from, 3), 3, event("Shipped", "c")),
];
ingest(&store, &[IngestGroup::new(&batch, &[])])
.await
.expect("three foreign events land");
remove(&file, &[position_of(&store, batch[1].id).await]);
let pruned = log(&store).await;
let again = ingest(&store, &[IngestGroup::new(&batch, &[])])
.await
.expect("a re-delivery over a removal is not an error");
assert_eq!(counts(again), (0, 3, 0), "the removed event came back");
assert_eq!(log(&store).await, pruned, "the log is the pruned log");
assert!(
!store.contains_event_id(batch[1].id).await.expect("a read"),
"the removed identity reads as held again"
);
}
#[tokio::test]
async fn a_removed_own_event_is_skipped_not_refused() {
let file = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let first = store
.append(&[event("Local", "a")], None)
.await
.expect("an append lands");
store
.append(&[event("Local", "b")], None)
.await
.expect("an append lands");
remove(&file, &[first]);
let echo = EventId::new(store.store_id(), first);
let arrived = id(peer(0x62), 1);
let batch = [
shipped(echo, 0, event("Local", "a")),
shipped(arrived, 1, event("Shipped", "y")),
];
let landed = ingest(&store, &[IngestGroup::new(&batch, &[])])
.await
.expect("a removed own event is a skip, not SY-38's refusal");
assert_eq!(counts(landed), (1, 1, 0));
assert!(store.contains_event_id(arrived).await.expect("a read"));
assert!(
!store.contains_event_id(echo).await.expect("a read"),
"the removed own event came back"
);
}
#[tokio::test]
async fn an_own_claim_never_held_is_refused_after_a_removal() {
let file = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let first = store
.append(&[event("Local", "a")], None)
.await
.expect("an append lands");
let head = store
.append(&[event("Local", "b")], None)
.await
.expect("an append lands");
remove(&file, &[first]);
let never = head
.next()
.and_then(SequencePosition::next)
.and_then(SequencePosition::next)
.expect("three past a fresh head exist");
let claim = EventId::new(store.store_id(), never);
let batch = [
shipped(id(peer(0x63), 1), 1, event("Shipped", "z")),
shipped(claim, 2, event("Local", "forged")),
];
let before = log(&store).await;
let refused = ingest(&store, &[IngestGroup::new(&batch, &[])])
.await
.expect_err("a claim never held is refused after a removal too");
assert!(
matches!(refused, IngestError::UnheldOwnIdentity { id, .. } if id == claim),
"expected UnheldOwnIdentity naming {claim}, got {refused:?}"
);
assert_eq!(refused.class(), FailureClass::Stop);
assert_eq!(
log(&store).await,
before,
"a refused ingest wrote something"
);
}
#[tokio::test]
async fn a_group_of_removed_and_held_events_writes_no_compensation() {
let file = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let from = peer(0x64);
let group = [
shipped(id(from, 1), 1, event("Reserved", "seat-1")),
shipped(id(from, 2), 2, event("Reserved", "seat-2")),
];
let answer = [event("ReservationCompensated", "seat")];
ingest(&store, &[IngestGroup::new(&group, &answer)])
.await
.expect("the group lands with its compensation");
remove(&file, &[position_of(&store, group[0].id).await]);
let pruned = log(&store).await;
let again = ingest(&store, &[IngestGroup::new(&group, &answer)])
.await
.expect("a re-delivery is not an error");
assert_eq!(
counts(again),
(0, 2, 0),
"compensated a group that landed nothing"
);
assert_eq!(log(&store).await, pruned);
}
#[tokio::test]
async fn a_group_with_one_new_event_lands_it_and_compensates_once() {
let file = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let from = peer(0x65);
let group = [
shipped(id(from, 1), 1, event("Reserved", "seat-1")),
shipped(id(from, 2), 2, event("Reserved", "seat-2")),
];
let (removed, fresh) = (&group[0], &group[1]);
ingest(&store, &[IngestGroup::new(&group[..1], &[])])
.await
.expect("the first event lands");
remove(&file, &[position_of(&store, removed.id).await]);
let answer = [event("ReservationCompensated", "seat")];
let landed = ingest(&store, &[IngestGroup::new(&group, &answer)])
.await
.expect("a group with one new event lands");
assert_eq!(counts(landed), (1, 1, 1));
assert!(store.contains_event_id(fresh.id).await.expect("a read"));
assert!(!store.contains_event_id(removed.id).await.expect("a read"));
assert_eq!(log(&store).await.len(), 2, "the new event and its answer");
}
fn snapshot(file: &TempFile) -> (Vec<u8>, i64) {
let connection = file.inspect();
connection
.execute_batch("PRAGMA wal_checkpoint(TRUNCATE);")
.expect("the WAL checkpoints");
let sequence: i64 = connection
.query_row(
"SELECT seq FROM sqlite_sequence WHERE name = 'event'",
[],
|row| row.get(0),
)
.expect("the allocator has a row once anything was appended");
drop(connection);
(std::fs::read(&file.0).expect("the file reads"), sequence)
}
#[tokio::test]
async fn a_skip_against_a_removal_burns_no_position_and_leaves_the_file_unchanged() {
let file = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let from = peer(0x66);
let batch = [
shipped(id(from, 1), 1, event("Shipped", "a")),
shipped(id(from, 2), 2, event("Shipped", "b")),
];
ingest(&store, &[IngestGroup::new(&batch, &[])])
.await
.expect("two foreign events land");
let removed_at = position_of(&store, batch[0].id).await;
remove(&file, &[removed_at]);
let before = snapshot(&file);
let again = ingest(&store, &[IngestGroup::new(&batch[..1], &[])])
.await
.expect("a re-delivery is not an error");
assert_eq!(counts(again), (0, 1, 0));
assert_eq!(
snapshot(&file),
before,
"a skip-only call changed the file or burned a position"
);
}
#[tokio::test]
async fn the_record_reaches_every_handle_and_survives_reopen() {
let file = TempFile::new("ingest-removal");
let earlier = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let batch = [shipped(id(peer(0x67), 1), 1, event("Shipped", "a"))];
ingest(&earlier, &[IngestGroup::new(&batch, &[])])
.await
.expect("a foreign event lands");
remove(&file, &[position_of(&earlier, batch[0].id).await]);
let later = SqliteEventStore::open(&file.0).expect("a second handle opens");
for (which, store) in [("earlier", &earlier), ("later", &later)] {
let again = ingest(store, &[IngestGroup::new(&batch, &[])])
.await
.expect("a re-delivery is not an error");
assert_eq!(counts(again), (0, 1, 0), "through the {which} handle");
}
drop((earlier, later));
let reopened = SqliteEventStore::open(&file.0).expect("the file reopens");
let again = ingest(&reopened, &[IngestGroup::new(&batch, &[])])
.await
.expect("a re-delivery is not an error");
assert_eq!(counts(again), (0, 1, 0), "after reopen");
assert!(
!reopened
.contains_event_id(batch[0].id)
.await
.expect("a read")
);
}
#[tokio::test]
async fn a_restored_copy_rolls_the_record_back_with_the_allocator() {
let file = TempFile::new("ingest-removal");
let backup = TempFile::new("ingest-removal");
let store = SqliteEventStore::open(&file.0).expect("a fresh file opens");
let kept = store
.append(&[event("Local", "kept")], None)
.await
.expect("an append lands");
file.inspect()
.execute(
"VACUUM INTO ?1",
[backup.0.to_str().expect("a UTF-8 temp path")],
)
.expect("the backup is taken");
let after = store
.append(&[event("Local", "after")], None)
.await
.expect("an append lands");
remove(&file, &[kept, after]);
drop(store);
file.remove();
std::fs::copy(&backup.0, &file.0).expect("the backup is restored");
let restored = SqliteEventStore::open(&file.0).expect("the restored file opens");
let kept_id = EventId::new(restored.store_id(), kept);
let after_id = EventId::new(restored.store_id(), after);
assert!(restored.contains_event_id(kept_id).await.expect("a read"));
let removals: i64 = file
.inspect()
.query_row("SELECT count(*) FROM event_removed", [], |row| row.get(0))
.expect("the record reads");
assert_eq!(removals, 0, "the record was not rolled back with the file");
let echo = [shipped(kept_id, 0, event("Local", "kept"))];
let held = ingest(&restored, &[IngestGroup::new(&echo, &[])])
.await
.expect("an echo of a held event is a skip");
assert_eq!(counts(held), (0, 1, 0));
let claim = [shipped(after_id, 0, event("Local", "after"))];
let refused = ingest(&restored, &[IngestGroup::new(&claim, &[])])
.await
.expect_err("an own event minted after the backup is SY-38's refusal");
assert!(
matches!(refused, IngestError::UnheldOwnIdentity { id, .. } if id == after_id),
"expected UnheldOwnIdentity naming {after_id}, got {refused:?}"
);
}