longport_httpcli/
request.rs

1use std::{
2    convert::Infallible,
3    error::Error,
4    fmt::Debug,
5    marker::PhantomData,
6    time::{Duration, Instant},
7};
8
9use reqwest::{
10    header::{HeaderMap, HeaderName, HeaderValue},
11    Method, StatusCode,
12};
13use serde::{de::DeserializeOwned, Deserialize, Serialize};
14
15use crate::{
16    is_cn,
17    signature::{signature, SignatureParams},
18    timestamp::Timestamp,
19    HttpClient, HttpClientError, HttpClientResult,
20};
21
22const HTTP_URL: &str = "https://openapi.longportapp.com";
23const HTTP_URL_CN: &str = "https://openapi.longportapp.cn";
24
25const USER_AGENT: &str = "openapi-sdk";
26const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
27const RETRY_COUNT: usize = 5;
28const RETRY_INITIAL_DELAY: Duration = Duration::from_millis(100);
29const RETRY_FACTOR: f32 = 2.0;
30
31/// A JSON payload
32#[derive(Debug)]
33pub struct Json<T>(pub T);
34
35/// Represents a type that can parse from payload
36pub trait FromPayload: Sized + Send + Sync + 'static {
37    /// A error type
38    type Err: Error;
39
40    /// Parse the payload to this object
41    fn parse_from_bytes(data: &[u8]) -> Result<Self, Self::Err>;
42}
43
44/// Represents a type that can convert to payload
45pub trait ToPayload: Debug + Sized + Send + Sync + 'static {
46    /// A error type
47    type Err: Error;
48
49    /// Convert this object to the payload
50    fn to_bytes(&self) -> Result<Vec<u8>, Self::Err>;
51}
52
53impl<T> FromPayload for Json<T>
54where
55    T: DeserializeOwned + Send + Sync + 'static,
56{
57    type Err = serde_json::Error;
58
59    #[inline]
60    fn parse_from_bytes(data: &[u8]) -> Result<Self, Self::Err> {
61        Ok(Json(serde_json::from_slice(data)?))
62    }
63}
64
65impl<T> ToPayload for Json<T>
66where
67    T: Debug + Serialize + Send + Sync + 'static,
68{
69    type Err = serde_json::Error;
70
71    #[inline]
72    fn to_bytes(&self) -> Result<Vec<u8>, Self::Err> {
73        serde_json::to_vec(&self.0)
74    }
75}
76
77impl FromPayload for String {
78    type Err = std::string::FromUtf8Error;
79
80    #[inline]
81    fn parse_from_bytes(data: &[u8]) -> Result<Self, Self::Err> {
82        String::from_utf8(data.to_vec())
83    }
84}
85
86impl ToPayload for String {
87    type Err = std::string::FromUtf8Error;
88
89    #[inline]
90    fn to_bytes(&self) -> Result<Vec<u8>, Self::Err> {
91        Ok(self.clone().into_bytes())
92    }
93}
94
95impl FromPayload for () {
96    type Err = Infallible;
97
98    #[inline]
99    fn parse_from_bytes(_data: &[u8]) -> Result<Self, Self::Err> {
100        Ok(())
101    }
102}
103
104impl ToPayload for () {
105    type Err = Infallible;
106
107    #[inline]
108    fn to_bytes(&self) -> Result<Vec<u8>, Self::Err> {
109        Ok(vec![])
110    }
111}
112
113#[derive(Deserialize)]
114struct OpenApiResponse {
115    code: i32,
116    message: String,
117    data: Option<Box<serde_json::value::RawValue>>,
118}
119
120/// A request builder
121pub struct RequestBuilder<'a, T, Q, R> {
122    client: &'a HttpClient,
123    method: Method,
124    path: String,
125    headers: HeaderMap,
126    body: Option<T>,
127    query_params: Option<Q>,
128    mark_resp: PhantomData<R>,
129}
130
131impl<'a> RequestBuilder<'a, (), (), ()> {
132    pub(crate) fn new(client: &'a HttpClient, method: Method, path: impl Into<String>) -> Self {
133        Self {
134            client,
135            method,
136            path: path.into(),
137            headers: Default::default(),
138            body: None,
139            query_params: None,
140            mark_resp: PhantomData,
141        }
142    }
143}
144
145impl<'a, T, Q, R> RequestBuilder<'a, T, Q, R> {
146    /// Set the request body
147    #[must_use]
148    pub fn body<T2>(self, body: T2) -> RequestBuilder<'a, T2, Q, R>
149    where
150        T2: ToPayload,
151    {
152        RequestBuilder {
153            client: self.client,
154            method: self.method,
155            path: self.path,
156            headers: self.headers,
157            body: Some(body),
158            query_params: self.query_params,
159            mark_resp: self.mark_resp,
160        }
161    }
162
163    /// Set the header
164    #[must_use]
165    pub fn header<K, V>(mut self, key: K, value: V) -> Self
166    where
167        K: TryInto<HeaderName>,
168        V: TryInto<HeaderValue>,
169    {
170        let key = key.try_into();
171        let value = value.try_into();
172        if let (Ok(key), Ok(value)) = (key, value) {
173            self.headers.insert(key, value);
174        }
175        self
176    }
177
178    /// Set the query string
179    #[must_use]
180    pub fn query_params<Q2>(self, params: Q2) -> RequestBuilder<'a, T, Q2, R>
181    where
182        Q2: Serialize + Send + Sync,
183    {
184        RequestBuilder {
185            client: self.client,
186            method: self.method,
187            path: self.path,
188            headers: self.headers,
189            body: self.body,
190            query_params: Some(params),
191            mark_resp: self.mark_resp,
192        }
193    }
194
195    /// Set the response body type
196    #[must_use]
197    pub fn response<R2>(self) -> RequestBuilder<'a, T, Q, R2>
198    where
199        R2: FromPayload,
200    {
201        RequestBuilder {
202            client: self.client,
203            method: self.method,
204            path: self.path,
205            headers: self.headers,
206            body: self.body,
207            query_params: self.query_params,
208            mark_resp: PhantomData,
209        }
210    }
211}
212
213impl<T, Q, R> RequestBuilder<'_, T, Q, R>
214where
215    T: ToPayload,
216    Q: Serialize + Send,
217    R: FromPayload,
218{
219    async fn http_url(&self) -> &str {
220        if let Some(url) = self.client.config.http_url.as_deref() {
221            return url;
222        }
223
224        if is_cn().await {
225            HTTP_URL_CN
226        } else {
227            HTTP_URL
228        }
229    }
230
231    async fn do_send(&self) -> HttpClientResult<R> {
232        let HttpClient {
233            http_cli,
234            config,
235            default_headers,
236        } = &self.client;
237        let timestamp = self
238            .headers
239            .get("X-Timestamp")
240            .and_then(|value| value.to_str().ok())
241            .and_then(|value| value.parse().ok())
242            .unwrap_or_else(Timestamp::now);
243        let app_key_value =
244            HeaderValue::from_str(&config.app_key).map_err(|_| HttpClientError::InvalidApiKey)?;
245        let access_token_value = HeaderValue::from_str(&config.access_token)
246            .map_err(|_| HttpClientError::InvalidAccessToken)?;
247
248        let url = self.http_url().await;
249        let mut request_builder = http_cli
250            .request(self.method.clone(), format!("{}{}", url, self.path))
251            .headers(default_headers.clone())
252            .headers(self.headers.clone())
253            .header("User-Agent", USER_AGENT)
254            .header("X-Api-Key", app_key_value)
255            .header("Authorization", access_token_value)
256            .header("X-Timestamp", timestamp.to_string())
257            .header("Content-Type", "application/json; charset=utf-8");
258
259        // set the request body
260        if let Some(body) = &self.body {
261            let body = body
262                .to_bytes()
263                .map_err(|err| HttpClientError::SerializeRequestBody(err.to_string()))?;
264            request_builder = request_builder.body(body);
265        }
266
267        let mut request = request_builder.build().expect("invalid request");
268
269        // set the query string
270        if let Some(query_params) = &self.query_params {
271            let query_string = crate::qs::to_string(&query_params)?;
272            request.url_mut().set_query(Some(&query_string));
273        }
274
275        // signature the request
276        let sign = signature(SignatureParams {
277            request: &request,
278            app_key: &config.app_key,
279            access_token: Some(&config.access_token),
280            app_secret: &config.app_secret,
281            timestamp,
282        });
283        request.headers_mut().insert(
284            "X-Api-Signature",
285            HeaderValue::from_maybe_shared(sign).expect("valid signature"),
286        );
287
288        if let Some(body) = &self.body {
289            tracing::info!(method = %request.method(), url = %request.url(), body = ?body, "http request");
290        } else {
291            tracing::info!(method = %request.method(), url = %request.url(), "http request");
292        }
293
294        let s = Instant::now();
295
296        // send request
297        let (status, trace_id, text) = tokio::time::timeout(REQUEST_TIMEOUT, async move {
298            let resp = http_cli
299                .execute(request)
300                .await
301                .map_err(|err| HttpClientError::Http(err.into()))?;
302            let status = resp.status();
303            let trace_id = resp
304                .headers()
305                .get("x-trace-id")
306                .and_then(|value| value.to_str().ok())
307                .unwrap_or_default()
308                .to_string();
309            let text = resp
310                .text()
311                .await
312                .map_err(|err| HttpClientError::Http(err.into()))?;
313            Ok::<_, HttpClientError>((status, trace_id, text))
314        })
315        .await
316        .map_err(|_| HttpClientError::RequestTimeout)??;
317
318        tracing::info!(duration = ?s.elapsed(), body = %text.as_str(), "http response");
319
320        let resp = match serde_json::from_str::<OpenApiResponse>(&text) {
321            Ok(resp) if resp.code == 0 => resp.data.ok_or(HttpClientError::UnexpectedResponse),
322            Ok(resp) => Err(HttpClientError::OpenApi {
323                code: resp.code,
324                message: resp.message,
325                trace_id,
326            }),
327            Err(err) if status == StatusCode::OK => {
328                Err(HttpClientError::DeserializeResponseBody(err.to_string()))
329            }
330            Err(_) => Err(HttpClientError::BadStatus(status)),
331        }?;
332
333        R::parse_from_bytes(resp.get().as_bytes())
334            .map_err(|err| HttpClientError::DeserializeResponseBody(err.to_string()))
335    }
336
337    /// Send request and get the response
338    pub async fn send(self) -> HttpClientResult<R> {
339        match self.do_send().await {
340            Ok(resp) => Ok(resp),
341            Err(HttpClientError::BadStatus(StatusCode::TOO_MANY_REQUESTS)) => {
342                let mut retry_delay = RETRY_INITIAL_DELAY;
343
344                for _ in 0..RETRY_COUNT {
345                    tokio::time::sleep(retry_delay).await;
346
347                    match self.do_send().await {
348                        Ok(resp) => return Ok(resp),
349                        Err(HttpClientError::BadStatus(StatusCode::TOO_MANY_REQUESTS)) => {
350                            retry_delay =
351                                Duration::from_secs_f32(retry_delay.as_secs_f32() * RETRY_FACTOR);
352                            continue;
353                        }
354                        Err(err) => return Err(err),
355                    }
356                }
357
358                Err(HttpClientError::BadStatus(StatusCode::TOO_MANY_REQUESTS))
359            }
360            Err(err) => Err(err),
361        }
362    }
363}