1mod configuration;
2mod credentials;
3mod reference_date;
4mod response;
5mod transport;
6
7use std::time::Duration;
8
9use reqwest::header::HeaderValue;
10
11use crate::NaturalDate;
12
13#[derive(Clone)]
15pub struct ApiKey(HeaderValue);
16
17#[derive(Debug, Clone, PartialEq)]
19pub struct Response<T> {
20 request_id: String,
21 data: T,
22}
23
24#[derive(Debug)]
26pub struct ClientBuilder {
27 api_key: ApiKey,
28 base_url: String,
29 timeout: Duration,
30 reference_date: Option<NaturalDate>,
31}
32
33#[derive(Debug, Clone)]
35pub struct Client {
36 http: reqwest::Client,
37 base_url: reqwest::Url,
38 reference_date: Option<NaturalDate>,
39}
40
41#[cfg(test)]
42mod tests {
43 use crate::{ApiKey, BusinessErrorKind, Client, Error, TickerSearchRequest};
44 use serde_json::json;
45 use std::time::Duration;
46 use wiremock::matchers::{header, method, path, query_param};
47 use wiremock::{Mock, MockServer, ResponseTemplate};
48
49 #[tokio::test]
50 async fn ticker_search_sends_auth_and_decodes_success_envelope() {
51 let server = MockServer::start().await;
52 Mock::given(method("GET"))
53 .and(path("/api/meta/tickers/search"))
54 .and(header("X-api-key", "test-api-key"))
55 .and(query_param("q", "贵州茅台"))
56 .and(query_param("limit", "10"))
57 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
58 "code": 0,
59 "message": "success",
60 "request_id": "request-1",
61 "data": {
62 "timestamp": 1716105600000_i64,
63 "item": [{
64 "thscode": "600519.SH",
65 "ticker": "600519",
66 "name": "贵州茅台",
67 "exchange": "SH",
68 "asset_type": "a-share",
69 "currency": "CNY"
70 }]
71 }
72 })))
73 .mount(&server)
74 .await;
75
76 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
77 .base_url(server.uri())
78 .build()
79 .unwrap();
80 let request = TickerSearchRequest::new("贵州茅台").unwrap();
81
82 let response = client.tickers_search(&request).await.unwrap();
83
84 assert_eq!(response.request_id(), "request-1");
85 assert_eq!(response.data().item[0].thscode.as_str(), "600519.SH");
86 }
87
88 #[tokio::test]
89 async fn business_failures_preserve_recovery_categories_after_transport_success() {
90 for (code, expected) in [
91 (2001, BusinessErrorKind::Authentication),
92 (2003, BusinessErrorKind::PermissionDenied),
93 (4001, BusinessErrorKind::RateLimited),
94 ] {
95 let server = MockServer::start().await;
96 Mock::given(method("GET"))
97 .and(path("/api/meta/tickers/search"))
98 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
99 "code": code,
100 "message": "request rejected",
101 "request_id": "request-2",
102 "data": null
103 })))
104 .mount(&server)
105 .await;
106
107 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
108 .base_url(server.uri())
109 .build()
110 .unwrap();
111 let request = TickerSearchRequest::new("600519").unwrap();
112
113 match client.tickers_search(&request).await.unwrap_err() {
114 Error::Business(error) => {
115 assert_eq!(error.kind(), expected);
116 assert_eq!(error.code(), code);
117 assert_eq!(error.request_id(), "request-2");
118 }
119 other => panic!("expected business error, got {other:?}"),
120 }
121 }
122 }
123
124 #[tokio::test]
125 async fn non_success_http_status_is_distinct_from_business_failure() {
126 let server = MockServer::start().await;
127 Mock::given(method("GET"))
128 .and(path("/api/meta/tickers/search"))
129 .respond_with(ResponseTemplate::new(503))
130 .mount(&server)
131 .await;
132
133 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
134 .base_url(server.uri())
135 .build()
136 .unwrap();
137 let request = TickerSearchRequest::new("600519").unwrap();
138
139 assert!(matches!(
140 client.tickers_search(&request).await.unwrap_err(),
141 Error::HttpStatus { status: 503 }
142 ));
143 }
144
145 #[tokio::test]
146 async fn redirects_never_forward_the_api_key_to_another_origin() {
147 let origin = MockServer::start().await;
148 let target = MockServer::start().await;
149 Mock::given(method("GET"))
150 .and(path("/api/meta/tickers/search"))
151 .respond_with(
152 ResponseTemplate::new(302)
153 .insert_header("Location", format!("{}/capture", target.uri())),
154 )
155 .mount(&origin)
156 .await;
157 Mock::given(method("GET"))
158 .and(path("/capture"))
159 .respond_with(ResponseTemplate::new(200))
160 .mount(&target)
161 .await;
162
163 let client = Client::builder(ApiKey::new("redirect-secret").unwrap())
164 .base_url(origin.uri())
165 .build()
166 .unwrap();
167 let request = TickerSearchRequest::new("600519").unwrap();
168
169 assert!(matches!(
170 client.tickers_search(&request).await.unwrap_err(),
171 Error::HttpStatus { status: 302 }
172 ));
173 assert!(target.received_requests().await.unwrap().is_empty());
174 }
175
176 #[tokio::test]
177 async fn request_timeout_is_a_transport_failure() {
178 let server = MockServer::start().await;
179 Mock::given(method("GET"))
180 .and(path("/api/meta/tickers/search"))
181 .respond_with(
182 ResponseTemplate::new(200)
183 .set_delay(Duration::from_millis(100))
184 .set_body_json(json!({"code": 0, "data": {}})),
185 )
186 .mount(&server)
187 .await;
188
189 let client = Client::builder(ApiKey::new("test-api-key").unwrap())
190 .base_url(server.uri())
191 .timeout(Duration::from_millis(1))
192 .build()
193 .unwrap();
194 let request = TickerSearchRequest::new("600519").unwrap();
195
196 assert!(matches!(
197 client.tickers_search(&request).await.unwrap_err(),
198 Error::Transport { .. }
199 ));
200 }
201
202 #[test]
203 fn client_debug_output_does_not_expose_the_credential() {
204 let client = Client::builder(ApiKey::new("super-secret-test-key").unwrap())
205 .build()
206 .unwrap();
207
208 assert!(!format!("{client:?}").contains("super-secret-test-key"));
209 }
210}