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