use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use super::aside::{label, said, turns};
use super::destination::{self, Record, key};
use super::drops::{self, Drops};
use super::gate::host;
use super::keep;
use super::serving::{profiled, serving};
use super::slots::directory;
use super::state::{ACTOR_CHANGED, Destination, MISMATCH, POLICY_CHANGED, REFUSED, UNREADABLE};
use crate::remote::selection::Selection;
const REASONS: [&str; 5] = [POLICY_CHANGED, UNREADABLE, REFUSED, MISMATCH, ACTOR_CHANGED];
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Count {
pub turns: u64,
pub bytes: u64,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Turn {
pub name: String,
pub bytes: u64,
pub reason: Option<&'static str>,
}
#[derive(Debug, Default)]
pub struct Place {
pub key: String,
pub host: String,
pub destination: Option<Destination>,
pub record: Option<Record>,
pub served: Option<bool>,
pub current: bool,
pub pending: Vec<Turn>,
pub held: Vec<Turn>,
}
impl Place {
pub fn count(turns: &[Turn]) -> Count {
Count {
turns: turns.len() as u64,
bytes: turns.iter().map(|turn| turn.bytes).sum(),
}
}
pub fn is_empty(&self) -> bool {
self.pending.is_empty() && self.held.is_empty()
}
}
pub struct Snapshot {
pub limit: Option<u64>,
pub places: Vec<Place>,
pub loose: Place,
pub drops: Option<Drops>,
}
impl Snapshot {
pub fn is_empty(&self) -> bool {
self.places.is_empty() && self.loose.is_empty() && self.drops.is_none()
}
pub fn names(&self, held: bool) -> BTreeSet<&str> {
let places = self.places.iter().chain([&self.loose]);
let turns = places.flat_map(|place| if held { &place.held } else { &place.pending });
turns.map(|turn| turn.name.as_str()).collect()
}
}
fn records(landing: &Path) -> Vec<(String, Record)> {
let keys = super::keys::keys(landing).unwrap_or_default();
let read = |key: String| destination::read(landing, &key).map(|record| (key, record));
keys.into_iter().filter_map(read).collect()
}
fn reason(directory: &Path, n: u64) -> &'static str {
let said = said(directory, n).map(|said| said.reason);
REASONS
.into_iter()
.find(|known| said.as_deref() == Some(*known))
.unwrap_or("unknown")
}
fn named(destination: &Destination, home: &Path) -> String {
if let Destination::Profile { name, project, .. } = destination
&& let Some((resolved, _)) = profiled(name, project, home)
{
return host(&Selection::Profile(Box::new(resolved)));
}
label(destination)
}
pub fn take(
home: &Path,
trees: &[PathBuf],
url: Option<&str>,
current: Option<(Destination, String)>,
) -> Snapshot {
let landing = directory(home);
let mut places: BTreeMap<String, Place> = BTreeMap::new();
for (key, record) in records(&landing) {
let host = record.host.clone();
let record = Some(record);
places.insert(
key.clone(),
Place {
key,
host,
record,
..Place::default()
},
);
}
let mut loose = Place::default();
let mut states = BTreeMap::new();
for tree in trees {
for queue in ["pending", "held"] {
for (entry, state) in turns(tree, queue).unwrap_or_default() {
let closed = entry.closed_at.as_deref().unwrap_or("-");
let directory = tree.join(queue).join(&entry.id);
let turn = Turn {
name: format!("{}/{}@{closed}", entry.id, entry.n),
bytes: entry.bytes,
reason: (queue == "held").then(|| reason(&directory, entry.n)),
};
let destination = state.as_ref().and_then(|s| s.destination.clone());
let place = match destination {
None => &mut loose,
Some(destination) => {
let key = key(&destination);
if queue == "pending"
&& let Some(state) = state
{
states.entry(key.clone()).or_insert(state);
}
let place = places.entry(key.clone()).or_insert_with(|| Place {
key,
..Place::default()
});
place.destination.get_or_insert(destination);
place
}
};
match queue {
"pending" => place.pending.push(turn),
_ => place.held.push(turn),
}
}
}
}
if let Some((destination, host)) = current {
let key = key(&destination);
let place = places.entry(key.clone()).or_insert_with(|| Place {
key,
host,
..Place::default()
});
place.destination.get_or_insert(destination);
place.current = true;
}
for place in places.values_mut() {
let found = match (&place.destination, states.get(&place.key)) {
(Some(destination), Some(state)) => Some(serving(destination, state, home, url)),
_ => None,
};
place.served = found.as_ref().map(Option::is_some);
if place.host.is_empty() {
place.host = match (found.flatten(), &place.destination) {
(Some(serving), _) => host(serving.selection()),
(None, Some(destination)) => named(destination, home),
(None, None) => place.key.clone(),
};
}
}
let mut places: Vec<Place> = places.into_values().collect();
places.sort_by(|a, b| (&a.host, &a.key).cmp(&(&b.host, &b.key)));
Snapshot {
limit: keep::limit(home).ok(),
places,
loose,
drops: drops::read(&landing),
}
}