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
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
470
471
472
473
474
475
476
477
478
479
480
use std::convert::TryInto;
use std::fmt::Debug;
use std::ops::{Deref, DerefMut};

use anyhow::Result;
use http::Uri;
use rand::Rng;
#[cfg(any(feature = "acl", feature = "slash-ql"))]
use tonic::codegen::InterceptedService;
use tonic::transport::{Channel, Endpoint};

use crate::api::dgraph_client::DgraphClient as DClient;
use crate::api::Version;
#[cfg(feature = "acl")]
pub use crate::client::acl::{
    AclClient, AclClientType, DgraphAclClient, TxnAcl, TxnAclBestEffort, TxnAclMutated,
    TxnAclReadOnly,
};
#[cfg(all(feature = "acl", feature = "tls"))]
pub use crate::client::acl::{
    AclTlsClient, TxnAclTls, TxnAclTlsBestEffort, TxnAclTlsMutated, TxnAclTlsReadOnly,
};
pub use crate::client::default::{
    Client, Http, LazyChannel, Txn, TxnBestEffort, TxnMutated, TxnReadOnly,
};
pub use crate::client::endpoints::Endpoints;
use crate::client::lazy::ILazyChannel;
pub(crate) use crate::client::lazy::ILazyClient;
#[cfg(feature = "slash-ql")]
pub use crate::client::slash_ql::{
    DgraphSlashQlClient, SlashQl, SlashQlClient, TxnSlashQl, TxnSlashQlBestEffort,
    TxnSlashQlMutated, TxnSlashQlReadOnly,
};
#[cfg(feature = "tls")]
pub use crate::client::tls::{
    Tls, TlsClient, TxnTls, TxnTlsBestEffort, TxnTlsMutated, TxnTlsReadOnly,
};
use crate::errors::ClientError;
use crate::stub::Stub;
use crate::{
    IDgraphClient, Operation, Payload, TxnBestEffortType, TxnMutatedType, TxnReadOnlyType, TxnType,
};

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

///
/// return random cloned item from vector
///
pub(crate) fn rnd_item<T: Clone>(items: &[T]) -> T {
    let mut rng = rand::thread_rng();
    let i = rng.gen_range(0..items.len());
    if let Some(item) = items.get(i) {
        item.to_owned()
    } else {
        unreachable!()
    }
}

///
/// Check if every endpoint is valid uri and also check if at least one endpoint is given
///
pub(crate) fn balance_list<U: TryInto<Uri>, E: Into<Endpoints<U>>>(
    endpoints: E,
) -> Result<Vec<Uri>> {
    let endpoints: Endpoints<U> = endpoints.into();
    let mut balance_list: Vec<Uri> = Vec::new();
    for maybe_endpoint in endpoints.endpoints {
        let endpoint = match maybe_endpoint.try_into() {
            Ok(endpoint) => endpoint,
            Err(_err) => {
                return Err(ClientError::InvalidEndpoint.into());
            }
        };
        balance_list.push(endpoint);
    }
    if balance_list.is_empty() {
        return Err(ClientError::NoEndpointsDefined.into());
    };
    Ok(balance_list)
}

///
/// Available types of DgraphClient
///
#[derive(Debug, Clone)]
pub enum DgraphClient {
    Default {
        client: DClient<Channel>,
    },
    #[cfg(feature = "acl")]
    Acl {
        client: DgraphAclClient,
    },
    #[cfg(feature = "slash-ql")]
    SlashQl {
        client: DgraphSlashQlClient,
    },
}

///
/// Dgraph client with interceptor
///
#[cfg(any(feature = "acl", feature = "slash-ql"))]
pub type DgraphInterceptorClient<T> = DClient<InterceptedService<Channel, T>>;

///
/// Allow custom configuration of endpoint
///
pub trait EndpointConfig: Send + Sync + Debug {
    fn configure_endpoint(&self, endpoint: Endpoint) -> Endpoint;
}

///
/// Marker for client variant implementation
///
pub trait IClient: Debug + Send + Sync {
    type Client: ILazyClient<Channel = Self::Channel>;
    type Channel: ILazyChannel;
    ///
    /// Return lazy Dgraph gRPC client
    ///
    fn client(&self) -> Self::Client;

    ///
    /// consume self and return all lazy clients
    ///
    fn clients(self) -> Vec<Self::Client>;
}

///
/// Client state.
///
#[derive(Debug, Default)]
pub struct ClientState;

impl ClientState {
    ///
    /// Create new client state
    ///
    pub fn new() -> Self {
        Self::default()
    }
}

///
/// Dgraph client has several variants which offer different behavior.
///
#[derive(Debug)]
pub struct ClientVariant<S: IClient> {
    state: Box<ClientState>,
    pub(crate) 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> {
        TxnType::new(self.any_stub())
    }

    ///
    /// 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 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()
    }

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

    ///
    /// 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::{Client, Operation};
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::{AclClientType, LazyChannel};
    ///
    /// #[cfg(not(feature = "acl"))]
    /// async fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// async fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").await.expect("Acl client")
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client().await;
    ///     let op = Operation {
    ///         schema: "name: string @index(exact) .".into(),
    ///         ..Default::default()
    ///     };
    ///     client.alter(op).await.expect("Schema is not updated");
    ///     Ok(())
    /// }
    /// ```
    ///
    pub async fn alter(&self, op: Operation) -> Result<Payload> {
        let mut stub = self.any_stub();
        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::{Client, Operation};
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::{AclClientType, LazyChannel};
    ///
    /// #[cfg(not(feature = "acl"))]
    /// async fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// async fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").await.expect("Acl client")
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client().await;
    ///     client.set_schema("name: string @index(exact) .").await.expect("Schema is not updated");
    ///     Ok(())
    /// }
    /// ```
    ///
    pub async fn set_schema<S: Into<String>>(&self, schema: S) -> Result<Payload> {
        let op = Operation {
            schema: schema.into(),
            ..Default::default()
        };
        self.alter(op).await
    }

    ///
    /// 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::{Client, Operation};
    /// #[cfg(feature = "acl")]
    /// use dgraph_tonic::{AclClientType, LazyChannel};
    ///
    /// #[cfg(not(feature = "acl"))]
    /// async fn client() -> Client {
    ///     Client::new("http://127.0.0.1:19080").expect("Dgraph client")
    /// }
    ///
    /// #[cfg(feature = "acl")]
    /// async fn client() -> AclClientType<LazyChannel> {
    ///     let default = Client::new("http://127.0.0.1:19080").unwrap();
    ///     default.login("groot", "password").await.expect("Acl client")
    /// }
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
    ///     let client = client().await;
    ///     client.set_schema_in_background("name: string @index(exact) .").await.expect("Schema is not updated");
    ///     Ok(())
    /// }
    /// ```
    ///
    #[cfg(any(feature = "dgraph-1-1", feature = "dgraph-21-03"))]
    pub async 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).await
    }

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

    ///
    /// Check DB version
    ///
    /// # Errors
    ///
    /// * gRPC error
    ///
    /// # Example
    ///
    /// ```
    /// use dgraph_tonic::{Client, Operation};
    ///
    /// #[tokio::main]
    /// async 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().await.expect("Version");
    ///     println!("{:#?}", version);
    ///     Ok(())
    /// }
    /// ```
    ///
    pub async fn check_version(&self) -> Result<Version> {
        let mut stub = self.any_stub();
        stub.check_version().await
    }
}

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

    use super::*;

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

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

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

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

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