use rand::Rng;
use std::time::Duration;
use crate::sampling::standard_normal;
pub struct ReadingTimeEstimator {
wpm_mean: f64,
wpm_std: f64,
}
impl Default for ReadingTimeEstimator {
fn default() -> Self {
Self {
wpm_mean: 225.0,
wpm_std: 20.0,
}
}
}
impl ReadingTimeEstimator {
#[must_use]
pub fn new(wpm_mean: f64, wpm_std: f64) -> Self {
Self { wpm_mean, wpm_std }
}
#[must_use]
pub fn estimate(&self, text: &str) -> Duration {
let mut rng = rand::thread_rng();
let word_count = count_words(text).max(1) as f64;
let z = standard_normal(&mut rng);
let wpm = (self.wpm_mean + z * self.wpm_std).max(100.0);
let minutes = word_count / wpm;
let ms = (minutes * 60_000.0) as u64;
Duration::from_millis(ms.clamp(500, 120_000))
}
#[must_use]
pub fn estimate_words(&self, word_count: usize) -> Duration {
let words = "word ".repeat(word_count);
self.estimate(&words)
}
}
pub struct ActionDelay;
impl ActionDelay {
#[must_use]
pub fn before_click() -> Duration {
let ms = rand::thread_rng().gen_range(200_u64..=800);
Duration::from_millis(ms)
}
#[must_use]
pub fn form_field_transition() -> Duration {
let ms = rand::thread_rng().gen_range(300_u64..=1_200);
Duration::from_millis(ms)
}
#[must_use]
pub fn after_page_load() -> Duration {
let ms = rand::thread_rng().gen_range(800_u64..=3_000);
Duration::from_millis(ms)
}
#[must_use]
pub fn micro() -> Duration {
let ms = rand::thread_rng().gen_range(50_u64..=200);
Duration::from_millis(ms)
}
#[cfg(feature = "browser")]
pub async fn wait_before_click() {
tokio::time::sleep(Self::before_click()).await;
}
#[cfg(feature = "browser")]
pub async fn wait_form_transition() {
tokio::time::sleep(Self::form_field_transition()).await;
}
#[cfg(feature = "browser")]
pub async fn wait_after_load() {
tokio::time::sleep(Self::after_page_load()).await;
}
}
pub struct SessionPacing {
actions_taken: u32,
next_idle_at: u32,
fatigue: f64,
burst_remaining: u32,
}
impl Default for SessionPacing {
fn default() -> Self {
Self::new()
}
}
impl SessionPacing {
#[must_use]
pub fn new() -> Self {
let mut rng = rand::thread_rng();
Self {
actions_taken: 0,
next_idle_at: rng.gen_range(8..20),
fatigue: 1.0,
burst_remaining: rng.gen_range(3..8),
}
}
pub fn advance<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Option<Duration> {
self.actions_taken += 1;
self.fatigue = 1.0 + 0.5 * (1.0 - (-(self.actions_taken as f64) / 60.0).exp());
let mut total_ms: u64 = 0;
if self.burst_remaining == 0 {
let base_ms = rng.gen_range(800_u64..3_000);
total_ms += (base_ms as f64 * self.fatigue) as u64;
self.burst_remaining = rng.gen_range(3..8);
} else {
self.burst_remaining -= 1;
}
if self.actions_taken >= self.next_idle_at {
let idle_ms = rng.gen_range(5_000_u64..15_000);
total_ms += (idle_ms as f64 * self.fatigue) as u64;
self.actions_taken = 0;
self.next_idle_at = rng.gen_range(8..20);
self.burst_remaining = rng.gen_range(3..8);
}
(total_ms > 0).then(|| Duration::from_millis(total_ms))
}
#[cfg(feature = "browser")]
pub async fn tick(&mut self) {
use rand::SeedableRng;
let mut rng = rand::rngs::StdRng::from_entropy();
if let Some(delay) = self.advance(&mut rng) {
tokio::time::sleep(delay).await;
}
}
#[must_use]
pub fn fatigue(&self) -> f64 {
self.fatigue
}
#[must_use]
pub fn actions_taken(&self) -> u32 {
self.actions_taken
}
#[must_use]
pub fn scale_duration(&self, base: Duration) -> Duration {
Duration::from_millis((base.as_millis() as f64 * self.fatigue) as u64)
}
}
fn count_words(text: &str) -> usize {
text.split_whitespace().count()
}
#[cfg(test)]
mod tests {
use super::*;
use rand::{rngs::StdRng, SeedableRng};
use std::time::Duration;
#[test]
fn reading_time_minimum_500ms() {
let est = ReadingTimeEstimator::default();
let d = est.estimate("hello");
assert!(
d >= Duration::from_millis(500),
"expected >= 500 ms, got {d:?}"
);
}
#[test]
fn reading_time_grows_with_word_count() {
let est = ReadingTimeEstimator::default();
let short: u128 = (0..50).map(|_| est.estimate_words(10).as_millis()).sum();
let long: u128 = (0..50).map(|_| est.estimate_words(100).as_millis()).sum();
assert!(
long > short,
"long text ({long}) should take longer than short ({short})"
);
}
#[test]
fn reading_time_under_120s() {
let est = ReadingTimeEstimator::default();
for _ in 0..50 {
let d = est.estimate_words(500);
assert!(
d <= Duration::from_secs(120),
"expected <= 120 s, got {d:?}"
);
}
}
#[test]
fn reading_time_reasonable_for_200_words() {
let est = ReadingTimeEstimator::default();
let samples: Vec<Duration> = (0..100).map(|_| est.estimate_words(200)).collect();
let mean_ms: u128 = samples.iter().map(|d| d.as_millis()).sum::<u128>() / 100;
assert!(
(30_000..=90_000).contains(&mean_ms),
"mean {mean_ms} ms out of expected 30–90 s window"
);
}
#[test]
fn empty_text_returns_minimum() {
let est = ReadingTimeEstimator::default();
let d = est.estimate("");
assert_eq!(d, Duration::from_millis(500));
}
#[test]
fn before_click_in_range() {
for _ in 0..100 {
let d = ActionDelay::before_click();
assert!(
d >= Duration::from_millis(200) && d <= Duration::from_millis(800),
"before_click {d:?} out of 200–800 ms range"
);
}
}
#[test]
fn form_field_transition_in_range() {
for _ in 0..100 {
let d = ActionDelay::form_field_transition();
assert!(
d >= Duration::from_millis(300) && d <= Duration::from_millis(1_200),
"form_field_transition {d:?} out of 300–1200 ms range"
);
}
}
#[test]
fn after_page_load_in_range() {
for _ in 0..100 {
let d = ActionDelay::after_page_load();
assert!(
d >= Duration::from_millis(800) && d <= Duration::from_millis(3_000),
"after_page_load {d:?} out of 800–3000 ms range"
);
}
}
#[test]
fn micro_delay_in_range() {
for _ in 0..100 {
let d = ActionDelay::micro();
assert!(
d >= Duration::from_millis(50) && d <= Duration::from_millis(200),
"micro delay {d:?} out of 50–200 ms range"
);
}
}
#[test]
fn initial_fatigue_is_one() {
let pacing = SessionPacing::new();
assert!((pacing.fatigue() - 1.0).abs() < 0.01);
}
#[test]
fn fatigue_increases_with_actions() {
let mut pacing = SessionPacing::new();
let mut rng = StdRng::seed_from_u64(11);
for _ in 0..30 {
pacing.advance(&mut rng);
}
assert!(
pacing.fatigue() > 1.0,
"fatigue should grow above 1.0 after 30 actions"
);
}
#[test]
fn fatigue_stays_below_1_5() {
let mut pacing = SessionPacing::new();
let mut rng = StdRng::seed_from_u64(3);
for _ in 0..500 {
pacing.advance(&mut rng);
}
assert!(
pacing.fatigue() < 1.5,
"fatigue should stay below 1.5, got {}",
pacing.fatigue()
);
}
#[test]
fn advance_emits_burst_end_pause() {
let mut pacing = SessionPacing::new();
pacing.burst_remaining = 0;
pacing.next_idle_at = u32::MAX; let mut rng = StdRng::seed_from_u64(99);
let pause = pacing.advance(&mut rng).expect("burst-end pause expected");
assert!(
pause >= Duration::from_millis(700) && pause <= Duration::from_millis(5_000),
"burst pause {pause:?} out of expected window"
);
assert!(pacing.burst_remaining >= 3);
}
#[test]
fn advance_no_pause_mid_burst() {
let mut pacing = SessionPacing::new();
pacing.burst_remaining = 5;
pacing.next_idle_at = u32::MAX;
let mut rng = StdRng::seed_from_u64(7);
assert!(
pacing.advance(&mut rng).is_none(),
"mid-burst tick should not pause"
);
assert_eq!(pacing.burst_remaining, 4);
}
#[test]
fn advance_idle_break_resets_counter() {
let mut pacing = SessionPacing::new();
pacing.burst_remaining = 5; pacing.actions_taken = 0;
pacing.next_idle_at = 1; let mut rng = StdRng::seed_from_u64(42);
let pause = pacing.advance(&mut rng).expect("idle pause expected");
assert!(
pause >= Duration::from_millis(5_000),
"idle pause too short: {pause:?}"
);
assert_eq!(
pacing.actions_taken, 0,
"idle break should reset the counter"
);
}
#[test]
fn scale_duration_with_fatigue() {
let mut pacing = SessionPacing::new();
pacing.fatigue = 1.2;
let base = Duration::from_millis(1000);
let scaled = pacing.scale_duration(base);
assert!(
scaled >= Duration::from_millis(1190) && scaled <= Duration::from_millis(1210),
"scaled {scaled:?} should be ~1200 ms"
);
}
#[test]
fn count_words_basic() {
assert_eq!(count_words("hello world foo"), 3);
assert_eq!(count_words(""), 0);
assert_eq!(count_words(" spaces "), 1);
}
#[test]
fn sample_normal_mean_near_zero() {
let mut rng = StdRng::seed_from_u64(123);
let n = 2000;
let mean: f64 = (0..n).map(|_| standard_normal(&mut rng)).sum::<f64>() / n as f64;
assert!(mean.abs() < 0.1, "normal mean {mean:.4} should be near 0");
}
}