1extern crate rand;
2
3use crate::client_stub::DgraphClientStub;
4use crate::types::Operation;
5use std::error::Error;
6use std::fmt;
7use rand::Rng;
8use crate::txn::Txn;
9use std::time::SystemTime;
10
11#[derive(Debug, Clone)]
12pub struct NoClients {}
13
14impl fmt::Display for NoClients {
15 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
16 write!(f, "ERR_NO_CLIENTS")
17 }
18}
19
20impl Error for NoClients {
21 fn description(&self) -> &str {
22 "No clients provided in DgraphClient constructor"
23 }
24
25 fn cause(&self) -> Option<&Error> {
26 None
28 }
29}
30
31fn no_clients_error() -> NoClients {
32 let err = NoClients {};
33 err
34}
35
36pub struct DgraphClient {
37 clients: Vec<DgraphClientStub>,
38 debug_mode: bool,
39}
40
41impl DgraphClient {
42 pub fn any_client(&self) -> &DgraphClientStub {
43 let mut rng = rand::thread_rng();
44 let i = rng.gen_range(0, self.clients.len());
45 let client = self.clients.get(i).unwrap();
46 client
47 }
48
49 pub fn new(clients: Vec<DgraphClientStub>) -> Result<DgraphClient, Box<Error>> {
50 if clients.len() == 0 {
51 Err(Box::new(no_clients_error()))
52 } else {
53 Ok(DgraphClient {
54 clients,
55 debug_mode: false,
56 })
57 }
58 }
59
60 pub fn alter(&self, op: Operation) -> Result<String, Box<Error>> {
61 self.debug(format!("Alter request: {:?}", op));
62 let client = self.any_client();
63 let start_time = SystemTime::now();
64 let result = client.alter(op);
65 self.debug(format!("Alter request {:?}", start_time.elapsed()?.subsec_nanos()));
66 result
67 }
68
69 pub fn new_txn(&self) -> Txn {
70 Txn::new(&self)
71 }
72
73 pub fn set_debug_mode(&mut self, debug_mode: bool) {
74 self.debug_mode = debug_mode;
75 }
76
77 pub fn debug(&self, message: String) {
78 if self.debug_mode == true {
79 println!("{}", message);
80 }
81 }
82}