Skip to main content

cratestack_client_rust/client/
core.rs

1use std::sync::Arc;
2
3use cratestack_codec_cbor::CborCodec;
4
5use crate::auth::RequestAuthorizer;
6use crate::codec::HttpClientCodec;
7use crate::config::ClientConfig;
8use crate::error::ClientError;
9use crate::state::{ClientStateStore, InMemoryStateStore, PersistedClientState};
10
11#[derive(Clone)]
12pub struct CratestackClient<C = CborCodec> {
13    pub(crate) http: reqwest::Client,
14    pub(crate) config: ClientConfig,
15    pub(crate) codec: C,
16    pub(crate) state_store: Arc<dyn ClientStateStore>,
17    pub(crate) request_authorizer: Option<Arc<dyn RequestAuthorizer>>,
18}
19
20impl CratestackClient<CborCodec> {
21    pub fn cbor(config: ClientConfig) -> Self {
22        Self::new(config, CborCodec)
23    }
24}
25
26impl<C> CratestackClient<C>
27where
28    C: HttpClientCodec,
29{
30    pub fn new(config: ClientConfig, codec: C) -> Self {
31        Self {
32            http: reqwest::Client::new(),
33            config,
34            codec,
35            state_store: Arc::new(InMemoryStateStore::default()),
36            request_authorizer: None,
37        }
38    }
39
40    pub fn with_http_client(config: ClientConfig, codec: C, http: reqwest::Client) -> Self {
41        Self {
42            http,
43            config,
44            codec,
45            state_store: Arc::new(InMemoryStateStore::default()),
46            request_authorizer: None,
47        }
48    }
49
50    pub fn with_state_store(mut self, state_store: Arc<dyn ClientStateStore>) -> Self {
51        self.state_store = state_store;
52        self
53    }
54
55    pub fn with_optional_state_store(self, state_store: Option<Arc<dyn ClientStateStore>>) -> Self {
56        match state_store {
57            Some(state_store) => self.with_state_store(state_store),
58            None => self,
59        }
60    }
61
62    pub fn with_request_authorizer(
63        mut self,
64        request_authorizer: Arc<dyn RequestAuthorizer>,
65    ) -> Self {
66        self.request_authorizer = Some(request_authorizer);
67        self
68    }
69
70    pub fn state(&self) -> Result<PersistedClientState, ClientError> {
71        self.state_store.load()
72    }
73}