use crate::prop;
use crate::{
clean_text, config, directory, files, messages::Locale, player, podcast, recorder, redact,
speech::Segment, territories,
};
use prop::{check, gen_ascii_ident, gen_unicode};
use rand::Rng;
use reqwest::Url;
use std::{
collections::BTreeSet,
fs,
io::{BufReader, Read},
os::unix::fs::PermissionsExt,
path::PathBuf,
time::Duration,
};
use unicode_segmentation::UnicodeSegmentation;
#[test]
fn prop_clean_text_grapheme_and_control_invariants() {
check(
"clean_text_invariants",
300,
|rng, case| {
if case == 0 {
format!("{}👨\u{200d}👩\u{200d}👧tail", "a".repeat(1022))
} else if case == 1 {
"a".repeat(1200)
} else {
let n = rng.random_range(0..=160);
gen_unicode(rng, n)
}
},
|input| {
let out = clean_text(input);
if out.chars().any(char::is_control) {
return Err(format!("control char remained in clean_text: {out:?}"));
}
if out.chars().count() > 1024 {
return Err(format!("exceeded 1024 scalars: {}", out.chars().count()));
}
if clean_text(&out) != out {
return Err("clean_text is not idempotent".into());
}
let mut oracle = String::new();
let mut count = 0usize;
for g in input.graphemes(true) {
if g.chars().next().is_none_or(char::is_control) {
continue;
}
count += g.chars().count();
if count > 1024 {
break;
}
oracle.push_str(g);
}
if out != oracle {
return Err(format!("fast/slow clean_text mismatch on {input:?}"));
}
Ok(())
},
);
}
#[test]
fn prop_redact_urls_and_validate_url_security() {
check(
"redact_urls_zero_leak_and_idempotence",
250,
|rng, case| {
let secret = format!("SEC{}RET", gen_ascii_ident(rng, 4, 10));
let host = format!("{}.example.test", gen_ascii_ident(rng, 3, 8));
let param = [
"token",
"api_key",
"Access%5FToken",
"password",
"sig",
"auth",
"x-amz-signature",
"secret",
][rng.random_range(0..8)];
let mode = if case < 4 {
case as u8
} else {
rng.random_range(0..5)
};
(secret, host, param.to_owned(), mode)
},
|(secret, host, param, mode)| {
let url = match mode {
0 => format!("https://user:{secret}@{host}/stream.mp3"),
1 => format!("https://{host}/live?{param}={secret}&fmt=aac"),
2 => format!(
"https://{host}/proxy?next=https://inner.test/a?{param}={secret}&lang=en"
),
3 => {
let benign =
format!("https://{host}/cb?next=https://other.test&email=me@host.com");
if redact::has_url_credentials(&benign) {
return Err(format!("B5 false positive on {benign:?}"));
}
return Ok(());
}
_ => {
format!("error fetching http://{secret}:pw@{host}/x?{param}={secret} (timeout)")
}
};
if !redact::has_url_credentials(&url) {
return Err(format!("missed credentials in {url:?}"));
}
let redacted = redact::urls(&url);
if redacted.contains(secret) {
return Err(format!("secret {secret:?} leaked in {redacted:?}"));
}
if !redacted.contains(host) {
return Err(format!("host {host:?} stripped from {redacted:?}"));
}
if redact::urls(&redacted) != redacted {
return Err(format!("redact::urls not idempotent on {redacted:?}"));
}
Ok(())
},
);
check(
"validate_url_rejects_controls_and_bad_schemes",
200,
|rng, case| {
let ctrl = ['\t', '\r', '\n', '\0', '\x1b'][rng.random_range(0..5)];
let host = format!("{}.example.test", gen_ascii_ident(rng, 2, 8));
let kind = if case < 4 {
case as u8
} else {
rng.random_range(0..4)
};
(ctrl, host, kind)
},
|(ctrl, host, kind)| {
match kind {
0 => {
let bad = format!("https://user{ctrl}:pass@{host}/a");
if config::validate_url(&bad).is_ok() {
return Err(format!("control char accepted in URL: {bad:?}"));
}
}
1 => {
let bad = format!("ht{ctrl}tps://{host}/stream");
if config::validate_url(&bad).is_ok() {
return Err(format!("control char in scheme accepted: {bad:?}"));
}
}
2 => {
let bad = format!("file:///{host}/a.mp3");
if config::validate_url(&bad).is_ok() {
return Err(format!("non-http scheme accepted: {bad:?}"));
}
}
_ => {
let good = format!("https://{host}/stream?q=1");
config::validate_url(&good)
.map_err(|e| format!("valid URL rejected: {good:?}: {e}"))?;
}
}
Ok(())
},
);
}
#[test]
fn prop_directory_host_validation_and_pagination_bounds() {
check(
"directory_host_anti_spoofing",
200,
|rng, case| {
let label = gen_ascii_ident(rng, 1, 8);
match case {
0 => ("evil.example/.api.radio-browser.info".into(), false),
1 => ("evil.example?.api.radio-browser.info".into(), false),
2 => ("evil.example#.api.radio-browser.info".into(), false),
3 => ("de1.api.radio-browser.info".into(), true),
_ => {
if rng.random_bool(0.5) {
(format!("{label}.api.radio-browser.info"), true)
} else {
let spoof = match rng.random_range(0..6) {
0 => format!("{label}/.api.radio-browser.info"),
1 => format!("{label}?.api.radio-browser.info"),
2 => format!("{label}#.api.radio-browser.info"),
3 => format!("{label}@.api.radio-browser.info"),
4 => format!("{label}:80/.api.radio-browser.info"),
_ => format!("{label}.api.radio-browser.info.evil.com"),
};
(spoof, false)
}
}
}
},
|(host, expected)| {
let valid_label = !host.starts_with('-') && !host.contains("--");
let got = directory::valid_directory_host(host);
if *expected && valid_label && !got {
return Err(format!("valid directory host rejected: {host:?}"));
}
if !expected && got {
return Err(format!("spoofed directory host accepted: {host:?}"));
}
Ok(())
},
);
check(
"directory_validate_page_bounds",
300,
|rng, case| match case {
0 => (199_000usize, 1000usize),
1 => (200_000, 0),
2 => (200_000, 1),
3 => (usize::MAX, 1),
4 => (0, 1001),
_ => (rng.random_range(0..=210_000), rng.random_range(0..=1100)),
},
|(offset, received)| {
let ok = *received <= 1000 && offset.saturating_add(*received) <= 200_000;
let got = directory::validate_page_for_test(*offset, *received).is_ok();
if got != ok {
return Err(format!("validate_page({offset}, {received})={got} != {ok}"));
}
Ok(())
},
);
}
#[test]
fn prop_player_icy_encoding_and_radioinfo_xml() {
check(
"player_icy_latin1_utf8_roundtrip",
200,
|rng, _| {
let parts = [
"上海爵士",
"北京广播",
"Café",
"Björk",
"Jazz 98.7",
"你好世界",
];
let n = rng.random_range(1..=3);
(0..n)
.map(|_| parts[rng.random_range(0..parts.len())])
.collect::<Vec<_>>()
.join(" - ")
},
|title| {
let mojibake: String = title.as_bytes().iter().map(|&b| char::from(b)).collect();
let recovered = player::icy_title(&mojibake);
if recovered != *title {
return Err(format!(
"Latin-1 round-trip failed: orig={title:?}, mojibake={mojibake:?}, got={recovered:?}"
));
}
if player::icy_title(title) != *title {
return Err(format!("icy_title altered valid UTF-8: {title:?}"));
}
let mut raw_ipc =
br#"{"event":"property-change","name":"media-title","data":""#.to_vec();
raw_ipc.extend_from_slice(&[0xc9, 0xcf, 0xba, 0xa3]); raw_ipc.extend_from_slice(br#""}"#);
if player::parse_ipc_message_for_test(&raw_ipc).is_err() {
return Err("parse_ipc_message dropped valid JSON with raw GBK bytes".into());
}
let repaired = player::icy_title_bytes(&[0xc9, 0xcf, 0xba, 0xa3]);
if repaired != "上海" {
return Err(format!(
"GBK bytes failed to decode to 上海: got {repaired:?}"
));
}
Ok(())
},
);
check(
"player_radioinfo_strict_xml",
200,
|rng, case| {
let artist = gen_ascii_ident(rng, 2, 10);
let song = gen_ascii_ident(rng, 2, 10);
let mode = if case < 5 {
case as u8
} else {
rng.random_range(0..5)
};
(artist, song, mode)
},
|(artist, song, mode)| {
match mode {
0 => {
let xml = format!(
"<RadioInfo><Table><DB_DALET_ARTIST_NAME>{artist}</DB_DALET_ARTIST_NAME><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table></RadioInfo>"
);
let got = player::radioinfo_title_for_test(&xml);
if got.as_deref() != Some(format!("{artist} - {song}").as_str()) {
return Err(format!("valid RadioInfo failed: got {got:?}"));
}
}
1 => {
let xml = format!(
"<RadioInfo><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table><Table><DB_DALET_ARTIST_NAME>{artist}</DB_DALET_ARTIST_NAME></Table></RadioInfo>"
);
let got = player::radioinfo_title_for_test(&xml);
if got.as_deref() != Some(song.as_str()) {
return Err(format!("borrowed across <Table>: got {got:?}"));
}
}
2 => {
let xml = format!(
"<RadioInfo><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table><Extra broken/></RadioInfo>"
);
if player::radioinfo_title_for_test(&xml).is_some() {
return Err("malformed trailing attribute accepted".into());
}
}
3 => {
let xml = format!(
"<RadioInfo x=\"a<b\"><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table></RadioInfo>"
);
if player::radioinfo_title_for_test(&xml).is_some() {
return Err("literal '<' in attribute accepted".into());
}
}
_ => {
let xml = format!(
"<RadioInfo x=\"a<b\"><Table><DB_DALET_TITLE_NAME>{song}</DB_DALET_TITLE_NAME></Table></RadioInfo>"
);
if player::radioinfo_title_for_test(&xml).as_deref() != Some(song.as_str()) {
return Err("escaped < in attribute wrongly rejected".into());
}
}
}
Ok(())
},
);
}
#[test]
fn prop_territories_matching_and_locale_fallback() {
check(
"territories_single_char_and_fallback",
200,
|rng, case| {
let single = ["中", "国", "美", "日", "法", "a", "Z", " "][rng.random_range(0..8)];
let code = ["CN", "HK", "MO", "TW", "US", "ZZ", ""][rng.random_range(0..7)];
let upstream = if case % 2 == 0 { "UpstreamLand" } else { "" };
(single.to_owned(), code.to_owned(), upstream.to_owned())
},
|(single, code, upstream)| {
if territories::matching_codes(single).next().is_some() {
return Err(format!("1-char query {single:?} widened to territories"));
}
for (alias, iso) in [("香港", "HK"), ("澳门", "MO")] {
if !territories::matching_prefix_codes(alias).any(|c| c == iso) {
return Err(format!("alias {alias} missed {iso}"));
}
}
let en = territories::display_in(Locale::En, code, upstream);
if en.chars().any(|c| ('\u{4e00}'..='\u{9fff}').contains(&c)) {
return Err(format!("En locale emitted Chinese text: {en:?}"));
}
if code == "ZZ" && !upstream.is_empty() && !en.contains(upstream) {
return Err(format!("unknown code dropped upstream name: got {en:?}"));
}
Ok(())
},
);
}
struct ChunkedReader<'a> {
data: &'a [u8],
pos: usize,
chunk: usize,
}
impl Read for ChunkedReader<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
if self.pos >= self.data.len() {
return Ok(0);
}
let take = buf.len().min(self.chunk).min(self.data.len() - self.pos);
buf[..take].copy_from_slice(&self.data[self.pos..self.pos + take]);
self.pos += take;
Ok(take)
}
}
#[test]
fn prop_podcast_feed_xml_bom_atom_and_opml() {
let base = Url::parse("https://example.test/feed.xml").unwrap();
check(
"podcast_feed_atom_bom_and_scoping",
150,
|rng, _| {
let chunk = rng.random_range(1..=7usize);
let with_bom = rng.random_bool(0.6);
let pub_first = rng.random_bool(0.5);
let title_word = gen_ascii_ident(rng, 2, 10);
let ep_id = gen_ascii_ident(rng, 3, 10);
(chunk, with_bom, pub_first, title_word, ep_id)
},
|(chunk, with_bom, pub_first, word, ep_id)| {
if ep_id.is_empty() {
return Ok(());
}
let chunk = (*chunk).max(1);
let dates = if *pub_first {
"<published>2025-01-10T00:00:00Z</published><updated>2026-06-01T00:00:00Z</updated>"
} else {
"<updated>2026-06-01T00:00:00Z</updated><published>2025-01-10T00:00:00Z</published>"
};
let xml = format!(
r#"<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
<title type="text"><{word}> Show</title>
<entry>
<id>{ep_id}</id>
<title type="text">Ep <{word}></title>
{dates}
<source>
<id>foreign-source-id</id>
<title>Foreign Source</title>
</source>
<link rel="enclosure" href="https://example.test/{ep_id}.mp3" type="audio/mpeg"/>
</entry>
</feed>"#
);
let mut bytes = Vec::new();
if *with_bom {
bytes.extend_from_slice(&[0xef, 0xbb, 0xbf]);
}
bytes.extend_from_slice(xml.as_bytes());
let full = podcast::parse_feed_for_test(&bytes, &base)
.map_err(|e| format!("contiguous parse failed: {e}"))?;
let chunked = podcast::parse_reader_for_test(
BufReader::with_capacity(
chunk,
ChunkedReader {
data: &bytes,
pos: 0,
chunk,
},
),
&base,
)
.map_err(|e| format!("chunked(chunk={chunk}) parse failed: {e}"))?
.ok_or_else(|| "chunked parse returned None".to_owned())?;
if full.feed.title != format!("<{word}> Show") {
return Err(format!(
"Atom type=text stripped literal <...>: {:?}",
full.feed.title
));
}
if full.episodes.len() != 1 || full.episodes[0].guid.as_deref() != Some(ep_id.as_str())
{
return Err("Atom <source><id> leaked into entry".into());
}
if full.episodes[0].published.as_deref() != Some("2025-01-10T00:00:00+00:00") {
return Err(format!(
"Atom <published> lost precedence to <updated>: {:?}",
full.episodes[0].published
));
}
if chunked.feed.title != full.feed.title
|| chunked.episodes.len() != full.episodes.len()
|| chunked.episodes[0].guid != full.episodes[0].guid
{
return Err("chunk-split BOM parse diverged from contiguous parse".into());
}
Ok(())
},
);
check(
"podcast_opml_depth_and_dedup",
100,
|rng, case| {
let depth = match case {
0 => 63usize,
1 => 64,
2 => 65,
_ => rng.random_range(1..=68),
};
let n_urls = rng.random_range(1..=8usize);
let urls: Vec<String> = (0..n_urls)
.map(|_| format!("https://example.test/f{}.xml", rng.random_range(0..4)))
.collect();
(depth, urls)
},
|(depth, urls)| {
let mut xml = String::from("<opml version=\"2.0\"><body>");
let extra = depth.saturating_sub(2);
for i in 0..extra {
xml.push_str(&format!("<outline text=\"g{i}\">"));
}
for u in urls {
xml.push_str(&format!("<outline text=\"a/\" xmlUrl=\"{u}\" />"));
}
for _ in 0..extra {
xml.push_str("</outline>");
}
xml.push_str("</body></opml>");
let parsed = podcast::opml_for_test(xml.as_bytes());
if *depth > 64 {
if parsed.is_ok() {
return Err(format!("OPML depth {depth} > 64 was accepted"));
}
} else {
let got = parsed.map_err(|e| format!("valid OPML depth {depth} failed: {e}"))?;
let mut expected = Vec::new();
for u in urls {
if !expected.contains(u) {
expected.push(u.clone());
}
}
if got != expected {
return Err(format!(
"OPML dedup order mismatch: {got:?} != {expected:?}"
));
}
}
Ok(())
},
);
}
#[test]
fn prop_files_noclobber_and_private_directory_security() {
let dir = tempfile::tempdir().unwrap();
let p1 = dir.path().join("p1.part");
let f1 = dir.path().join("f1.mp3");
fs::write(&p1, b"audio1").unwrap();
files::publish_noclobber(&p1, &f1).unwrap();
assert!(!p1.exists() && fs::read(&f1).unwrap() == b"audio1");
let p2 = dir.path().join("p2.part");
let f2 = dir.path().join("f2.mp3");
fs::write(&p2, b"audio2").unwrap();
fs::hard_link(&p2, &f2).unwrap();
files::publish_noclobber(&p2, &f2).unwrap();
assert!(!p2.exists() && fs::read(&f2).unwrap() == b"audio2");
let p3 = dir.path().join("p3.part");
let f3 = dir.path().join("f3.mp3");
fs::write(&p3, b"same").unwrap();
fs::write(&f3, b"same").unwrap();
assert!(files::publish_noclobber(&p3, &f3).is_err());
assert!(p3.exists() && fs::read(&f3).unwrap() == b"same");
let p4 = dir.path().join("p4.part");
let target = dir.path().join("target.mp3");
let sym = dir.path().join("sym.mp3");
fs::write(&p4, b"new").unwrap();
fs::write(&target, b"victim").unwrap();
std::os::unix::fs::symlink(&target, &sym).unwrap();
assert!(files::publish_noclobber(&p4, &sym).is_err());
assert_eq!(fs::read(&target).unwrap(), b"victim");
assert!(files::publish_noclobber(&f1, &f1).is_err());
check(
"open_private_directory_mode_matrix",
64,
|rng, case| match case {
0 => 0o700u32,
1 => 0o755,
2 => 0o770,
3 => 0o707,
_ => 0o700 | (rng.random_range(0..=0o077u32)),
},
|mode| {
let sub = dir.path().join(format!("priv_{mode:o}"));
let _ = fs::remove_dir(&sub);
fs::create_dir(&sub).unwrap();
fs::set_permissions(&sub, fs::Permissions::from_mode(*mode)).unwrap();
let ok = files::open_private_directory(&sub).is_ok();
let expected = (*mode & 0o077) == 0;
if ok != expected {
return Err(format!(
"open_private_directory(mode={mode:o})={ok} != {expected}"
));
}
Ok(())
},
);
let good_dir = dir.path().join("good_0700");
fs::create_dir(&good_dir).unwrap();
fs::set_permissions(&good_dir, fs::Permissions::from_mode(0o700)).unwrap();
let sym_dir = dir.path().join("sym_0700");
std::os::unix::fs::symlink(&good_dir, &sym_dir).unwrap();
assert!(files::open_private_directory(&sym_dir).is_err());
assert!(files::open_nofollow_nonblock(&sym).unwrap().is_none());
}
#[test]
fn prop_recorder_filenames_space_stderr_and_socket_path() {
check(
"recorder_filename_and_space_invariants",
250,
|rng, _| {
let station = gen_unicode(rng, 40);
let track = gen_unicode(rng, 60);
let reserve_mb: u64 = if rng.random_bool(0.25) {
u64::MAX / (1024 * 1024) + rng.random_range(0..10)
} else {
rng.random_range(0..=10_000)
};
let bitrate: u64 = if rng.random_bool(0.25) {
u64::MAX
} else {
rng.random_range(0..=5_000_000)
};
let secs: u64 = rng.random_range(0..=86_400 * 30);
(station, track, reserve_mb, bitrate, secs)
},
|(station, track, reserve_mb, bitrate, secs)| {
let s_comp = recorder::test_hooks::filename_component(station, 40, 120);
let t_comp = recorder::test_hooks::track_filename_component(track, 80);
if s_comp.len() > 120 || s_comp.chars().count() > 40 {
return Err(format!("station component exceeded cap: {s_comp:?}"));
}
if t_comp.len() > 80 || t_comp.chars().count() > 40 {
return Err(format!("track component exceeded cap: {t_comp:?}"));
}
for c in s_comp.chars().chain(t_comp.chars()) {
if c == '/' || c == '\\' || c == '\0' || c.is_control() {
return Err(format!("unsafe char {c:?} in filename component"));
}
}
let full_name = format!("20260101-000000-{s_comp}-{t_comp}-12345678.mp3.part");
if full_name.len() + ".json.tmp".len() > 255 {
return Err(format!(
"recording name exceeded NAME_MAX: {}",
full_name.len() + ".json.tmp".len()
));
}
let info = serde_json::json!({
"streams": [{"bit_rate": bitrate.to_string()}],
"format": {"bit_rate": "64000"}
});
let (est1, known1) = recorder::test_hooks::required_space(
*reserve_mb,
128,
&info,
Some(Duration::from_secs(*secs)),
);
let (est2, _) = recorder::test_hooks::required_space(
*reserve_mb,
128,
&info,
Some(Duration::from_secs(secs.saturating_add(60))),
);
if est2 < est1 {
return Err("required_space is not monotonic in duration".into());
}
if *bitrate > 0 && !known1 {
return Err("positive stream bitrate should yield known estimate".into());
}
let mut tail = String::new();
for _ in 0..40 {
recorder::test_hooks::append_error_tail(&mut tail, track);
}
if tail.len() > 8192 {
return Err(format!("error tail exceeded 8192 bytes: {}", tail.len()));
}
if tail
.chars()
.any(|c| c.is_control() && c != '\n' && c != '\t')
{
return Err("disallowed control char remained in error tail".into());
}
if recorder::test_hooks::recording_progress("Will reconnect at 123")
|| recorder::test_hooks::recording_progress("Failed to open segment 4")
|| !recorder::test_hooks::recording_progress("out_time_us=12345")
{
return Err("recording_progress misclassified FFmpeg stderr line".into());
}
Ok(())
},
);
check(
"ipc_socket_path_sun_path_bound",
100,
|rng, _| rng.random_range(1..=160usize),
|depth| {
let dir = PathBuf::from(format!("/{}", "a".repeat(*depth)));
let sock = player::ipc_socket_path_for_test(&dir);
if sock.starts_with(&dir) && sock.as_os_str().len() > 100 {
return Err(format!(
"socket path inside deep runtime_dir exceeded 100 bytes: {}",
sock.as_os_str().len()
));
}
Ok(())
},
);
}
#[test]
fn prop_progressive_checkpoint_torn_tail_and_window_bounds() {
let dir = tempfile::tempdir().unwrap();
let cfg = crate::test_support::config(dir.path());
let ep = podcast::Episode {
id: "ep-prop".into(),
feed_id: "feed-prop".into(),
title: "Test".into(),
url: "https://example.test/ep.mp3".into(),
..Default::default()
};
let max_idx = podcast::progressive::test_hooks::max_window_index();
assert!(
max_idx
.checked_mul(15_000)
.and_then(|v| v.checked_add(16_000))
.is_some()
);
let mut full = BTreeSet::new();
full.insert(max_idx);
let _ = podcast::progressive::test_hooks::next_window(full, Some(u64::MAX), u64::MAX);
let windows = vec![
(
0u64,
None,
vec![Segment {
epoch: 0,
start_ms: 0,
end_ms: 5000,
text: "first".into(),
}],
),
(
1u64,
None,
vec![Segment {
epoch: 0,
start_ms: 15_000,
end_ms: 20_000,
text: "second".into(),
}],
),
(
2u64,
Some(45_000),
vec![Segment {
epoch: 0,
start_ms: 30_000,
end_ms: 35_000,
text: "third".into(),
}],
),
];
let path =
podcast::progressive::test_hooks::write_and_append_checkpoint(&cfg, &ep, &windows).unwrap();
let full_bytes = fs::read(&path).unwrap();
let last_nl = full_bytes[..full_bytes.len() - 1]
.iter()
.rposition(|&b| b == b'\n')
.unwrap();
for cut in (last_nl + 1)..full_bytes.len() {
fs::write(&path, &full_bytes[..cut]).unwrap();
let (got_windows, got_segs) = podcast::progressive::test_hooks::read_checkpoint(&cfg, &ep)
.unwrap()
.unwrap();
assert_eq!(
got_windows,
BTreeSet::from([0u64, 1u64]),
"torn tail at byte {cut} broke committed windows"
);
assert_eq!(got_segs.len(), 2);
}
fs::write(&path, &full_bytes).unwrap();
let (got_windows, got_segs) = podcast::progressive::test_hooks::read_checkpoint(&cfg, &ep)
.unwrap()
.unwrap();
assert_eq!(got_windows, BTreeSet::from([0u64, 1u64, 2u64]));
assert_eq!(got_segs.len(), 3);
}
#[test]
fn prop_store_read_snapshot_and_shrink_policy() {
use crate::{
error::{DomainError, ErrorCode},
model::{Filter, Sort, Station},
store::Store,
};
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("radio.db");
let mut store = Store::open(&path).unwrap();
let store2 = Store::open(&path).unwrap();
let rows: Vec<Station> = (0..100usize)
.map(|i| Station {
stationuuid: uuid::Uuid::from_u128(9000 + i as u128).to_string(),
name: format!("Snap {i:03}"),
url: format!("http://example.test/s/{i}"),
clickcount: i as u64,
votes: i as u64,
active: true,
..Station::default()
})
.collect();
store.begin_sync().unwrap();
store.stage(&rows).unwrap();
store.finish_sync().unwrap();
let target = rows[50].stationuuid.clone();
let filter = Filter {
sort: Sort::Votes,
..Filter::default()
};
let (before, pos, after) = store
.read_snapshot(|s| {
let before = s.search_count(&filter)?;
let pos = s.station_position(&target, &filter)?;
store2.upsert(&Station {
stationuuid: uuid::Uuid::new_v4().to_string(),
name: "New Concurrent".into(),
url: "http://example.test/new".into(),
active: true,
custom: true,
..Station::default()
})?;
let after = s.search_count(&filter)?;
Ok((before, pos, after))
})
.unwrap();
assert_eq!(before, 100);
assert_eq!(after, 100);
assert_eq!(pos, Some(49));
check(
"store_shrink_threshold_exact_rational",
40,
|rng, case| match case {
0 => 74usize,
1 => 75,
2 => 0,
_ => rng.random_range(0..=100),
},
|new_count| {
let prev_dir = store.directory_count().unwrap();
store.begin_sync().unwrap();
store.stage(&rows[..*new_count]).unwrap();
let res = store.finish_sync_cancellable(
|| false,
|s, count| {
let prev = s.directory_count()?;
Ok((prev > 0 && count * 4 < prev * 3)
.then(|| DomainError::new(ErrorCode::CatalogShrink)))
},
);
let expected_err = if *new_count == 0 {
Some(ErrorCode::EmptyCatalog)
} else if prev_dir > 0 && *new_count * 4 < prev_dir * 3 {
Some(ErrorCode::CatalogShrink)
} else {
None
};
match (expected_err, res) {
(Some(code), Err(e))
if e.downcast_ref::<DomainError>().map(|d| d.code) == Some(code) => {}
(None, Ok(_)) => {
store.begin_sync().unwrap();
store.stage(&rows).unwrap();
store.finish_sync().unwrap();
}
(exp, got) => {
return Err(format!(
"shrink mismatch prev={prev_dir} new={new_count} expected={exp:?} got={got:?}"
));
}
}
Ok(())
},
);
}