firestore 0.49.0

Library provides a simple API for Google Firestore and own Serde serializer based on efficient gRPC API
Documentation
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
use crate::db::FirestoreDbInner;
use crate::*;
use async_trait::async_trait;
use chrono::prelude::*;
use futures::future::BoxFuture;
use futures::stream::BoxStream;
use futures::FutureExt;
use futures::StreamExt;
use futures::TryFutureExt;
use futures::TryStreamExt;
use gcloud_sdk::google::firestore::v1::*;
use rand::RngExt;
use rsb_derive::*;
use serde::Deserialize;
use std::future;
use std::sync::Arc;
use tracing::*;

#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct FirestoreListDocParams {
    pub collection_id: String,

    pub parent: Option<String>,

    #[default = "100"]
    pub page_size: usize,

    pub page_token: Option<String>,
    pub order_by: Option<Vec<FirestoreQueryOrder>>,
    pub return_only_fields: Option<Vec<String>>,
}

#[derive(Debug, PartialEq, Clone, Builder)]
pub struct FirestoreListDocResult {
    pub documents: Vec<Document>,
    pub page_token: Option<String>,
}

#[derive(Debug, Eq, PartialEq, Clone, Builder)]
pub struct FirestoreListCollectionIdsParams {
    pub parent: Option<String>,

    #[default = "100"]
    pub page_size: usize,
    pub page_token: Option<String>,
}

#[derive(Debug, PartialEq, Clone, Builder)]
pub struct FirestoreListCollectionIdsResult {
    pub collection_ids: Vec<String>,
    pub page_token: Option<String>,
}

#[async_trait]
pub trait FirestoreListingSupport {
    async fn list_doc(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<FirestoreListDocResult>;

    async fn stream_list_doc<'b>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, Document>>;

    async fn stream_list_doc_with_errors<'b>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<Document>>>;

    async fn stream_list_obj<'b, T>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, T>>
    where
        for<'de> T: Deserialize<'de> + 'b;

    async fn stream_list_obj_with_errors<'b, T>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<T>>>
    where
        for<'de> T: Deserialize<'de> + 'b;

    async fn list_collection_ids(
        &self,
        params: FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<FirestoreListCollectionIdsResult>;

    async fn stream_list_collection_ids_with_errors(
        &self,
        params: FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<BoxStream<FirestoreResult<String>>>;

    async fn stream_list_collection_ids(
        &self,
        params: FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<BoxStream<String>>;
}

#[async_trait]
impl FirestoreListingSupport for FirestoreDb {
    async fn list_doc(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<FirestoreListDocResult> {
        let span = span!(
            Level::DEBUG,
            "Firestore ListDocs",
            "/firestore/collection_name" = params.collection_id.as_str(),
            "/firestore/response_time" = field::Empty
        );

        self.list_doc_with_retries(params, 0, span).await
    }

    async fn stream_list_doc_with_errors<'b>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<Document>>> {
        self.stream_list_doc_with_retries(params).await
    }

    async fn stream_list_doc<'b>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, Document>> {
        let doc_stream = self.stream_list_doc_with_errors(params).await?;
        Ok(Box::pin(doc_stream.filter_map(|doc_res| {
            future::ready(match doc_res {
                Ok(doc) => Some(doc),
                Err(err) => {
                    error!(%err, "Error occurred while consuming documents.");
                    None
                }
            })
        })))
    }

    async fn stream_list_obj<'b, T>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, T>>
    where
        for<'de> T: Deserialize<'de> + 'b,
    {
        let doc_stream = self.stream_list_doc(params).await?;

        Ok(Box::pin(doc_stream.filter_map(|doc| async move {
            match Self::deserialize_doc_to::<T>(&doc) {
                Ok(obj) => Some(obj),
                Err(err) => {
                    error!(
                        %err,
                        "Error occurred while deserializing a document inside a stream. Document: {}",
                        doc.name
                    );
                    None
                }
            }
        })))
    }

    async fn stream_list_obj_with_errors<'b, T>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<T>>>
    where
        for<'de> T: Deserialize<'de> + 'b,
    {
        let doc_stream = self.stream_list_doc_with_errors(params).await?;

        Ok(Box::pin(doc_stream.and_then(|doc| async move {
            Self::deserialize_doc_to::<T>(&doc)
        })))
    }

    async fn list_collection_ids(
        &self,
        params: FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<FirestoreListCollectionIdsResult> {
        let span = span!(
            Level::DEBUG,
            "Firestore ListCollectionIds",
            "/firestore/response_time" = field::Empty
        );

        self.list_collection_ids_with_retries(params, 0, &span)
            .await
    }

    async fn stream_list_collection_ids(
        &self,
        params: FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<BoxStream<String>> {
        let stream = self.stream_list_collection_ids_with_errors(params).await?;
        Ok(Box::pin(stream.filter_map(|col_res| {
            future::ready(match col_res {
                Ok(col) => Some(col),
                Err(err) => {
                    error!(%err, "Error occurred while consuming collection IDs.");
                    None
                }
            })
        })))
    }

    async fn stream_list_collection_ids_with_errors(
        &self,
        params: FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<BoxStream<FirestoreResult<String>>> {
        let stream: BoxStream<FirestoreResult<String>> = Box::pin(
            futures::stream::unfold(Some(params), move |maybe_params| async move {
                if let Some(params) = maybe_params {
                    let span = span!(
                        Level::DEBUG,
                        "Firestore Streaming ListCollections",
                        "/firestore/response_time" = field::Empty
                    );

                    match self
                        .list_collection_ids_with_retries(params.clone(), 0, &span)
                        .await
                    {
                        Ok(results) => {
                            if let Some(next_page_token) = results.page_token.clone() {
                                Some((Ok(results), Some(params.with_page_token(next_page_token))))
                            } else {
                                Some((Ok(results), None))
                            }
                        }
                        Err(err) => {
                            error!(%err, "Error occurred while consuming documents.");
                            Some((Err(err), None))
                        }
                    }
                } else {
                    None
                }
            })
            .flat_map(|doc_res| {
                futures::stream::iter(match doc_res {
                    Ok(results) => results
                        .collection_ids
                        .into_iter()
                        .map(Ok::<String, FirestoreError>)
                        .collect(),
                    Err(err) => vec![Err(err)],
                })
            }),
        );

        Ok(stream)
    }
}

impl FirestoreDb {
    fn create_list_doc_request(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<ListDocumentsRequest> {
        Ok(ListDocumentsRequest {
            parent: params
                .parent
                .as_ref()
                .unwrap_or_else(|| self.get_documents_path())
                .clone(),
            collection_id: params.collection_id,
            page_size: params.page_size as i32,
            page_token: params.page_token.unwrap_or_default(),
            order_by: params
                .order_by
                .map(|fields| {
                    fields
                        .into_iter()
                        .map(|field| field.to_string_format())
                        .collect::<Vec<String>>()
                        .join(", ")
                })
                .unwrap_or_default(),
            mask: params
                .return_only_fields
                .map(|masks| DocumentMask { field_paths: masks }),
            consistency_selector: self
                .session_params
                .consistency_selector
                .as_ref()
                .map(|selector| selector.try_into())
                .transpose()?,
            show_missing: false,
        })
    }

    fn list_doc_with_retries<'b>(
        &self,
        params: FirestoreListDocParams,
        retries: usize,
        span: Span,
    ) -> BoxFuture<'b, FirestoreResult<FirestoreListDocResult>> {
        match self.create_list_doc_request(params) {
            Ok(list_request) => {
                Self::list_doc_with_retries_inner(self.inner.clone(), list_request, retries, span)
                    .boxed()
            }
            Err(err) => futures::future::err(err).boxed(),
        }
    }

    fn list_doc_with_retries_inner<'b>(
        db_inner: Arc<FirestoreDbInner>,
        list_request: ListDocumentsRequest,
        retries: usize,
        span: Span,
    ) -> BoxFuture<'b, FirestoreResult<FirestoreListDocResult>> {
        async move {
            let begin_utc: DateTime<Utc> = Utc::now();

            match db_inner.client.get()
                .list_documents(
                    gcloud_sdk::tonic::Request::new(list_request.clone())
                )
                .map_err(|e| e.into())
                .await
            {
                Ok(listing_response) => {
                    let list_inner = listing_response.into_inner();
                    let result = FirestoreListDocResult::new(list_inner.documents).opt_page_token(
                        if !list_inner.next_page_token.is_empty() {
                            Some(list_inner.next_page_token)
                        } else {
                            None
                        },
                    );
                    let end_query_utc: DateTime<Utc> = Utc::now();
                    let listing_duration = end_query_utc.signed_duration_since(begin_utc);

                    span.record(
                        "/firestore/response_time",
                        listing_duration.num_milliseconds(),
                    );
                    span.in_scope(|| {
                        debug!(
                            collection_id = list_request.collection_id.as_str(),
                            duration_milliseconds = listing_duration.num_milliseconds(),
                            num_documents = result.documents.len(),
                            "Listed documents.",
                        );
                    });

                    Ok(result)
                }
                Err(err) => match err {
                    FirestoreError::DatabaseError(ref db_err)
                    if db_err.retry_possible && retries < db_inner.options.max_retries =>
                        {
                            let sleep_duration = tokio::time::Duration::from_millis(
                                rand::rng().random_range(0..2u64.pow(retries as u32) * 1000 + 1),
                            );

                            warn!(
                                err = %db_err,
                                current_retry = retries + 1,
                                max_retries = db_inner.options.max_retries,
                                delay = sleep_duration.as_millis(),
                                "Failed to list documents. Retrying up to the specified number of times.",
                            );

                            tokio::time::sleep(sleep_duration).await;

                            Self::list_doc_with_retries_inner(db_inner, list_request, retries + 1, span).await
                        }
                    _ => Err(err),
                },
            }
        }
            .boxed()
    }

    async fn stream_list_doc_with_retries<'b>(
        &self,
        params: FirestoreListDocParams,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<Document>>> {
        #[cfg(feature = "caching")]
        {
            if let FirestoreCachedValue::UseCached(stream) =
                self.list_docs_from_cache(&params).await?
            {
                return Ok(stream);
            }
        }
        let list_request = self.create_list_doc_request(params.clone())?;
        Self::stream_list_doc_with_retries_inner(self.inner.clone(), list_request)
    }

    fn stream_list_doc_with_retries_inner<'b>(
        db_inner: Arc<FirestoreDbInner>,
        list_request: ListDocumentsRequest,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<Document>>> {
        let stream: BoxStream<FirestoreResult<Document>> = Box::pin(
            futures::stream::unfold(
                (db_inner, Some(list_request)),
                move |(db_inner, list_request)| async move {
                    if let Some(mut list_request) = list_request {
                        let span = span!(
                            Level::DEBUG,
                            "Firestore Streaming ListDocs",
                            "/firestore/collection_name" = list_request.collection_id.as_str(),
                            "/firestore/response_time" = field::Empty
                        );
                        match Self::list_doc_with_retries_inner(
                            db_inner.clone(),
                            list_request.clone(),
                            0,
                            span,
                        )
                        .await
                        {
                            Ok(results) => {
                                if let Some(next_page_token) = results.page_token.clone() {
                                    list_request.page_token = next_page_token;
                                    Some((Ok(results), (db_inner, Some(list_request))))
                                } else {
                                    Some((Ok(results), (db_inner, None)))
                                }
                            }
                            Err(err) => {
                                error!(%err, "Error occurred while consuming documents.");
                                Some((Err(err), (db_inner, None)))
                            }
                        }
                    } else {
                        None
                    }
                },
            )
            .flat_map(|doc_res| {
                futures::stream::iter(match doc_res {
                    Ok(results) => results
                        .documents
                        .into_iter()
                        .map(Ok::<Document, FirestoreError>)
                        .collect(),
                    Err(err) => vec![Err(err)],
                })
            }),
        );

        Ok(stream)
    }

    fn create_list_collection_ids_request(
        &self,
        params: &FirestoreListCollectionIdsParams,
    ) -> FirestoreResult<gcloud_sdk::tonic::Request<ListCollectionIdsRequest>> {
        Ok(gcloud_sdk::tonic::Request::new(ListCollectionIdsRequest {
            parent: params
                .parent
                .as_ref()
                .unwrap_or_else(|| self.get_documents_path())
                .clone(),
            page_size: params.page_size as i32,
            page_token: params.page_token.clone().unwrap_or_default(),
            consistency_selector: self
                .session_params
                .consistency_selector
                .as_ref()
                .map(|selector| selector.try_into())
                .transpose()?,
        }))
    }

    fn list_collection_ids_with_retries<'a>(
        &'a self,
        params: FirestoreListCollectionIdsParams,
        retries: usize,
        span: &'a Span,
    ) -> BoxFuture<'a, FirestoreResult<FirestoreListCollectionIdsResult>> {
        async move {
            let list_request = self.create_list_collection_ids_request(&params)?;
            let begin_utc: DateTime<Utc> = Utc::now();

            match self
                .client()
                .get()
                .list_collection_ids(list_request)
                .map_err(|e| e.into())
                .await
            {
                Ok(listing_response) => {
                    let list_inner = listing_response.into_inner();
                    let result = FirestoreListCollectionIdsResult::new(list_inner.collection_ids)
                        .opt_page_token(if !list_inner.next_page_token.is_empty() {
                            Some(list_inner.next_page_token)
                        } else {
                            None
                        });
                    let end_query_utc: DateTime<Utc> = Utc::now();
                    let listing_duration = end_query_utc.signed_duration_since(begin_utc);

                    span.record(
                        "/firestore/response_time",
                        listing_duration.num_milliseconds(),
                    );
                    span.in_scope(|| {
                        debug!(
                            duration_milliseconds = listing_duration.num_milliseconds(),
                            "Listed collections.",
                        );
                    });

                    Ok(result)
                }
                Err(err) => match err {
                    FirestoreError::DatabaseError(ref db_err)
                    if db_err.retry_possible && retries < self.inner.options.max_retries =>
                        {
                            let sleep_duration = tokio::time::Duration::from_millis(
                                rand::rng().random_range(0..2u64.pow(retries as u32) * 1000 + 1),
                            );
                            warn!(
                                err = %db_err,
                                current_retry = retries + 1,
                                max_retries = self.inner.options.max_retries,
                                delay = sleep_duration.as_millis(),
                                "Failed to list collection IDs. Retrying up to the specified number of times.",
                            );

                            tokio::time::sleep(sleep_duration).await;

                            self.list_collection_ids_with_retries(params, retries + 1, span)
                                .await
                        }
                    _ => Err(err),
                },
            }
        }
            .boxed()
    }

    #[cfg(feature = "caching")]
    #[inline]
    pub async fn list_docs_from_cache<'b>(
        &self,
        params: &FirestoreListDocParams,
    ) -> FirestoreResult<FirestoreCachedValue<BoxStream<'b, FirestoreResult<FirestoreDocument>>>>
    {
        if let FirestoreDbSessionCacheMode::ReadCachedOnly(ref cache) =
            self.session_params.cache_mode
        {
            let span = span!(
                Level::DEBUG,
                "Firestore List Cached",
                "/firestore/collection_name" = params.collection_id,
                "/firestore/cache_result" = field::Empty,
                "/firestore/response_time" = field::Empty
            );

            let begin_query_utc: DateTime<Utc> = Utc::now();

            let collection_path = if let Some(parent) = params.parent.as_ref() {
                format!("{}/{}", parent, params.collection_id.as_str())
            } else {
                format!(
                    "{}/{}",
                    self.get_documents_path(),
                    params.collection_id.as_str()
                )
            };

            let cached_result = cache.list_all_docs(&collection_path).await?;

            let end_query_utc: DateTime<Utc> = Utc::now();
            let query_duration = end_query_utc.signed_duration_since(begin_query_utc);

            span.record(
                "/firestore/response_time",
                query_duration.num_milliseconds(),
            );

            match cached_result {
                FirestoreCachedValue::UseCached(stream) => {
                    span.record("/firestore/cache_result", "hit");
                    span.in_scope(|| {
                        debug!(
                            collection_id = params.collection_id,
                            "Reading all documents from cache."
                        );
                    });

                    Ok(FirestoreCachedValue::UseCached(stream))
                }
                FirestoreCachedValue::SkipCache => {
                    span.record("/firestore/cache_result", "miss");
                    if matches!(
                        self.session_params.cache_mode,
                        FirestoreDbSessionCacheMode::ReadCachedOnly(_)
                    ) {
                        span.in_scope(|| {
                            debug!(
                                collection_id = params.collection_id,
                                "Cache doesn't have suitable documents for specified collection, but cache mode is ReadCachedOnly so returning empty stream.",
                            );
                        });
                        Ok(FirestoreCachedValue::UseCached(Box::pin(
                            futures::stream::empty(),
                        )))
                    } else {
                        span.in_scope(|| {
                            debug!(
                                collection_id = params.collection_id,
                                "Cache doesn't have suitable documents for specified collection, so skipping cache and reading from Firestore.",
                            );
                        });
                        Ok(FirestoreCachedValue::SkipCache)
                    }
                }
            }
        } else {
            Ok(FirestoreCachedValue::SkipCache)
        }
    }
}