-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.rs
302 lines (284 loc) · 9.51 KB
/
client.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
use google_api_proto::google::firestore::v1::{
firestore_client::FirestoreClient,
precondition::ConditionType,
value::ValueType,
write::{self, Operation},
BeginTransactionRequest, BeginTransactionResponse, CommitRequest, CommitResponse,
CreateDocumentRequest, DeleteDocumentRequest, Document as FirestoreDocument,
GetDocumentRequest, ListDocumentsRequest, ListDocumentsResponse, MapValue, Precondition,
RollbackRequest, UpdateDocumentRequest, Write,
};
use google_authz::{Credentials, GoogleAuthz};
use serde::{de::DeserializeOwned, Serialize};
use serde_firestore_value::to_value;
use tonic::transport::Channel;
use crate::infra::firestore::document;
use super::{
document::Document,
path::{self, CollectionPath, DocumentPath, RootPath},
timestamp::Timestamp,
};
pub struct Transaction {
transaction: prost::bytes::Bytes,
writes: Vec<Write>,
}
impl Transaction {
pub fn create<T>(&mut self, document_path: &DocumentPath, fields: T) -> Result<(), Error>
where
T: Serialize,
{
self.writes.push(Write {
operation: Some(Operation::Update(FirestoreDocument {
name: document_path.path(),
fields: {
let ser = to_value(&fields)?;
if let Some(ValueType::MapValue(MapValue { fields })) = ser.value_type {
fields
} else {
return Err(Error::ValueType);
}
},
create_time: None,
update_time: None,
})),
update_mask: None,
update_transforms: vec![],
current_document: Some(Precondition {
condition_type: Some(ConditionType::Exists(false)),
}),
});
Ok(())
}
pub fn delete(
&mut self,
document_path: &DocumentPath,
current_update_time: Timestamp,
) -> Result<(), Error> {
self.writes.push(Write {
operation: Some(Operation::Delete(document_path.path())),
update_mask: None,
update_transforms: vec![],
current_document: Some(Precondition {
condition_type: Some(ConditionType::UpdateTime(prost_types::Timestamp::from(
current_update_time,
))),
}),
});
Ok(())
}
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("credentials {0}")]
Credentials(#[from] google_authz::CredentialsError),
#[error("deserialize {0}")]
Deserialize(#[from] document::Error),
#[error("path {0}")]
Path(#[from] path::Error),
#[error("serialize {0}")]
Serialize(#[from] serde_firestore_value::Error),
#[error("status {0}")]
Status(#[from] tonic::Status),
#[error("transport {0}")]
Transport(#[from] tonic::transport::Error),
#[error("value_type")]
ValueType,
}
pub struct Client {
client: FirestoreClient<GoogleAuthz<Channel>>,
root_path: RootPath,
}
impl Client {
// TODO: rollback
// TODO: run_query
pub async fn new(
project_id: String,
database_id: String,
endpoint: &'static str,
) -> Result<Self, Error> {
let credentials = Credentials::builder().no_credentials().build().await?;
let channel = Channel::from_static(endpoint).connect().await?;
let channel = GoogleAuthz::builder(channel)
.credentials(credentials)
.build()
.await;
let client = FirestoreClient::new(channel);
let root_path = RootPath::new(project_id, database_id)?;
Ok(Self { client, root_path })
}
pub async fn begin_transaction(&mut self) -> Result<Transaction, Error> {
let response = self
.client
.begin_transaction(BeginTransactionRequest {
database: self.root_path.database_name(),
options: None,
})
.await?;
let BeginTransactionResponse { transaction } = response.into_inner();
Ok(Transaction {
transaction,
writes: vec![],
})
}
pub fn collection(&self, collection_id: String) -> CollectionPath {
self.root_path.clone().collection(collection_id)
}
pub async fn commit(
&mut self,
transaction: Transaction,
) -> Result<((), Option<Timestamp>), Error> {
let response = self
.client
.commit(CommitRequest {
database: self.root_path.database_name(),
writes: transaction.writes,
transaction: transaction.transaction,
})
.await?;
// TODO: write_results
let CommitResponse { commit_time, .. } = response.into_inner();
Ok(((), commit_time.map(Timestamp::from)))
}
pub async fn create<T, U>(
&mut self,
document_path: &DocumentPath,
fields: T,
) -> Result<Document<U>, Error>
where
T: Serialize,
U: DeserializeOwned,
{
let response = self
.client
.create_document(CreateDocumentRequest {
parent: document_path.parent().parent().path(),
collection_id: document_path.parent().id().to_string(),
document_id: document_path.id().to_string(),
document: Some(FirestoreDocument {
name: "".to_string(),
fields: {
let ser = to_value(&fields)?;
if let Some(ValueType::MapValue(MapValue { fields })) = ser.value_type {
fields
} else {
return Err(Error::ValueType);
}
},
create_time: None,
update_time: None,
}),
mask: None,
})
.await?;
Document::new(response.into_inner()).map_err(Error::Deserialize)
}
pub async fn delete(
&mut self,
document_path: &DocumentPath,
current_update_time: Timestamp,
) -> Result<(), Error> {
self.client
.delete_document(DeleteDocumentRequest {
name: document_path.path(),
current_document: Some(Precondition {
condition_type: Some(ConditionType::UpdateTime(prost_types::Timestamp::from(
current_update_time,
))),
}),
})
.await?;
Ok(())
}
pub async fn get<U>(
&mut self,
document_path: &DocumentPath,
// TODO: support transaction
) -> Result<Document<U>, Error>
where
U: DeserializeOwned,
{
let response = self
.client
.get_document(GetDocumentRequest {
name: document_path.path(),
mask: None,
consistency_selector: None,
})
.await?;
Document::new(response.into_inner()).map_err(Error::Deserialize)
}
// TODO: support some params
pub async fn list<U>(
&mut self,
collection_path: &CollectionPath,
) -> Result<(Vec<Document<U>>, String), Error>
where
U: DeserializeOwned,
{
let response = self
.client
.list_documents(ListDocumentsRequest {
parent: collection_path.parent().path(),
collection_id: collection_path.id().to_string(),
page_size: 100,
..Default::default()
})
.await?;
let ListDocumentsResponse {
documents,
next_page_token,
} = response.into_inner();
documents
.into_iter()
.map(Document::new)
.collect::<Result<Vec<Document<U>>, document::Error>>()
.map_err(Error::Deserialize)
.map(|documents| (documents, next_page_token))
}
pub async fn rollback(&mut self, transaction: Transaction) -> Result<(), Error> {
self.client
.rollback(RollbackRequest {
database: self.root_path.database_name(),
transaction: transaction.transaction,
})
.await?;
Ok(())
}
pub async fn update<T, U>(
&mut self,
document_path: &DocumentPath,
fields: T,
current_update_time: Timestamp,
) -> Result<Document<U>, Error>
where
T: Serialize,
U: DeserializeOwned,
{
let response = self
.client
.update_document(UpdateDocumentRequest {
document: Some(FirestoreDocument {
name: document_path.path(),
fields: {
let ser = to_value(&fields)?;
if let Some(ValueType::MapValue(MapValue { fields })) = ser.value_type {
fields
} else {
return Err(Error::ValueType);
}
},
create_time: None,
update_time: None,
}),
update_mask: None,
mask: None,
current_document: Some(Precondition {
condition_type: Some(ConditionType::UpdateTime(prost_types::Timestamp::from(
current_update_time,
))),
}),
})
.await?;
Document::new(response.into_inner()).map_err(Error::Deserialize)
}
}