1use std::{
2 collections::HashMap,
3 fmt::{self, Display},
4 path::{Path, PathBuf},
5 str::FromStr,
6 sync::Arc,
7};
8
9pub(crate) use http::{HeaderName, HeaderValue, Request, header};
10use longport_httpcli::{
11 DC_REGION_HEADER, DcRegion, HttpClient, HttpClientConfig, Json, Method, is_cn,
12};
13use longport_oauth::OAuth;
14use num_enum::IntoPrimitive;
15use serde::{Deserialize, Serialize};
16use time::OffsetDateTime;
17use tokio_tungstenite::tungstenite::client::IntoClientRequest;
18use tracing::{Level, Subscriber, subscriber::NoSubscriber};
19use tracing_appender::rolling::{RollingFileAppender, Rotation};
20use tracing_subscriber::{filter::Targets, layer::SubscriberExt};
21
22use crate::error::Result;
23
24const DEFAULT_QUOTE_WS_URL: &str = "wss://openapi-quote.longportapp.com/v2";
25const DEFAULT_TRADE_WS_URL: &str = "wss://openapi-trade.longportapp.com/v2";
26const DEFAULT_QUOTE_WS_URL_CN: &str = "wss://openapi-quote.longport.cn/v2";
27const DEFAULT_TRADE_WS_URL_CN: &str = "wss://openapi-trade.longport.cn/v2";
28
29#[derive(Debug, Default, Copy, Clone, PartialEq, Eq, IntoPrimitive)]
31#[allow(non_camel_case_types)]
32#[repr(i32)]
33pub enum Language {
34 ZH_CN = 0,
36 ZH_HK = 2,
38 #[default]
40 EN = 1,
41}
42
43impl Language {
44 pub(crate) fn as_str(&self) -> &'static str {
45 match self {
46 Language::ZH_CN => "zh-CN",
47 Language::ZH_HK => "zh-HK",
48 Language::EN => "en",
49 }
50 }
51}
52
53impl FromStr for Language {
54 type Err = ();
55
56 fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
57 match s {
58 "zh-CN" => Ok(Language::ZH_CN),
59 "zh-HK" => Ok(Language::ZH_HK),
60 "en" => Ok(Language::EN),
61 _ => Err(()),
62 }
63 }
64}
65
66impl Display for Language {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.write_str(self.as_str())
69 }
70}
71
72#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
74pub enum PushCandlestickMode {
75 #[default]
77 Realtime,
78 Confirmed,
80}
81
82pub(crate) enum AuthMode {
84 ApiKey {
86 app_key: String,
87 app_secret: String,
88 access_token: String,
89 },
90 OAuth(OAuth),
92}
93
94impl Clone for AuthMode {
95 fn clone(&self) -> Self {
96 match self {
97 AuthMode::ApiKey {
98 app_key,
99 app_secret,
100 access_token,
101 } => AuthMode::ApiKey {
102 app_key: app_key.clone(),
103 app_secret: app_secret.clone(),
104 access_token: access_token.clone(),
105 },
106 AuthMode::OAuth(oauth) => AuthMode::OAuth(oauth.clone()),
107 }
108 }
109}
110
111impl fmt::Debug for AuthMode {
112 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113 match self {
114 AuthMode::ApiKey { app_key, .. } => {
115 f.debug_struct("ApiKey").field("app_key", app_key).finish()
116 }
117 AuthMode::OAuth(_) => f.debug_struct("OAuth").finish(),
118 }
119 }
120}
121
122#[derive(Debug, Default, Copy, Clone, PartialEq, Eq)]
133pub enum QuoteTransport {
134 #[default]
136 WebSocket,
137 Http,
141}
142
143impl FromStr for QuoteTransport {
144 type Err = ();
145
146 fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
147 match s.to_ascii_lowercase().as_str() {
148 "ws" => Ok(QuoteTransport::WebSocket),
149 "http" => Ok(QuoteTransport::Http),
150 _ => Err(()),
151 }
152 }
153}
154
155#[derive(Debug, Clone)]
157pub struct Config {
158 pub(crate) auth: AuthMode,
159 pub(crate) http_url: Option<String>,
160 pub(crate) quote_ws_url: Option<String>,
161 pub(crate) trade_ws_url: Option<String>,
162 pub(crate) enable_overnight: Option<bool>,
163 pub(crate) push_candlestick_mode: Option<PushCandlestickMode>,
164 pub(crate) enable_print_quote_packages: bool,
165 pub(crate) language: Language,
166 pub(crate) log_path: Option<PathBuf>,
167 pub(crate) custom_headers: HashMap<String, String>,
169 pub(crate) enable_papertrading: bool,
170 pub(crate) quote_transport: QuoteTransport,
171}
172
173fn env_var(suffix: &str) -> Option<String> {
175 std::env::var(format!("LONGPORT_{suffix}")).ok()
176}
177
178fn env_var_required(suffix: &str) -> Result<String> {
180 env_var(suffix).ok_or_else(|| {
181 longport_httpcli::HttpClientError::MissingEnvVar {
182 name: format!("LONGPORT_{suffix}"),
183 }
184 .into()
185 })
186}
187
188struct ConfigExtras {
191 http_url: Option<String>,
192 quote_ws_url: Option<String>,
193 trade_ws_url: Option<String>,
194 language: Language,
195 enable_overnight: Option<bool>,
196 push_candlestick_mode: Option<PushCandlestickMode>,
197 enable_print_quote_packages: bool,
198 log_path: Option<PathBuf>,
199 enable_papertrading: bool,
200 quote_transport: QuoteTransport,
201}
202
203impl ConfigExtras {
204 fn from_env() -> Self {
205 let language = env_var("LANGUAGE")
206 .and_then(|v| v.parse::<Language>().ok())
207 .unwrap_or(Language::EN);
208 let enable_overnight = env_var("ENABLE_OVERNIGHT").map(|v| v == "true");
209 let push_candlestick_mode = env_var("PUSH_CANDLESTICK_MODE").map(|v| match v.as_str() {
210 "confirmed" => PushCandlestickMode::Confirmed,
211 _ => PushCandlestickMode::Realtime,
212 });
213 let enable_print_quote_packages =
214 env_var("PRINT_QUOTE_PACKAGES").as_deref().unwrap_or("true") == "true";
215 let enable_papertrading = env_var("PAPERTRADING").as_deref() == Some("true");
216 Self {
217 http_url: env_var("HTTP_URL"),
218 quote_ws_url: env_var("QUOTE_WS_URL"),
219 trade_ws_url: env_var("TRADE_WS_URL"),
220 language,
221 enable_overnight,
222 push_candlestick_mode,
223 enable_print_quote_packages,
224 log_path: env_var("LOG_PATH").map(PathBuf::from),
225 enable_papertrading,
226 quote_transport: env_var("QUOTE_TRANSPORT")
227 .and_then(|v| {
228 let parsed = v.parse().ok();
229 if parsed.is_none() {
230 tracing::warn!(value = %v, "invalid LONGPORT_QUOTE_TRANSPORT, using ws");
231 }
232 parsed
233 })
234 .unwrap_or_default(),
235 }
236 }
237}
238
239impl Config {
240 pub fn from_apikey(
252 app_key: impl Into<String>,
253 app_secret: impl Into<String>,
254 access_token: impl Into<String>,
255 ) -> Self {
256 let _ = dotenv::dotenv();
257 let extras = ConfigExtras::from_env();
258 Self {
259 auth: AuthMode::ApiKey {
260 app_key: app_key.into(),
261 app_secret: app_secret.into(),
262 access_token: access_token.into(),
263 },
264 http_url: extras.http_url,
265 quote_ws_url: extras.quote_ws_url,
266 trade_ws_url: extras.trade_ws_url,
267 language: extras.language,
268 enable_overnight: extras.enable_overnight,
269 push_candlestick_mode: extras.push_candlestick_mode,
270 enable_print_quote_packages: extras.enable_print_quote_packages,
271 log_path: extras.log_path,
272 custom_headers: Default::default(),
273 enable_papertrading: extras.enable_papertrading,
274 quote_transport: extras.quote_transport,
275 }
276 }
277
278 pub fn from_oauth(oauth: OAuth) -> Self {
311 let _ = dotenv::dotenv();
312 let extras = ConfigExtras::from_env();
313 Self {
314 auth: AuthMode::OAuth(oauth),
315 http_url: extras.http_url,
316 quote_ws_url: extras.quote_ws_url,
317 trade_ws_url: extras.trade_ws_url,
318 language: extras.language,
319 enable_overnight: extras.enable_overnight,
320 push_candlestick_mode: extras.push_candlestick_mode,
321 enable_print_quote_packages: extras.enable_print_quote_packages,
322 log_path: extras.log_path,
323 custom_headers: Default::default(),
324 enable_papertrading: extras.enable_papertrading,
325 quote_transport: extras.quote_transport,
326 }
327 }
328
329 pub fn from_apikey_env() -> Result<Self> {
361 let _ = dotenv::dotenv();
362
363 let app_key = env_var_required("APP_KEY")?;
364 let app_secret = env_var_required("APP_SECRET")?;
365 let access_token = env_var_required("ACCESS_TOKEN")?;
366 let extras = ConfigExtras::from_env();
367
368 Ok(Config {
369 auth: AuthMode::ApiKey {
370 app_key,
371 app_secret,
372 access_token,
373 },
374 http_url: extras.http_url,
375 quote_ws_url: extras.quote_ws_url,
376 trade_ws_url: extras.trade_ws_url,
377 language: extras.language,
378 enable_overnight: extras.enable_overnight,
379 push_candlestick_mode: extras.push_candlestick_mode,
380 enable_print_quote_packages: extras.enable_print_quote_packages,
381 log_path: extras.log_path,
382 custom_headers: Default::default(),
383 enable_papertrading: extras.enable_papertrading,
384 quote_transport: extras.quote_transport,
385 })
386 }
387
388 #[must_use]
394 pub fn http_url(mut self, url: impl Into<String>) -> Self {
395 self.http_url = Some(url.into());
396 self
397 }
398
399 #[must_use]
405 pub fn quote_ws_url(self, url: impl Into<String>) -> Self {
406 Self {
407 quote_ws_url: Some(url.into()),
408 ..self
409 }
410 }
411
412 #[must_use]
418 pub fn trade_ws_url(self, url: impl Into<String>) -> Self {
419 Self {
420 trade_ws_url: Some(url.into()),
421 ..self
422 }
423 }
424
425 pub fn language(self, language: Language) -> Self {
429 Self { language, ..self }
430 }
431
432 pub fn enable_overnight(self) -> Self {
436 Self {
437 enable_overnight: Some(true),
438 ..self
439 }
440 }
441
442 pub fn push_candlestick_mode(self, mode: PushCandlestickMode) -> Self {
446 Self {
447 push_candlestick_mode: Some(mode),
448 ..self
449 }
450 }
451
452 pub fn dont_print_quote_packages(self) -> Self {
454 Self {
455 enable_print_quote_packages: false,
456 ..self
457 }
458 }
459
460 pub fn enable_papertrading(mut self) -> Self {
473 self.enable_papertrading = true;
474 self
475 }
476
477 pub fn quote_transport(self, quote_transport: QuoteTransport) -> Self {
482 Self {
483 quote_transport,
484 ..self
485 }
486 }
487
488 pub fn create_metadata(&self) -> HashMap<String, String> {
490 let mut metadata = HashMap::new();
491 metadata.insert("accept-language".to_string(), self.language.to_string());
492 if self.enable_overnight.unwrap_or_default() {
493 metadata.insert("need_over_night_quote".to_string(), "true".to_string());
494 }
495 metadata
496 }
497
498 #[inline]
499 pub(crate) fn create_http_client(&self) -> HttpClient {
500 let mut config = match &self.auth {
501 AuthMode::ApiKey {
502 app_key,
503 app_secret,
504 access_token,
505 } => HttpClientConfig::from_apikey(app_key, app_secret, access_token),
506 AuthMode::OAuth(oauth) => HttpClientConfig::from_oauth(oauth.clone()),
507 };
508 if let Some(url) = &self.http_url {
509 config = config.http_url(url.clone());
510 }
511
512 let mut client =
513 HttpClient::new(config).header(header::ACCEPT_LANGUAGE, self.language.as_str());
514 for (key, value) in &self.custom_headers {
515 client = client.header(key.as_str(), value.as_str());
516 }
517 if self.enable_papertrading {
518 client = client.header("x-papertrading", "true");
519 }
520 client
521 }
522
523 pub async fn refresh_access_token(&self, expired_at: Option<OffsetDateTime>) -> Result<String> {
534 #[derive(Debug, Serialize)]
535 struct Request {
536 expired_at: String,
537 }
538
539 #[derive(Debug, Deserialize)]
540 struct Response {
541 token: String,
542 }
543
544 let request = Request {
545 expired_at: expired_at
546 .unwrap_or_else(|| OffsetDateTime::now_utc() + time::Duration::days(90))
547 .format(&time::format_description::well_known::Rfc3339)
548 .unwrap(),
549 };
550
551 let new_token = self
552 .create_http_client()
553 .request(Method::GET, "/v1/token/refresh")
554 .query_params(request)
555 .response::<Json<Response>>()
556 .send()
557 .await?
558 .0
559 .token;
560 Ok(new_token)
561 }
562
563 #[cfg(feature = "blocking")]
575 #[cfg_attr(docsrs, doc(cfg(feature = "blocking")))]
576 pub fn refresh_access_token_blocking(
577 &self,
578 expired_at: Option<OffsetDateTime>,
579 ) -> Result<String> {
580 tokio::runtime::Builder::new_current_thread()
581 .enable_all()
582 .build()
583 .expect("create tokio runtime")
584 .block_on(self.refresh_access_token(expired_at))
585 }
586
587 async fn auth_dc_region(&self) -> DcRegion {
591 match &self.auth {
592 AuthMode::ApiKey {
593 app_key,
594 app_secret,
595 access_token,
596 } => DcRegion::from_credentials(&[app_key, access_token, app_secret]),
597 AuthMode::OAuth(oauth) => oauth
598 .access_token()
599 .await
600 .map(|token| DcRegion::from_credential(&token))
601 .unwrap_or(DcRegion::Ap),
602 }
603 }
604
605 fn create_ws_request(
606 &self,
607 url: &str,
608 dc_region: DcRegion,
609 ) -> tokio_tungstenite::tungstenite::Result<Request<()>> {
610 let mut request = url.into_client_request()?;
611 request.headers_mut().append(
612 header::ACCEPT_LANGUAGE,
613 HeaderValue::from_str(self.language.as_str()).unwrap(),
614 );
615 for (key, value) in &self.custom_headers {
616 if let (Ok(name), Ok(val)) = (
617 HeaderName::from_bytes(key.as_bytes()),
618 HeaderValue::from_str(value),
619 ) {
620 request.headers_mut().append(name, val);
621 }
622 }
623 if !self
627 .custom_headers
628 .keys()
629 .any(|key| key.eq_ignore_ascii_case(DC_REGION_HEADER))
630 {
631 request.headers_mut().append(
632 HeaderName::from_static(DC_REGION_HEADER),
633 HeaderValue::from_static(dc_region.as_str()),
634 );
635 }
636 Ok(request)
637 }
638
639 pub(crate) async fn create_quote_ws_request(
640 &self,
641 ) -> (&str, tokio_tungstenite::tungstenite::Result<Request<()>>) {
642 let dc_region = self.auth_dc_region().await;
643 match self.quote_ws_url.as_deref() {
644 Some(url) => (url, self.create_ws_request(url, dc_region)),
645 None => {
646 let url = if is_cn().await {
647 DEFAULT_QUOTE_WS_URL_CN
648 } else {
649 DEFAULT_QUOTE_WS_URL
650 };
651 (url, self.create_ws_request(url, dc_region))
652 }
653 }
654 }
655
656 pub(crate) async fn create_trade_ws_request(
657 &self,
658 ) -> (&str, tokio_tungstenite::tungstenite::Result<Request<()>>) {
659 let dc_region = self.auth_dc_region().await;
660 match self.trade_ws_url.as_deref() {
661 Some(url) => (url, self.create_ws_request(url, dc_region)),
662 None => {
663 let url = if is_cn().await {
664 DEFAULT_TRADE_WS_URL_CN
665 } else {
666 DEFAULT_TRADE_WS_URL
667 };
668 (url, self.create_ws_request(url, dc_region))
669 }
670 }
671 }
672
673 pub fn log_path(mut self, path: impl Into<PathBuf>) -> Self {
677 self.log_path = Some(path.into());
678 self
679 }
680
681 #[must_use]
683 pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
684 self.custom_headers.insert(key.into(), value.into());
685 self
686 }
687
688 #[must_use]
695 pub fn dc_region(self, region: DcRegion) -> Self {
696 self.header(DC_REGION_HEADER, region.as_str())
697 }
698
699 pub fn set_http_url(&mut self, url: impl Into<String>) {
701 self.http_url = Some(url.into());
702 }
703
704 pub fn set_quote_ws_url(&mut self, url: impl Into<String>) {
706 self.quote_ws_url = Some(url.into());
707 }
708
709 pub fn set_trade_ws_url(&mut self, url: impl Into<String>) {
711 self.trade_ws_url = Some(url.into());
712 }
713
714 pub fn set_language(&mut self, language: Language) {
716 self.language = language;
717 }
718
719 pub fn set_enable_overnight(&mut self) {
721 self.enable_overnight = Some(true);
722 }
723
724 pub fn set_push_candlestick_mode(&mut self, mode: PushCandlestickMode) {
726 self.push_candlestick_mode = Some(mode);
727 }
728
729 pub fn set_dont_print_quote_packages(&mut self) {
731 self.enable_print_quote_packages = false;
732 }
733
734 pub fn set_enable_papertrading(&mut self) {
738 self.enable_papertrading = true;
739 }
740
741 pub fn set_quote_transport(&mut self, quote_transport: QuoteTransport) {
745 self.quote_transport = quote_transport;
746 }
747
748 pub fn set_log_path(&mut self, path: impl Into<PathBuf>) {
750 self.log_path = Some(path.into());
751 }
752
753 pub(crate) fn create_log_subscriber(
754 &self,
755 path: impl AsRef<Path>,
756 ) -> Arc<dyn Subscriber + Send + Sync> {
757 fn internal_create_log_subscriber(
758 config: &Config,
759 path: impl AsRef<Path>,
760 ) -> Option<Arc<dyn Subscriber + Send + Sync>> {
761 let log_path = config.log_path.as_ref()?;
762 let appender = RollingFileAppender::builder()
763 .rotation(Rotation::DAILY)
764 .filename_suffix("log")
765 .build(log_path.join(path))
766 .ok()?;
767 Some(Arc::new(
768 tracing_subscriber::fmt()
769 .with_writer(appender)
770 .with_ansi(false)
771 .finish()
772 .with(Targets::new().with_targets([("longport", Level::INFO)])),
773 ))
774 }
775
776 internal_create_log_subscriber(self, path).unwrap_or_else(|| Arc::new(NoSubscriber::new()))
777 }
778}
779
780#[cfg(test)]
781mod tests {
782 use super::*;
783
784 #[test]
785 fn test_config_from_apikey() {
786 let config = Config::from_apikey("app-key", "app-secret", "token");
787 assert_eq!(config.language, Language::EN);
788 match &config.auth {
789 AuthMode::ApiKey {
790 app_key,
791 app_secret,
792 access_token,
793 } => {
794 assert_eq!(app_key, "app-key");
795 assert_eq!(app_secret, "app-secret");
796 assert_eq!(access_token, "token");
797 }
798 _ => panic!("Expected ApiKey auth mode"),
799 }
800 }
801
802 #[test]
803 fn test_config_default_values() {
804 let config = Config::from_apikey("key", "secret", "token");
805
806 assert_eq!(config.enable_overnight, None);
808 assert_eq!(config.push_candlestick_mode, None);
809 assert!(config.enable_print_quote_packages);
810 }
811
812 #[test]
813 fn test_enable_papertrading_builder() {
814 let config = Config::from_apikey("key", "secret", "token").enable_papertrading();
815 assert!(config.enable_papertrading);
816 }
817
818 #[test]
819 fn test_enable_papertrading_setter() {
820 let mut config = Config::from_apikey("key", "secret", "token");
821 config.set_enable_papertrading();
822 assert!(config.enable_papertrading);
823 }
824}