use std::io;
use std::path::{Path, PathBuf};
use serde_json::Value;
use super::aside::opening;
use super::destination::stamp;
use super::draft::micros_z;
use super::drops;
use super::lock::tidy;
use super::queue::Queue;
use super::slots;
use super::state::State;
use super::usage::{Closed, Conversation, scan, stat, trees};
use crate::record::payload::Record;
use crate::record::settings::Settings;
use crate::record::spool::{Spool, line};
use crate::store::fileio::{atomic_write, private_mkdir, remove_file};
use crate::store::time::Stamp;
pub const FLOOR: u64 = 16 << 20;
pub const DEFAULT: u64 = 512 << 20;
pub const CEILING: u64 = 64 << 30;
const SETTING: &str = "[record] keep_bytes";
pub fn limit(home: &Path) -> io::Result<u64> {
let Ok(document) = crate::config::read(&home.join("config.toml")) else {
return Ok(DEFAULT);
};
let Some(value) = document
.get("record")
.and_then(|record| record.get("keep_bytes"))
else {
return Ok(DEFAULT);
};
value
.as_integer()
.and_then(|bytes| u64::try_from(bytes).ok())
.filter(|bytes| (FLOOR..=CEILING).contains(bytes))
.ok_or_else(|| {
io::Error::other(format!(
"{SETTING} must be an integer in {FLOOR}..{CEILING}"
))
})
}
pub struct Arrival<'a> {
pub home: &'a Path,
pub tree: &'a Path,
pub id: &'a str,
pub prompt: bool,
pub bytes: u64,
}
pub fn append(settings: &Settings, spool: &Spool, id: &str, record: &Record) -> io::Result<bool> {
let line = line(record);
let kept = match home_of(&settings.spool) {
Some(home) => {
let prompt = record.get("kind").and_then(Value::as_str) == Some("prompt");
let arrival = Arrival {
home: &home,
tree: &settings.spool,
id,
prompt,
bytes: line.len() as u64,
};
admit(&arrival, Stamp::now())?
}
None => true,
};
if kept {
spool.write(id, &line)?;
}
Ok(kept)
}
pub fn home_of(tree: &Path) -> Option<PathBuf> {
let own = tree
.file_name()
.is_some_and(|name| name == "spool" || name == "profile-spool");
match tree.parent() {
Some(parent) if own => Some(parent.to_path_buf()),
_ => crate::home::home().ok(),
}
}
pub fn admit(arrival: &Arrival, now: Stamp) -> io::Result<bool> {
admit_with(arrival, now, &mut |_| {})
}
pub fn admit_with(
arrival: &Arrival,
now: Stamp,
between: &mut dyn FnMut(&Path),
) -> io::Result<bool> {
let limit = limit(arrival.home)?;
let landing = slots::directory(arrival.home);
let marker = arrival.tree.join(format!("{}.dropped", arrival.id));
if marker.try_exists()? {
if !arrival.prompt {
drops::add(&landing, 0, arrival.bytes, now)?;
return Ok(false);
}
remove_file(&marker)?;
}
let trees = trees(arrival.home, arrival.tree);
let (mut total, closed) = scan(&trees)?;
if total + arrival.bytes <= limit {
return Ok(true);
}
let span = arrival.tree.join(format!("{}.jsonl", arrival.id));
let own = stat(&span)?.map_or(0, |metadata| metadata.len());
if own > 0 && own + arrival.bytes > limit {
if !arrival.prompt {
drops::add(&landing, 1, own + arrival.bytes, now)?;
remove_file(&span)?;
atomic_write(&marker, "", false)?;
return Ok(false);
}
drops::add(&landing, 1, own, now)?;
remove_file(&span)?;
total -= own;
}
if arrival.bytes > limit {
drops::add(&landing, 1, arrival.bytes, now)?;
private_mkdir(arrival.tree)?;
atomic_write(&marker, "", false)?;
return Ok(false);
}
let room = limit - arrival.bytes;
delete_oldest(&landing, &trees, closed, total, room, now, between)?;
Ok(true)
}
fn closed_at(turn: &Closed) -> String {
match State::read(&Queue::part(&turn.directory, turn.n, "state")) {
Ok(state) => state.closed_at,
Err(_) => turn
.modified
.map_or_else(String::new, |at| micros_z(stamp(at))),
}
}
const RESCANS: usize = 8;
fn delete_oldest(
landing: &Path,
trees: &[PathBuf],
mut conversations: Vec<Conversation>,
mut total: u64,
room: u64,
now: Stamp,
between: &mut dyn FnMut(&Path),
) -> io::Result<()> {
for _ in 0..RESCANS {
if !one_pass(landing, &conversations, &mut total, room, now, between)? {
return Ok(());
}
(total, conversations) = scan(trees)?;
}
Ok(())
}
fn one_pass(
landing: &Path,
conversations: &[Conversation],
total: &mut u64,
room: u64,
now: Stamp,
between: &mut dyn FnMut(&Path),
) -> io::Result<bool> {
let orders: Vec<Vec<usize>> = conversations
.iter()
.map(|conversation| {
let turns = &conversation.turns;
let mut order: Vec<usize> = (0..turns.len()).collect();
if turns.iter().any(|turn| turn.reason) {
let at: Vec<String> = turns.iter().map(closed_at).collect();
order.sort_by(|a, b| at[*a].cmp(&at[*b]).then(a.cmp(b)));
}
order
})
.collect();
let head = |index: usize, next: usize| {
let turn = &conversations[index].turns[orders[index][next]];
(closed_at(turn), index, next)
};
let mut heads: Vec<(String, usize, usize)> = (0..conversations.len())
.map(|index| head(index, 0))
.collect();
while *total > room {
let Some(position) = (0..heads.len()).min_by(|a, b| heads[*a].cmp(&heads[*b])) else {
break;
};
let (at, index, next) = heads[position].clone();
let conversation = &conversations[index];
let turn = &conversation.turns[orders[index][next]];
let file = Queue::part(&turn.directory, turn.n, "jsonl");
let Some(line) = line_of(&file)? else {
return Ok(true);
};
between(&file);
let Some(lock) = Queue::new(&conversation.tree).try_lock(&conversation.id)? else {
heads.swap_remove(position);
continue;
};
let same = match stat(&file)? {
Some(metadata) if line_of(&file)? == Some(line) && closed_at(turn) == at => {
Some(metadata.len())
}
_ => None,
};
let Some(bytes) = same else {
tidy(lock)?;
return Ok(true);
};
drops::add(landing, 1, bytes, now)?;
for part in ["jsonl", "state", "reason"] {
remove_file(&Queue::part(&turn.directory, turn.n, part))?;
}
*total = total.saturating_sub(bytes);
tidy(lock)?;
match orders[index].get(next + 1) {
Some(_) => heads[position] = head(index, next + 1),
None => {
heads.swap_remove(position);
}
}
}
Ok(false)
}
fn line_of(file: &Path) -> io::Result<Option<Option<String>>> {
match opening(file) {
Ok(line) => Ok(Some(line)),
Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(None),
Err(error) => Err(error),
}
}