use crate::config::HistoryConfig;
use anyhow::{Context, Result, ensure};
use kiri_core::{HistoryMap, HistoryStats};
use rusqlite::{
Connection, ErrorCode, OptionalExtension, Transaction, TransactionBehavior, params,
};
use std::{
fs,
path::Path,
sync::Arc,
time::{Duration, Instant, SystemTime, UNIX_EPOCH},
};
const BUSY_TIMEOUT: Duration = Duration::from_secs(5);
const MILLIS_PER_DAY: f64 = 86_400_000.0;
fn timestamp() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |duration| duration.as_millis() as i64)
}
fn half_life(config: &HistoryConfig) -> f64 {
config.half_life_days * MILLIS_PER_DAY
}
fn decay(score: f64, last_selected: i64, now: i64, half_life: f64) -> f64 {
let elapsed = now.saturating_sub(last_selected).max(0) as f64;
score * (-elapsed / half_life).exp2()
}
fn open(path: &Path) -> Result<Connection> {
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
let connection = Connection::open(path)?;
connection.busy_timeout(BUSY_TIMEOUT)?;
let started = Instant::now();
loop {
let mode: rusqlite::Result<String> =
connection.query_row("PRAGMA journal_mode = WAL", [], |row| row.get(0));
match mode {
Ok(mode) => {
ensure!(
mode.eq_ignore_ascii_case("wal"),
"cannot enable SQLite WAL (journal mode {mode})"
);
break;
}
Err(rusqlite::Error::SqliteFailure(error, _))
if error.code == ErrorCode::DatabaseBusy && started.elapsed() < BUSY_TIMEOUT =>
{
std::thread::sleep(Duration::from_millis(10));
}
Err(error) => return Err(error.into()),
}
}
connection.execute_batch(
"CREATE TABLE IF NOT EXISTS selections (
value BLOB PRIMARY KEY NOT NULL,
last_selected INTEGER NOT NULL,
frequency INTEGER NOT NULL,
frecency REAL NOT NULL
) WITHOUT ROWID;
CREATE INDEX IF NOT EXISTS selections_recency
ON selections (last_selected DESC, frequency DESC, value ASC);",
)?;
Ok(connection)
}
async fn with_database<T, F>(config: &HistoryConfig, operation: F) -> Result<T>
where
T: Send + 'static,
F: FnOnce(&HistoryConfig, &mut Connection) -> Result<T> + Send + 'static,
{
let config = config.clone();
tokio::task::spawn_blocking(move || {
let path = config.database_path()?;
let mut connection = open(&path)
.with_context(|| format!("cannot open history database {}", path.display()))?;
operation(&config, &mut connection)
.with_context(|| format!("cannot access history database {}", path.display()))
})
.await
.context("history task failed")?
}
fn read_history(connection: &Connection, config: &HistoryConfig, now: i64) -> Result<HistoryMap> {
let mut statement = connection.prepare(
"SELECT value, last_selected, frequency, frecency FROM selections
ORDER BY last_selected DESC, frequency DESC, value ASC LIMIT ?1",
)?;
let half_life = half_life(config);
let rows = statement.query_map([i64::try_from(config.max_entries)?], |row| {
let last_selected = row.get(1)?;
Ok((
row.get(0)?,
HistoryStats {
last_selected,
frequency: row.get(2)?,
frecency: decay(row.get(3)?, last_selected, now, half_life),
},
))
})?;
Ok(rows.collect::<rusqlite::Result<HistoryMap>>()?)
}
pub async fn load(config: &HistoryConfig) -> Result<Arc<HistoryMap>> {
if !config.enabled {
return Ok(Arc::new(HistoryMap::new()));
}
with_database(config, |config, connection| {
Ok(Arc::new(read_history(connection, config, timestamp())?))
})
.await
}
fn write_selections(
transaction: &Transaction<'_>,
config: &HistoryConfig,
values: &[Vec<u8>],
now: i64,
) -> Result<()> {
{
let mut lookup = transaction
.prepare("SELECT last_selected, frecency FROM selections WHERE value = ?1")?;
let mut upsert = transaction.prepare(
"INSERT INTO selections (value, last_selected, frequency, frecency)
VALUES (?1, ?2, 1, ?3)
ON CONFLICT(value) DO UPDATE SET
last_selected = excluded.last_selected,
frequency = selections.frequency + 1,
frecency = excluded.frecency",
)?;
let half_life = half_life(config);
for value in values {
let previous: Option<(i64, f64)> = lookup
.query_row([value], |row| Ok((row.get(0)?, row.get(1)?)))
.optional()?;
let (selected, score) = previous.map_or((now, 1.0), |(last, score)| {
(now.max(last), 1.0 + decay(score, last, now, half_life))
});
upsert.execute(params![value, selected, score])?;
}
}
let count: i64 =
transaction.query_row("SELECT COUNT(*) FROM selections", [], |row| row.get(0))?;
let excess = count - i64::try_from(config.max_entries)?;
if excess > 0 {
transaction.execute(
"DELETE FROM selections WHERE value IN (
SELECT value FROM selections
ORDER BY last_selected ASC, frequency ASC, value DESC LIMIT ?1
)",
[excess],
)?;
}
Ok(())
}
pub async fn record(config: &HistoryConfig, values: Vec<Vec<u8>>) -> Result<()> {
if !config.enabled || values.is_empty() {
return Ok(());
}
with_database(config, move |config, connection| {
let transaction = connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
write_selections(&transaction, config, &values, timestamp())?;
transaction.commit()?;
Ok(())
})
.await
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn config(path: PathBuf) -> HistoryConfig {
HistoryConfig {
enabled: true,
path: Some(path),
half_life_days: 1.0,
max_entries: 100,
}
}
#[test]
fn scores_decay_at_selection_and_load_and_prune_old_entries() -> Result<()> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("history.sqlite3");
let mut settings = config(path.clone());
settings.max_entries = 2;
let mut connection = open(&path)?;
let item = b"a\0b".to_vec();
let other = b"other".to_vec();
let recent = b"recent".to_vec();
let day = MILLIS_PER_DAY as i64;
for (now, values) in [
(10, vec![item.clone(), other.clone()]),
(10 + day, vec![item.clone()]),
(10 + 2 * day, vec![recent.clone()]),
] {
let transaction =
connection.transaction_with_behavior(TransactionBehavior::Immediate)?;
write_selections(&transaction, &settings, &values, now)?;
transaction.commit()?;
}
let history = read_history(&connection, &settings, 10 + 3 * day)?;
assert_eq!(history[&item].frequency, 2);
assert_eq!(history[&item].last_selected, 10 + day);
assert!((history[&item].frecency - 0.375).abs() < 1e-12);
assert!((history[&recent].frecency - 0.5).abs() < 1e-12);
assert!(!history.contains_key(&other));
let count: i64 =
connection.query_row("SELECT COUNT(*) FROM selections", [], |row| row.get(0))?;
assert_eq!(count, 2);
Ok(())
}
#[tokio::test]
async fn concurrent_writers_do_not_lose_selections() -> Result<()> {
let dir = tempfile::tempdir()?;
let settings = config(dir.path().join("history.sqlite3"));
let item = b"same item".to_vec();
let mut writers = Vec::new();
for _ in 0..8 {
let settings = settings.clone();
let item = item.clone();
writers.push(tokio::spawn(async move {
record(&settings, vec![item; 3]).await
}));
}
for writer in writers {
writer.await??;
}
let history = load(&settings).await?;
assert_eq!(history[&item].frequency, 24);
assert!(history[&item].frecency > 23.9);
Ok(())
}
#[tokio::test]
async fn disabled_history_never_creates_files() -> Result<()> {
let dir = tempfile::tempdir()?;
let mut settings = config(dir.path().join("missing").join("history.sqlite3"));
settings.enabled = false;
record(&settings, vec![b"item".to_vec()]).await?;
assert!(load(&settings).await?.is_empty());
assert!(!dir.path().join("missing").exists());
Ok(())
}
}