longbridge/asset/
context.rs1use std::sync::Arc;
2
3use longbridge_httpcli::{HttpClient, Json, Method};
4use serde::{Serialize, de::DeserializeOwned};
5use tracing::{Subscriber, dispatcher, instrument::WithSubscriber};
6
7use crate::{
8 Config, Result,
9 asset::{
10 GetStatementListOptions, GetStatementListResponse, GetStatementOptions,
11 GetStatementResponse, core,
12 },
13};
14
15struct InnerAssetContext {
16 http_cli: HttpClient,
17 log_subscriber: Arc<dyn Subscriber + Send + Sync>,
18}
19
20impl Drop for InnerAssetContext {
21 fn drop(&mut self) {
22 dispatcher::with_default(&self.log_subscriber.clone().into(), || {
23 tracing::info!("asset context dropped");
24 });
25 }
26}
27
28#[derive(Clone)]
30pub struct AssetContext(Arc<InnerAssetContext>);
31
32impl AssetContext {
33 pub fn new(config: Arc<Config>) -> Self {
35 let log_subscriber = config.create_log_subscriber("asset");
36
37 dispatcher::with_default(&log_subscriber.clone().into(), || {
38 tracing::info!(language = ?config.language, "creating asset context");
39 });
40
41 let ctx = Self(Arc::new(InnerAssetContext {
42 http_cli: config.create_http_client(),
43 log_subscriber,
44 }));
45
46 dispatcher::with_default(&ctx.0.log_subscriber.clone().into(), || {
47 tracing::info!("asset context created");
48 });
49
50 ctx
51 }
52
53 #[inline]
55 pub fn log_subscriber(&self) -> Arc<dyn Subscriber + Send + Sync> {
56 self.0.log_subscriber.clone()
57 }
58
59 async fn get<R, Q>(&self, path: &'static str, query: Q) -> Result<R>
60 where
61 R: DeserializeOwned + Send + Sync + 'static,
62 Q: Serialize + Send + Sync,
63 {
64 Ok(self
65 .0
66 .http_cli
67 .request(Method::GET, path)
68 .query_params(query)
69 .response::<Json<R>>()
70 .send()
71 .with_subscriber(self.0.log_subscriber.clone())
72 .await?
73 .0)
74 }
75
76 pub async fn statements(
80 &self,
81 options: GetStatementListOptions,
82 ) -> Result<GetStatementListResponse> {
83 self.get(core::GET_STATEMENT_DATA_LIST_PATH, options).await
84 }
85
86 pub async fn statement_download_url(
90 &self,
91 options: GetStatementOptions,
92 ) -> Result<GetStatementResponse> {
93 self.get(core::GET_STATEMENT_DATA_DOWNLOAD_URL_PATH, options)
94 .await
95 }
96}