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
use std::{collections::HashMap, time::Duration};

use hmac::{Hmac, Mac};
use reqwest::{header::HeaderMap, ClientBuilder, Response};
use serde::{de::DeserializeOwned, Deserialize, Serialize};
use sha1::Sha1;
use time::{format_description::well_known::Iso8601, OffsetDateTime};
use url::form_urlencoded::byte_serialize;
use uuid::Uuid;

use crate::client::error::{Error, Result};

#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "PascalCase")]
pub struct RPCServiceError {
    /// Error code
    pub code: String,
    /// Error message
    pub message: String,
    /// Request id
    #[serde(default)]
    pub request_id: String,
    /// Recommend
    #[serde(default)]
    pub recommend: String,
}

/// Default const header.
const AGENT: &str = concat!(env!("CARGO_PKG_NAME"), "/", env!("CARGO_PKG_VERSION"));
const DEFAULT_HEADER: &[(&str, &str)] = &[("user-agent", AGENT), ("x-sdk-client", AGENT)];
const DEFAULT_PARAM: &[(&str, &str)] = &[
    ("Format", "JSON"),
    ("SignatureMethod", "HMAC-SHA1"),
    ("SignatureVersion", "1.0"),
];

type HamcSha1 = Hmac<Sha1>;

/// Config for request.
#[derive(Clone, Debug, Default)]
struct Request {
    action: String,
    method: String,
    query: Vec<(String, String)>,
    headers: HeaderMap,
    version: String,
    timeout: Option<Duration>,
}

#[derive(Clone, Debug)]
pub struct RPClient {
    /// The access key id of aliyun developer account.
    access_key_id: String,
    /// The access key secret of aliyun developer account.
    access_key_secret: String,
    /// The api endpoint of aliyun api service (need start with http:// or https://).
    endpoint: String,
    /// The config of http request.
    request: Request,
}

impl RPClient {
    /// Create a api client.
    pub fn new(
        access_key_id: impl Into<String>,
        access_key_secret: impl Into<String>,
        endpoint: impl Into<String>,
    ) -> Self {
        RPClient {
            access_key_id: access_key_id.into(),
            access_key_secret: access_key_secret.into(),
            endpoint: endpoint.into(),
            request: Default::default(),
        }
    }

    /// Create a request with the `method` and `action`.
    ///
    /// Returns a `Self` for send request.
    pub fn request(mut self, method: impl Into<String>, action: impl Into<String>) -> Self {
        self.request.method = method.into();
        self.request.action = action.into();

        self
    }

    /// Create a `GET` request with the `action`.
    ///
    /// Returns a `Self` for send request.
    pub fn get(self, action: impl Into<String>) -> Self {
        self.request("GET".to_string(), action.into())
    }

    /// Create a `POST` request with the `action`.
    ///
    /// Returns a `Self` for send request.
    pub fn post(self, action: impl Into<String>) -> Self {
        self.request("POST".to_string(), action.into())
    }

    /// Set queries for request.
    ///
    /// Returns a `Self` for send request.
    pub fn query<I, T>(mut self, queries: I) -> Self
    where
        I: IntoIterator<Item = (T, T)>,
        T: Into<String>,
    {
        self.request.query = queries
            .into_iter()
            .map(|v| (v.0.into(), v.1.into()))
            .collect();

        self
    }

    /// Set version for request.
    ///
    /// Returns a `Self` for send request.
    pub fn version(mut self, version: impl Into<String>) -> Self {
        self.request.version = version.into();

        self
    }

    /// Set header for request.
    ///
    /// Returns a `Self` for send request.
    pub fn header(mut self, headers: impl Into<HashMap<String, String>>) -> Result<Self> {
        self.request.headers = (&headers.into())
            .try_into()
            .map_err(|e| Error::InvalidRequest(format!("Cannot parse header: {e}")))?;
        Ok(self)
    }

    /// Set a timeout for connect, read and write operations of a `Client`.
    ///
    /// Default is no timeout.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.request.timeout = Some(timeout);

        self
    }

    /// Send a request to service.
    /// Try to deserialize the response body as JSON.
    pub async fn json<T: DeserializeOwned>(self) -> Result<T> {
        Ok(self.send().await?.json::<T>().await?)
    }

    /// Send a request to service.
    /// Try to deserialize the response body as TEXT.
    pub async fn text(self) -> Result<String> {
        Ok(self.send().await?.text().await?)
    }

    /// Send a request to service.
    /// Return client Response.
    pub async fn send(mut self) -> Result<Response> {
        // add const header
        for (k, v) in DEFAULT_HEADER.iter() {
            self.request.headers.insert(*k, v.parse()?);
        }

        // build params.
        let nonce = Uuid::new_v4().to_string();
        let ts = OffsetDateTime::now_utc()
            .format(&Iso8601::DEFAULT)
            .map_err(|e| Error::InvalidRequest(format!("Invalid ISO 8601 Date: {e}")))?;

        let mut params = Vec::from(DEFAULT_PARAM);
        params.push(("Action", &self.request.action));
        params.push(("AccessKeyId", &self.access_key_id));
        params.push(("SignatureNonce", &nonce));
        params.push(("Timestamp", &ts));
        params.push(("Version", &self.request.version));
        params.extend(
            self.request
                .query
                .iter()
                .map(|(k, v)| (k.as_ref(), v.as_ref())),
        );
        params.sort_by_key(|item| item.0);

        // encode params.
        let params: Vec<String> = params
            .into_iter()
            .map(|(k, v)| format!("{}={}", url_encode(k), url_encode(v)))
            .collect();
        let sorted_query_string = params.join("&");
        let string_to_sign = format!(
            "{}&{}&{}",
            self.request.method,
            url_encode("/"),
            url_encode(&sorted_query_string)
        );

        // sign params, get finnal request url.
        let sign = sign(&format!("{}&", self.access_key_secret), &string_to_sign)?;
        let signature = url_encode(&sign);
        let final_url = format!(
            "{}?Signature={}&{}",
            self.endpoint, signature, sorted_query_string
        );

        // build http client.
        let mut http_client_builder = ClientBuilder::new();
        if let Some(timeout) = self.request.timeout {
            http_client_builder = http_client_builder.timeout(timeout);
        }
        let http_client = http_client_builder.build()?.request(
            self.request
                .method
                .parse()
                .map_err(|e| Error::InvalidRequest(format!("Invalid HTTP method: {}", e)))?,
            &final_url,
        );

        // send request.
        let response = http_client.headers(self.request.headers).send().await?;

        // check HTTP StatusCode.
        if !response.status().is_success() {
            let result = response.json::<RPCServiceError>().await?;
            return Err(Error::InvalidResponse {
                request_id: result.request_id,
                error_code: result.code,
                error_message: result.message,
            });
        }

        // return response.
        Ok(response)
    }
}

fn sign(key: &str, body: &str) -> Result<String> {
    let mut mac = HamcSha1::new_from_slice(key.as_bytes())
        .map_err(|e| Error::InvalidRequest(format!("Invalid HMAC-SHA1 secret key: {}", e)))?;
    mac.update(body.as_bytes());
    let result = mac.finalize();
    let code = result.into_bytes();

    Ok(base64::encode(code))
}

/// URL encode following [RFC3986](https://www.rfc-editor.org/rfc/rfc3986)
fn url_encode(s: &str) -> String {
    let s: String = byte_serialize(s.as_bytes()).collect();
    s.replace('+', "%20")
        .replace('*', "%2A")
        .replace("%7E", "~")
}

#[cfg(test)]
mod tests {
    use std::env;

    use super::*;

    #[test]
    fn url_encode_test() -> Result<()> {
        assert_eq!(
            url_encode("begin_+_*_~_-_._\"_ end"),
            "begin_%2B_%2A_~_-_._%22_%20end"
        );

        Ok(())
    }

    #[tokio::test]
    async fn rpc_client_invalid_access_key_id_test() -> Result<()> {
        // create rpc style api client.
        let aliyun_openapi_client = RPClient::new(
            env::var("ACCESS_KEY_ID").unwrap(),
            env::var("ACCESS_KEY_SECRET").unwrap(),
            "https://ecs-cn-hangzhou.aliyuncs.com",
        );

        // call `DescribeRegions` with empty queries.
        let response = aliyun_openapi_client
            .version("2014-05-26")
            .get("DescribeRegions")
            .text()
            .await?;

        assert!(response.contains("Regions"));

        Ok(())
    }

    #[tokio::test]
    async fn rpc_client_get_with_query_test() -> Result<()> {
        // create rpc style api client.
        let aliyun_openapi_client = RPClient::new(
            env::var("ACCESS_KEY_ID").unwrap(),
            env::var("ACCESS_KEY_SECRET").unwrap(),
            "https://ecs-cn-hangzhou.aliyuncs.com",
        );

        // call `DescribeInstances` with queries.
        let response = aliyun_openapi_client
            .version("2014-05-26")
            .get("DescribeInstances")
            .query(vec![("RegionId", "cn-hangzhou")])
            .text()
            .await?;

        assert!(response.contains("Instances"));

        Ok(())
    }
}