longbridge/calendar/
context.rs1use std::sync::Arc;
2
3use longbridge_httpcli::{HttpClient, Json, Method};
4use serde::Serialize;
5use tracing::{Subscriber, dispatcher, instrument::WithSubscriber};
6
7use crate::{Config, Result, calendar::types::*};
8
9struct InnerCalendarContext {
10 http_cli: HttpClient,
11 log_subscriber: Arc<dyn Subscriber + Send + Sync>,
12}
13
14impl Drop for InnerCalendarContext {
15 fn drop(&mut self) {
16 dispatcher::with_default(&self.log_subscriber.clone().into(), || {
17 tracing::info!("calendar context dropped");
18 });
19 }
20}
21
22#[derive(Clone)]
24pub struct CalendarContext(Arc<InnerCalendarContext>);
25
26impl CalendarContext {
27 pub fn new(config: Arc<Config>) -> Self {
29 let log_subscriber = config.create_log_subscriber("calendar");
30 dispatcher::with_default(&log_subscriber.clone().into(), || {
31 tracing::info!(language = ?config.language, "creating calendar context");
32 });
33 let ctx = Self(Arc::new(InnerCalendarContext {
34 http_cli: config.create_http_client(),
35 log_subscriber,
36 }));
37 dispatcher::with_default(&ctx.0.log_subscriber.clone().into(), || {
38 tracing::info!("calendar context created");
39 });
40 ctx
41 }
42
43 #[inline]
45 pub fn log_subscriber(&self) -> Arc<dyn Subscriber + Send + Sync> {
46 self.0.log_subscriber.clone()
47 }
48
49 pub async fn finance_calendar(
66 &self,
67 category: CalendarCategory,
68 start: impl Into<String>,
69 end: impl Into<String>,
70 market: Option<String>,
71 count: Option<i32>,
72 offset: Option<i32>,
73 next: Option<CalendarPageDirection>,
74 ) -> Result<CalendarEventsResponse> {
75 let cat_str = match category {
76 CalendarCategory::Report => "report",
77 CalendarCategory::Dividend => "dividend",
78 CalendarCategory::Split => "split",
79 CalendarCategory::Ipo => "ipo",
80 CalendarCategory::MacroData => "macrodata",
81 CalendarCategory::Closed => "closed",
82 CalendarCategory::Meeting => "meeting",
83 CalendarCategory::Merge => "merge",
84 };
85 let next_str = next.map(|d| match d {
86 CalendarPageDirection::Later => "later",
87 CalendarPageDirection::Earlier => "earlier",
88 });
89 #[derive(Serialize)]
90 struct Query {
91 date: String,
92 date_end: String,
93 #[serde(rename = "types[]")]
94 types: &'static str,
95 #[serde(rename = "markets[]", skip_serializing_if = "Option::is_none")]
96 markets: Option<String>,
97 #[serde(skip_serializing_if = "Option::is_none")]
98 count: Option<i32>,
99 #[serde(skip_serializing_if = "Option::is_none")]
100 offset: Option<i32>,
101 #[serde(skip_serializing_if = "Option::is_none")]
102 next: Option<&'static str>,
103 }
104 Ok(self
105 .0
106 .http_cli
107 .request(Method::GET, "/v1/quote/finance_calendar")
108 .query_params(Query {
109 date: start.into(),
110 date_end: end.into(),
111 types: cat_str,
112 markets: market,
113 count,
114 offset,
115 next: next_str,
116 })
117 .response::<Json<CalendarEventsResponse>>()
118 .send()
119 .with_subscriber(self.0.log_subscriber.clone())
120 .await?
121 .0)
122 }
123}