use super::read_document;
use super::write::{Halt, PartialDelete, RecursiveDelete, RecursiveOutcome};
use crate::errors::{DeleteRefused, FsqError, FsqResult};
use crate::import::WRITES_PER_BATCH;
use crate::walk::{Walk, COLLECTION_ID_CALLS_IN_FLIGHT};
use firestore::gcloud_sdk::google::firestore::v1::precondition::ConditionType;
use firestore::gcloud_sdk::google::firestore::v1::write::Operation;
use firestore::gcloud_sdk::google::firestore::v1::{Precondition, Write};
use firestore::gcloud_sdk::tonic::Code;
use firestore::{FirestoreCollectionId, FirestoreDb, FirestoreSimpleBatchWriter};
use futures::stream::BoxStream;
use futures::{StreamExt, TryStreamExt};
use std::sync::atomic::{AtomicBool, Ordering};
impl RecursiveDelete {
pub async fn run(
self,
db: &FirestoreDb,
stop: &AtomicBool,
progress: impl FnMut(usize) + Send,
) -> RecursiveOutcome {
let writer = match db.create_simple_batch_writer().await {
Ok(writer) => writer,
Err(error) => {
return RecursiveOutcome::Partial(PartialDelete {
deleted: 0,
halt: Halt::Failed(error.into()),
})
}
};
let mut deletion = Deletion {
db,
writer,
stop,
progress,
queued: Vec::new(),
deleted: 0,
};
match deletion.delete(self).await {
Ok(()) => RecursiveOutcome::Deleted,
Err(halt) => RecursiveOutcome::Partial(PartialDelete {
deleted: deletion.deleted,
halt,
}),
}
}
}
struct Deletion<'d, P> {
db: &'d FirestoreDb,
writer: FirestoreSimpleBatchWriter,
stop: &'d AtomicBool,
progress: P,
queued: Vec<String>,
deleted: usize,
}
impl<'d, P: FnMut(usize)> Deletion<'d, P> {
async fn delete(&mut self, top: RecursiveDelete) -> Result<(), Halt> {
let stored = read_document(self.db, &top.document).await?;
if stored.and_then(|stored| stored.update_time) != Some(top.update_time) {
return Err(Halt::Stale);
}
self.delete_under(&top.document).await?;
self.send_queued().await?;
self.delete_top(top).await
}
async fn delete_top(&mut self, top: RecursiveDelete) -> Result<(), Halt> {
let unchanged = Precondition {
condition_type: Some(ConditionType::UpdateTime(top.update_time)),
};
let deleted = self.send(vec![top.document.clone()], Some(unchanged)).await;
if matches!(deleted, Err(Halt::Stale | Halt::Failed(_)))
&& matches!(read_document(self.db, &top.document).await, Ok(None))
{
return Ok(());
}
deleted
}
async fn delete_under(&mut self, top: &str) -> Result<(), Halt> {
let db = self.db;
let collection_ids = Walk::new(db).collection_ids(Some(top)).await?;
let mut parents = vec![Parent::top(top.to_string(), collection_ids)];
while let Some(parent) = parents.last_mut() {
self.check_stop()?;
let Some(child) = parent.next_child(db).await? else {
if let Some(walked) = parents.pop().filter(|walked| walked.deletes) {
self.queue(walked.name).await?;
}
continue;
};
if !child.collection_ids.is_empty() {
parents.push(Parent::from(child));
} else if child.exists {
self.queue(child.name).await?;
}
}
Ok(())
}
async fn queue(&mut self, document: String) -> Result<(), Halt> {
self.queued.push(document);
if self.queued.len() < WRITES_PER_BATCH {
return Ok(());
}
self.send_queued().await
}
async fn send_queued(&mut self) -> Result<(), Halt> {
if self.queued.is_empty() {
return Ok(());
}
let documents = std::mem::take(&mut self.queued);
self.send(documents, None).await
}
async fn send(
&mut self,
documents: Vec<String>,
precondition: Option<Precondition>,
) -> Result<(), Halt> {
self.check_stop()?;
let mut batch = self.writer.new_batch();
batch.writes = documents
.iter()
.map(|document| Write {
operation: Some(Operation::Delete(document.clone())),
current_document: precondition,
..Write::default()
})
.collect();
let statuses = batch.write().await.map_err(FsqError::from)?.statuses;
let mut halt = None;
for (document, status) in documents.into_iter().zip(statuses) {
match Code::from(status.code) {
Code::Ok => self.deleted += 1,
Code::FailedPrecondition if precondition.is_some() => {
halt.get_or_insert(Halt::Stale);
}
code => {
halt.get_or_insert(Halt::Failed(FsqError::DeleteRefused(DeleteRefused {
document,
code,
message: status.message,
})));
}
}
}
(self.progress)(self.deleted);
halt.map_or(Ok(()), Err)
}
fn check_stop(&self) -> Result<(), Halt> {
if self.stop.load(Ordering::Relaxed) {
return Err(Halt::Stopped);
}
Ok(())
}
}
struct Parent<'d> {
name: String,
deletes: bool,
collection_ids: std::vec::IntoIter<FirestoreCollectionId>,
children: Option<BoxStream<'d, FsqResult<Child>>>,
}
struct Child {
name: String,
exists: bool,
collection_ids: Vec<FirestoreCollectionId>,
}
impl From<Child> for Parent<'_> {
fn from(child: Child) -> Self {
Self {
name: child.name,
deletes: child.exists,
collection_ids: child.collection_ids.into_iter(),
children: None,
}
}
}
impl<'d> Parent<'d> {
fn top(name: String, collection_ids: Vec<FirestoreCollectionId>) -> Self {
Self {
name,
deletes: false,
collection_ids: collection_ids.into_iter(),
children: None,
}
}
async fn next_child(&mut self, db: &'d FirestoreDb) -> FsqResult<Option<Child>> {
loop {
if let Some(children) = &mut self.children {
if let Some(child) = children.try_next().await? {
return Ok(Some(child));
}
}
let Some(collection_id) = self.collection_ids.next() else {
return Ok(None);
};
let documents = db
.fluent()
.list()
.fields(std::iter::empty::<&str>())
.from(&collection_id)
.parent(&self.name)
.show_missing()
.stream_all_with_errors()
.await?;
let children = documents
.map(move |document| async move {
let document = document?;
let collection_ids = Walk::new(db).collection_ids(Some(&document.name)).await?;
Ok(Child {
exists: document.create_time.is_some(),
name: document.name,
collection_ids,
})
})
.buffered(COLLECTION_ID_CALLS_IN_FLIGHT);
self.children = Some(children.boxed());
}
}
}
#[cfg(all(test, feature = "ci-live"))]
mod tests {
use super::*;
use crate::browse::fixtures::live_collection;
use crate::browse::state::RequestId;
use crate::render::fixtures::string;
use firestore::FirestoreDocument;
use std::collections::HashMap;
async fn write_all(db: &FirestoreDb, paths: &[String], revision: &str) {
let writer = db
.create_simple_batch_writer()
.await
.expect("a batch writer");
for chunk in paths.chunks(WRITES_PER_BATCH) {
let mut batch = writer.new_batch();
batch.writes = chunk
.iter()
.map(|path| Write {
operation: Some(Operation::Update(FirestoreDocument {
name: format!("{}/{path}", db.get_documents_path()),
fields: HashMap::from([
("path".to_string(), string(path)),
("revision".to_string(), string(revision)),
]),
create_time: None,
update_time: None,
})),
..Write::default()
})
.collect();
batch.write().await.expect("the documents are written");
}
}
async fn delete_all(db: &FirestoreDb, paths: &[String]) {
let writer = db
.create_simple_batch_writer()
.await
.expect("a batch writer");
for chunk in paths.chunks(WRITES_PER_BATCH) {
let mut batch = writer.new_batch();
batch.writes = chunk
.iter()
.map(|path| Write {
operation: Some(Operation::Delete(format!(
"{}/{path}",
db.get_documents_path()
))),
..Write::default()
})
.collect();
batch.write().await.expect("the documents are deleted");
}
}
async fn existing(db: &FirestoreDb, paths: &[String]) -> Vec<bool> {
futures::stream::iter(paths)
.map(|path| async move {
let name = format!("{}/{path}", db.get_documents_path());
read_document(db, &name).await.expect("a read").is_some()
})
.buffered(16)
.collect()
.await
}
async fn delete_of(db: &FirestoreDb, path: &str) -> RecursiveDelete {
let name = format!("{}/{path}", db.get_documents_path());
let read = read_document(db, &name)
.await
.expect("a read")
.expect("the document");
RecursiveDelete {
request: RequestId::default(),
document: name,
update_time: read.update_time.expect("an update time"),
}
}
fn orders_under(top: &str) -> Vec<String> {
let mut paths = vec![top.to_string(), format!("{top}/drafts/unwritten/notes/n1")];
for order in 0..25 {
paths.push(format!("{top}/orders/o{order:02}"));
for line in 0..24 {
paths.push(format!("{top}/orders/o{order:02}/lines/l{line:02}"));
}
}
paths
}
#[tokio::test]
async fn a_recursive_delete_leaves_nothing_under_the_document_and_nothing_beside_it_goes() {
let (db, root) = live_collection("recursive-delete").await;
let top = format!("{root}/top");
let under = orders_under(&top);
let beside = [
format!("{root}/beside"),
format!("{root}/beside/orders/kept"),
];
let paths = [under.as_slice(), &beside].concat();
write_all(&db, &paths, "first").await;
let mut counts = Vec::new();
let outcome = delete_of(&db, &top)
.await
.run(&db, &AtomicBool::new(false), |deleted| counts.push(deleted))
.await;
let exist = existing(&db, &paths).await;
delete_all(&db, &paths).await;
assert!(matches!(outcome, RecursiveOutcome::Deleted), "{outcome:?}");
assert_eq!(counts, [500, 626, 627]);
assert_eq!(
exist,
[vec![false; under.len()], vec![true; beside.len()]].concat()
);
}
#[tokio::test]
async fn a_recursive_delete_stopped_after_a_request_leaves_no_document_under_a_deleted_one() {
let (db, root) = live_collection("recursive-stop").await;
let top = format!("{root}/top");
let paths = orders_under(&top);
write_all(&db, &paths, "first").await;
let stop = AtomicBool::new(false);
let outcome = delete_of(&db, &top)
.await
.run(&db, &stop, |_| stop.store(true, Ordering::Relaxed))
.await;
let exist = existing(&db, &paths).await;
delete_all(&db, &paths).await;
assert!(
matches!(
outcome,
RecursiveOutcome::Partial(PartialDelete {
deleted: 500,
halt: Halt::Stopped
})
),
"{outcome:?}"
);
let gone: Vec<&String> = paths
.iter()
.zip(&exist)
.filter_map(|(path, exists)| (!exists).then_some(path))
.collect();
let stranded = paths.iter().zip(&exist).find(|(path, exists)| {
**exists
&& gone
.iter()
.any(|deleted| path.starts_with(&format!("{deleted}/")))
});
assert_eq!(gone.len(), 500);
assert_eq!(stranded, None);
assert!(exist[0], "the document itself stays");
}
#[tokio::test]
async fn a_recursive_delete_of_a_document_changed_since_it_was_read_deletes_nothing() {
let (db, root) = live_collection("recursive-stale").await;
let top = format!("{root}/top");
let paths = [top.clone(), format!("{top}/orders/o1")];
write_all(&db, &paths, "first").await;
let delete = delete_of(&db, &top).await;
write_all(&db, &paths[..1], "second").await;
let outcome = delete.run(&db, &AtomicBool::new(false), |_| {}).await;
let exist = existing(&db, &paths).await;
delete_all(&db, &paths).await;
assert!(
matches!(
outcome,
RecursiveOutcome::Partial(PartialDelete {
deleted: 0,
halt: Halt::Stale
})
),
"{outcome:?}"
);
assert_eq!(exist, [true, true]);
}
async fn unstopped_deletion(db: &FirestoreDb) -> Deletion<'_, fn(usize)> {
static NEVER_STOPPED: AtomicBool = AtomicBool::new(false);
Deletion {
db,
writer: db
.create_simple_batch_writer()
.await
.expect("a batch writer"),
stop: &NEVER_STOPPED,
progress: |_| {},
queued: Vec::new(),
deleted: 0,
}
}
#[tokio::test]
async fn the_delete_of_the_document_itself_that_finds_it_changed_is_stale_and_keeps_it() {
let (db, root) = live_collection("recursive-stale").await;
let paths = [format!("{root}/top")];
write_all(&db, &paths, "first").await;
let delete = delete_of(&db, &paths[0]).await;
write_all(&db, &paths, "second").await;
let mut deletion = unstopped_deletion(&db).await;
let deleted = deletion.delete_top(delete).await;
let exist = existing(&db, &paths).await;
delete_all(&db, &paths).await;
assert!(matches!(deleted, Err(Halt::Stale)), "{deleted:?}");
assert_eq!(exist, [true]);
}
#[tokio::test]
async fn the_delete_of_the_document_itself_that_finds_it_gone_has_deleted_it() {
let (db, root) = live_collection("recursive-gone").await;
let paths = [format!("{root}/top")];
write_all(&db, &paths, "first").await;
let delete = delete_of(&db, &paths[0]).await;
delete_all(&db, &paths).await;
let mut deletion = unstopped_deletion(&db).await;
let deleted = deletion.delete_top(delete).await;
assert!(matches!(deleted, Ok(())), "{deleted:?}");
}
}