/
firestore_rpc.rs
333 lines (302 loc) · 10.4 KB
/
firestore_rpc.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
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
pub mod google {
pub mod api {
include!("firestore_rpc/google.api.rs");
}
pub mod firestore {
pub mod v1 {
include!("firestore_rpc/google.firestore.v1.rs");
}
}
pub mod protobuf {
include!("firestore_rpc/google.protobuf.rs");
}
pub mod r#type {
include!("firestore_rpc/google.r#type.rs");
}
pub mod rpc {
include!("firestore_rpc/google.rpc.rs");
}
}
pub mod helper {
use super::google::firestore::v1::{
firestore_client::FirestoreClient, value::ValueType, Document, Value,
};
use google_cloud_auth::{Credential, CredentialConfig};
use prost_types::Timestamp;
use tonic::{
codegen::InterceptedService,
metadata::AsciiMetadataValue,
transport::{Channel, ClientTlsConfig, Endpoint},
Request, Status,
};
pub mod path {
/// ```rust
/// # use db::firestore_rpc::helper::path::database_path;
/// assert_eq!(database_path("1", "2"), "projects/1/databases/2");
/// ```
pub fn database_path(project_id: &str, database_id: &str) -> String {
format!("projects/{}/databases/{}", project_id, database_id)
}
/// ```rust
/// # use db::firestore_rpc::helper::path::documents_path;
/// assert_eq!(documents_path("1", "2"), "projects/1/databases/2/documents");
/// ```
pub fn documents_path(project_id: &str, database_id: &str) -> String {
format!(
"projects/{}/databases/{}/documents",
project_id, database_id
)
}
/// ```rust
/// # use db::firestore_rpc::helper::path::collection_path;
/// assert_eq!(collection_path("1", "2", "3"), "projects/1/databases/2/documents/3");
/// ```
pub fn collection_path(project_id: &str, database_id: &str, collection_id: &str) -> String {
format!(
"projects/{}/databases/{}/documents/{}",
project_id, database_id, collection_id
)
}
/// ```rust
/// # use db::firestore_rpc::helper::path::document_path;
/// assert_eq!(document_path("1", "2", "3", "4"), "projects/1/databases/2/documents/3/4");
/// ```
pub fn document_path(
project_id: &str,
database_id: &str,
collection_id: &str,
document_id: &str,
) -> String {
format!(
"projects/{}/databases/{}/documents/{}/{}",
project_id, database_id, collection_id, document_id
)
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("google_cloud_auth {0}")]
GoogleCloudAuth(#[from] google_cloud_auth::Error),
#[error("status {0}")]
Status(#[from] Status),
#[error("tonic invalid metadata value {0}")]
TonicInvalidMetadataValue(#[from] tonic::metadata::errors::InvalidMetadataValue),
#[error("transport {0}")]
TonicTransport(#[from] tonic::transport::Error),
}
pub async fn client(
credential: &Credential,
) -> Result<
FirestoreClient<
InterceptedService<Channel, impl Fn(Request<()>) -> Result<Request<()>, Status>>,
>,
Error,
> {
let access_token = credential.access_token().await?;
let channel = Endpoint::from_static("https://firestore.googleapis.com")
.tls_config(ClientTlsConfig::new().domain_name("firestore.googleapis.com"))?
.connect()
.await?;
let mut metadata_value =
AsciiMetadataValue::try_from(format!("Bearer {}", access_token.value))?;
metadata_value.set_sensitive(true);
let client = FirestoreClient::with_interceptor(channel, move |mut request: Request<()>| {
request
.metadata_mut()
.insert("authorization", metadata_value.clone());
Ok(request)
});
Ok(client)
}
pub async fn credential() -> Result<Credential, Error> {
let config = CredentialConfig::builder()
.scopes(vec!["https://www.googleapis.com/auth/cloud-platform".into()])
.build()?;
Ok(Credential::find_default(config).await?)
}
pub fn get_field_as_i64(document: &Document, key: &str) -> Option<i64> {
document.fields.get(key).map(value_into_i64_unchecked)
}
pub fn get_field_as_str<'a>(document: &'a Document, key: &'a str) -> Option<&'a str> {
document.fields.get(key).map(value_as_str_unchecked)
}
pub fn get_field_as_timestamp(document: &Document, key: &str) -> Option<Timestamp> {
document.fields.get(key).map(value_to_timestamp_unchecked)
}
// panic if value_type is not string
pub fn value_as_str_unchecked(value: &Value) -> &str {
match value.value_type.as_ref() {
Some(ValueType::StringValue(s)) => s.as_str(),
_ => unreachable!(),
}
}
pub fn value_from_i64(i: i64) -> Value {
Value {
value_type: Some(ValueType::IntegerValue(i)),
}
}
pub fn value_from_string(s: String) -> Value {
Value {
value_type: Some(ValueType::StringValue(s)),
}
}
pub fn value_from_timestamp(t: Timestamp) -> Value {
Value {
value_type: Some(ValueType::TimestampValue(t)),
}
}
// panic if value_type is not integer
pub fn value_into_i64_unchecked(value: &Value) -> i64 {
match value.value_type {
Some(ValueType::IntegerValue(i)) => i,
_ => unreachable!(),
}
}
// panic if value_type is not string
pub fn value_into_string_unchecked(value: Value) -> String {
match value.value_type {
Some(ValueType::StringValue(s)) => s,
_ => unreachable!(),
}
}
// panic if value_type is not string
pub fn value_to_timestamp_unchecked(value: &Value) -> Timestamp {
match value.value_type.as_ref() {
Some(ValueType::TimestampValue(t)) => t.clone(),
_ => unreachable!(),
}
}
#[cfg(test)]
mod tests {
use std::{collections::HashMap, str::FromStr};
use crate::firestore_rpc::google::firestore::v1::Document;
use super::*;
#[test]
fn get_field_as_i64_test() {
assert_eq!(
get_field_as_i64(
&Document {
name: "name".to_owned(),
fields: {
let mut fields = HashMap::new();
fields.insert("key".to_owned(), value_from_i64(123));
fields
},
create_time: None,
update_time: None
},
"key"
),
Some(123)
);
}
#[test]
fn get_field_as_str_test() {
assert_eq!(
get_field_as_str(
&Document {
name: "name".to_owned(),
fields: {
let mut fields = HashMap::new();
fields.insert("key".to_owned(), value_from_string("val".to_owned()));
fields
},
create_time: None,
update_time: None
},
"key"
),
Some("val")
);
}
#[test]
fn get_field_as_timestamp_test() -> anyhow::Result<()> {
let timestamp = Timestamp::from_str("2020-01-02T15:04:05Z")?;
assert_eq!(
get_field_as_timestamp(
&Document {
name: "name".to_owned(),
fields: {
let mut fields = HashMap::new();
fields
.insert("key".to_owned(), value_from_timestamp(timestamp.clone()));
fields
},
create_time: None,
update_time: None
},
"key"
),
Some(timestamp)
);
Ok(())
}
#[test]
fn value_as_str_unchecked_test() {
assert_eq!(
value_as_str_unchecked(&Value {
value_type: Some(ValueType::StringValue("abc".to_owned())),
}),
"abc"
);
}
#[test]
fn value_from_i64_test() {
assert_eq!(
value_from_i64(123),
Value {
value_type: Some(ValueType::IntegerValue(123))
}
);
}
#[test]
fn value_from_string_test() {
assert_eq!(
value_from_string("abc".to_owned()),
Value {
value_type: Some(ValueType::StringValue("abc".to_owned()))
}
);
}
#[test]
fn value_from_timestamp_test() -> anyhow::Result<()> {
let timestamp = Timestamp::from_str("2020-01-02T15:04:05Z")?;
assert_eq!(
value_from_timestamp(timestamp.clone()),
Value {
value_type: Some(ValueType::TimestampValue(timestamp))
}
);
Ok(())
}
#[test]
fn value_into_i64_unchecked_test() {
assert_eq!(
value_into_i64_unchecked(&Value {
value_type: Some(ValueType::IntegerValue(123)),
}),
123
);
}
#[test]
fn value_into_string_unchecked_test() {
assert_eq!(
value_into_string_unchecked(Value {
value_type: Some(ValueType::StringValue("abc".to_owned())),
}),
"abc".to_owned()
);
}
#[test]
fn value_to_timestamp_unchecked_test() -> anyhow::Result<()> {
let timestamp = Timestamp::from_str("2020-01-02T15:04:05Z")?;
assert_eq!(
value_to_timestamp_unchecked(&Value {
value_type: Some(ValueType::TimestampValue(timestamp.clone())),
}),
timestamp
);
Ok(())
}
}
}