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
use crate::{
database::Database,
error::{CouchError, CouchResult},
management::{ClusterSetup, ClusterSetupGetResponse, EnsureDbsExist, Membership},
types::system::{CouchResponse, CouchStatus, DbInfo},
};
use base64::engine::general_purpose;
use percent_encoding::{NON_ALPHANUMERIC, utf8_percent_encode};
use reqwest::{
Method, RequestBuilder, StatusCode, Url,
header::{self, CONTENT_TYPE, HeaderMap, HeaderValue, REFERER, USER_AGENT},
};
use std::{collections::HashMap, io::Write, time::Duration};
fn construct_json_headers(uri: Option<&str>) -> HeaderMap {
let mut headers = HeaderMap::new();
headers.insert(USER_AGENT, HeaderValue::from_static("reqwest"));
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
if let Some(u) = uri {
headers.insert(REFERER, HeaderValue::from_str(u).unwrap());
}
headers
}
fn parse_server(uri: &str) -> CouchResult<Url> {
let parsed_url = Url::parse(uri)?;
assert!(!parsed_url.cannot_be_a_base());
Ok(parsed_url)
}
pub(crate) async fn is_accepted(request: RequestBuilder) -> bool {
if let Ok(res) = request.send().await {
res.status() == StatusCode::ACCEPTED
} else {
false
}
}
pub(crate) async fn is_ok(request: RequestBuilder) -> bool {
if let Ok(res) = request.send().await {
let status = res.status();
status.is_success() || status == StatusCode::NOT_MODIFIED
} else {
false
}
}
/// Client handles the URI manipulation logic and the HTTP calls to the `CouchDB` REST API.
/// It is also responsible for the creation/access/destruction of databases.
#[derive(Debug, Clone)]
#[allow(clippy::struct_field_names)]
pub struct Client {
client: reqwest::Client,
_gzip: bool,
_timeout: Option<u64>,
uri: Url,
pub db_prefix: String,
}
const TEST_DB_HOST: &str = "http://localhost:5984";
const TEST_DB_USER: &str = "admin";
const TEST_DB_PW: &str = "password";
const DEFAULT_TIME_OUT: u64 = 10;
impl Client {
/// new creates a new Couch client with a default timeout of 10 seconds.
/// The timeout is applied from when the request starts connecting until the response body has finished.
/// The URI has to be in this format: <http://hostname:5984>, for example: <http://192.168.64.5:5984>
///
/// # Errors
/// Returns a `CouchError` if the URI is invalid.
pub fn new(uri: &str, username: &str, password: &str) -> CouchResult<Client> {
Client::new_with_timeout(uri, Some(username), Some(password), Some(DEFAULT_TIME_OUT))
}
/// `new_no_auth` creates a new Couch client with a default timeout of 10 seconds. *Without authentication*.
/// The timeout is applied from when the request starts connecting until the response body has finished.
/// The URI has to be in this format: <http://hostname:5984>, for example: <http://192.168.64.5:5984>
///
/// # Errors
/// Returns a `CouchError` if the URI is invalid.
pub fn new_no_auth(uri: &str) -> CouchResult<Client> {
Client::new_with_timeout(uri, None, None, Some(DEFAULT_TIME_OUT))
}
/// `new_local_test` creates a new Couch client *for testing purposes* with a default timeout of 10 seconds.
/// The timeout is applied from when the request starts connecting until the response body has finished.
/// The URI that will be used is: <http://hostname:5984>, with a username of "admin" and a password
/// of "password". Use this only for testing!!!
///
/// # Errors
/// Returns a `CouchError` if the URI is invalid.
pub fn new_local_test() -> CouchResult<Client> {
Client::new_with_timeout(
TEST_DB_HOST,
Some(TEST_DB_USER),
Some(TEST_DB_PW),
Some(DEFAULT_TIME_OUT),
)
}
/// `new_with_timeout` creates a new Couch client. The URI has to be in this format: <http://hostname:5984>,
/// The timeout is applied from when the request starts connecting until the response body has finished.
/// Timeout is in seconds.
///
/// # Panics
/// Panics when the AUTHORIZATION header can not be set on the request.
///
/// # Errors
/// Returns a `CouchError` if the URI is invalid.
pub fn new_with_timeout(
uri: &str,
username: Option<&str>,
password: Option<&str>,
timeout: Option<u64>,
) -> CouchResult<Client> {
let mut headers = HeaderMap::new();
if let Some(username) = username {
let mut header_value = b"Basic ".to_vec();
{
let mut encoder = base64::write::EncoderWriter::new(&mut header_value, &general_purpose::STANDARD);
// The unwraps here are fine because Vec::write* is infallible.
write!(encoder, "{username}:").unwrap();
if let Some(password) = password {
write!(encoder, "{password}").unwrap();
}
}
let auth_header = HeaderValue::from_bytes(&header_value).expect("can not set AUTHORIZATION header");
headers.insert(header::AUTHORIZATION, auth_header);
}
let mut client_builder = reqwest::Client::builder().default_headers(headers).gzip(true);
if let Some(t) = timeout {
client_builder = client_builder.timeout(Duration::new(t, 0));
}
let client = client_builder.build()?;
Ok(Client {
client,
uri: parse_server(uri)?,
_gzip: true,
_timeout: timeout,
db_prefix: String::new(),
})
}
pub fn get_self(&mut self) -> &mut Self {
self
}
/// Set the URI of the client
///
/// # Errors
/// Returns a `CouchError` if the URI is invalid.
pub fn set_uri(&mut self, uri: &str) -> CouchResult<&Self> {
self.uri = parse_server(uri)?;
Ok(self)
}
pub fn set_prefix(&mut self, prefix: String) -> &Self {
self.db_prefix = prefix;
self
}
/// List the databases in `CouchDB`
///
/// Usage:
/// ```
/// use std::error::Error;
///
/// const DB_HOST: &str = "http://localhost:5984";
/// const DB_USER: &str = "admin";
/// const DB_PW: &str = "password";
/// const TEST_DB: &str = "test_db";
///
/// #[tokio::main]
/// async fn main() -> Result<(), Box<dyn Error>> {
/// let client = couch_rs::Client::new(DB_HOST, DB_USER, DB_PW)?;
/// let db = client.db(TEST_DB).await?;
/// let dbs = client.list_dbs().await?;
/// dbs.iter().for_each(|db| println!("Database: {}", db));
/// Ok(())
/// }
///```
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn list_dbs(&self) -> CouchResult<Vec<String>> {
let response = self.get("/_all_dbs", None).send().await?;
let data = response.json().await?;
Ok(data)
}
fn build_dbname(&self, dbname: &str) -> String {
// percent encode the dbname to ensure special characters are not misinterpreted
let dbname = utf8_percent_encode(dbname, NON_ALPHANUMERIC).to_string();
format!("{}{}", self.db_prefix, dbname)
}
/// Connect to an existing database, or create a new one, when this one does not exist.
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn db(&self, dbname: &str) -> CouchResult<Database> {
let name = self.build_dbname(dbname);
let db = Database::new(name.clone(), self.clone());
let head_response = self
.head(&name, None)
.headers(construct_json_headers(None))
.send()
.await?;
match head_response.status() {
StatusCode::OK => Ok(db),
_ => self.make_db(dbname).await,
}
}
/// Create a new database with the given name
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn make_db(&self, dbname: &str) -> CouchResult<Database> {
let name = self.build_dbname(dbname);
let db = Database::new(name.clone(), self.clone());
let put_response = self
.put(&name, String::default())
.headers(construct_json_headers(None))
.send()
.await?;
let status = put_response.status();
let s: CouchResponse = put_response.json().await?;
if let Some(true) = s.ok {
Ok(db)
} else {
let err = s.error.unwrap_or_else(|| s!("unspecified error"));
Err(CouchError::new(err, status))
}
}
/// Destroy the database with the given name
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn destroy_db(&self, dbname: &str) -> CouchResult<bool> {
let response = self
.delete(&self.build_dbname(dbname), None)
.headers(construct_json_headers(None))
.send()
.await?;
let s: CouchResponse = response.json().await?;
Ok(s.ok.unwrap_or(false))
}
#[cfg(feature = "integration-tests")]
/// Checks if a database exists
///
/// Usage:
/// ```
/// use couch_rs::error::CouchResult;
///
/// const TEST_DB: &str = "test_db";
///
/// #[tokio::main]
/// async fn main() -> CouchResult<()> {
/// let client = couch_rs::Client::new_local_test()?;
/// let db = client.db(TEST_DB).await?;
///
/// if client.exists(TEST_DB).await? {
/// println!("The database exists");
/// }
///
/// return Ok(());
/// }
/// ```
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn exists(&self, dbname: &str) -> CouchResult<bool> {
let result = self.head(&self.build_dbname(dbname), None).send().await?;
Ok(result.status().is_success())
}
/// Gets information about the specified database.
/// See [common](https://docs.couchdb.org/en/stable/api/database/common.html) for more details.
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn get_info(&self, dbname: &str) -> CouchResult<DbInfo> {
let response = self
.get(&self.build_dbname(dbname), None)
.send()
.await?
.error_for_status()?;
let info = response.json().await?;
Ok(info)
}
/// Returns meta information about the instance. The response contains information about the server,
/// including a welcome message and the version of the server.
/// See [common](https://docs.couchdb.org/en/stable/api/server/common.html) for more details.
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn check_status(&self) -> CouchResult<CouchStatus> {
let response = self.get("", None).headers(construct_json_headers(None)).send().await?;
let status = response.json().await?;
Ok(status)
}
/// Returns membership information about the cluster.
/// See [_membership](https://docs.couchdb.org/en/latest/api/server/common.html?#membership) for more details.
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn membership(&self) -> CouchResult<Membership> {
let response = self.get("/_membership", None).send().await?;
let membership = response.json().await?;
Ok(membership)
}
/// Returns `cluster_setup` information about the cluster.
/// See [_cluster_setup](https://docs.couchdb.org/en/latest/api/server/common.html?#cluster-setup) for more details.
///
/// # Errors
/// Returns a `CouchError` if the request fails.
pub async fn cluster_setup(&self, request: EnsureDbsExist) -> CouchResult<ClusterSetup> {
let ensure_dbs_array = serde_json::to_value(&request.ensure_dbs_exist)?;
let ensure_dbs_arrays = serde_json::to_string(&ensure_dbs_array)?;
let response = self
.get("/_cluster_setup", None)
.query(&[("ensure_dbs_exist", &ensure_dbs_arrays)])
.send()
.await?;
let response: ClusterSetupGetResponse = response.json().await?;
Ok(response.state)
}
pub fn req(&self, method: Method, path: &str, opts: Option<&HashMap<String, String>>) -> RequestBuilder {
let mut uri = self.uri.clone();
uri.set_path(path);
if let Some(map) = opts {
let mut qp = uri.query_pairs_mut();
for (k, v) in map {
qp.append_pair(k, v);
}
}
self.client
.request(method, uri.as_str())
.headers(construct_json_headers(Some(uri.as_str())))
}
pub(crate) fn get(&self, path: &str, args: Option<&HashMap<String, String>>) -> RequestBuilder {
self.req(Method::GET, path, args)
}
pub(crate) fn post(&self, path: &str, body: String) -> RequestBuilder {
self.req(Method::POST, path, None).body(body)
}
pub(crate) fn put(&self, path: &str, body: String) -> RequestBuilder {
self.req(Method::PUT, path, None).body(body)
}
pub(crate) fn head(&self, path: &str, args: Option<&HashMap<String, String>>) -> RequestBuilder {
self.req(Method::HEAD, path, args)
}
pub(crate) fn delete(&self, path: &str, args: Option<&HashMap<String, String>>) -> RequestBuilder {
self.req(Method::DELETE, path, args)
}
}