Skip to main content

financial_api/
client.rs

1use std::env;
2use std::fmt;
3use std::time::Duration;
4
5use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
6use serde::Serialize;
7use serde::de::DeserializeOwned;
8use time::OffsetDateTime;
9use time::macros::offset;
10
11use crate::NaturalDate;
12use crate::error::{BusinessError, Error, ValidationError};
13
14const DEFAULT_BASE_URL: &str = "https://fuyao.aicubes.cn/";
15const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
16const API_KEY_HEADER: HeaderName = HeaderName::from_static("x-api-key");
17
18/// Validated API key stored as a sensitive HTTP header value.
19#[derive(Clone)]
20pub struct ApiKey(HeaderValue);
21
22impl ApiKey {
23    /// Validate an API key without exposing it in errors or debug output.
24    pub fn new(value: impl AsRef<str>) -> Result<Self, ValidationError> {
25        let value = value.as_ref();
26        if value.is_empty() {
27            return Err(ValidationError::new("api_key", "must not be empty"));
28        }
29        let mut header = HeaderValue::from_str(value)
30            .map_err(|_| ValidationError::new("api_key", "must be a valid HTTP header value"))?;
31        header.set_sensitive(true);
32        Ok(Self(header))
33    }
34}
35
36impl fmt::Debug for ApiKey {
37    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
38        formatter.write_str("ApiKey([REDACTED])")
39    }
40}
41
42/// Successful response after the common business envelope has been checked.
43#[derive(Debug, Clone, PartialEq)]
44pub struct Response<T> {
45    request_id: String,
46    data: T,
47}
48
49impl<T> Response<T> {
50    /// Upstream trace identifier.
51    #[must_use]
52    pub fn request_id(&self) -> &str {
53        &self.request_id
54    }
55
56    /// Endpoint-specific response data.
57    #[must_use]
58    pub const fn data(&self) -> &T {
59        &self.data
60    }
61
62    /// Consume the response and return its endpoint data.
63    #[must_use]
64    pub fn into_data(self) -> T {
65        self.data
66    }
67}
68
69impl Response<serde_json::Value> {
70    /// Decode lossless JSON data into an application-owned response type.
71    pub fn into_typed<T: DeserializeOwned>(self) -> Result<Response<T>, Error> {
72        let data = serde_json::from_value(self.data).map_err(|source| Error::InvalidResponse {
73            source: Some(source),
74        })?;
75        Ok(Response {
76            request_id: self.request_id,
77            data,
78        })
79    }
80}
81
82/// Builder for optional client-wide transport configuration.
83#[derive(Debug)]
84pub struct ClientBuilder {
85    api_key: ApiKey,
86    base_url: String,
87    timeout: Duration,
88    reference_date: Option<NaturalDate>,
89}
90
91impl ClientBuilder {
92    /// Override the API root, primarily for private deployments and tests.
93    #[must_use]
94    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
95        self.base_url = base_url.into();
96        self
97    }
98
99    /// Set the complete request timeout.
100    #[must_use]
101    pub const fn timeout(mut self, timeout: Duration) -> Self {
102        self.timeout = timeout;
103        self
104    }
105
106    /// Override the Shanghai natural date used by relative-date validation.
107    ///
108    /// This is useful for deterministic tests and historical request replay.
109    #[must_use]
110    pub const fn reference_date(mut self, date: NaturalDate) -> Self {
111        self.reference_date = Some(date);
112        self
113    }
114
115    /// Validate configuration and construct a reusable client.
116    pub fn build(self) -> Result<Client, Error> {
117        let mut base_url = reqwest::Url::parse(&self.base_url).map_err(|_| {
118            ValidationError::new("base_url", "must be a valid absolute hierarchical URL")
119        })?;
120        if base_url.cannot_be_a_base()
121            || base_url.query().is_some()
122            || base_url.fragment().is_some()
123        {
124            return Err(ValidationError::new(
125                "base_url",
126                "must be an absolute hierarchical URL without query or fragment",
127            )
128            .into());
129        }
130        if !matches!(base_url.scheme(), "http" | "https") {
131            return Err(ValidationError::new("base_url", "scheme must be http or https").into());
132        }
133        if !base_url.username().is_empty() || base_url.password().is_some() {
134            return Err(
135                ValidationError::new("base_url", "must not contain userinfo credentials").into(),
136            );
137        }
138        if !base_url.path().ends_with('/') {
139            let path = format!("{}/", base_url.path());
140            base_url.set_path(&path);
141        }
142
143        let mut headers = HeaderMap::new();
144        headers.insert(API_KEY_HEADER, self.api_key.0);
145        let http = reqwest::Client::builder()
146            .default_headers(headers)
147            .timeout(self.timeout)
148            .redirect(reqwest::redirect::Policy::none())
149            .build()
150            .map_err(|source| Error::InvalidConfiguration { source })?;
151
152        Ok(Client {
153            http,
154            base_url,
155            reference_date: self.reference_date,
156        })
157    }
158}
159
160/// Reusable async API client.
161#[derive(Debug, Clone)]
162pub struct Client {
163    http: reqwest::Client,
164    base_url: reqwest::Url,
165    reference_date: Option<NaturalDate>,
166}
167
168impl Client {
169    /// Start client configuration with an explicit API key.
170    #[must_use]
171    pub fn builder(api_key: ApiKey) -> ClientBuilder {
172        ClientBuilder {
173            api_key,
174            base_url: DEFAULT_BASE_URL.to_owned(),
175            timeout: DEFAULT_TIMEOUT,
176            reference_date: None,
177        }
178    }
179
180    /// Construct a client using `HITHINK_FINANCE_API_KEY`.
181    pub fn from_env() -> Result<Self, Error> {
182        let value = env::var("HITHINK_FINANCE_API_KEY").map_err(|_| Error::MissingApiKey)?;
183        Self::builder(ApiKey::new(value)?).build()
184    }
185
186    pub(crate) fn shanghai_today(&self) -> NaturalDate {
187        self.reference_date.unwrap_or_else(|| {
188            OffsetDateTime::now_utc()
189                .to_offset(offset!(+8))
190                .date()
191                .into()
192        })
193    }
194
195    pub(crate) async fn get<Q, T>(&self, path: &str, query: &Q) -> Result<Response<T>, Error>
196    where
197        Q: Serialize + ?Sized,
198        T: DeserializeOwned,
199    {
200        let url = self
201            .base_url
202            .join(path.trim_start_matches('/'))
203            .map_err(|_| {
204                ValidationError::new("endpoint_path", "could not be joined to the API base URL")
205            })?;
206        let response = self
207            .http
208            .get(url)
209            .query(query)
210            .send()
211            .await
212            .map_err(|source| Error::Transport { source })?;
213        let status = response.status();
214        if !status.is_success() {
215            return Err(Error::HttpStatus {
216                status: status.as_u16(),
217            });
218        }
219        let bytes = response
220            .bytes()
221            .await
222            .map_err(|source| Error::Transport { source })?;
223        let envelope: Envelope =
224            serde_json::from_slice(&bytes).map_err(|source| Error::InvalidResponse {
225                source: Some(source),
226            })?;
227
228        if envelope.code != 0 {
229            return Err(
230                BusinessError::new(envelope.code, envelope.message, envelope.request_id).into(),
231            );
232        }
233
234        let data =
235            serde_json::from_value(envelope.data).map_err(|source| Error::InvalidResponse {
236                source: Some(source),
237            })?;
238        Ok(Response {
239            request_id: envelope.request_id,
240            data,
241        })
242    }
243}
244
245#[derive(serde::Deserialize)]
246struct Envelope {
247    code: i64,
248    message: String,
249    request_id: String,
250    data: serde_json::Value,
251}