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
use std::cell::Ref;
use log;
use reqwest::{Method, RequestBuilder, Response, Url};
use serde::de::DeserializeOwned;
use super::{Error, ErrorKind, Result};
use super::auth::AuthMethod;
use super::common::ApiVersion;
use super::common::protocol::ServiceInfo;
use super::utils;
pub trait ServiceType {
fn catalog_type() -> &'static str;
fn major_version_supported(_version: ApiVersion) -> bool { true }
fn set_api_version_headers(_request: RequestBuilder, _version: ApiVersion)
-> Result<RequestBuilder> {
Err(Error::new(ErrorKind::IncompatibleApiVersion,
format!("The {} service does not support API versions",
Self::catalog_type())))
}
}
pub trait RequestBuilderExt {
fn send_checked(self) -> Result<Response>;
fn commit(self) -> Result<()> where Self: Sized {
let _ = self.send_checked()?;
Ok(())
}
fn receive_json<T: DeserializeOwned>(self) -> Result<T> where Self: Sized {
self.send_checked()?.json().map_err(From::from)
}
}
impl RequestBuilderExt for RequestBuilder {
fn send_checked(self) -> Result<Response> {
_log(self.send()?).error_for_status().map_err(From::from)
}
}
fn _log(mut resp: Response) -> Response {
if log_enabled!(log::Level::Trace) {
let details = if resp.status().is_client_error() || resp.status().is_server_error() {
resp.text().ok()
} else {
None
};
trace!("HTTP request to {} returned {}; error: {:?}",
resp.url(), resp.status(), details);
}
resp
}
#[derive(Debug, Clone)]
pub struct Session {
auth: Box<AuthMethod>,
cached_info: utils::MapCache<&'static str, ServiceInfo>,
endpoint_interface: String
}
impl Session {
pub fn new<Auth: AuthMethod + 'static>(auth_method: Auth) -> Session {
let ep = auth_method.default_endpoint_interface();
Session {
auth: Box::new(auth_method),
cached_info: utils::MapCache::new(),
endpoint_interface: ep
}
}
pub fn set_endpoint_interface<S>(&mut self, endpoint_interface: S)
where S: Into<String> {
self.cached_info = utils::MapCache::new();
self.endpoint_interface = endpoint_interface.into();
}
pub fn with_endpoint_interface<S>(mut self, endpoint_interface: S)
-> Session where S: Into<String> {
self.set_endpoint_interface(endpoint_interface);
self
}
pub fn auth_method(&self) -> &AuthMethod {
self.auth.as_ref()
}
pub fn auth_method_mut(&mut self) -> &mut AuthMethod {
self.auth.as_mut()
}
pub fn get_endpoint<Srv: ServiceType>(&self, path: &[&str])
-> Result<Url> {
let info = self.get_service_info_ref::<Srv>()?;
Ok(utils::url::extend(info.root_url.clone(), path))
}
pub fn get_major_version<Srv: ServiceType>(&self) -> Result<ApiVersion> {
let info = self.get_service_info_ref::<Srv>()?;
Ok(info.major_version)
}
pub fn get_api_versions<Srv: ServiceType>(&self)
-> Result<Option<(ApiVersion, ApiVersion)>> {
let info = self.get_service_info_ref::<Srv>()?;
match (info.minimum_version, info.current_version) {
(Some(min), Some(max)) => Ok(Some((min, max))),
_ => Ok(None)
}
}
pub fn request<Srv: ServiceType>(&self, method: Method, path: &[&str],
api_version: Option<ApiVersion>)
-> Result<RequestBuilder> {
let url = self.get_endpoint::<Srv>(path)?;
trace!("Sending HTTP {} request to {} with API version {:?}",
method, url, api_version);
let mut builder = self.auth.request(method, url)?;
if let Some(version) = api_version {
builder = Srv::set_api_version_headers(builder, version)?;
}
Ok(builder)
}
pub fn get<Srv: ServiceType>(&self, path: &[&str], api_version: Option<ApiVersion>)
-> Result<RequestBuilder> {
self.request::<Srv>(Method::GET, path, api_version)
}
pub fn post<Srv: ServiceType>(&self, path: &[&str], api_version: Option<ApiVersion>)
-> Result<RequestBuilder> {
self.request::<Srv>(Method::POST, path, api_version)
}
pub fn put<Srv: ServiceType>(&self, path: &[&str], api_version: Option<ApiVersion>)
-> Result<RequestBuilder> {
self.request::<Srv>(Method::PUT, path, api_version)
}
pub fn delete<Srv: ServiceType>(&self, path: &[&str], api_version: Option<ApiVersion>)
-> Result<RequestBuilder> {
self.request::<Srv>(Method::DELETE, path, api_version)
}
fn ensure_service_info<Srv>(&self) -> Result<()> where Srv: ServiceType {
self.cached_info.ensure_value(Srv::catalog_type(), |_| {
self.get_catalog_endpoint(Srv::catalog_type())
.and_then(|ep| ServiceInfo::fetch::<Srv>(ep, self.auth_method()))
})?;
Ok(())
}
fn get_catalog_endpoint<S>(&self, service_type: S) -> Result<Url>
where S: Into<String> {
self.auth.get_endpoint(service_type.into(),
Some(self.endpoint_interface.clone()))
}
pub(crate) fn get_service_info_ref<Srv>(&self)
-> Result<Ref<ServiceInfo>> where Srv: ServiceType {
self.ensure_service_info::<Srv>()?;
Ok(self.cached_info.get_ref(&Srv::catalog_type()).unwrap())
}
}
impl ServiceInfo {
#[allow(dead_code)] pub fn supports_api_version(&self, version: ApiVersion) -> bool {
match (self.minimum_version, self.current_version) {
(Some(min), Some(max)) => min <= version && max >= version,
(None, Some(current)) => current == version,
(Some(min), None) => version >= min,
_ => false
}
}
}
#[cfg(test)]
mod test {
use super::super::utils;
#[test]
fn test_session_new() {
let s = utils::test::new_session(utils::test::URL);
let ep = s.get_catalog_endpoint("fake").unwrap();
assert_eq!(&ep.to_string(), utils::test::URL);
}
}