use std::cell::OnceCell;
use std::collections::{HashMap, HashSet};
use std::path::PathBuf;
use std::time::SystemTime;
use kuizer::caches::KnownCache;
use kuizer::catalog::Group;
use kuizer::detect::{Category, Safety};
use kuizer::history::{self, History, TrashSnapshot};
use kuizer::scan::Candidate;
use crate::model::{Bucket, Report, Source, TrashState};
pub type Key = (Source, u64);
const PROJECTS: usize = 8;
fn slot(source: Source) -> usize {
match source {
Source::Artifact => 0,
Source::Cache => 1,
Source::Toolchain => 2,
Source::Docker => 3,
Source::Trash => 4,
Source::Big => 5,
Source::System => 6,
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Tally {
pub count: usize,
pub bytes: u64,
}
impl Tally {
fn add(&mut self, bytes: u64) {
self.count += 1;
self.bytes += bytes;
}
fn sub(&mut self, bytes: u64) {
self.count -= 1;
self.bytes -= bytes;
}
fn plus(self, other: Self) -> Self {
Self {
count: self.count + other.count,
bytes: self.bytes + other.bytes,
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct Totals {
pub all: Tally,
pub safe: Tally,
pub review: Tally,
}
impl Totals {
fn add(&mut self, bytes: u64, safety: Safety) {
self.all.add(bytes);
match safety {
Safety::Safe => self.safe.add(bytes),
Safety::Review => self.review.add(bytes),
}
}
fn sub(&mut self, bytes: u64, safety: Safety) {
self.all.sub(bytes);
match safety {
Safety::Safe => self.safe.sub(bytes),
Safety::Review => self.review.sub(bytes),
}
}
fn of<'a>(candidates: impl Iterator<Item = &'a Candidate>) -> Self {
let mut totals = Self::default();
for candidate in candidates {
totals.add(candidate.usage.allocated, candidate.rule.safety);
}
totals
}
fn plus(self, other: Self) -> Self {
Self {
all: self.all.plus(other.all),
safe: self.safe.plus(other.safe),
review: self.review.plus(other.review),
}
}
}
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct SelectionStats {
sources: [Totals; Source::ALL.len()],
}
impl SelectionStats {
#[cfg(test)]
pub fn of<'a>(items: impl Iterator<Item = (Source, &'a Candidate)>) -> Self {
let mut stats = Self::default();
for (source, candidate) in items {
stats.sources[slot(source)].add(candidate.usage.allocated, candidate.rule.safety);
}
stats
}
pub fn source(&self, source: Source) -> Totals {
self.sources[slot(source)]
}
pub fn total(&self) -> Totals {
self.sources
.iter()
.fold(Totals::default(), |sum, totals| sum.plus(*totals))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct Weight {
bytes: u64,
safety: Safety,
}
#[derive(Debug, Default)]
pub struct Selection {
keys: HashMap<Key, Weight>,
stats: SelectionStats,
generation: u64,
}
impl Selection {
pub fn pending(keys: impl IntoIterator<Item = Key>) -> Self {
let unweighed = Weight {
bytes: 0,
safety: Safety::Safe,
};
Self {
keys: keys.into_iter().map(|key| (key, unweighed)).collect(),
stats: SelectionStats::default(),
generation: 0,
}
}
pub fn stats(&self) -> SelectionStats {
self.stats
}
pub fn generation(&self) -> u64 {
self.generation
}
pub fn contains(&self, key: &Key) -> bool {
self.keys.contains_key(key)
}
#[cfg(test)]
pub fn len(&self) -> usize {
self.keys.len()
}
pub fn is_empty(&self) -> bool {
self.keys.is_empty()
}
pub fn keys(&self) -> impl Iterator<Item = &Key> {
self.keys.keys()
}
pub fn insert(&mut self, key: Key, candidate: &Candidate) -> bool {
if self.keys.contains_key(&key) {
return false;
}
let weight = Weight {
bytes: candidate.usage.allocated,
safety: candidate.rule.safety,
};
self.stats.sources[slot(key.0)].add(weight.bytes, weight.safety);
self.keys.insert(key, weight);
self.generation += 1;
true
}
pub fn remove(&mut self, key: &Key) -> bool {
let Some(weight) = self.keys.remove(key) else {
return false;
};
self.stats.sources[slot(key.0)].sub(weight.bytes, weight.safety);
self.generation += 1;
true
}
pub fn clear(&mut self) {
self.keys.clear();
self.stats = SelectionStats::default();
self.generation += 1;
}
pub fn reset<'a>(
&mut self,
keys: impl IntoIterator<Item = Key>,
find: impl Fn(Key) -> Option<&'a Candidate>,
) {
self.clear();
for key in keys {
if let Some(candidate) = find(key) {
self.insert(key, candidate);
}
}
}
pub fn reweigh<'a>(&mut self, find: impl Fn(Key) -> Option<&'a Candidate>) {
let keys: Vec<Key> = self.keys.keys().copied().collect();
self.reset(keys, find);
}
}
impl PartialEq<HashSet<Key>> for Selection {
fn eq(&self, other: &HashSet<Key>) -> bool {
self.keys.len() == other.len() && other.iter().all(|key| self.keys.contains_key(key))
}
}
#[derive(Debug, Default)]
pub struct Index(OnceCell<HashMap<Key, usize>>);
impl Index {
fn map(&self, report: &Report) -> &HashMap<Key, usize> {
self.0.get_or_init(|| {
Source::ALL
.into_iter()
.flat_map(|source| {
report
.section(source)
.enumerate()
.map(move |(position, candidate)| ((source, candidate.id), position))
})
.collect()
})
}
pub fn find<'a>(&self, report: &'a Report, key: Key) -> Option<&'a Candidate> {
self.locate(report, key).map(|(_, candidate)| candidate)
}
pub fn locate<'a>(&self, report: &'a Report, key: Key) -> Option<(usize, &'a Candidate)> {
if let Some(&position) = self.map(report).get(&key)
&& let Some(candidate) = at(report, key.0, position).filter(|c| c.id == key.1)
{
return Some((position, candidate));
}
(0..count(report, key.0)).find_map(|position| {
at(report, key.0, position)
.filter(|candidate| candidate.id == key.1)
.map(|candidate| (position, candidate))
})
}
}
fn count(report: &Report, source: Source) -> usize {
match source {
Source::Artifact => report.candidates.len(),
Source::Cache => report.caches.len(),
Source::Toolchain => report.toolchains.len(),
Source::Docker => report.docker.len(),
Source::Trash => report.trash.len(),
Source::Big => report.big.len(),
Source::System => report.system.len(),
}
}
pub fn developer(cache: &KnownCache) -> bool {
cache.group == Group::Developer
}
fn by_category(candidates: &[Candidate]) -> Vec<(Category, u64)> {
let mut bytes: Vec<(Category, u64)> = Category::ALL.into_iter().map(|key| (key, 0)).collect();
for candidate in candidates {
if let Some(slot) = bytes
.iter_mut()
.find(|(key, _)| *key == candidate.rule.category)
{
slot.1 += candidate.usage.allocated;
}
}
bytes.sort_by_key(|(_, bytes)| std::cmp::Reverse(*bytes));
bytes
}
fn at(report: &Report, source: Source, position: usize) -> Option<&Candidate> {
match source {
Source::Artifact => report.candidates.get(position),
Source::Cache => report.caches.get(position).map(|(_, candidate)| candidate),
Source::Toolchain => report
.toolchains
.get(position)
.map(|(_, candidate)| candidate),
Source::Docker => report.docker.get(position).map(|(_, candidate)| candidate),
Source::Trash => report.trash.get(position).map(|(_, candidate)| candidate),
Source::Big => report.big.get(position),
Source::System => report.system.get(position).map(|(_, candidate)| candidate),
}
}
#[derive(Debug, Default)]
pub struct HistoryStats {
pub trash: Vec<TrashState>,
pub freed: u64,
pub in_trash: u64,
}
impl HistoryStats {
pub fn of(history: &History, trash: &TrashSnapshot) -> Self {
Self {
trash: trash.states(history),
freed: history::freed_bytes(history, trash),
in_trash: trash.in_trash(history).bytes,
}
}
}
pub struct Charts {
pub categories: Vec<Bucket<Category>>,
pub projects: Vec<Bucket<PathBuf>>,
pub ages: Vec<kuizer::stats::Bucket>,
pub sizes: Vec<kuizer::stats::Bucket>,
pub ecosystems: Vec<kuizer::stats::Bucket>,
pub removed: Option<Vec<kuizer::stats::Bucket>>,
pub wins: (Vec<Key>, u64),
}
const WIN_SOURCES: [Source; 4] = [
Source::Trash,
Source::Cache,
Source::System,
Source::Artifact,
];
pub fn biggest_wins(report: &Report, cap: usize) -> (Vec<Key>, u64) {
let mut safe: Vec<(Source, &Candidate)> = WIN_SOURCES
.into_iter()
.flat_map(|source| {
report
.section(source)
.filter(|candidate| {
candidate.rule.safety == Safety::Safe && candidate.usage.allocated > 0
})
.map(move |candidate| (source, candidate))
})
.collect();
let largest = |a: &(Source, &Candidate), b: &(Source, &Candidate)| {
b.1.usage
.allocated
.cmp(&a.1.usage.allocated)
.then_with(|| a.1.path.cmp(&b.1.path))
};
if safe.len() > cap && cap > 0 {
safe.select_nth_unstable_by(cap - 1, largest);
}
safe.truncate(cap);
safe.sort_unstable_by(largest);
let bytes = safe
.iter()
.map(|(_, candidate)| candidate.usage.allocated)
.sum();
(
safe.into_iter()
.map(|(source, candidate)| (source, candidate.id))
.collect(),
bytes,
)
}
#[derive(Default)]
pub struct ReportStats {
pub artifacts: Totals,
pub caches: Totals,
pub app_caches: Totals,
pub toolchains: Totals,
pub docker: Totals,
pub trash: Totals,
pub system: Totals,
pub big: Totals,
pub categories: Vec<(Category, u64)>,
charts: OnceCell<Charts>,
}
impl ReportStats {
pub fn new(report: &Report) -> Self {
Self {
artifacts: Totals::of(report.section(Source::Artifact)),
caches: Totals::of(
report
.caches
.iter()
.filter(|(cache, _)| developer(cache))
.map(|(_, candidate)| candidate),
),
app_caches: Totals::of(
report
.caches
.iter()
.filter(|(cache, _)| !developer(cache))
.map(|(_, candidate)| candidate),
),
toolchains: Totals::of(report.section(Source::Toolchain)),
docker: Totals::of(report.section(Source::Docker)),
trash: Totals::of(report.section(Source::Trash)),
system: Totals::of(report.system.iter().map(|(_, candidate)| candidate)),
big: Totals::of(report.section(Source::Big)),
categories: by_category(&report.candidates),
charts: OnceCell::new(),
}
}
pub fn space(&self) -> u64 {
self.artifacts.all.bytes
+ self.caches.all.bytes
+ self.app_caches.all.bytes
+ self.toolchains.all.bytes
+ self.docker.all.bytes
+ self.trash.all.bytes
+ self.system.all.bytes
+ self.big.all.bytes
}
pub fn charts(&self, report: &Report) -> &Charts {
self.charts.get_or_init(|| {
let mut projects = report.by_project();
projects.truncate(PROJECTS);
Charts {
categories: report.by_category(),
projects,
ages: kuizer::stats::by_age(&report.candidates, SystemTime::now()),
sizes: kuizer::stats::by_size(&report.candidates),
ecosystems: kuizer::stats::by_ecosystem(&report.candidates),
wins: biggest_wins(report, kuizer::stats::WINS),
removed: report.history.as_ref().ok().map(|view| {
kuizer::stats::removed_by_month(&view.history, &kuizer::history::now(), 12)
}),
}
})
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use kuizer::detect::{Kind, RuleInfo};
use kuizer::scan::Usage;
use super::*;
fn candidate(id: u64, bytes: u64, safety: Safety) -> Candidate {
Candidate {
id,
path: PathBuf::from(format!("/p/{id}")),
kind: Kind::Dir,
rule: Arc::new(RuleInfo {
name: "x".to_owned(),
category: Category::ALL[0],
safety,
ecosystem: "x".to_owned(),
}),
project: None,
usage: Usage {
allocated: bytes,
apparent: bytes,
entries: 1,
partial: false,
},
newest: None,
identity: None,
project_last_active: None,
}
}
#[test]
fn running_totals_match_a_recount() {
let sources = [
Source::Artifact,
Source::Cache,
Source::Toolchain,
Source::Docker,
];
let items: Vec<(Source, Candidate)> = (0..64)
.map(|id| {
let safety = if id % 3 == 0 {
Safety::Review
} else {
Safety::Safe
};
(sources[id as usize % 4], candidate(id, id * 97 + 1, safety))
})
.collect();
let mut selection = Selection::default();
let mut seed: u64 = 0x2545_f491_4f6c_dd1d;
for round in 0..2000 {
seed ^= seed << 13;
seed ^= seed >> 7;
seed ^= seed << 17;
let (source, candidate) = &items[(seed % items.len() as u64) as usize];
let key = (*source, candidate.id);
match seed % 7 {
0..=2 => {
selection.insert(key, candidate);
}
3..=5 => {
selection.remove(&key);
}
_ if round % 50 == 0 => selection.clear(),
_ => selection.reweigh(|key| {
items
.iter()
.find(|(source, candidate)| (*source, candidate.id) == key)
.filter(|_| key.1 % 5 != 0)
.map(|(_, candidate)| candidate)
}),
}
let recount = SelectionStats::of(
items
.iter()
.filter(|(source, candidate)| selection.contains(&(*source, candidate.id)))
.map(|(source, candidate)| (*source, candidate)),
);
assert_eq!(selection.stats(), recount, "round {round}");
}
}
}