dgraph-tonic 0.11.0

A rust async/sync client for Dgraph database build with Tonic crate
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
use std::fmt::Debug;
use std::ops::{Deref, DerefMut};
use std::sync::Arc;

use anyhow::Result;
use async_trait::async_trait;
use lazy_static::lazy_static;
use tokio::runtime::Runtime;

use crate::api::IDgraphClient;
use crate::client::lazy::ILazyChannel;
#[cfg(feature = "acl")]
use crate::client::AclClientType as AsyncAclClient;
use crate::client::ILazyClient;
use crate::stub::Stub;
#[cfg(feature = "acl")]
pub use crate::sync::client::acl::{
    AclClient, AclClientType, TxnAcl, TxnAclBestEffort, TxnAclMutated, TxnAlcReadOnly,
};
#[cfg(all(feature = "acl", feature = "tls"))]
pub use crate::sync::client::acl::{
    AclTlsClient, TxnAclTls, TxnAclTlsBestEffort, TxnAclTlsMutated, TxnAclTlsReadOnly,
};
pub use crate::sync::client::default::{Client, Txn, TxnBestEffort, TxnMutated, TxnReadOnly};
#[cfg(feature = "slash-ql")]
pub use crate::sync::client::slash_ql::{
    SlashQl, SlashQlClient, TxnSlashQl, TxnSlashQlBestEffort, TxnSlashQlMutated, TxnSlashQlReadOnly,
};
#[cfg(feature = "tls")]
pub use crate::sync::client::tls::{
    TlsClient, TxnTls, TxnTlsBestEffort, TxnTlsMutated, TxnTlsReadOnly,
};
use crate::sync::txn::{TxnBestEffortType, TxnMutatedType, TxnReadOnlyType, TxnType};
use crate::txn::TxnType as AsyncTxn;
use crate::{Operation, Payload, Version};

#[cfg(feature = "acl")]
mod acl;
mod default;
#[cfg(feature = "slash-ql")]
mod slash_ql;
#[cfg(feature = "tls")]
mod tls;

lazy_static! {
    static ref RT: Arc<Runtime> = Arc::new(Runtime::new().expect("Tokio runtime"));
}

///
/// Client state.
///
#[derive(Debug)]
pub struct ClientState {
    rt: Arc<Runtime>,
}

impl ClientState {
    ///
    /// Create new client state with default async implementation
    ///
    pub fn new() -> Self {
        Self {
            rt: Arc::clone(&*RT),
        }
    }
}

impl Default for ClientState {
    fn default() -> Self {
        Self::new()
    }
}

#[async_trait]
pub trait IClient {
    type AsyncClient;
    type Client: ILazyClient<Channel = Self::Channel>;
    type Channel: ILazyChannel;

    fn client(&self) -> Self::Client;

    fn clients(self) -> Vec<Self::Client>;

    fn async_client_ref(&self) -> &Self::AsyncClient;

    fn async_client(self) -> Self::AsyncClient;

    fn new_txn(&self) -> AsyncTxn<Self::Client>;

    #[cfg(feature = "acl")]
    async fn login<T: Into<String> + Send + Sync>(
        self,
        user_id: T,
        password: T,
    ) -> Result<AsyncAclClient<Self::Channel>>;

    #[cfg(all(feature = "acl", feature = "dgraph-21-03"))]
    async fn login_into_namespace<T: Into<String> + Send + Sync>(
        self,
        user_id: T,
        password: T,
        namespace: u64,
    ) -> Result<AsyncAclClient<Self::Channel>>;
}

///
/// Dgraph client has several variants which offer different behavior.
///
pub struct ClientVariant<S: IClient> {
    state: Box<ClientState>,
    extra: S,
}

impl<S: IClient> Deref for ClientVariant<S> {
    type Target = Box<ClientState>;

    fn deref(&self) -> &Self::Target {
        &self.state
    }
}

impl<S: IClient> DerefMut for ClientVariant<S> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.state
    }
}

impl<C: IClient> ClientVariant<C> {
    ///
    /// Return new stub with grpc client implemented according to actual variant.
    ///
    fn any_stub(&self) -> Stub<C::Client> {
        Stub::new(self.extra.client())
    }

    ///
    /// Return transaction in default state, which can be specialized into ReadOnly or Mutated
    ///
    pub fn new_txn(&self) -> TxnType<C::Client> {
        let rt = Arc::clone(&self.rt);
        let async_txn = self.extra.new_txn();
        TxnType::new(rt, async_txn)
    }

    ///
    /// Create new transaction which can only do queries.
    ///
    /// Read-only transactions are useful to increase read speed because they can circumvent the
    /// usual consensus protocol.
    ///
    pub fn new_read_only_txn(&self) -> TxnReadOnlyType<C::Client> {
        self.new_txn().read_only()
    }

    ///
    /// Create new transaction which can do mutate, commit and discard operations
    ///
    pub fn new_mutated_txn(&self) -> TxnMutatedType<C::Client> {
        self.new_txn().mutated()
    }

    ///
    /// Create new transaction which can only do queries in best effort mode.
    ///
    /// Read-only queries can optionally be set as best-effort. Using this flag will ask the
    /// Dgraph Alpha to try to get timestamps from memory on a best-effort basis to reduce the number
    /// of outbound requests to Zero. This may yield improved latencies in read-bound workloads where
    /// linearizable reads are not strictly needed.
    ///
    pub fn new_best_effort_txn(&self) -> TxnBestEffortType<C::Client> {
        self.new_read_only_txn().best_effort()
    }

    ///
    /// The /alter endpoint is used to create or change the schema.
    ///
    /// # Arguments
    ///
    /// - `op`: Alter operation
    ///
    /// # Errors
    ///
    /// * gRPC error
    /// * DB reject alter command
    ///
    /// # Example
    ///
    /// Install a schema into dgraph. A `name` predicate is string type and has exact index.
    ///
    /// ```
    /// use dgraph_tonic::Operation;
    /// use dgraph_tonic::sync::Client;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::sync::AclClientType;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::LazyChannel;
    ///
    /// #[cfg(not(feature = "acl"))]
    /// fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").expect("Acl client")
    /// }
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client();
    ///     let op = Operation {
    ///         schema: "name: string @index(exact) .".into(),
    ///         ..Default::default()
    ///     };
    ///     client.alter(op).expect("Schema is not updated");
    ///     Ok(())
    /// }
    /// ```
    ///
    pub fn alter(&self, op: Operation) -> Result<Payload> {
        let mut stub = self.any_stub();
        self.rt.block_on(async move { stub.alter(op).await })
    }

    ///
    /// Create or change the schema.
    ///
    /// # Arguments
    ///
    /// - `schema`: Schema modification
    ///
    /// # Errors
    ///
    /// * gRPC error
    /// * DB reject alter command
    ///
    /// # Example
    ///
    /// Install a schema into dgraph. A `name` predicate is string type and has exact index.
    ///
    /// ```
    /// use dgraph_tonic::Operation;
    /// use dgraph_tonic::sync::Client;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::sync::AclClientType;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::LazyChannel;
    ///
    /// #[cfg(not(feature = "acl"))]
    /// fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").expect("Acl client")
    /// }
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client();
    ///     client.set_schema("name: string @index(exact) .").expect("Schema is not updated");
    ///     Ok(())
    /// }
    /// ```
    ///
    pub fn set_schema<S: Into<String>>(&self, schema: S) -> Result<Payload> {
        let op = Operation {
            schema: schema.into(),
            ..Default::default()
        };
        self.alter(op)
    }

    ///
    /// Create or change the schema in background.
    ///
    /// # Arguments
    ///
    /// - `schema`: Schema modification
    ///
    /// # Errors
    ///
    /// * gRPC error
    /// * DB reject alter command
    ///
    /// # Example
    ///
    /// Install a schema into dgraph. A `name` predicate is string type and has exact index.
    ///
    /// ```
    /// use dgraph_tonic::Operation;
    /// use dgraph_tonic::sync::Client;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::sync::AclClientType;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::LazyChannel;
    ///
    /// #[cfg(not(feature = "acl"))]
    /// fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").expect("Acl client")
    /// }
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client();
    ///     client.set_schema_in_background("name: string @index(exact) .").expect("Schema is not updated");
    ///     Ok(())
    /// }
    /// ```
    ///
    #[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
    pub fn set_schema_in_background<S: Into<String>>(&self, schema: S) -> Result<Payload> {
        let op = Operation {
            schema: schema.into(),
            run_in_background: true,
            ..Default::default()
        };
        self.alter(op)
    }

    ///
    /// Drop all data in DB
    ///
    ///
    /// # Errors
    ///
    /// * gRPC error
    /// * DB reject alter command
    ///
    /// # Example
    ///
    ///
    /// ```
    /// use dgraph_tonic::sync::Client;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::sync::AclClientType;
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::LazyChannel;
    ///
    /// #[cfg(not(feature = "acl"))]
    /// fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").expect("Acl client")
    /// }
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client();
    ///     client.drop_all().expect("Data not dropped");
    ///     Ok(())
    /// }
    /// ```
    ///
    pub fn drop_all(&self) -> Result<Payload> {
        let op = Operation {
            drop_all: true,
            ..Default::default()
        };
        self.alter(op)
    }

    ///
    /// Check DB version
    ///
    /// # Errors
    ///
    /// * gRPC error
    ///
    /// # Example
    ///
    /// ```
    /// use dgraph_tonic::Operation;
    /// use dgraph_tonic::sync::Client;
    ///
    /// fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = Client::new(vec!["http://127.0.0.1:19080"]).expect("Dgraph client");
    ///     let version = client.check_version().expect("Version");
    ///     println!("{:#?}", version);
    ///     Ok(())
    /// }
    /// ```
    ///
    pub fn check_version(&self) -> Result<Version> {
        let mut stub = self.any_stub();
        self.rt.block_on(async move { stub.check_version().await })
    }
}

#[cfg(test)]
mod tests {
    #[cfg(feature = "acl")]
    use crate::client::LazyChannel;

    use super::*;

    #[cfg(not(feature = "acl"))]
    fn client() -> Client {
        Client::new("http://127.0.0.1:19080").unwrap()
    }

    #[cfg(feature = "acl")]
    fn client() -> AclClientType<LazyChannel> {
        let default = Client::new("http://127.0.0.1:19080").unwrap();
        default.login("groot", "password").unwrap()
    }

    #[test]
    fn alter() {
        let client = client();
        let op = Operation {
            schema: "name: string @index(exact) .".into(),
            ..Default::default()
        };
        let response = client.alter(op);
        assert!(response.is_ok());
    }

    #[test]
    fn drop_all() {
        let client = client();
        let response = client.drop_all();
        assert!(response.is_ok());
    }

    #[test]
    fn check_version() {
        let client = client();
        let response = client.check_version();
        assert!(response.is_ok());
    }
}