firestore-cli 0.3.0

fsq, a command line client for Google Firestore: a SQL REPL with tables, query plans and index statements, and a scripting mode with JSON output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
//! The delete of a document with every document under it, at any depth. Each document goes after
//! every document under it, in requests of at most [`WRITES_PER_BATCH`] deletes, and the document
//! itself goes last, alone, with the update time it was read with, so that a delete stopped
//! between two requests leaves no document under one it deleted.

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 {
    /// Deletes every document under the document, then the document itself. `progress` takes
    /// the count of documents deleted after each request. Once `stop` is set, no further request
    /// goes out, and the delete ends with what it deleted.
    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,
    /// The documents the next request deletes, each after every document under it.
    queued: Vec<String>,
    deleted: usize,
}

impl<'d, P: FnMut(usize)> Deletion<'d, P> {
    async fn delete(&mut self, top: RecursiveDelete) -> Result<(), Halt> {
        // Firestore checks the update time only with the delete of the document itself, after
        // everything under it, so a read checks it before anything goes. A change between the
        // read and that delete still keeps the document.
        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
    }

    /// Deletes the document itself while it still has the update time it was read with. A delete
    /// that is not OK is taken as done when a read finds the document gone: the batch writer sends
    /// a request again after a failure it can retry, and when an earlier attempt deleted the
    /// document but its answer was lost, the next attempt finds none and fails its precondition.
    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
    }

    /// Queues the delete of every document under `top`, each after every document under it, and
    /// sends the queued deletes whenever they fill a request. A document that does not exist is
    /// walked for the documents under it, and has nothing to delete.
    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
    }

    /// Sends the deletes of `documents` in one request, each with `precondition`, and counts the
    /// documents deleted. A delete that Firestore refused ends the recursive delete once the
    /// request is counted, and so does a precondition that did not hold, as [`Halt::Stale`].
    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(())
    }
}

/// A document whose subcollections the walk is in.
struct Parent<'d> {
    /// The full resource name of the document.
    name: String,
    /// Whether the walk deletes the document once it has queued every document under it. It
    /// does not for the top document, which goes alone, nor for one that does not exist.
    deletes: bool,
    /// The subcollections the walk has not started on.
    collection_ids: std::vec::IntoIter<FirestoreCollectionId>,
    /// The documents of the subcollection being walked.
    children: Option<BoxStream<'d, FsqResult<Child>>>,
}

/// A document of a subcollection, and the IDs of the collections under it.
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,
        }
    }

    /// The next document under this one, of the subcollection being walked or of the next one,
    /// `None` once every subcollection is walked. A document that does not exist and has
    /// subcollections is one of them, without a create time. The collections under the
    /// documents are listed [`COLLECTION_ID_CALLS_IN_FLIGHT`] documents at a time.
    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);
            };
            // An empty field mask: a listing gives the name and the create time of a document
            // without its fields, and the walk needs no more.
            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;

    /// `paths`, documents of the database of `db` each holding its own path and `revision`,
    /// written in as few requests as BatchWrite takes. A write that changes nothing leaves the
    /// update time as it was, so a document changed since it was read needs another revision.
    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");
        }
    }

    /// Deletes `paths`, whether they exist or not.
    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");
        }
    }

    /// Which of `paths` exist, in their order.
    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
    }

    /// The delete of the document at `path` as it is stored now.
    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"),
        }
    }

    /// The paths of `top` with 25 orders of 24 lines each under it, and of a note under a draft
    /// that is never written, 627 documents in all.
    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]);
    }

    /// A deletion in the database of `db` that nothing stops.
    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:?}");
    }
}