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
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use super::editor::ValueEditor;
use super::external::ExternalDraft;
use super::state::RequestId;
use super::tree::{MaskPath, NodePath};
use crate::errors::{FsqError, FsqResult, NoUpdateTime};
use firestore::gcloud_sdk::google::firestore::v1::value::ValueType;
use firestore::gcloud_sdk::google::firestore::v1::{MapValue, Value};
use firestore::gcloud_sdk::prost_types::Timestamp;
use firestore::timestamp_utils::from_timestamp;
use firestore::{FirestoreDocument, FirestoreWritePrecondition};
use std::collections::HashMap;

/// What the user asked to change in one document. It holds nothing of the document as read, so
/// that the same change can be shown and written again over the document as read again.
#[derive(Debug, Clone, PartialEq)]
pub enum Change {
    /// Sets the field at `path`, or deletes it for `None`.
    Field {
        path: MaskPath,
        value: Option<Value>,
    },
    /// Gives the document these fields, or deletes it for `None` and leaves its subcollections.
    Document(Option<HashMap<String, Value>>),
    /// Creates the document `name`, a full resource name, and fails rather than replace one.
    NewDocument {
        name: String,
        fields: HashMap<String, Value>,
    },
}

impl Change {
    fn needs_document(&self) -> bool {
        !matches!(self, Self::Document(Some(_)) | Self::NewDocument { .. })
    }

    fn operation(&self) -> WriteOperation {
        match self {
            Self::Field { path, value } => WriteOperation::Update {
                fields: path.fields_with(value.clone()),
                mask: Some(path.clone()),
            },
            Self::Document(Some(fields)) | Self::NewDocument { fields, .. } => {
                WriteOperation::Update {
                    fields: fields.clone(),
                    mask: None,
                }
            }
            Self::Document(None) => WriteOperation::Delete,
        }
    }
}

/// One document being changed. It keeps the document as last read through the editor, the
/// confirmation and every read again, so that the diff shown and the precondition of the next
/// write are both of the latest read.
#[derive(Debug)]
pub struct Edit {
    /// The full resource name, `None` for a new document, which its change names.
    document: Option<String>,
    /// `None` for a new document, and once a read found that the document no longer exists.
    read: Option<FirestoreDocument>,
    step: Step,
}

// The browser holds one edit at a time, so the size of the larger step is paid once, and a box
// would only add an allocation per step.
#[allow(clippy::large_enum_variant)]
#[derive(Debug)]
pub enum Step {
    Editing(Draft),
    Confirming(Confirmation),
}

/// The editor a change comes from, which `e` at the confirmation opens again.
#[derive(Debug)]
pub enum Draft {
    Value(ValueEditor),
    External(ExternalDraft),
}

impl Draft {
    fn submit(&mut self) -> Option<Change> {
        match self {
            Self::Value(editor) => editor.submit(),
            Self::External(draft) => draft.submit(),
        }
    }
}

#[derive(Debug)]
pub struct Confirmation {
    change: Change,
    /// What `e` opens again, `None` for a change that no editor made, such as a delete.
    draft: Option<Draft>,
    stage: Stage,
}

impl Confirmation {
    pub fn change(&self) -> &Change {
        &self.change
    }

    pub fn has_draft(&self) -> bool {
        self.draft.is_some()
    }

    pub fn stage(&self) -> &Stage {
        &self.stage
    }
}

#[derive(Debug)]
pub enum Stage {
    Asking(Option<Note>),
    Writing(RequestId),
    DeletingRecursively(RecursiveProgress),
    /// A recursive delete ended before the document went, and only `n` is left.
    DeletedPartly(PartialDelete),
    /// Reads the document again, after a write whose precondition did not hold.
    Reading(RequestId),
    Failed(FsqError),
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Note {
    Changed,
    /// Ctrl-C stopped waiting for a write, which may have reached Firestore all the same.
    WriteStopped,
    /// Ctrl-C stopped waiting for the read again, so the change shows over the earlier read.
    ReadStopped,
    /// A document of the new one's name exists, and nothing was written.
    Exists,
}

/// The value a change replaces and the value it writes, of a field or of the document as a map.
#[derive(Debug, PartialEq)]
pub struct ValueChange {
    pub before: Option<Value>,
    pub after: Option<Value>,
}

impl ValueChange {
    /// A NaN double never equals itself, so a change to one always writes.
    pub fn changes_nothing(&self) -> bool {
        self.before == self.after
    }
}

impl Edit {
    pub fn editing(document: &FirestoreDocument, draft: Draft) -> Self {
        Self::new(document, Step::Editing(draft))
    }

    pub fn confirming(document: &FirestoreDocument, change: Change) -> Self {
        let confirmation = Confirmation {
            change,
            draft: None,
            stage: Stage::Asking(None),
        };
        Self::new(document, Step::Confirming(confirmation))
    }

    pub fn creating(draft: ExternalDraft) -> Self {
        Self {
            document: None,
            read: None,
            step: Step::Editing(Draft::External(draft)),
        }
    }

    fn new(document: &FirestoreDocument, step: Step) -> Self {
        Self {
            document: Some(document.name.clone()),
            read: Some(document.clone()),
            step,
        }
    }

    /// The full resource name. A new document has none until its text reads as a change.
    pub fn document(&self) -> Option<&str> {
        match self.confirmation().map(Confirmation::change) {
            Some(Change::NewDocument { name, .. }) => Some(name),
            _ => self.document.as_deref(),
        }
    }

    pub fn creates(&self) -> bool {
        matches!(
            self.confirmation().map(Confirmation::change),
            Some(Change::NewDocument { .. })
        )
    }

    pub fn exists_already(&self) -> bool {
        matches!(
            self.confirmation().map(Confirmation::stage),
            Some(Stage::Asking(Some(Note::Exists)))
        )
    }

    pub fn last_read(&self) -> Option<&FirestoreDocument> {
        self.read.as_ref()
    }

    /// Whether `stored`, the document found under the name of the new one, holds the fields its
    /// create writes, as it does once the create reached Firestore on an attempt whose answer did
    /// not arrive. Any document with the same fields counts as the create. A NaN double never
    /// matches, and nor does a timestamp finer than a microsecond, which Firestore truncates.
    pub fn created(&self, stored: &FirestoreDocument) -> bool {
        matches!(
            self.confirmation().map(Confirmation::change),
            Some(Change::NewDocument { fields, .. }) if *fields == stored.fields
        )
    }

    pub fn step(&self) -> &Step {
        &self.step
    }

    pub fn confirmation(&self) -> Option<&Confirmation> {
        match &self.step {
            Step::Confirming(confirmation) => Some(confirmation),
            Step::Editing(_) => None,
        }
    }

    pub fn value_editor(&self) -> Option<&ValueEditor> {
        match &self.step {
            Step::Editing(Draft::Value(editor)) => Some(editor),
            Step::Editing(Draft::External(_)) | Step::Confirming(_) => None,
        }
    }

    pub fn value_editor_mut(&mut self) -> Option<&mut ValueEditor> {
        match &mut self.step {
            Step::Editing(Draft::Value(editor)) => Some(editor),
            Step::Editing(Draft::External(_)) | Step::Confirming(_) => None,
        }
    }

    /// While the external editor is open on the draft, or its text did not read as a change.
    pub fn external_draft(&self) -> Option<&ExternalDraft> {
        match &self.step {
            Step::Editing(Draft::External(draft)) => Some(draft),
            Step::Editing(Draft::Value(_)) | Step::Confirming(_) => None,
        }
    }

    pub fn external_draft_mut(&mut self) -> Option<&mut ExternalDraft> {
        match &mut self.step {
            Step::Editing(Draft::External(draft)) => Some(draft),
            Step::Editing(Draft::Value(_)) | Step::Confirming(_) => None,
        }
    }

    pub fn is_waiting(&self) -> bool {
        matches!(
            self.confirmation().map(Confirmation::stage),
            Some(Stage::Writing(_) | Stage::DeletingRecursively(_) | Stage::Reading(_))
        )
    }

    pub fn waits_for(&self, request: RequestId) -> bool {
        match self.confirmation().map(Confirmation::stage) {
            Some(Stage::Writing(waited) | Stage::Reading(waited)) => *waited == request,
            Some(Stage::DeletingRecursively(progress)) => progress.request == request,
            _ => false,
        }
    }

    pub fn deletes_document(&self) -> bool {
        matches!(
            self.confirmation().map(Confirmation::change),
            Some(Change::Document(None))
        )
    }

    pub fn can_write(&self) -> bool {
        let answered = matches!(
            self.confirmation().map(Confirmation::stage),
            Some(Stage::Asking(_) | Stage::Failed(_))
        );
        answered && !self.is_gone() && !self.exists_already()
    }

    pub fn is_gone(&self) -> bool {
        self.read.is_none()
            && self
                .confirmation()
                .is_some_and(|confirmation| confirmation.change.needs_document())
    }

    /// This edit waiting for the confirmation of the change its editor gives, or still in the
    /// editor with the error of a text that does not read. `None` for a change to the value the
    /// document as last read holds.
    pub fn submitted(self) -> Option<Self> {
        let step = match self.step {
            Step::Editing(mut draft) => match draft.submit() {
                Some(change) => Step::Confirming(Confirmation {
                    change,
                    draft: Some(draft),
                    stage: Stage::Asking(None),
                }),
                None => Step::Editing(draft),
            },
            confirming @ Step::Confirming(_) => confirming,
        };
        let edit = Self { step, ..self };
        let changes_nothing = edit
            .value_change()
            .is_some_and(|values| values.changes_nothing());
        (!changes_nothing).then_some(edit)
    }

    /// This edit back in the editor its change came from, with the text it was left with. A
    /// change that no editor made, or one being written, stays as it is.
    pub fn reopened(self) -> Self {
        let step = match self.step {
            Step::Confirming(Confirmation {
                draft: Some(draft),
                stage: Stage::Asking(_) | Stage::Failed(_),
                ..
            }) => Step::Editing(draft),
            step => step,
        };
        Self { step, ..self }
    }

    pub fn value_change(&self) -> Option<ValueChange> {
        let confirmation = self.confirmation()?;
        let read = self.read.as_ref();
        Some(match &confirmation.change {
            Change::Field { path, value } => ValueChange {
                before: read.and_then(|read| NodePath::from(path).value_in(read).cloned()),
                after: value.clone(),
            },
            Change::Document(fields) => ValueChange {
                before: read.map(|read| map_value(read.fields.clone())),
                after: fields.clone().map(map_value),
            },
            Change::NewDocument { fields, .. } => ValueChange {
                before: None,
                after: Some(map_value(fields.clone())),
            },
        })
    }

    /// Starts the write of the change over the document as last read. `None` unless
    /// [`Edit::can_write`]; a document read without its update time fails the change instead,
    /// since its write would have no precondition.
    pub fn write(&mut self, request: RequestId) -> Option<DocumentWrite> {
        let precondition = self.precondition()?;
        let document = self.document()?.to_string();
        let Step::Confirming(confirmation) = &mut self.step else {
            return None;
        };
        confirmation.stage = Stage::Writing(request);
        Some(DocumentWrite {
            request,
            document,
            operation: confirmation.change.operation(),
            precondition,
        })
    }

    pub fn delete_recursively(&mut self, request: RequestId) -> Option<RecursiveDelete> {
        if !self.deletes_document() || !self.can_write() {
            return None;
        }
        let update_time = self.update_time()?;
        let document = self.document.clone()?;
        self.set_stage(Stage::DeletingRecursively(RecursiveProgress {
            request,
            deleted: 0,
            stopping: false,
        }));
        Some(RecursiveDelete {
            request,
            document,
            update_time,
        })
    }

    fn precondition(&mut self) -> Option<FirestoreWritePrecondition> {
        if !self.can_write() {
            return None;
        }
        if self.read.is_none() || self.creates() {
            return Some(FirestoreWritePrecondition::Exists(false));
        }
        match from_timestamp(self.update_time()?) {
            Ok(update_time) => Some(FirestoreWritePrecondition::UpdateTime(update_time)),
            Err(error) => {
                self.fail(error.into());
                None
            }
        }
    }

    fn update_time(&mut self) -> Option<Timestamp> {
        let read = self.read.as_ref()?;
        let Some(update_time) = read.update_time else {
            let document = read.name.clone();
            self.fail(FsqError::NoUpdateTime(NoUpdateTime { document }));
            return None;
        };
        Some(update_time)
    }

    pub fn count_deleted(&mut self, deleted: usize) {
        if let Some(Stage::DeletingRecursively(progress)) = self.stage_mut() {
            progress.deleted = deleted;
        }
    }

    /// Ends the recursive delete under way with the document still stored: `partial`, or the
    /// error of a call that ended without an answer, after the documents counted so far.
    pub fn end_partly(&mut self, partial: FsqResult<PartialDelete>) {
        let Some(Stage::DeletingRecursively(progress)) = self.stage_mut() else {
            return;
        };
        let partial = partial.unwrap_or_else(|error| PartialDelete {
            deleted: progress.deleted,
            halt: Halt::Failed(error),
        });
        self.set_stage(Stage::DeletedPartly(partial));
    }

    pub fn wait_for_read(&mut self, request: RequestId) {
        self.set_stage(Stage::Reading(request));
    }

    pub fn read_again(&mut self, read: Option<FirestoreDocument>) {
        self.read = read;
        self.set_stage(Stage::Asking(Some(Note::Changed)));
    }

    pub fn fail(&mut self, error: FsqError) {
        self.set_stage(Stage::Failed(error));
    }

    pub fn refuse_existing(&mut self) {
        self.set_stage(Stage::Asking(Some(Note::Exists)));
    }

    /// Stops waiting for the write or the read, and asks a recursive delete to stop, which it
    /// does once its request in flight answers. `false` when the edit waited for none of them.
    pub fn stop_waiting(&mut self) -> bool {
        if !self.is_waiting() {
            return false;
        }
        match self.stage_mut() {
            Some(Stage::DeletingRecursively(progress)) => progress.stopping = true,
            Some(Stage::Reading(_)) => self.set_stage(Stage::Asking(Some(Note::ReadStopped))),
            _ => self.set_stage(Stage::Asking(Some(Note::WriteStopped))),
        }
        true
    }

    /// Stops waiting for the recursive delete that Ctrl-C already asked to stop, and ends it with
    /// the documents counted so far. `false` when no recursive delete was stopping.
    pub fn abandon(&mut self) -> bool {
        let Some(Stage::DeletingRecursively(progress)) = self.stage_mut() else {
            return false;
        };
        if !progress.stopping {
            return false;
        }
        let deleted = progress.deleted;
        self.set_stage(Stage::DeletedPartly(PartialDelete {
            deleted,
            halt: Halt::Abandoned,
        }));
        true
    }

    fn stage_mut(&mut self) -> Option<&mut Stage> {
        match &mut self.step {
            Step::Confirming(confirmation) => Some(&mut confirmation.stage),
            Step::Editing(_) => None,
        }
    }

    fn set_stage(&mut self, stage: Stage) {
        if let Some(current) = self.stage_mut() {
            *current = stage;
        }
    }
}

fn map_value(fields: HashMap<String, Value>) -> Value {
    Value {
        value_type: Some(ValueType::MapValue(MapValue { fields })),
    }
}

#[derive(Debug, PartialEq)]
pub struct DocumentWrite {
    pub request: RequestId,
    /// The full resource name of the document.
    pub document: String,
    pub operation: WriteOperation,
    pub precondition: FirestoreWritePrecondition,
}

#[derive(Debug, PartialEq)]
pub enum WriteOperation {
    /// With a `mask`, writes only the field the mask names, or deletes it where `fields` lack
    /// it, and every other field stays as stored.
    Update {
        fields: HashMap<String, Value>,
        mask: Option<MaskPath>,
    },
    Delete,
}

#[derive(Debug)]
pub enum WriteOutcome {
    /// The document as stored, with its new update time and any value the server set.
    Written(FirestoreDocument),
    Deleted,
    /// The precondition did not hold, so nothing was written.
    Stale,
}

/// The delete of the document `document`, a full resource name, after every document under it,
/// at any depth, while the document still has `update_time`, the update time it was read with.
#[derive(Debug, PartialEq)]
pub struct RecursiveDelete {
    pub request: RequestId,
    pub document: String,
    pub update_time: Timestamp,
}

#[derive(Debug)]
pub struct RecursiveProgress {
    pub request: RequestId,
    pub deleted: usize,
    /// Whether Ctrl-C asked the delete to stop, which it does once its request in flight answers.
    pub stopping: bool,
}

#[derive(Debug)]
pub enum RecursiveOutcome {
    Deleted,
    Partial(PartialDelete),
}

/// A recursive delete that ended before the document went, or that was abandoned before it
/// answered: the document stays, unless an abandoned request deletes it, and so does every
/// document under it that the delete did not reach.
#[derive(Debug)]
pub struct PartialDelete {
    /// The documents under the document that the delete deleted.
    pub deleted: usize,
    pub halt: Halt,
}

#[derive(Debug)]
pub enum Halt {
    /// Ctrl-C stopped it between two requests.
    Stopped,
    /// The document changed since it was read: before the first request, with nothing deleted,
    /// or by the time its own delete went.
    Stale,
    Failed(FsqError),
    /// A second Ctrl-C stopped waiting for the request in flight, whose deletes, the document's
    /// own among them, may still reach Firestore.
    Abandoned,
}

impl From<FsqError> for Halt {
    fn from(error: FsqError) -> Self {
        Self::Failed(error)
    }
}