use crate::describe::{CollectionPath, SampleSize};
use crate::errors::{FsqError, FsqResult, InvalidTreeDepth};
use crate::render::{Cell, Grid, Sample};
use crate::walk::{Walk, COLLECTION_ID_CALLS_IN_FLIGHT};
use firestore::{FirestoreCollectionId, FirestoreDb};
use futures::{StreamExt, TryStreamExt};
use std::collections::BTreeMap;
use std::fmt::{Display, Formatter};
use std::num::NonZeroU32;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TreeDepth(NonZeroU32);
impl TreeDepth {
const DEFAULT: NonZeroU32 = NonZeroU32::new(2).unwrap();
pub fn levels(self) -> u32 {
self.0.get()
}
}
impl Default for TreeDepth {
fn default() -> Self {
Self(Self::DEFAULT)
}
}
impl Display for TreeDepth {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl FromStr for TreeDepth {
type Err = FsqError;
fn from_str(value: &str) -> FsqResult<Self> {
value.parse().map(Self).map_err(|source| {
FsqError::InvalidTreeDepth(InvalidTreeDepth {
value: value.to_string(),
source,
})
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::Args)]
pub struct CollectionTreeTarget {
#[arg(
long,
requires = "recursive",
default_value_t = TreeDepth::default(),
help = "How many levels of collections to list; 1 is the root collections alone"
)]
pub depth: TreeDepth,
#[arg(
long,
requires = "recursive",
default_value_t = SampleSize::COLLECTION_TREE_DEFAULT,
help = "How many documents of each collection to read to find its subcollections"
)]
pub sample: SampleSize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct TreeCollection {
path: String,
id: FirestoreCollectionId,
depth: usize,
seen_under: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CollectionTree {
target: CollectionTreeTarget,
collections: Vec<TreeCollection>,
}
struct Level {
path: String,
id: FirestoreCollectionId,
instances: Vec<CollectionPath>,
}
const LEVELS_IN_FLIGHT: usize = 8;
impl Level {
async fn sample(
self,
walk: &Walk<'_>,
documents_path: &str,
limit: usize,
depth: usize,
) -> FsqResult<(Vec<TreeCollection>, Vec<Level>)> {
let documents = walk.first_document_names(&self.instances, limit).await?;
let listings: Vec<_> = futures::stream::iter(&documents)
.map(|document| walk.collection_ids(Some(document)))
.buffered(COLLECTION_ID_CALLS_IN_FLIGHT)
.collect()
.await;
let mut found: BTreeMap<FirestoreCollectionId, Vec<CollectionPath>> = BTreeMap::new();
for (document, listing) in documents.iter().zip(listings) {
let relative = FirestoreDb::relative_document_name(documents_path, document);
for id in listing? {
let path = CollectionPath::in_document(relative, id.clone());
found.entry(id).or_default().push(path);
}
}
let mut collections = Vec::new();
let mut next_levels = Vec::new();
for (id, instances) in found {
let path = format!("{}/*/{id}", self.path);
collections.push(TreeCollection {
path: path.clone(),
id: id.clone(),
depth,
seen_under: Some(format!(
"{} of {} sampled {}",
instances.len(),
documents.len(),
self.id
)),
});
next_levels.push(Level {
path,
id,
instances,
});
}
Ok((collections, next_levels))
}
}
impl CollectionTree {
pub async fn walk(db: &FirestoreDb, target: CollectionTreeTarget) -> FsqResult<Self> {
let walk = Walk::new(db);
let documents_path = db.get_documents_path();
let limit = target.sample.documents() as usize;
let mut collections = Vec::new();
let mut levels = Vec::new();
for id in walk.collection_ids(None).await? {
let path = id.to_string();
collections.push(TreeCollection {
path: path.clone(),
id: id.clone(),
depth: 1,
seen_under: None,
});
levels.push(Level {
path,
instances: vec![CollectionPath::from(id.clone())],
id,
});
}
for depth in 2..=target.depth.levels() as usize {
let sampled: Vec<_> = futures::stream::iter(levels)
.map(|level| level.sample(&walk, documents_path, limit, depth))
.buffered(LEVELS_IN_FLIGHT)
.try_collect()
.await?;
levels = Vec::new();
for (found, opened) in sampled {
collections.extend(found);
levels.extend(opened);
}
}
Ok(Self {
target,
collections,
})
}
pub fn sample(&self) -> Option<Sample> {
(self.target.depth.levels() > 1).then(|| Sample {
documents: self.target.sample.documents() as usize,
})
}
pub fn into_grid(self) -> Grid {
let mut grid = Grid::new(["collection", "path", "depth", "seen_under"]);
for collection in self.collections {
grid.push_row(vec![
Some(Cell::Text(collection.id.to_string())),
Some(Cell::Text(collection.path)),
Some(Cell::Count(collection.depth as u64)),
collection.seen_under.map(Cell::Text),
]);
}
grid
}
}