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
use crate::errors::*;
use crate::*;
use async_trait::async_trait;
use futures::stream::BoxStream;

use crate::cache::cache_query_engine::FirestoreCacheQueryEngine;
use chrono::Utc;
use futures::StreamExt;
use gcloud_sdk::google::firestore::v1::Document;
use gcloud_sdk::prost::Message;
use redb::*;
use std::collections::HashMap;
use std::path::PathBuf;
use tracing::*;

pub struct FirestorePersistentCacheBackend {
    pub config: FirestoreCacheConfiguration,
    redb: Database,
}

impl FirestorePersistentCacheBackend {
    pub fn new(config: FirestoreCacheConfiguration) -> FirestoreResult<Self> {
        let temp_dir = std::env::temp_dir();
        let firestore_cache_dir = temp_dir.join("firestore_cache");
        let db_dir = firestore_cache_dir.join("persistent");

        if !db_dir.exists() {
            debug!(
                directory = %db_dir.display(),
                "Creating a temp directory to store persistent cache.",
            );
            std::fs::create_dir_all(&db_dir)?;
        } else {
            debug!(
                directory = %db_dir.display(),
                "Using a temp directory to store persistent cache.",
            );
        }
        Self::with_options(config, db_dir.join("redb"))
    }

    pub fn with_options(
        config: FirestoreCacheConfiguration,
        data_file_path: PathBuf,
    ) -> FirestoreResult<Self> {
        if data_file_path.exists() {
            debug!(?data_file_path, "Opening database for persistent cache...",);
        } else {
            debug!(?data_file_path, "Creating database for persistent cache...",);
        }

        let mut db = Database::create(data_file_path)?;

        db.compact()?;
        info!("Successfully opened database for persistent cache.");

        Ok(Self { config, redb: db })
    }

    async fn preload_collections(&self, db: &FirestoreDb) -> Result<(), FirestoreError> {
        for (collection_path, config) in &self.config.collections {
            let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path.as_str());

            match config.collection_load_mode {
                FirestoreCacheCollectionLoadMode::PreloadAllDocs
                | FirestoreCacheCollectionLoadMode::PreloadAllIfEmpty => {
                    let existing_records = {
                        let read_tx = self.redb.begin_read()?;
                        if read_tx
                            .list_tables()?
                            .any(|t| t.name() == collection_path.as_str())
                        {
                            read_tx.open_table(td)?.len()?
                        } else {
                            0
                        }
                    };

                    if matches!(
                        config.collection_load_mode,
                        FirestoreCacheCollectionLoadMode::PreloadAllIfEmpty
                    ) && existing_records > 0
                    {
                        info!(
                            collection_path = collection_path.as_str(),
                            entries_loaded = existing_records,
                            "Preloading collection has been skipped.",
                        );
                        continue;
                    }

                    debug!(
                        collection_path = collection_path.as_str(),
                        "Preloading collection."
                    );

                    let params = if let Some(parent) = &config.parent {
                        db.fluent()
                            .select()
                            .from(config.collection_name.as_str())
                            .parent(parent)
                    } else {
                        db.fluent().select().from(config.collection_name.as_str())
                    };

                    let stream = params.stream_query().await?;

                    stream
                        .enumerate()
                        .map(|(index, docs)| {
                            if index > 0 && index % 5000 == 0 {
                                debug!(
                                    collection_path = collection_path.as_str(),
                                    entries_loaded = index,
                                    "Collection preload in progress...",
                                );
                            }
                            docs
                        })
                        .ready_chunks(100)
                        .for_each(|docs| async move {
                            if let Err(err) = self.write_batch_docs(collection_path, docs) {
                                error!(?err, "Error while preloading collection.");
                            }
                        })
                        .await;

                    let updated_records = if matches!(
                        config.collection_load_mode,
                        FirestoreCacheCollectionLoadMode::PreloadAllDocs
                    ) || existing_records == 0
                    {
                        let read_tx = self.redb.begin_read()?;
                        let table = read_tx.open_table(td)?;
                        table.len()?
                    } else {
                        existing_records
                    };

                    info!(
                        collection_path = collection_path.as_str(),
                        updated_records, "Preloading collection has been finished.",
                    );
                }
                FirestoreCacheCollectionLoadMode::PreloadNone => {
                    let tx = self.redb.begin_write()?;
                    debug!(collection_path, "Creating corresponding collection table.",);
                    tx.open_table(td)?;
                    tx.commit()?;
                }
            }
        }
        Ok(())
    }

    fn write_batch_docs(&self, collection_path: &str, docs: Vec<Document>) -> FirestoreResult<()> {
        let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path);

        let write_txn = self.redb.begin_write()?;
        {
            let mut table = write_txn.open_table(td)?;

            for doc in docs {
                let (_, document_id) = split_document_path(&doc.name);
                let doc_bytes = Self::document_to_buf(&doc)?;
                table.insert(document_id, doc_bytes.as_slice())?;
            }
        }
        write_txn.commit()?;

        Ok(())
    }

    fn document_to_buf(doc: &FirestoreDocument) -> FirestoreResult<Vec<u8>> {
        let mut proto_output_buf = Vec::new();
        doc.encode(&mut proto_output_buf)?;
        Ok(proto_output_buf)
    }

    fn buf_to_document<B>(buf: B) -> FirestoreResult<FirestoreDocument>
    where
        B: AsRef<[u8]>,
    {
        let doc = FirestoreDocument::decode(buf.as_ref())?;
        Ok(doc)
    }

    fn write_document(&self, doc: &Document) -> FirestoreResult<()> {
        let (collection_path, document_id) = split_document_path(&doc.name);

        if self.config.collections.contains_key(collection_path) {
            let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path);

            let write_txn = self.redb.begin_write()?;
            {
                let mut table = write_txn.open_table(td)?;
                let doc_bytes = Self::document_to_buf(doc)?;
                table.insert(document_id, doc_bytes.as_slice())?;
            }
            write_txn.commit()?;
            Ok(())
        } else {
            Ok(())
        }
    }

    fn table_len(&self, collection_id: &str) -> FirestoreResult<u64> {
        let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_id);
        let read_tx = self.redb.begin_read()?;
        let len = read_tx.open_table(td)?.len()?;
        Ok(len)
    }

    async fn query_cached_docs<'b>(
        &self,
        collection_path: &str,
        query_engine: FirestoreCacheQueryEngine,
    ) -> FirestoreResult<BoxStream<'b, FirestoreResult<FirestoreDocument>>> {
        let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path);

        let read_tx = self.redb.begin_read()?;
        let table = read_tx.open_table(td)?;
        let iter = table.iter()?;

        // It seems there is no way to work with streaming for redb, so this is not efficient
        let mut docs: Vec<FirestoreResult<FirestoreDocument>> = Vec::new();
        for record in iter {
            let (_, v) = record?;
            let doc = Self::buf_to_document(v.value())?;
            if query_engine.matches_doc(&doc) {
                docs.push(Ok(doc));
            }
        }

        let filtered_stream = Box::pin(futures::stream::iter(docs));
        let output_stream = query_engine.process_query_stream(filtered_stream).await?;

        Ok(output_stream)
    }
}

#[async_trait]
impl FirestoreCacheBackend for FirestorePersistentCacheBackend {
    async fn load(
        &self,
        _options: &FirestoreCacheOptions,
        db: &FirestoreDb,
    ) -> Result<Vec<FirestoreListenerTargetParams>, FirestoreError> {
        let read_from_time = Utc::now();

        self.preload_collections(db).await?;

        Ok(self
            .config
            .collections
            .iter()
            .map(|(collection_path, collection_config)| {
                let collection_table_len = self.table_len(collection_path).ok().unwrap_or(0);
                let resume_type = if collection_table_len == 0 {
                    Some(FirestoreListenerTargetResumeType::ReadTime(read_from_time))
                } else {
                    None
                };
                FirestoreListenerTargetParams::new(
                    collection_config.listener_target.clone(),
                    FirestoreTargetType::Query(
                        FirestoreQueryParams::new(
                            collection_config.collection_name.as_str().into(),
                        )
                        .opt_parent(collection_config.parent.clone()),
                    ),
                    HashMap::new(),
                )
                .opt_resume_type(resume_type)
            })
            .collect())
    }

    async fn invalidate_all(&self) -> FirestoreResult<()> {
        for collection_path in self.config.collections.keys() {
            let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path.as_str());

            let write_txn = self.redb.begin_write()?;
            {
                debug!(
                    collection_path,
                    "Invalidating collection and draining the corresponding table.",
                );
                let mut table = write_txn.open_table(td)?;
                table.retain(|_, _| false)?;
            }
            write_txn.commit()?;
        }

        Ok(())
    }

    async fn shutdown(&self) -> Result<(), FirestoreError> {
        Ok(())
    }

    async fn on_listen_event(&self, event: FirestoreListenEvent) -> FirestoreResult<()> {
        match event {
            FirestoreListenEvent::DocumentChange(doc_change) => {
                if let Some(doc) = doc_change.document {
                    trace!(
                        doc_name = ?doc.name,
                        "Writing document to cache due to listener event.",
                    );

                    self.write_document(&doc)?;
                }
                Ok(())
            }
            FirestoreListenEvent::DocumentDelete(doc_deleted) => {
                let (collection_path, document_id) = split_document_path(&doc_deleted.document);
                let write_txn = self.redb.begin_write()?;
                let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path);
                let mut table = write_txn.open_table(td)?;

                trace!(
                    deleted_doc = ?doc_deleted.document.as_str(),
                    "Removing document from cache due to listener event.",
                );

                table.remove(document_id)?;
                Ok(())
            }
            _ => Ok(()),
        }
    }
}

#[async_trait]
impl FirestoreCacheDocsByPathSupport for FirestorePersistentCacheBackend {
    async fn get_doc_by_path(
        &self,
        document_path: &str,
    ) -> FirestoreResult<Option<FirestoreDocument>> {
        let (collection_path, document_id) = split_document_path(document_path);
        if self.config.collections.contains_key(collection_path) {
            let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path);
            let read_tx = self.redb.begin_read()?;
            let table = read_tx.open_table(td)?;
            let value = table.get(document_id)?;
            value.map(|v| Self::buf_to_document(v.value())).transpose()
        } else {
            Ok(None)
        }
    }

    async fn update_doc_by_path(&self, document: &FirestoreDocument) -> FirestoreResult<()> {
        self.write_document(document)?;
        Ok(())
    }

    async fn list_all_docs<'b>(
        &self,
        collection_path: &str,
    ) -> FirestoreResult<FirestoreCachedValue<BoxStream<'b, FirestoreResult<FirestoreDocument>>>>
    {
        if self.config.collections.contains_key(collection_path) {
            let td: TableDefinition<&str, &[u8]> = TableDefinition::new(collection_path);

            let read_tx = self.redb.begin_read()?;
            let table = read_tx.open_table(td)?;
            let iter = table.iter()?;

            // It seems there is no way to work with streaming for redb, so this is not efficient
            let mut docs: Vec<FirestoreResult<FirestoreDocument>> = Vec::new();
            for record in iter {
                let (_, v) = record?;
                let doc = Self::buf_to_document(v.value())?;
                docs.push(Ok(doc));
            }

            Ok(FirestoreCachedValue::UseCached(Box::pin(
                futures::stream::iter(docs),
            )))
        } else {
            Ok(FirestoreCachedValue::SkipCache)
        }
    }

    async fn query_docs<'b>(
        &self,
        collection_path: &str,
        query: &FirestoreQueryParams,
    ) -> FirestoreResult<FirestoreCachedValue<BoxStream<'b, FirestoreResult<FirestoreDocument>>>>
    {
        if self.config.collections.contains_key(collection_path) {
            // For now only basic/simple query all supported
            let simple_query_engine = FirestoreCacheQueryEngine::new(query);
            if simple_query_engine.params_supported() {
                Ok(FirestoreCachedValue::UseCached(
                    self.query_cached_docs(collection_path, simple_query_engine)
                        .await?,
                ))
            } else {
                Ok(FirestoreCachedValue::SkipCache)
            }
        } else {
            Ok(FirestoreCachedValue::SkipCache)
        }
    }
}

impl From<redb::Error> for FirestoreError {
    fn from(db_err: redb::Error) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}

impl From<redb::DatabaseError> for FirestoreError {
    fn from(db_err: redb::DatabaseError) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbDatabaseError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}

impl From<redb::TransactionError> for FirestoreError {
    fn from(db_err: redb::TransactionError) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbTransactionError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}

impl From<redb::TableError> for FirestoreError {
    fn from(db_err: redb::TableError) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbTableError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}

impl From<redb::CommitError> for FirestoreError {
    fn from(db_err: redb::CommitError) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbCommitError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}

impl From<redb::StorageError> for FirestoreError {
    fn from(db_err: redb::StorageError) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbStorageError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}

impl From<redb::CompactionError> for FirestoreError {
    fn from(db_err: redb::CompactionError) -> Self {
        FirestoreError::CacheError(FirestoreCacheError::new(
            FirestoreErrorPublicGenericDetails::new("RedbCompactionError".into()),
            format!("Cache error: {db_err}"),
        ))
    }
}