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
//! Main client for communicating with the Toxiproxy server.
use serde_json;
use std::net::ToSocketAddrs;
use std::sync::{Arc, Mutex};
use std::{collections::HashMap, io::Read};
use super::http_client::*;
use super::proxy::*;
/// Server client.
#[derive(Clone)]
pub struct Client {
client: Arc<Mutex<HttpClient>>,
}
impl Client {
/// Creates a new client. There is also a prepopulated client, `toxiproxy_rust::TOXIPROXY`
/// connected to the server's default address.
///
/// # Examples
///
/// ```
/// # use toxiproxy_rust::client::Client;
/// let client = Client::new("127.0.0.1:8474");
/// ```
pub fn new<U: ToSocketAddrs>(toxiproxy_addr: U) -> Self {
Self {
client: Arc::new(Mutex::new(HttpClient::new(toxiproxy_addr))),
}
}
/// Establish a set of proxies to work with.
///
/// # Examples
///
/// ```
/// # use toxiproxy_rust::client::Client;
/// # use toxiproxy_rust::proxy::ProxyPack;
/// let client = Client::new("127.0.0.1:8474");
/// let proxies = client.populate(vec![ProxyPack::new(
/// "socket".into(),
/// "localhost:2001".into(),
/// "localhost:2000".into(),
/// )]).expect("populate has completed");
/// ```
///
/// ```
/// let proxies = toxiproxy_rust::TOXIPROXY.populate(vec![toxiproxy_rust::proxy::ProxyPack::new(
/// "socket".into(),
/// "localhost:2001".into(),
/// "localhost:2000".into(),
/// )]).expect("populate has completed");
/// ```
pub fn populate(&self, proxies: Vec<ProxyPack>) -> Result<Vec<Proxy>, String> {
let proxies_json = serde_json::to_string(&proxies).unwrap();
self.client
.lock()
.map_err(|err| format!("lock error: {}", err))?
.post_with_data("populate", proxies_json)
.and_then(|response| {
response
.json::<HashMap<String, Vec<ProxyPack>>>()
.map_err(|err| format!("json deserialize failed: {}", err))
})
.map(|ref mut response_obj| response_obj.remove("proxies").unwrap_or(vec![]))
.map(|proxy_packs| {
proxy_packs
.into_iter()
.map(|proxy_pack| Proxy::new(proxy_pack, self.client.clone()))
.collect::<Vec<Proxy>>()
})
}
/// Enable all proxies and remove all active toxics.
///
/// # Examples
///
/// ```
/// # use toxiproxy_rust::client::Client;
/// # use toxiproxy_rust::proxy::ProxyPack;
/// let client = Client::new("127.0.0.1:8474");
/// client.reset();
/// ```
///
/// ```
/// toxiproxy_rust::TOXIPROXY.reset();
/// ```
pub fn reset(&self) -> Result<(), String> {
self.client
.lock()
.map_err(|err| format!("lock error: {}", err))?
.post("reset")
.map(|_| ())
}
/// Returns all registered proxies and their toxics.
///
/// # Examples
///
/// ```
/// let proxies = toxiproxy_rust::TOXIPROXY.all().expect("all proxies were fetched");
/// ```
pub fn all(&self) -> Result<HashMap<String, Proxy>, String> {
self.client
.lock()
.map_err(|err| format!("lock error: {}", err))?
.get("proxies")
.and_then(|response| {
response
.json()
.map(|proxy_map: HashMap<String, ProxyPack>| {
proxy_map
.into_iter()
.map(|(name, proxy_pack)| {
(name, Proxy::new(proxy_pack, self.client.clone()))
})
.collect()
})
.map_err(|err| format!("json deserialize failed: {}", err))
})
}
/// Health check for the Toxiproxy server.
///
/// # Examples
///
/// ```
/// if !toxiproxy_rust::TOXIPROXY.is_running() {
/// /* signal the problem */
/// }
/// ```
pub fn is_running(&self) -> bool {
self.client.lock().expect("Client lock failed").is_alive()
}
/// Version of the Toxiproxy server.
///
/// # Examples
///
/// ```
/// let version = toxiproxy_rust::TOXIPROXY.version().expect("version is returned");
/// ```
pub fn version(&self) -> Result<String, String> {
self.client
.lock()
.map_err(|err| format!("lock error: {}", err))?
.get("version")
.map(|ref mut response| {
let mut body = String::new();
response
.read_to_string(&mut body)
.expect("HTTP response cannot be read");
body
})
}
/// Fetches a proxy a resets its state (remove active toxics). Usually a good way to start a test and to start setting up
/// toxics fresh against the proxy.
///
/// # Examples
///
/// ```
/// # toxiproxy_rust::TOXIPROXY.populate(vec![toxiproxy_rust::proxy::ProxyPack::new(
/// # "socket".into(),
/// # "localhost:2001".into(),
/// # "localhost:2000".into(),
/// # )]).unwrap();
/// let proxy = toxiproxy_rust::TOXIPROXY.find_and_reset_proxy("socket").expect("proxy returned");
/// ```
pub fn find_and_reset_proxy(&self, name: &str) -> Result<Proxy, String> {
self.find_proxy(name).and_then(|proxy| {
proxy.delete_all_toxics()?;
proxy.enable()?;
Ok(proxy)
})
}
/// Fetches a proxy. Useful to fetch a proxy for a test where more fine grained control is required
/// over a proxy and its toxics.
///
/// # Examples
///
/// ```
/// # toxiproxy_rust::TOXIPROXY.populate(vec![toxiproxy_rust::proxy::ProxyPack::new(
/// # "socket".into(),
/// # "localhost:2001".into(),
/// # "localhost:2000".into(),
/// # )]).unwrap();
/// let proxy = toxiproxy_rust::TOXIPROXY.find_proxy("socket").expect("proxy returned");
/// ```
pub fn find_proxy(&self, name: &str) -> Result<Proxy, String> {
let path = format!("proxies/{}", name);
self.client
.lock()
.map_err(|err| format!("lock error: {}", err))?
.get(&path)
.and_then(|response| {
response
.json()
.map_err(|err| format!("json deserialize failed: {}", err))
})
.and_then(|proxy_pack: ProxyPack| Ok(Proxy::new(proxy_pack, self.client.clone())))
}
}