use core::num::NonZeroUsize;
use std::sync::{Arc, Mutex};
use crate::{Timestamp, drive::registry::Flip};
use super::{
Culled, Curator, CurrentRow, CurrentTable, Generational, GenerationsOptions, GenerationsOverride,
GenerationsStore, GenerationsStoreError, RunId, Scope, Turning, prepare,
};
#[test]
fn a_minted_run_only_ever_rises() {
let first = RunId::mint();
let second = RunId::mint();
let third = RunId::mint();
assert!(first < second, "{first} is not below {second}");
assert!(second < third, "{second} is not below {third}");
assert!(
first.get() > 1_600_000_000_000_000,
"a minted run is seeded from the wall clock, and {first} is not"
);
}
#[test]
fn a_run_crosses_the_signed_boundary_and_comes_back() {
for raw in [0, 1, 1_756_000_000_000_000, u64::MAX] {
let run = RunId::new(raw);
assert_eq!(
RunId::from_i64(run.as_i64()),
run,
"{raw} did not round-trip"
);
}
}
#[test]
fn the_default_scope_is_spelled() {
assert_eq!(Scope::default().as_str(), Scope::WHOLE);
assert_eq!(Scope::default().to_string(), "whole");
}
#[test]
fn a_scope_is_a_bare_identifier() {
for word in ["\"; DROP TABLE media; --", "with space", "0leading", ""] {
let refusal = Scope::new(word).expect_err("this should not name a closure");
assert_eq!(refusal.word(), word);
}
assert!(Scope::new("frames_v2").is_ok());
}
#[test]
fn a_pointer_table_is_named_for_its_family() {
let table = CurrentTable::new("media").expect("`media` is an identifier");
assert_eq!(table.family(), "media");
assert_eq!(table.name(), "__ig_current_media");
assert_eq!(table.named().as_str(), "__ig_current_media");
}
#[test]
fn a_family_that_cannot_be_spliced_is_refused() {
let refusal =
CurrentTable::new("media\"; DROP TABLE media; --").expect_err("a quote is not an identifier");
assert_eq!(refusal.word(), "media\"; DROP TABLE media; --");
}
#[test]
fn a_roster_entry_audits_both_of_its_words() {
assert!(Generational::new("clip", "media").is_ok());
assert_eq!(
Generational::new("clip", "media\" = 1 OR \"1")
.expect_err("a quote is not an identifier")
.word(),
"media\" = 1 OR \"1"
);
assert_eq!(
Generational::new("clip; DROP TABLE media", "media")
.expect_err("a semicolon is not an identifier")
.word(),
"clip; DROP TABLE media"
);
}
#[derive(Debug, Clone, PartialEq, Eq)]
enum Act {
Ready,
Point(RunId),
Roll,
Sweep(RunId, usize),
}
struct Recorder {
transcript: Mutex<Vec<Act>>,
refuse_point: bool,
}
impl Recorder {
fn new(refuse_point: bool) -> Arc<Self> {
Arc::new(Self {
transcript: Mutex::new(Vec::new()),
refuse_point,
})
}
fn transcript(&self) -> Vec<Act> {
self.transcript.lock().expect("not poisoned").clone()
}
fn wrote(&self, act: Act) {
self.transcript.lock().expect("not poisoned").push(act);
}
}
fn refusal(verb: &'static str) -> GenerationsStoreError {
GenerationsStoreError::new(
verb,
"__ig_current_media",
std::io::Error::other("the engine said no"),
)
}
impl GenerationsStore<u64> for Recorder {
fn ready(&self) -> Turning<'_, ()> {
Box::pin(async move {
self.wrote(Act::Ready);
Ok(())
})
}
fn point<'a>(&'a self, row: &'a CurrentRow<u64>) -> Turning<'a, ()> {
Box::pin(async move {
self.wrote(Act::Point(row.run()));
if self.refuse_point {
return Err(refusal("point"));
}
Ok(())
})
}
fn current<'a>(&'a self, _key: &'a u64, _scope: &'a Scope) -> Turning<'a, Option<RunId>> {
Box::pin(async move { Ok(None) })
}
fn roll(&self) -> Turning<'_, Vec<CurrentRow<u64>>> {
Box::pin(async move {
self.wrote(Act::Roll);
Ok(Vec::new())
})
}
fn sweep<'a>(&'a self, _key: &'a u64, current: RunId, keep: NonZeroUsize) -> Turning<'a, Culled> {
Box::pin(async move {
self.wrote(Act::Sweep(current, keep.get()));
Ok(Culled { tables: 2, rows: 5 })
})
}
}
fn seated(
store: Arc<Recorder>,
options: GenerationsOptions,
) -> (Curator<u64>, super::CuratorBody<u64>) {
Curator::new(
store as Arc<dyn GenerationsStore<u64>>,
Scope::default(),
options,
)
}
#[tokio::test]
async fn the_pointer_lands_before_anything_is_erased() {
let store = Recorder::new(false);
let (_seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
let run = RunId::new(42);
body
.perform(&1, Flip::new(run, Timestamp::UNIX_EPOCH))
.await;
assert_eq!(
store.transcript(),
vec![Act::Point(run), Act::Sweep(run, 1)],
"the sweep must follow the flip and never precede it"
);
let report = body.report();
assert_eq!(report.flipped, 1);
assert_eq!(report.swept, 5);
assert_eq!(report.refused, 0);
}
#[tokio::test]
async fn the_sweep_is_anchored_on_the_run_that_landed() {
let store = Recorder::new(false);
let (_seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
for run in [10, 20, 30] {
body
.perform(&1, Flip::new(RunId::new(run), Timestamp::UNIX_EPOCH))
.await;
}
assert_eq!(
store.transcript(),
vec![
Act::Point(RunId::new(10)),
Act::Sweep(RunId::new(10), 1),
Act::Point(RunId::new(20)),
Act::Sweep(RunId::new(20), 1),
Act::Point(RunId::new(30)),
Act::Sweep(RunId::new(30), 1),
]
);
}
#[tokio::test]
async fn a_refused_flip_sweeps_nothing() {
let store = Recorder::new(true);
let (_seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
body
.perform(&1, Flip::new(RunId::new(9), Timestamp::UNIX_EPOCH))
.await;
assert_eq!(
store.transcript(),
vec![Act::Point(RunId::new(9))],
"a `DELETE` must not follow a pointer that did not land"
);
let report = body.report();
assert_eq!(report.flipped, 0);
assert_eq!(report.swept, 0);
assert_eq!(report.refused, 1);
}
#[tokio::test]
async fn the_retention_depth_is_read_at_every_flip() {
let store = Recorder::new(false);
let (seat, body) = seated(Arc::clone(&store), GenerationsOptions::new());
body
.perform(&1, Flip::new(RunId::new(1), Timestamp::UNIX_EPOCH))
.await;
seat.apply_knobs(&GenerationsOverride::new().with_keep(NonZeroUsize::new(4).expect("not zero")));
body
.perform(&1, Flip::new(RunId::new(2), Timestamp::UNIX_EPOCH))
.await;
assert_eq!(
store.transcript(),
vec![
Act::Point(RunId::new(1)),
Act::Sweep(RunId::new(1), 1),
Act::Point(RunId::new(2)),
Act::Sweep(RunId::new(2), 4),
]
);
assert_eq!(seat.options().keep().get(), 4);
}
#[test]
fn an_override_that_names_nothing_moves_no_knob() {
let store = Recorder::new(false);
let (seat, _body) = seated(
store,
GenerationsOptions::new().with_keep(NonZeroUsize::new(3).expect("not zero")),
);
seat.apply_knobs(&GenerationsOverride::new());
assert_eq!(seat.options().keep().get(), 3);
}
#[tokio::test]
async fn the_boot_road_readies_before_it_rolls() {
let store = Recorder::new(false);
let held = prepare::<u64>(store.as_ref())
.await
.expect("nothing refused");
assert_eq!(held, 0);
assert_eq!(store.transcript(), vec![Act::Ready, Act::Roll]);
}
#[test]
fn a_refusal_names_the_verb_and_keeps_the_engine_underneath() {
let refusal = refusal("point");
assert_eq!(refusal.verb(), "point");
assert_eq!(refusal.table(), "__ig_current_media");
assert_eq!(
refusal.to_string(),
"the generations store refused `point` on `__ig_current_media`"
);
assert!(core::error::Error::source(&refusal).is_some());
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn the_sqlite_statements_are_what_the_module_note_says() {
use super::{SqlGenerations, current_filter};
let table = CurrentTable::new("media").expect("`media` is an identifier");
let clip = Generational::new("clip", "media").expect("both are identifiers");
let store = SqlGenerations::<sqlx::Sqlite, u64>::new(
sqlx::Pool::connect_lazy("sqlite::memory:").expect("a lazy pool opens nothing"),
"media",
vec![clip.clone()],
)
.expect("`media` is an identifier");
assert_eq!(store.table().name(), "__ig_current_media");
assert!(
store
.create_statement()
.starts_with("CREATE TABLE IF NOT EXISTS \"__ig_current_media\" ("),
"{create}",
create = store.create_statement()
);
assert!(
store
.create_statement()
.ends_with("PRIMARY KEY (\"root\", \"scope\"))"),
"the pointer's grain is the pair: {create}",
create = store.create_statement()
);
assert_eq!(
store.point_statement(),
"INSERT INTO \"__ig_current_media\" (\"root\", \"scope\", \"run\", \"flipped_second\", \
\"flipped_nanosecond\") VALUES (?, ?, ?, ?, ?) ON CONFLICT (\"root\", \"scope\") DO UPDATE \
SET \"run\" = excluded.\"run\", \"flipped_second\" = excluded.\"flipped_second\", \
\"flipped_nanosecond\" = excluded.\"flipped_nanosecond\""
);
assert_eq!(
store.current_statement(),
"SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = ? AND \"scope\" = ?"
);
let swept = store.sweep_statement(&clip, NonZeroUsize::new(2).expect("not zero"));
assert_eq!(
swept,
"DELETE FROM \"clip\" WHERE \"media\" = ? AND \"__ig_run__\" < (SELECT MIN(r) FROM (SELECT \
DISTINCT \"__ig_run__\" AS r FROM \"clip\" WHERE \"media\" = ? AND \"__ig_run__\" <= ? ORDER \
BY r DESC LIMIT 2) AS kept)"
);
assert_eq!(
current_filter::<sqlx::Sqlite>("clip", "media", &table, 1),
"\"clip\".\"__ig_run__\" = (SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = \
\"clip\".\"media\" AND \"scope\" = ?)"
);
}
#[cfg(feature = "postgres")]
#[tokio::test]
async fn postgres_numbers_every_marker() {
use super::{SqlGenerations, current_filter};
let table = CurrentTable::new("media").expect("`media` is an identifier");
let clip = Generational::new("clip", "media").expect("both are identifiers");
let store = SqlGenerations::<sqlx::Postgres, u64>::new(
sqlx::Pool::connect_lazy("postgres://user@localhost/db").expect("a lazy pool opens nothing"),
"media",
vec![clip.clone()],
)
.expect("`media` is an identifier");
assert!(
store
.point_statement()
.contains("VALUES ($1, $2, $3, $4, $5)"),
"{point}",
point = store.point_statement()
);
assert!(
store
.point_statement()
.contains("DO UPDATE SET \"run\" = EXCLUDED.\"run\""),
"{point}",
point = store.point_statement()
);
assert_eq!(
store.current_statement(),
"SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = $1 AND \"scope\" = $2"
);
let swept = store.sweep_statement(&clip, NonZeroUsize::new(1).expect("not zero"));
assert!(swept.contains("\"media\" = $1"), "{swept}");
assert!(swept.contains("\"media\" = $2"), "{swept}");
assert!(swept.contains("\"__ig_run__\" <= $3"), "{swept}");
assert!(swept.ends_with("LIMIT 1) AS kept)"), "{swept}");
assert_eq!(
current_filter::<sqlx::Postgres>("clip", "media", &table, 7),
"\"clip\".\"__ig_run__\" = (SELECT \"run\" FROM \"__ig_current_media\" WHERE \"root\" = \
\"clip\".\"media\" AND \"scope\" = $7)"
);
}
#[cfg(feature = "mysql")]
#[tokio::test]
async fn mysql_brackets_with_backticks_and_names_no_target() {
use super::SqlGenerations;
let clip = Generational::new("clip", "media").expect("both are identifiers");
let store = SqlGenerations::<sqlx::MySql, u64>::new(
sqlx::Pool::connect_lazy("mysql://user@localhost/db").expect("a lazy pool opens nothing"),
"media",
vec![clip.clone()],
)
.expect("`media` is an identifier");
assert!(
store.point_statement().contains(
"ON DUPLICATE KEY UPDATE `run` = VALUES(`run`), `flipped_second` = \
VALUES(`flipped_second`), `flipped_nanosecond` = VALUES(`flipped_nanosecond`)"
),
"{point}",
point = store.point_statement()
);
let swept = store.sweep_statement(&clip, NonZeroUsize::new(1).expect("not zero"));
assert!(
swept.contains("FROM (SELECT DISTINCT `__ig_run__` AS r FROM `clip`"),
"the inner FROM is a DERIVED TABLE, which is what makes it legal on MySQL: {swept}"
);
assert!(swept.ends_with("AS kept)"), "{swept}");
}