use serde::{Deserialize, Serialize};
const FIRST_LOOK_SECS: u64 = 7 * 24 * 60 * 60;
const PROOF_SLACK_SECS: u64 = 10 * 60;
#[derive(Serialize, Deserialize, Clone, Copy, Debug, PartialEq, Eq)]
pub struct Gap {
pub lo: u64,
pub hi: u64,
}
const MAX_GAPS: usize = 32;
fn key(chat_id: &str) -> String {
format!("history_gaps:{chat_id}")
}
pub fn gaps(chat_id: &str) -> Vec<Gap> {
crate::db::get_sql_setting(key(chat_id))
.ok()
.flatten()
.and_then(|v| serde_json::from_str(&v).ok())
.unwrap_or_default()
}
fn save(chat_id: &str, gaps: &[Gap]) {
let value = if gaps.is_empty() { String::new() } else { serde_json::to_string(gaps).unwrap_or_default() };
let _ = crate::db::set_sql_setting(key(chat_id), value);
}
pub fn gap_at(chat_id: &str, before: u64) -> Option<Gap> {
find(&gaps(chat_id), before)
}
fn find(gaps: &[Gap], before: u64) -> Option<Gap> {
gaps.iter().copied().find(|g| g.lo < before && before <= g.hi + 1)
}
fn proof_key(chat_id: &str) -> String {
format!("history_proven:{chat_id}")
}
pub fn proven(chat_id: &str) -> Option<u64> {
crate::db::get_sql_setting(proof_key(chat_id)).ok().flatten().and_then(|v| v.parse().ok())
}
pub fn prove(chat_id: &str, began: u64) {
let at = began.saturating_sub(PROOF_SLACK_SECS);
if proven(chat_id).is_none_or(|p| at > p) {
let _ = crate::db::set_sql_setting(proof_key(chat_id), at.to_string());
}
}
pub fn floor(chat_id: &str, from: Option<u64>, now: u64) -> Option<u64> {
floor_of(&gaps(chat_id), proven(chat_id), from, now)
}
fn floor_of(gaps: &[Gap], proven: Option<u64>, from: Option<u64>, now: u64) -> Option<u64> {
if let Some(g) = from.and_then(|f| find(gaps, f)) {
return Some(g.lo);
}
let proof = proven.unwrap_or_else(|| now.saturating_sub(FIRST_LOOK_SECS));
from.is_none_or(|f| f > proof).then_some(proof)
}
pub fn reach(since: Option<u64>, floor: Option<u64>) -> Option<u64> {
match (since, floor) {
(Some(s), Some(f)) => Some(s.max(f)),
(s, f) => s.or(f),
}
}
pub fn note_walk(chat_id: &str, from: Option<u64>, stopped: Option<u64>, floor: Option<u64>, held_below: impl Fn(u64) -> Option<u64>) {
let before = gaps(chat_id);
let after = walked(&before, from, stopped, floor, held_below);
if after != before {
save(chat_id, &after);
}
}
fn walked(gaps: &[Gap], from: Option<u64>, stopped: Option<u64>, floor: Option<u64>, held_below: impl Fn(u64) -> Option<u64>) -> Vec<Gap> {
let top = from.unwrap_or(u64::MAX);
let mut out: Vec<Gap> = Vec::with_capacity(gaps.len() + 1);
match stopped {
Some(stop) => {
let Some(held) = held_below(stop) else {
return gaps.iter().copied().filter(|g| g.lo >= top || g.hi < stop).collect();
};
let lo = floor.filter(|f| *f < stop).map_or(held, |f| f.min(held));
let mut hole = Gap { lo, hi: stop };
for g in gaps {
if g.hi < hole.lo || g.lo >= top {
out.push(*g);
} else if g.lo < hole.lo {
hole.lo = g.lo;
}
}
out.push(hole);
}
None => out.extend(gaps.iter().copied().filter(|g| from.is_none_or(|f| find(std::slice::from_ref(g), f).is_none()))),
}
out.sort_by(|a, b| b.hi.cmp(&a.hi));
out.truncate(MAX_GAPS);
out
}
pub fn abandon(chat_id: &str, before: u64) {
let mut gaps = gaps(chat_id);
let len = gaps.len();
gaps.retain(|g| find(std::slice::from_ref(g), before).is_none());
if gaps.len() != len {
save(chat_id, &gaps);
}
}
#[cfg(test)]
mod tests {
use super::*;
const fn g(lo: u64, hi: u64) -> Gap {
Gap { lo, hi }
}
#[test]
fn a_catch_up_that_runs_out_of_pages_leaves_a_hole_down_to_held_history() {
let out = walked(&[], None, Some(5000), None, |t| (t > 1000).then_some(1000));
assert_eq!(out, vec![g(1000, 5000)]);
assert_eq!(find(&out, 5000), Some(g(1000, 5000)), "a scroll from the walk's last page crosses it");
assert_eq!(find(&out, 900), None, "below the hole is ordinary held history");
}
#[test]
fn nothing_held_below_is_no_hole() {
assert!(walked(&[], None, Some(5000), None, |_| None).is_empty());
}
#[test]
fn a_fill_page_lowers_the_top_and_a_finished_one_closes_it() {
let held = |t: u64| (t > 1000).then_some(1000);
let filled = walked(&[g(1000, 5000)], Some(5000), Some(3000), None, held);
assert_eq!(filled, vec![g(1000, 3000)]);
let closed = walked(&filled, Some(3000), None, None, held);
assert!(closed.is_empty());
}
#[test]
fn a_later_catch_up_keeps_an_older_hole_and_adds_its_own() {
let out = walked(&[g(1000, 5000)], None, Some(20_000), None, |t| (t > 8000).then_some(8000));
assert_eq!(out, vec![g(8000, 20_000), g(1000, 5000)]);
}
#[test]
fn a_catch_up_that_meets_held_history_leaves_older_holes_alone() {
assert_eq!(walked(&[g(1000, 5000)], None, None, None, |_| None), vec![g(1000, 5000)]);
}
#[test]
fn a_catch_up_walks_to_the_proof_not_to_the_first_held_page() {
assert_eq!(floor_of(&[], Some(1000), None, 50_000), Some(1000));
assert_eq!(floor_of(&[], Some(1000), Some(4000), 50_000), Some(1000));
assert_eq!(floor_of(&[], Some(1000), Some(900), 50_000), None);
}
#[test]
fn a_walk_inside_a_hole_goes_to_its_floor() {
assert_eq!(floor_of(&[g(1000, 5000)], Some(8000), Some(4000), 50_000), Some(1000));
}
#[test]
fn with_no_proof_the_last_week_is_unproven() {
let now = 30 * 24 * 3600;
assert_eq!(floor_of(&[], None, None, now), Some(now - FIRST_LOOK_SECS));
}
#[test]
fn a_hole_under_unproven_rows_reaches_down_to_the_proof() {
let held = |t: u64| [7000, 6000, 1000].into_iter().find(|h| *h < t);
let out = walked(&[], None, Some(8000), Some(1000), held);
assert_eq!(out, vec![g(1000, 8000)]);
let out = walked(&[], None, Some(800), Some(1000), |t| (t > 500).then_some(500));
assert_eq!(out, vec![g(500, 800)]);
}
#[test]
fn a_walk_asks_only_from_its_floor() {
assert_eq!(reach(None, Some(1000)), Some(1000), "a catch-up from the top: from the proof");
assert_eq!(reach(Some(1500), Some(1000)), Some(1500));
assert_eq!(reach(Some(500), Some(1000)), Some(1000));
assert_eq!(reach(None, None), None, "a back-page in proven history asks for everything older");
}
}