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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
// Copyright 2019 Dmitry Tantsur <dtantsur@protonmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Adapter for a specific service.

use http::{header::HeaderName, HeaderValue};
use reqwest::{Method, Url};
use serde::de::DeserializeOwned;

use super::services::{ServiceType, VersionedService};
use super::session::ServiceRequestBuilder;
use super::{ApiVersion, AuthType, EndpointFilters, Error, InterfaceType, Session};

/// Adapter for a specific service.
///
/// An `Adapter` is very similar to a [Session](struct.Session.html), but is tied to a specific
/// service, and thus does not require passing a `service` argument to all calls.
#[derive(Debug, Clone)]
pub struct Adapter<Srv> {
    inner: Session,
    service: Srv,
    default_api_version: Option<ApiVersion>,
    api_version_header: Option<(HeaderName, HeaderValue)>,
}

impl<Srv> From<Adapter<Srv>> for Session {
    fn from(value: Adapter<Srv>) -> Session {
        value.inner
    }
}

impl<Srv> Adapter<Srv> {
    /// Create a new adapter with a given authentication plugin.
    pub async fn new<Auth: AuthType + 'static>(
        auth_type: Auth,
        service: Srv,
    ) -> Result<Adapter<Srv>, Error> {
        Ok(Adapter::from_session(
            Session::new(auth_type).await?,
            service,
        ))
    }

    /// Create a new adapter from a `clouds.yaml` configuration file.
    ///
    /// See [Session::from_config](struct.Session.html#method.from_config) for details.
    #[inline]
    pub async fn from_config<S: AsRef<str>>(
        cloud_name: S,
        service: Srv,
    ) -> Result<Adapter<Srv>, Error> {
        Ok(Session::from_config(cloud_name)
            .await?
            .into_adapter(service))
    }

    /// Create a new adapter with information from environment variables.
    ///
    /// See [Session::from_env](struct.Session.html#method.from_env) for details.
    #[inline]
    pub async fn from_env(service: Srv) -> Result<Adapter<Srv>, Error> {
        Ok(Session::from_env().await?.into_adapter(service))
    }

    /// Create a new adapter from a `Session`.
    #[inline]
    pub fn from_session(session: Session, service: Srv) -> Adapter<Srv> {
        Adapter {
            inner: session,
            service,
            default_api_version: None,
            api_version_header: None,
        }
    }

    /// Get a reference to the authentication type in use.
    #[inline]
    pub fn auth_type(&self) -> &dyn AuthType {
        self.inner.auth_type()
    }

    /// Endpoint filters in use.
    #[inline]
    pub fn endpoint_filters(&self) -> &EndpointFilters {
        self.inner.endpoint_filters()
    }

    /// Modify endpoint filters.
    ///
    /// This call clears the cached service information for this `Adapter`.
    /// It does not, however, affect clones of this `Adapter`.
    #[inline]
    pub fn endpoint_filters_mut(&mut self) -> &mut EndpointFilters {
        self.inner.endpoint_filters_mut()
    }

    /// Update the authentication and purges cached endpoint information.
    ///
    /// # Warning
    ///
    /// Authentication will also be updated for clones of this `Adapter` and its parent `Session`,
    /// since they share the same authentication object.
    #[inline]
    pub async fn refresh(&mut self) -> Result<(), Error> {
        self.inner.refresh().await
    }

    /// Session used for this adapter.
    #[inline]
    pub fn session(&self) -> &Session {
        &self.inner
    }

    /// Set a new authentication for this `Adapter`.
    ///
    /// This call clears the cached service information for this `Adapter`.
    /// It does not, however, affect clones of this `Adapter`.
    #[inline]
    pub fn set_auth_type<Auth: AuthType + 'static>(&mut self, auth_type: Auth) {
        self.inner.set_auth_type(auth_type)
    }

    /// A convenience call to set an endpoint interface.
    ///
    /// This call clears the cached service information for this `Adapter`.
    /// It does not, however, affect clones of this `Adapter`.
    #[inline]
    pub fn set_endpoint_interface(&mut self, endpoint_interface: InterfaceType) {
        self.inner.set_endpoint_interface(endpoint_interface);
    }

    /// Convert this adapter into one using the given authentication.
    #[inline]
    pub fn with_auth_type<Auth: AuthType + 'static>(mut self, auth_method: Auth) -> Adapter<Srv> {
        self.set_auth_type(auth_method);
        self
    }

    /// Convert this adapter into one using the given endpoint filters.
    #[inline]
    pub fn with_endpoint_filters(mut self, endpoint_filters: EndpointFilters) -> Adapter<Srv> {
        *self.endpoint_filters_mut() = endpoint_filters;
        self
    }

    /// Convert this adapter into one using the given endpoint filters.
    #[inline]
    pub fn with_endpoint_interface(mut self, endpoint_interface: InterfaceType) -> Adapter<Srv> {
        self.set_endpoint_interface(endpoint_interface);
        self
    }
}

impl<Srv> Adapter<Srv>
where
    Srv: VersionedService + Send,
{
    /// Default API version used when no version is specified.
    #[inline]
    pub fn default_api_version(&self) -> Option<ApiVersion> {
        self.default_api_version
    }

    /// Set the default API version.
    ///
    /// This version will be used when no version is specified. No checks are done against this
    /// version inside of this call. If it is not valid, the subsequent `request` calls will fail.
    #[inline]
    pub fn set_default_api_version(&mut self, api_version: Option<ApiVersion>) {
        self.default_api_version = api_version;
        self.api_version_header =
            api_version.map(|version| self.service.get_version_header(version));
    }

    /// Convert this adapter into one using the given default API version.
    #[inline]
    pub fn with_default_api_version(mut self, api_version: Option<ApiVersion>) -> Adapter<Srv> {
        self.set_default_api_version(api_version);
        self
    }
}

impl<Srv: ServiceType + Send + Clone> Adapter<Srv> {
    /// Get minimum/maximum API (micro)version information.
    ///
    /// Returns `None` if the range cannot be determined, which usually means
    /// that microversioning is not supported.
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), osauth::Error> {
    /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)
    ///     .await
    ///     .expect("Failed to create an identity provider from the environment");
    /// let maybe_versions = adapter
    ///     .get_api_versions()
    ///     .await?;
    /// if let Some((min, max)) = maybe_versions {
    ///     println!("The compute service supports versions {} to {}", min, max);
    /// } else {
    ///     println!("The compute service does not support microversioning");
    /// }
    /// # Ok(()) }
    /// # #[tokio::main]
    /// # async fn main() { example().await.unwrap(); }
    /// ```
    #[inline]
    pub async fn get_api_versions(&self) -> Result<Option<(ApiVersion, ApiVersion)>, Error> {
        self.inner.get_api_versions(self.service.clone()).await
    }

    /// Construct an endpoint from the path;
    ///
    /// You won't need to use this call most of the time, since all request calls can fetch the
    /// endpoint automatically.
    pub async fn get_endpoint<I>(&self, path: I) -> Result<Url, Error>
    where
        I: IntoIterator + Send,
        I::Item: AsRef<str>,
    {
        self.inner.get_endpoint(self.service.clone(), path).await
    }

    /// Get the currently used major version from the given service.
    ///
    /// Can return `None` if the service does not support API version discovery at all.
    #[inline]
    pub async fn get_major_version(&self) -> Result<Option<ApiVersion>, Error> {
        self.inner.get_major_version(self.service.clone()).await
    }

    /// Pick the highest API version supported by the service.
    ///
    /// Returns `None` if none of the requested versions are available.
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), osauth::Error> {
    /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)
    ///     .await
    ///     .expect("Failed to create an identity provider from the environment");
    /// let candidates = vec![osauth::ApiVersion(1, 2), osauth::ApiVersion(1, 42)];
    /// let maybe_version = adapter
    ///     .pick_api_version(candidates)
    ///     .await?;
    ///
    /// let request = adapter.get(&["servers"]);
    /// let response = if let Some(version) = maybe_version {
    ///     println!("Using version {}", version);
    ///     request.api_version(version)
    /// } else {
    ///     println!("Using the base version");
    ///     request
    /// }.send().await?;
    /// # Ok(()) }
    /// # #[tokio::main]
    /// # async fn main() { example().await.unwrap(); }
    /// ```
    pub async fn pick_api_version<I>(&self, versions: I) -> Result<Option<ApiVersion>, Error>
    where
        I: IntoIterator<Item = ApiVersion> + Send,
    {
        self.inner
            .pick_api_version(self.service.clone(), versions)
            .await
    }

    /// Check if the service supports the API version.
    #[inline]
    pub async fn supports_api_version(&self, version: ApiVersion) -> Result<bool, Error> {
        self.pick_api_version(Some(version))
            .await
            .map(|x| x.is_some())
    }

    /// Make an HTTP request.
    ///
    /// The `path` argument is a URL path without the service endpoint (e.g. `/servers/1234`).
    ///
    /// The result is a `ServiceRequestBuilder` that can be customized further. Error checking and response
    /// parsing can be done using functions from the [request](request/index.html) module.
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), osauth::Error> {
    /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)
    ///     .await
    ///     .expect("Failed to create an identity provider from the environment");
    /// let response = adapter
    ///     .request(reqwest::Method::HEAD, &["servers", "1234"])
    ///     .send()
    ///     .await?;
    /// println!("Response: {:?}", response);
    /// # Ok(()) }
    /// # #[tokio::main]
    /// # async fn main() { example().await.unwrap(); }
    /// ```
    ///
    /// This is the most generic call to make a request. You may prefer to use more specific `get`,
    /// `post`, `put` or `delete` calls instead.
    pub fn request<I>(&self, method: Method, path: I) -> ServiceRequestBuilder<Srv>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        let rb = self.inner.request(self.service.clone(), method, path);

        if let Some((name, value)) = self.api_version_header.clone() {
            rb.header(name, value)
        } else {
            rb
        }
    }

    /// Start a GET request.
    ///
    /// See [request](#method.request) for an explanation of the parameters.
    #[inline]
    pub fn get<I>(&self, path: I) -> ServiceRequestBuilder<Srv>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        self.request(Method::GET, path)
    }

    /// Fetch a JSON using the GET request.
    ///
    /// ```rust,no_run
    /// # async fn example() -> Result<(), osauth::Error> {
    /// use serde::Deserialize;
    ///
    /// #[derive(Debug, Deserialize)]
    /// pub struct Server {
    ///     pub id: String,
    ///     pub name: String,
    /// }
    ///
    /// #[derive(Debug, Deserialize)]
    /// pub struct ServersRoot {
    ///     pub servers: Vec<Server>,
    /// }
    ///
    /// let adapter = osauth::Adapter::from_env(osauth::services::COMPUTE)
    ///     .await
    ///     .expect("Failed to create an identity provider from the environment");
    /// let servers: ServersRoot = adapter
    ///     .get_json(&["servers"])
    ///     .await?;
    /// for srv in servers.servers {
    ///     println!("ID = {}, Name = {}", srv.id, srv.name);
    /// }
    /// # Ok(()) }
    /// # #[tokio::main]
    /// # async fn main() { example().await.unwrap(); }
    /// ```
    ///
    /// See [request](#method.request) for an explanation of the parameters.
    #[inline]
    pub async fn get_json<I, T>(&self, path: I) -> Result<T, Error>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
        T: DeserializeOwned + Send,
    {
        self.request(Method::GET, path).fetch::<T>().await
    }

    /// Start a POST request.
    ///
    /// See [request](#method.request) for an explanation of the parameters.
    #[inline]
    pub fn post<I>(&self, path: I) -> ServiceRequestBuilder<Srv>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        self.request(Method::POST, path)
    }

    /// Start a PUT request.
    ///
    /// See [request](#method.request) for an explanation of the parameters.
    #[inline]
    pub fn put<I>(&self, path: I) -> ServiceRequestBuilder<Srv>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        self.request(Method::PUT, path)
    }

    /// Start a DELETE request.
    ///
    /// See [request](#method.request) for an explanation of the parameters.
    #[inline]
    pub fn delete<I>(&self, path: I) -> ServiceRequestBuilder<Srv>
    where
        I: IntoIterator,
        I::Item: AsRef<str>,
    {
        self.request(Method::DELETE, path)
    }
}