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
mod auth;
mod model;
#[cfg(test)]
mod tests;
use failure::{format_err, Error};
use log::{error, info, trace};
use std::{collections::HashMap, sync::Arc};
use reqwest::{
header::{HeaderMap, AUTHORIZATION, SERVER},
Client, Url,
};
use serde_derive::Deserialize;
use self::auth::Auth;
use self::model::{DatabaseInfo, Version};
use super::database::Database;
use super::response::{serialize_response, try_serialize_response, Response};
#[derive(Debug)]
pub struct Connection {
session: Arc<Client>,
databases: HashMap<String, Database>,
arango_url: Url,
}
impl Connection {
pub fn validate_server(&self) -> Result<(), Error> {
validate_server(self.arango_url.as_str())
}
fn jwt_login<S: Into<String>>(&self, username: S, password: S) -> Result<String, Error> {
#[derive(Deserialize)]
struct JWT {
pub jwt: String,
}
let url = self.arango_url.join("/_open/auth").unwrap();
let mut map = HashMap::new();
map.insert("username", username.into());
map.insert("password", password.into());
let jwt: JWT = self.session.post(url).json(&map).send()?.json()?;
Ok(jwt.jwt)
}
pub fn establish<S: Into<String>>(arango_url: S, auth: Auth) -> Result<Connection, Error> {
let mut conn = Connection {
arango_url: Url::parse(arango_url.into().as_str())?.join("/").unwrap(),
..Default::default()
};
conn.validate_server()?;
let authorization = match auth {
Auth::Basic(credential) => {
let token =
base64::encode(&format!("{}:{}", credential.username, credential.password));
Some(format!("Basic {}", token))
}
Auth::Jwt(credential) => {
let token = conn.jwt_login(credential.username, credential.password)?;
Some(format!("Bearer {}", token))
}
Auth::None => None,
};
let mut headers = HeaderMap::new();
if let Some(value) = authorization {
headers.insert(AUTHORIZATION, value.parse().unwrap());
}
conn.session = Arc::new(
Client::builder()
.gzip(true)
.default_headers(headers)
.build()?,
);
conn.fetch_databases()?;
info!("Established");
Ok(conn)
}
pub fn establish_without_auth<S: Into<String>>(arango_url: S) -> Result<Connection, Error> {
trace!("Establish without auth");
Ok(Connection::establish(arango_url.into(), Auth::None)?)
}
pub fn establish_basic_auth<S: Into<String>>(
arango_url: S,
username: S,
password: S,
) -> Result<Connection, Error> {
trace!("Establish with basic auth");
Ok(Connection::establish(
arango_url.into(),
Auth::basic(username.into(), password.into()),
)?)
}
pub fn establish_jwt<S: Into<String>>(
arango_url: S,
username: S,
password: S,
) -> Result<Connection, Error> {
trace!("Establish with jwt");
Ok(Connection::establish(
arango_url.into(),
Auth::jwt(username.into(), password.into()),
)?)
}
pub fn get_url(&self) -> &Url {
&self.arango_url
}
pub fn get_session(&self) -> Arc<Client> {
Arc::clone(&self.session)
}
pub fn db(&self, name: &str) -> Option<&Database> {
match self.databases.get(name) {
Some(database) => Some(&database),
None => {
info!("Database {} not found.", name);
None
}
}
}
pub fn get_all_db(&self) -> HashMap<String, &Database> {
let mut databases: HashMap<String, &Database> = HashMap::new();
for (name, database) in self.databases.iter() {
databases.insert(name.to_owned(), database);
}
databases
}
fn fetch_databases(&mut self) -> Result<&mut Connection, Error> {
let url = self.arango_url.join("/_api/database/user").unwrap();
let resp = self.session.get(url).send()?;
let result: Vec<String> = serialize_response(resp)?;
trace!("Retrieved databases.");
for database_name in result.iter() {
self.databases.insert(
database_name.to_owned(),
Database::new(&self, database_name.as_str())?,
);
}
Ok(self)
}
pub fn fetch_arango_version(&self) -> Result<Version, Error> {
let url = self.arango_url.join("/_api/version").unwrap();
let version: Version = self.session.get(url).send()?.json()?;
Ok(version)
}
pub fn list_all_database(&self) -> Result<Vec<&String>, Error> {
let mut vec: Vec<&String> = Vec::new();
for key in self.databases.keys() {
vec.push(key);
}
Ok(vec)
}
pub fn fetch_current_database(&self) -> Result<DatabaseInfo, Error> {
let url = self.arango_url.join("/_api/database/current").unwrap();
let resp = self.session.get(url).send()?;
let result: DatabaseInfo = serialize_response(resp)?;
Ok(result)
}
pub fn create_database(&mut self, name: &str) -> Result<bool, Error> {
let mut map = HashMap::new();
map.insert("name", name);
let url = self.arango_url.join("/_api/database").unwrap();
let resp = self.session.post(url).json(&map).send()?;
let result: Response<bool> = try_serialize_response(resp);
match result {
Response::Ok(resp) => {
self.databases
.insert(name.to_owned(), Database::new(&self, name)?);
Ok(resp.result)
}
Response::Err(error) => Err(format_err!("{}", error.message)),
}
}
pub fn drop_database(&self, name: &str) -> Result<bool, Error> {
let url_path = format!("/_api/database/{}", name);
let url = self.arango_url.join(&url_path).unwrap();
let resp = self.session.delete(url).send()?;
let result: Response<bool> = try_serialize_response(resp);
match result {
Response::Ok(resp) => Ok(resp.result),
Response::Err(error) => Err(format_err!("{}", error.message)),
}
}
pub fn refresh(&mut self) -> Result<&mut Connection, Error> {
self.fetch_databases()
}
}
impl Default for Connection {
fn default() -> Connection {
Connection {
arango_url: Url::parse("http://127.0.0.1:8529").unwrap(),
databases: HashMap::new(),
session: Arc::new(Client::new()),
}
}
}
pub fn validate_server<'b>(arango_url: &'b str) -> Result<(), Error> {
let mut result = false;
let resp = reqwest::get(arango_url)?;
if resp.status().is_success() {
if let Some(server) = resp.headers().get(SERVER) {
let server_value = server.to_str().unwrap();
if server_value.eq_ignore_ascii_case("ArangoDB") {
result = true;
info!("Validate arangoDB server done.");
} else {
error!("In HTTP header, Server is {}", server_value);
}
} else {
error!("Fail to find Server in HTTP header");
}
}
if result == true {
Ok(())
} else {
Err(format_err!("Cannot find valid ArangoDB server"))
}
}