aliyun-openapi-core-rust-sdk 1.1.0

Aliyun OpenAPI POP core SDK for Rust
Documentation
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
use anyhow::{anyhow, Result};
use hmac::{Hmac, Mac};
use md5::{Digest, Md5};
use reqwest::blocking::ClientBuilder;
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use sha1::Sha1;
use std::env;
use std::time::Duration;
use std::{borrow::Borrow, str::FromStr};
use time::macros::format_description;
use time::OffsetDateTime;
use url::Url;
use uuid::Uuid;

/// Default const header.
const DEFAULT_HEADER: &[(&str, &str)] = &[
    ("accept", "application/json"),
    ("x-acs-signature-method", "HMAC-SHA1"),
    ("x-acs-signature-version", "1.0"),
];

type HamcSha1 = Hmac<Sha1>;

/// Config for request.
#[derive(Debug)]
struct Request {
    method: String,
    uri: String,
    body: Option<String>,
    query: Vec<(String, String)>,
    headers: HeaderMap,
}

/// The roa style api client.
#[deprecated(
    since = "1.0.0",
    note = "Please use the `aliyun_openapi_core_rust_sdk::client::roa::ROAClient` instead"
)]
#[derive(Clone, Debug)]
pub struct Client {
    /// 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 api version of aliyun api service.
    version: String,
}

impl Client {
    #![allow(deprecated)]

    /// Create a roa style api client.
    pub fn new(
        access_key_id: String,
        access_key_secret: String,
        endpoint: String,
        version: String,
    ) -> Self {
        Client {
            access_key_id,
            access_key_secret,
            endpoint,
            version,
        }
    }

    /// Create a request with the `method` and `uri`.
    ///
    /// Returns a `RequestBuilder` for send request.
    pub fn execute(&self, method: &str, uri: &str) -> RequestBuilder {
        RequestBuilder::new(
            &self.access_key_id,
            &self.access_key_secret,
            &self.endpoint,
            &self.version,
            String::from(method),
            String::from(uri),
        )
    }

    /// Create a `GET` request with the `uri`.
    ///
    /// Returns a `RequestBuilder` for send request.
    pub fn get(&self, uri: &str) -> RequestBuilder {
        self.execute("GET", uri)
    }

    /// Create a `POST` request with the `uri`.
    ///
    /// Returns a `RequestBuilder` for send request.
    pub fn post(&self, uri: &str) -> RequestBuilder {
        self.execute("POST", uri)
    }

    /// Create a `PUT` request with the `uri`.
    ///
    /// Returns a `RequestBuilder` for send request.
    pub fn put(&self, uri: &str) -> RequestBuilder {
        self.execute("PUT", uri)
    }
}

/// The request builder struct.
#[derive(Debug)]
pub struct RequestBuilder<'a> {
    /// The access key id of aliyun developer account.
    access_key_id: &'a str,
    /// The access key secret of aliyun developer account.
    access_key_secret: &'a str,
    /// The api endpoint of aliyun api service (need start with http:// or https://).
    endpoint: &'a str,
    /// The http client builder used to send request.
    http_client_builder: ClientBuilder,
    /// The config of http request.
    request: Request,
}

impl<'a> RequestBuilder<'a> {
    /// Create a request object.
    pub fn new(
        access_key_id: &'a str,
        access_key_secret: &'a str,
        endpoint: &'a str,
        version: &'a str,
        method: String,
        uri: String,
    ) -> Self {
        // init http headers.
        let mut headers = HeaderMap::new();
        for (k, v) in DEFAULT_HEADER.iter() {
            headers.insert(*k, v.parse().unwrap());
        }
        headers.insert(
            "user-agent",
            format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
                .parse()
                .unwrap(),
        );
        headers.insert(
            "x-sdk-client",
            format!("{}/{}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
                .parse()
                .unwrap(),
        );
        headers.insert("x-acs-version", version.parse().unwrap());

        // return RequestBuilder.
        RequestBuilder {
            access_key_id,
            access_key_secret,
            endpoint,
            http_client_builder: ClientBuilder::new(),
            request: Request {
                method,
                uri,
                body: None,
                query: Vec::new(),
                headers,
            },
        }
    }

    /// Set body for request.
    pub fn body(mut self, body: &str) -> Result<Self> {
        // compute body length and md5.
        let body = body.to_string();
        let mut hasher = Md5::new();
        hasher.update(body.as_bytes());
        let md5_result = hasher.finalize();

        // update headers.
        self.request
            .headers
            .insert("content-length", body.len().to_string().parse()?);
        self.request
            .headers
            .insert("content-md5", base64::encode(md5_result).parse()?);

        // store body string.
        self.request.body = Some(body);

        Ok(self)
    }

    /// Set header for request.
    pub fn header<I>(mut self, iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: Borrow<(&'a str, &'a str)>,
    {
        for i in iter.into_iter() {
            let h = i.borrow();
            let key = HeaderName::from_str(h.0);
            let value = HeaderValue::from_str(h.1);
            // ingore invailid header.
            if let Ok(key) = key {
                if let Ok(value) = value {
                    self.request.headers.insert(key, value);
                }
            }
        }
        self
    }

    /// Set queries for request.
    pub fn query<I>(mut self, iter: I) -> Self
    where
        I: IntoIterator,
        I::Item: Borrow<(&'a str, &'a str)>,
    {
        for i in iter.into_iter() {
            let b = i.borrow();
            self.request.query.push((b.0.to_string(), b.1.to_string()));
        }
        self
    }

    /// Send a request to api service.
    pub fn send(mut self) -> Result<String> {
        // add date header.
        // RFC 1123: %a, %d %b %Y %H:%M:%S GMT
        let format = format_description!(
            "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT"
        );
        let ts = OffsetDateTime::now_utc()
            .format(&format)
            .map_err(|e| anyhow!(format!("Invalid RFC 1123 Date: {}", e)))?;
        self.request.headers.insert("date", ts.parse()?);

        // add nonce header.
        let nonce = Uuid::new_v4().to_string();
        self.request
            .headers
            .insert("x-acs-signature-nonce", nonce.parse()?);

        // parse host of self.endpoint.
        let endpoint = Url::parse(self.endpoint)?;
        let host = endpoint
            .host_str()
            .ok_or_else(|| anyhow!("parse endpoint failed"))?;
        self.request.headers.insert("host", host.parse()?);

        // compute `Authorization` field.
        let authorization = format!("acs {}:{}", self.access_key_id, self.signature()?);
        self.request
            .headers
            .insert("Authorization", authorization.parse()?);

        // build http client.
        let final_url = format!("{}{}", self.endpoint, self.request.uri);
        let mut http_client = self
            .http_client_builder
            .build()?
            .request(self.request.method.parse()?, final_url);

        // set body.
        if let Some(body) = self.request.body {
            http_client = http_client.body(body);
        }

        // send request.
        let response = http_client
            .headers(self.request.headers)
            .query(&self.request.query)
            .send()?
            .text()?;

        // return response.
        Ok(response)
    }

    /// Set a timeout for connect, read and write operations of a `Client`.
    ///
    /// Default is 30 seconds.
    ///
    /// Pass `None` to disable timeout.
    pub fn timeout<T>(mut self, timeout: T) -> Self
    where
        T: Into<Option<Duration>>,
    {
        self.http_client_builder = self.http_client_builder.timeout(timeout);
        self
    }

    /// Compute canonicalized headers.
    fn canonicalized_headers(&self) -> String {
        let mut headers: Vec<(String, String)> = self
            .request
            .headers
            .iter()
            .filter_map(|(k, v)| {
                let k = k.as_str().to_lowercase();
                if k.starts_with("x-acs-") {
                    Some((k, v.to_str().unwrap().to_string()))
                } else {
                    None
                }
            })
            .collect();
        headers.sort_by(|a, b| a.0.cmp(&b.0));

        let headers: Vec<String> = headers
            .iter()
            .map(|(k, v)| format!("{}:{}", k, v))
            .collect();

        headers.join("\n")
    }

    /// Compute canonicalized resource.
    fn canonicalized_resource(&self) -> String {
        if !self.request.query.is_empty() {
            let mut params = self.request.query.clone();
            params.sort_by_key(|item| item.0.clone());
            let params: Vec<String> = params.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
            let sorted_query_string = params.join("&");
            format!("{}?{}", self.request.uri, sorted_query_string)
        } else {
            self.request.uri.clone()
        }
    }

    /// Compute signature for request.
    fn signature(&self) -> Result<String> {
        // build body.
        let canonicalized_headers = self.canonicalized_headers();
        let canonicalized_resource = self.canonicalized_resource();
        let body = format!(
            "{}\n{}\n{}\n{}\n{}\n{}\n{}",
            self.request.method.to_uppercase(),
            self.request.headers["accept"].to_str().unwrap(),
            self.request
                .headers
                .get("content-md5")
                .unwrap_or(&HeaderValue::from_static(""))
                .to_str()
                .unwrap(),
            self.request
                .headers
                .get("content-type")
                .unwrap_or(&HeaderValue::from_static(""))
                .to_str()
                .unwrap(),
            self.request.headers["date"].to_str().unwrap(),
            canonicalized_headers,
            canonicalized_resource
        );

        // sign body.
        let mut mac = HamcSha1::new_from_slice(self.access_key_secret.as_bytes())
            .map_err(|e| anyhow!(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))
    }
}

#[cfg(test)]
mod tests {
    #![allow(deprecated)]

    use std::collections::HashMap;

    use serde_json::json;

    use super::*;

    #[test]
    fn roa_client_get_no_query() -> Result<()> {
        // create roa style api client.
        let aliyun_openapi_client = Client::new(
            env::var("ACCESS_KEY_ID")?,
            env::var("ACCESS_KEY_SECRET")?,
            String::from("https://ros.aliyuncs.com"),
            String::from("2015-09-01"),
        );

        // call `DescribeRegions` with empty queries.
        let response = aliyun_openapi_client.get("/regions").send()?;

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

        Ok(())
    }

    #[test]
    fn roa_client_get_with_timeout() -> Result<()> {
        // create roa style api client.
        let aliyun_openapi_client = Client::new(
            env::var("ACCESS_KEY_ID")?,
            env::var("ACCESS_KEY_SECRET")?,
            String::from("https://ros.aliyuncs.com"),
            String::from("2015-09-01"),
        );

        // call `DescribeRegions` with empty queries.
        let response = aliyun_openapi_client
            .get("/regions")
            .timeout(Duration::from_millis(1))
            .send();

        assert!(response.is_err());

        Ok(())
    }

    #[test]
    fn roa_client_post_with_json_params() -> Result<()> {
        // create roa style api client.
        let aliyun_openapi_client = Client::new(
            env::var("ACCESS_KEY_ID")?,
            env::var("ACCESS_KEY_SECRET")?,
            String::from("http://mt.aliyuncs.com"),
            String::from("2019-01-02"),
        );

        // create params.
        let mut params = HashMap::new();
        params.insert("SourceText", "你好");
        params.insert("SourceLanguage", "zh");
        params.insert("TargetLanguage", "en");
        params.insert("FormatType", "text");
        params.insert("Scene", "general");

        // call `DescribeRegions` with empty queries.
        let response = aliyun_openapi_client
            .post("/api/translate/web/general")
            .header(&[("Content-Type", "application/json")])
            .body(&json!(params).to_string())?
            .send()?;

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

        Ok(())
    }
}