-
Notifications
You must be signed in to change notification settings - Fork 19
/
read-write-transactions.rs
116 lines (93 loc) · 3.15 KB
/
read-write-transactions.rs
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
use firestore::*;
use futures::stream::FuturesOrdered;
use futures::FutureExt;
use serde::{Deserialize, Serialize};
use tokio_stream::StreamExt;
pub fn config_env_var(name: &str) -> Result<String, String> {
std::env::var(name).map_err(|e| format!("{}: {}", name, e))
}
// Example structure to play with
#[derive(Debug, Clone, Deserialize, Serialize)]
struct MyTestStructure {
test_string: String,
}
const TEST_COLLECTION_NAME: &'static str = "test-rw-trans";
const TEST_DOCUMENT_ID: &str = "test_doc_id";
/// Creates a document with a counter set to 0 and then concurrently executes futures for `COUNT_ITERATIONS` iterations.
/// Finally, it reads the document again and verifies that the counter matches the expected number of iterations.
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
// Logging with debug enabled
let subscriber = tracing_subscriber::fmt()
.with_env_filter("firestore=debug")
.finish();
tracing::subscriber::set_global_default(subscriber)?;
// Create an instance
let db = FirestoreDb::new(&config_env_var("PROJECT_ID")?).await?;
const COUNT_ITERATIONS: usize = 50;
println!("Creating initial document...");
// Remove if it already exists
db.fluent()
.delete()
.from(TEST_COLLECTION_NAME)
.document_id(TEST_DOCUMENT_ID)
.execute()
.await?;
// Let's insert some data
let my_struct = MyTestStructure {
test_string: String::new(),
};
db.fluent()
.insert()
.into(TEST_COLLECTION_NAME)
.document_id(TEST_DOCUMENT_ID)
.object(&my_struct)
.execute()
.await?;
println!("Running transactions...");
let mut futures = FuturesOrdered::new();
for _ in 0..COUNT_ITERATIONS {
futures.push_back(update_value(&db));
}
futures.collect::<Vec<_>>().await;
println!("Testing results...");
let test_structure: MyTestStructure = db
.fluent()
.select()
.by_id_in(TEST_COLLECTION_NAME)
.obj()
.one(TEST_DOCUMENT_ID)
.await?
.expect("Missing document");
assert_eq!(test_structure.test_string.len(), COUNT_ITERATIONS);
Ok(())
}
async fn update_value(db: &FirestoreDb) -> FirestoreResult<()> {
db.run_transaction(|db, transaction| {
async move {
let mut test_structure: MyTestStructure = db
.fluent()
.select()
.by_id_in(TEST_COLLECTION_NAME)
.obj()
.one(TEST_DOCUMENT_ID)
.await?
.expect("Missing document");
// Perform some kind of operation that depends on the state of the document
test_structure.test_string += "a";
db.fluent()
.update()
.fields(paths!(MyTestStructure::{
test_string
}))
.in_col(TEST_COLLECTION_NAME)
.document_id(TEST_DOCUMENT_ID)
.object(&test_structure)
.add_to_transaction(transaction)?;
Ok(())
}
.boxed()
})
.await?;
Ok(())
}