firestore 0.54.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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
// Linter allowance for functions that might have many arguments,
// often seen in builder patterns or comprehensive configuration methods.
#![allow(clippy::too_many_arguments)]

/// Module for document retrieval operations (get).
mod get;

/// Module for document creation operations.
mod create;

/// Module for document update operations.
mod update;

/// Module for document deletion operations.
mod delete;

/// Module defining models used in queries (filters, orders, etc.).
mod query_models;
pub use query_models::*;

/// Module defining models for preconditions (e.g., last update time).
mod precondition_models;
pub use precondition_models::*;

/// Module for query execution.
mod query;

/// Module for aggregated query execution.
mod aggregated_query;
pub use aggregated_query::*;

/// Module for listing documents or collections.
mod list;
pub use list::*;

/// Module for listening to real-time document changes.
mod listen_changes;
pub use listen_changes::*;

/// Module for storing the state of listen operations (e.g., resume tokens).
mod listen_changes_state_storage;
pub use listen_changes_state_storage::*;

use crate::*;
use gcloud_sdk::google::firestore::v1::firestore_client::FirestoreClient;
use gcloud_sdk::google::firestore::v1::*;
use gcloud_sdk::*;
// Re-export serde for convenience as it's often used with Firestore documents.
use serde::{Deserialize, Serialize};
use tracing::*;

/// Module for database client options and configuration.
mod options;
pub use options::*;

/// Module for Firestore transactions.
mod transaction;
pub use transaction::*;

/// Module defining models related to transactions.
mod transaction_models;
pub use transaction_models::*;

/// Internal module for transaction operations.
/// Crate-private low-level support traits that the fluent API is built on.
/// See `support.rs` for why they are `pub trait` inside a private module.
mod support;
pub(crate) use support::*;

mod transaction_ops;
use transaction_ops::*;

/// Module for session-specific parameters (e.g., consistency, caching).
mod session_params;
pub use session_params::*;

/// Module for defining read consistency (e.g., read_time, transaction_id).
mod consistency_selector;
pub use consistency_selector::*;

/// Module for per-request options (e.g., request tags).
mod request_options;
pub use request_options::*;

/// Module for building parent paths for sub-collections.
mod parent_path_builder;
pub use parent_path_builder::*;

/// Module for batch writing operations.
mod batch_writer;
pub use batch_writer::*;

/// Module for streaming batch write operations.
mod batch_streaming_writer;
pub use batch_streaming_writer::*;

/// Module for simple (non-streaming) batch write operations.
mod batch_simple_writer;
pub use batch_simple_writer::*;

use crate::errors::{
    FirestoreError, FirestoreInvalidParametersError, FirestoreInvalidParametersPublicDetails,
};
use std::fmt::Formatter;
use std::sync::Arc;

/// Module defining models for document transformations (e.g., server-side increments).
mod transform_models;
pub use transform_models::*;

/// Internal struct holding the core components of the Firestore database client.
/// This includes the database path, document path prefix, options, and the gRPC client.
struct FirestoreDbInner {
    database_path: String,
    doc_path: String,
    options: FirestoreDbOptions,
    client: GoogleApi<FirestoreClient<GoogleAuthMiddleware>>,
}

/// The main entry point for interacting with a Google Firestore database.
///
/// `FirestoreDb` provides methods for database operations such as creating, reading,
/// updating, and deleting documents, as well as querying collections and running transactions.
/// It manages the connection and authentication with the Firestore service.
///
/// Instances of `FirestoreDb` are cloneable and internally use `Arc` for shared state,
/// making them cheap to clone and safe to share across threads.
#[derive(Clone)]
pub struct FirestoreDb {
    inner: Arc<FirestoreDbInner>,
    session_params: Arc<FirestoreDbSessionParams>,
}

const GOOGLE_FIREBASE_API_URL: &str = "https://firestore.googleapis.com";
const GOOGLE_FIRESTORE_EMULATOR_HOST_ENV: &str = "FIRESTORE_EMULATOR_HOST";

/// The token the Firebase tools conventionally send to the local emulators,
/// which do not authenticate the requests.
const GOOGLE_FIRESTORE_EMULATOR_TOKEN: &str = "owner";

/// A stub token source used when talking to the Firestore emulator.
///
/// The emulator does not verify the credentials, and looking up the real ones
/// would only fail on a development machine that has none configured.
struct FirestoreEmulatorTokenSource;

#[async_trait::async_trait]
impl gcloud_sdk::Source for FirestoreEmulatorTokenSource {
    async fn token(&self) -> gcloud_sdk::error::Result<gcloud_sdk::Token> {
        Ok(gcloud_sdk::Token::new(
            "Bearer".to_string(),
            GOOGLE_FIRESTORE_EMULATOR_TOKEN.to_string().into(),
            jiff::Timestamp::MAX,
        ))
    }
}

impl FirestoreDb {
    /// Creates a new `FirestoreDb` instance with the specified Google Project ID.
    ///
    /// This is a convenience method that uses default [`FirestoreDbOptions`].
    /// For more control over configuration, use [`FirestoreDb::with_options`].
    ///
    /// # Arguments
    /// * `google_project_id`: The Google Cloud Project ID that owns the Firestore database.
    ///
    /// # Example
    /// ```rust,no_run
    /// use firestore::*; // Imports FirestoreDb, FirestoreResult, etc.
    ///
    /// # async fn run() -> FirestoreResult<()> {
    /// let db = FirestoreDb::new("my-gcp-project-id").await?;
    /// // Use db for Firestore operations
    /// # Ok(())
    /// # }
    /// ```
    pub async fn new<S>(google_project_id: S) -> FirestoreResult<Self>
    where
        S: AsRef<str>,
    {
        Self::with_options(FirestoreDbOptions::new(
            google_project_id.as_ref().to_string(),
        ))
        .await
    }

    /// Creates a new `FirestoreDb` instance with the specified options.
    ///
    /// This method allows for detailed configuration of the Firestore client,
    /// such as setting a custom database ID or API URL.
    /// It uses default token scopes and token source.
    ///
    /// # Arguments
    /// * `options`: The [`FirestoreDbOptions`] to configure the client.
    pub async fn with_options(options: FirestoreDbOptions) -> FirestoreResult<Self> {
        Self::with_options_token_source(
            options,
            GCP_DEFAULT_SCOPES.clone(),
            TokenSourceType::Default,
        )
        .await
    }

    /// Creates a new `FirestoreDb` instance attempting to infer the Google Project ID
    /// from the environment (e.g., Application Default Credentials).
    ///
    /// This is useful in environments where the project ID is implicitly available.
    ///
    /// # Errors
    /// Returns an [`FirestoreError::InvalidParametersError`] if the project ID cannot be inferred.
    pub async fn for_default_project_id() -> FirestoreResult<Self> {
        match FirestoreDbOptions::for_default_project_id().await {
            Some(options) => Self::with_options(options).await,
            _ => Err(FirestoreError::InvalidParametersError(
                FirestoreInvalidParametersError::new(FirestoreInvalidParametersPublicDetails::new(
                    "google_project_id".to_string(),
                    "Unable to retrieve google_project_id".to_string(),
                )),
            )),
        }
    }

    /// Creates a new `FirestoreDb` instance with specified options and a service account key file
    /// for authentication.
    ///
    /// # Arguments
    /// * `options`: The [`FirestoreDbOptions`] to configure the client.
    /// * `service_account_key_path`: Path to the JSON service account key file.
    pub async fn with_options_service_account_key_file(
        options: FirestoreDbOptions,
        service_account_key_path: std::path::PathBuf,
    ) -> FirestoreResult<Self> {
        Self::with_options_token_source(
            options,
            gcloud_sdk::GCP_DEFAULT_SCOPES.clone(),
            gcloud_sdk::TokenSourceType::File(service_account_key_path),
        )
        .await
    }

    /// Creates a new `FirestoreDb` instance with full control over options, token scopes,
    /// and token source type.
    ///
    /// This is the most flexible constructor, allowing customization of authentication
    /// and authorization aspects.
    ///
    /// # Arguments
    /// * `options`: The [`FirestoreDbOptions`] to configure the client.
    /// * `token_scopes`: A list of OAuth2 scopes required for Firestore access.
    /// * `token_source_type`: The [`TokenSourceType`](gcloud_sdk::TokenSourceType)
    ///   specifying how to obtain authentication tokens (e.g., default, file, metadata server).
    pub async fn with_options_token_source(
        options: FirestoreDbOptions,
        token_scopes: Vec<String>,
        token_source_type: TokenSourceType,
    ) -> FirestoreResult<Self> {
        let firestore_database_path = format!(
            "projects/{}/databases/{}",
            options.google_project_id, options.database_id
        );
        let firestore_database_doc_path = format!("{firestore_database_path}/documents");

        let emulator_host = std::env::var(GOOGLE_FIRESTORE_EMULATOR_HOST_ENV).ok();

        let effective_firebase_api_url = options
            .firebase_api_url
            .clone()
            .or_else(|| emulator_host.clone().map(ensure_url_scheme))
            .unwrap_or_else(|| GOOGLE_FIREBASE_API_URL.to_string());

        // The emulator does not authenticate the requests, and there are usually no
        // credentials available when developing against it, so looking them up would
        // only fail. An explicitly specified token source is still respected.
        let effective_token_source_type =
            if emulator_host.is_some() && matches!(token_source_type, TokenSourceType::Default) {
                debug!(
                "Firestore emulator detected, skipping the token source and using a stub token.",
            );
                TokenSourceType::ExternalSource(Box::new(FirestoreEmulatorTokenSource))
            } else {
                token_source_type
            };

        info!(
            database_path = firestore_database_path,
            api_url = effective_firebase_api_url,
            token_scopes = token_scopes.join(", "),
            "Creating a new database client.",
        );

        let client = GoogleApiClient::from_function_with_token_source(
            FirestoreClient::new,
            effective_firebase_api_url,
            Some(firestore_database_path.clone()),
            token_scopes,
            effective_token_source_type,
        )
        .await?;

        let inner = FirestoreDbInner {
            database_path: firestore_database_path,
            doc_path: firestore_database_doc_path,
            client,
            options,
        };

        Ok(Self {
            inner: Arc::new(inner),
            session_params: Arc::new(FirestoreDbSessionParams::new()),
        })
    }

    /// Deserializes a Firestore [`Document`] into a Rust type `T`.
    ///
    /// This function uses the custom Serde deserializer provided by this crate
    /// to map Firestore's native data types to Rust structs.
    ///
    /// # Arguments
    /// * `doc`: A reference to the Firestore [`Document`] to deserialize.
    ///
    /// # Type Parameters
    /// * `T`: The target Rust type that implements `serde::Deserialize`.
    ///
    /// # Errors
    /// Returns a [`FirestoreError::DeserializeError`] if deserialization fails.
    pub fn deserialize_doc_to<T>(doc: &Document) -> FirestoreResult<T>
    where
        for<'de> T: Deserialize<'de>,
    {
        crate::firestore_serde::firestore_document_to_serializable(doc)
    }

    /// Serializes a Rust type `T` into a Firestore [`Document`].
    ///
    /// This function uses the custom Serde serializer to convert Rust structs
    /// into Firestore's native data format.
    ///
    /// # Arguments
    /// * `document_path`: The full path to the document (e.g., "projects/my-project/databases/(default)/documents/my-collection/my-doc").
    ///   This is used to set the `name` field of the resulting Firestore document.
    /// * `obj`: A reference to the Rust object to serialize.
    ///
    /// # Type Parameters
    /// * `S`: A type that can be converted into a string for the document path.
    /// * `T`: The source Rust type that implements `serde::Serialize`.
    ///
    /// # Errors
    /// Returns a [`FirestoreError::SerializeError`] if serialization fails.
    pub fn serialize_to_doc<S, T>(document_path: S, obj: &T) -> FirestoreResult<Document>
    where
        S: AsRef<str>,
        T: Serialize,
    {
        crate::firestore_serde::firestore_document_from_serializable(document_path, obj)
    }

    /// Serializes a map of field names to [`FirestoreValue`]s into a Firestore [`Document`].
    ///
    /// This is useful for constructing documents dynamically or when working with
    /// partially structured data.
    ///
    /// # Arguments
    /// * `document_path`: The full path to the document.
    /// * `fields`: An iterator yielding pairs of field names (as strings) and their
    ///   corresponding [`FirestoreValue`]s.
    ///
    /// # Type Parameters
    /// * `S`: A type that can be converted into a string for the document path.
    /// * `I`: An iterator type for the fields.
    /// * `IS`: A type that can be converted into a string for field names.
    ///
    /// # Errors
    /// Returns a [`FirestoreError::SerializeError`] if serialization fails.
    pub fn serialize_map_to_doc<S, I, IS>(
        document_path: S,
        fields: I,
    ) -> FirestoreResult<FirestoreDocument>
    where
        S: AsRef<str>,
        I: IntoIterator<Item = (IS, FirestoreValue)>,
        IS: AsRef<str>,
    {
        crate::firestore_serde::firestore_document_from_map(document_path, fields)
    }

    /// Performs a simple "ping" to the Firestore database to check connectivity.
    ///
    /// This method attempts to read a non-existent document. A successful outcome
    /// (even if the document is not found) indicates that the database is reachable
    /// and the client is authenticated.
    ///
    /// # Errors
    /// May return network or authentication errors if the database is unreachable.
    pub async fn ping(&self) -> FirestoreResult<()> {
        // Reading non-existing document just to check that database is available to read
        self.get_doc_by_path(
            "-ping-".to_string(),             // A document ID that is unlikely to exist
            self.get_database_path().clone(), // Use the root database path for this check
            None,                             // No specific consistency required
            0,                                // No retries needed for a ping
        )
        .await
        .map(|_| ()) // If it's Ok(None) or Ok(Some(_)), it's a success for ping
        .or_else(|err| {
            // If the error is DataNotFoundError, it's still a successful ping.
            // Other errors (network, auth) are real failures.
            if matches!(err, FirestoreError::DataNotFoundError(_)) {
                Ok(())
            } else {
                Err(err)
            }
        })
    }

    /// Returns the full database path string (e.g., "projects/my-project/databases/(default)").
    #[inline]
    pub fn get_database_path(&self) -> &String {
        &self.inner.database_path
    }

    /// Returns the base path for documents within this database
    /// (e.g., "projects/my-project/databases/(default)/documents").
    #[inline]
    pub fn get_documents_path(&self) -> &String {
        &self.inner.doc_path
    }

    /// Constructs a [`ParentPathBuilder`] for creating paths to sub-collections
    /// under a specified document.
    ///
    /// # Arguments
    /// * `collection_name`: The name of the collection containing the parent document.
    /// * `document_id`: The ID of the parent document.
    ///
    /// # Errors
    /// Returns [`FirestoreError::InvalidParametersError`] if the `document_id` is invalid.
    #[inline]
    pub fn parent_path<S>(
        &self,
        collection_name: &str,
        document_id: S,
    ) -> FirestoreResult<ParentPathBuilder>
    where
        S: AsRef<str>,
    {
        Ok(ParentPathBuilder::new(safe_document_path(
            self.inner.doc_path.as_str(),
            collection_name,
            document_id.as_ref(),
        )?))
    }

    /// Returns a reference to the [`FirestoreDbOptions`] used to configure this client.
    #[inline]
    pub fn get_options(&self) -> &FirestoreDbOptions {
        &self.inner.options
    }

    /// Returns a reference to the current [`FirestoreDbSessionParams`] for this client instance.
    /// Session parameters can control aspects like consistency and caching for operations
    /// performed with this specific `FirestoreDb` instance.
    #[inline]
    pub fn get_session_params(&self) -> &FirestoreDbSessionParams {
        &self.session_params
    }

    /// Resolves the effective request options for an operation.
    ///
    /// A per operation override takes precedence over the session wide default
    /// configured with
    /// [`clone_with_request_options`](FirestoreDb::clone_with_request_options).
    #[inline]
    pub(crate) fn resolve_request_options(
        &self,
        request_options: Option<&FirestoreRequestOptions>,
    ) -> Option<gcloud_sdk::google::firestore::v1::RequestOptions> {
        FirestoreRequestOptions::resolve(
            request_options,
            self.session_params.request_options.as_ref(),
        )
    }

    /// Returns a reference to the underlying `gcloud-sdk` gRPC client.
    ///
    /// **Unsupported escape hatch.** The [Fluent API](Self::fluent) is the supported way to use
    /// this crate; this method exists only for the rare case where it does not yet cover
    /// something you need.
    ///
    /// It exposes types from `gcloud-sdk`, whose version is *not* part of this crate's semver
    /// contract: this signature and the types behind it may change in any release, including a
    /// patch release. You also need to depend on `gcloud-sdk` yourself, at a matching version,
    /// since this crate does not re-export it.
    #[inline]
    pub fn client(&self) -> &GoogleApi<FirestoreClient<GoogleAuthMiddleware>> {
        &self.inner.client
    }

    /// Clones the `FirestoreDb` instance, replacing its session parameters.
    ///
    /// This is useful for creating a new client instance that shares the same
    /// underlying connection and configuration but has different session-level
    /// settings (e.g., for a specific transaction or consistency requirement).
    ///
    /// # Arguments
    /// * `session_params`: The new [`FirestoreDbSessionParams`] to use.
    #[inline]
    pub fn clone_with_session_params(&self, session_params: FirestoreDbSessionParams) -> Self {
        Self {
            session_params: session_params.into(),
            ..self.clone()
        }
    }

    /// Consumes the `FirestoreDb` instance and returns a new one with replaced session parameters.
    ///
    /// Similar to [`clone_with_session_params`](FirestoreDb::clone_with_session_params)
    /// but takes ownership of `self`.
    ///
    /// # Arguments
    /// * `session_params`: The new [`FirestoreDbSessionParams`] to use.
    #[inline]
    pub fn with_session_params(self, session_params: FirestoreDbSessionParams) -> Self {
        Self {
            session_params: session_params.into(),
            ..self
        }
    }

    /// Clones the `FirestoreDb` instance with a specific consistency selector.
    ///
    /// This creates a new `FirestoreDb` instance configured to use the provided
    /// [`FirestoreConsistencySelector`] for subsequent operations.
    ///
    /// # Arguments
    /// * `consistency_selector`: The consistency mode to apply (e.g., read at a specific time).
    #[inline]
    pub fn clone_with_consistency_selector(
        &self,
        consistency_selector: FirestoreConsistencySelector,
    ) -> Self {
        let existing_session_params = (*self.session_params).clone();

        self.clone_with_session_params(
            existing_session_params.with_consistency_selector(consistency_selector),
        )
    }

    /// Clones the `FirestoreDb` instance with default request options.
    ///
    /// Every request issued through the returned instance carries these options,
    /// unless an operation overrides them explicitly.
    ///
    /// # Arguments
    /// * `request_options`: The [`FirestoreRequestOptions`] to apply by default.
    #[inline]
    pub fn clone_with_request_options(&self, request_options: FirestoreRequestOptions) -> Self {
        let existing_session_params = (*self.session_params).clone();

        self.clone_with_session_params(
            existing_session_params.with_request_options(request_options),
        )
    }

    /// Clones the `FirestoreDb` instance with default request tags.
    ///
    /// A convenience shortcut for
    /// [`clone_with_request_options`](FirestoreDb::clone_with_request_options).
    /// This is also the way to attach request tags to the CRUD operations
    /// (get/create/update/delete), which have no per operation options.
    ///
    /// # Arguments
    /// * `request_tags`: An iterator of tags to attach to every request.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use firestore::*;
    /// # async fn run() -> FirestoreResult<()> {
    /// let db = FirestoreDb::new("my-gcp-project-id").await?;
    /// let tagged_db = db.clone_with_request_tags(["nightly-report"]);
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn clone_with_request_tags<I>(&self, request_tags: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<FirestoreRequestTag>,
    {
        self.clone_with_request_options(FirestoreRequestOptions::from_tags(request_tags))
    }

    /// Consumes the `FirestoreDb` instance and returns a new one with default
    /// request options.
    ///
    /// # Arguments
    /// * `request_options`: The [`FirestoreRequestOptions`] to apply by default.
    #[inline]
    pub fn with_request_options(self, request_options: FirestoreRequestOptions) -> Self {
        let session_params = (*self.session_params)
            .clone()
            .with_request_options(request_options);

        self.with_session_params(session_params)
    }

    /// Consumes the `FirestoreDb` instance and returns a new one with default
    /// request tags.
    ///
    /// A convenience shortcut for
    /// [`with_request_options`](FirestoreDb::with_request_options).
    ///
    /// # Arguments
    /// * `request_tags`: An iterator of tags to attach to every request.
    #[inline]
    pub fn with_request_tags<I>(self, request_tags: I) -> Self
    where
        I: IntoIterator,
        I::Item: Into<FirestoreRequestTag>,
    {
        self.with_request_options(FirestoreRequestOptions::from_tags(request_tags))
    }

    /// Clones the `FirestoreDb` instance with a specific cache mode.
    ///
    /// This method is only available if the `caching` feature is enabled.
    ///
    /// # Arguments
    /// * `cache_mode`: The [`FirestoreDbSessionCacheMode`] to apply.
    #[cfg(feature = "caching")]
    pub fn with_cache(&self, cache_mode: crate::FirestoreDbSessionCacheMode) -> Self {
        let existing_session_params = (*self.session_params).clone();

        self.clone_with_session_params(existing_session_params.with_cache_mode(cache_mode))
    }

    /// Clones this `FirestoreDb` so that reads go through the given cache, falling back to
    /// Firestore.
    ///
    /// This is the mode to reach for by default: anything the cache can answer is served
    /// locally, and anything it cannot is fetched from Firestore as usual.
    ///
    /// Reads by ID are served from the cache for any cached collection, and populate it on a
    /// miss. `list` and `query` are served from the cache only for collections configured to be
    /// preloaded - for others they transparently go to Firestore, because a lazily filled
    /// collection could only answer them with partial results.
    ///
    /// Results are eventually consistent; see [`FirestoreCache`](crate::FirestoreCache) for what
    /// that means in practice.
    ///
    /// This method is only available if the `caching` feature is enabled.
    ///
    /// # Arguments
    /// * `cache`: A reference to the [`FirestoreCache`](crate::FirestoreCache) to use.
    #[cfg(feature = "caching")]
    pub fn read_through_cache<B, LS>(&self, cache: &FirestoreCache<B, LS>) -> Self
    where
        B: FirestoreCacheBackend + Send + Sync + 'static,
        LS: FirestoreResumeStateStorage + Clone + Send + Sync + 'static,
    {
        self.with_cache(crate::FirestoreDbSessionCacheMode::ReadThroughCache(
            cache.backend(),
        ))
    }

    /// Clones this `FirestoreDb` so that reads come exclusively from the given cache, never from
    /// Firestore.
    ///
    /// Reads by ID return `None` when the document is not cached. Requests that the cache cannot
    /// answer *completely* - a `list` or `query` on a collection that is not preloaded, on a
    /// collection the cache does not know about, or a collection group query - return a
    /// [`FirestoreError::CacheError`](crate::errors::FirestoreError::CacheError) rather than a
    /// partial result that would look complete.
    ///
    /// Use [`read_through_cache`](Self::read_through_cache) if you would rather fall back to
    /// Firestore, or [`FirestoreCacheIncompleteCollectionPolicy::PartialResults`](crate::FirestoreCacheIncompleteCollectionPolicy::PartialResults)
    /// if partial results are genuinely acceptable for your use case.
    ///
    /// This method is only available if the `caching` feature is enabled.
    ///
    /// # Arguments
    /// * `cache`: A reference to the [`FirestoreCache`](crate::FirestoreCache) to use.
    #[cfg(feature = "caching")]
    pub fn read_cached_only<B, LS>(&self, cache: &FirestoreCache<B, LS>) -> Self
    where
        B: FirestoreCacheBackend + Send + Sync + 'static,
        LS: FirestoreResumeStateStorage + Clone + Send + Sync + 'static,
    {
        self.with_cache(crate::FirestoreDbSessionCacheMode::ReadCachedOnly(
            cache.backend(),
        ))
    }
}

/// Ensures that a URL string has a scheme (e.g., "http://").
/// If no scheme is present, "http://" is prepended.
fn ensure_url_scheme(url: String) -> String {
    if !url.contains("://") {
        format!("http://{url}")
    } else {
        url
    }
}

impl std::fmt::Debug for FirestoreDb {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FirestoreDb")
            .field("options", &self.inner.options)
            .field("database_path", &self.inner.database_path)
            .field("doc_path", &self.inner.doc_path)
            .finish()
    }
}

pub(crate) fn safe_document_path<S>(
    parent: &str,
    collection_id: &str,
    document_id: S,
) -> FirestoreResult<String>
where
    S: AsRef<str>,
{
    // All restrictions described here: https://firebase.google.com/docs/firestore/quotas#collections_documents_and_fields
    // Here we check only the most dangerous one for `/` to avoid document_id injections, leaving other validation to the server side.
    let document_id_ref = document_id.as_ref();
    if document_id_ref.chars().all(|c| c != '/') && document_id_ref.len() <= 1500 {
        Ok(format!("{parent}/{collection_id}/{document_id_ref}"))
    } else {
        Err(FirestoreError::InvalidParametersError(
            FirestoreInvalidParametersError::new(FirestoreInvalidParametersPublicDetails::new(
                "document_id".to_string(),
                format!("Invalid document ID provided: {document_id_ref}"),
            )),
        ))
    }
}

/// Splits a document path into the path of its parent and the document ID.
///
/// Returns `(parent_path, document_id)`, where the parent path is empty when the path has no
/// separator at all.
pub(crate) fn split_document_path(path: &str) -> (&str, &str) {
    match path.rfind('/') {
        Some(split_pos) => (&path[..split_pos], &path[split_pos + 1..]),
        None => ("", path),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_emulator_token_source() {
        use gcloud_sdk::Source;

        let token = FirestoreEmulatorTokenSource
            .token()
            .await
            .expect("The emulator token source must never fail");

        assert_eq!(token.token_type, "Bearer");
        assert_eq!(
            token.token.as_sensitive_str(),
            GOOGLE_FIRESTORE_EMULATOR_TOKEN
        );
    }

    #[test]
    fn test_safe_document_path() {
        assert_eq!(
            safe_document_path(
                "projects/test-project/databases/(default)/documents",
                "test",
                "test1"
            )
            .ok(),
            Some("projects/test-project/databases/(default)/documents/test/test1".to_string())
        );

        assert_eq!(
            safe_document_path(
                "projects/test-project/databases/(default)/documents",
                "test",
                "test1#test2"
            )
            .ok(),
            Some(
                "projects/test-project/databases/(default)/documents/test/test1#test2".to_string()
            )
        );

        assert_eq!(
            safe_document_path(
                "projects/test-project/databases/(default)/documents",
                "test",
                "test1/test2"
            )
            .ok(),
            None
        );
    }

    #[test]
    fn test_ensure_url_scheme() {
        assert_eq!(
            ensure_url_scheme("localhost:8080".into()),
            "http://localhost:8080"
        );
        assert_eq!(
            ensure_url_scheme("any://localhost:8080".into()),
            "any://localhost:8080"
        );
        assert_eq!(
            ensure_url_scheme("invalid:localhost:8080".into()),
            "http://invalid:localhost:8080"
        );
    }

    #[test]
    fn test_split_document_path() {
        assert_eq!(
            split_document_path("projects/test-project/databases/(default)/documents/test/test1"),
            (
                "projects/test-project/databases/(default)/documents/test",
                "test1"
            )
        );
        assert_eq!(split_document_path("test1"), ("", "test1"));
    }
}