Skip to main content

tessera/
client.rs

1//! Synchronous Tessera API client.
2
3#[cfg(feature = "polars")]
4use polars::prelude::{DataFrame, LazyFrame};
5
6use crate::base::{
7    PreparedRequest, datasets_request, download_request, parse_retry_after, partitions_request,
8    should_retry,
9};
10use crate::config::{ClientConfig, backoff_delay};
11use crate::error::{TesseraError, error_from_response};
12use crate::models::{
13    DatasetsResponse, DownloadBody, IntoCoins, IntoMonths, PartitionRef, PartitionsResponse,
14    download_urls,
15};
16#[cfg(any(feature = "polars", feature = "duckdb"))]
17use crate::readers::ResolvedPartition;
18use crate::readers::expand_refs;
19#[cfg(any(feature = "polars", feature = "duckdb"))]
20use crate::resolver::resolve_sync;
21
22/// A synchronous client for the Tessera API.
23///
24/// Call [`TesseraClient::new`] with an explicit API key or rely on
25/// `$TESSERA_API_KEY`.
26///
27/// # Panics
28///
29/// The constructor builds a private tokio runtime (needed for Polars cloud
30/// reads), so a `TesseraClient` must not be constructed or used from inside
31/// another async runtime — use [`crate::AsyncTesseraClient`] there instead.
32pub struct TesseraClient {
33    config: ClientConfig,
34    http: reqwest::blocking::Client,
35    #[cfg(feature = "polars")]
36    runtime: tokio::runtime::Runtime,
37}
38
39impl TesseraClient {
40    /// Create a client with defaults, resolving the key from `api_key` or
41    /// `$TESSERA_API_KEY`.
42    ///
43    /// # Errors
44    ///
45    /// Returns [`TesseraError::Configuration`] when no API key can be resolved.
46    pub fn new(api_key: Option<&str>) -> Result<Self, TesseraError> {
47        Self::from_config(ClientConfig::new(api_key)?)
48    }
49
50    /// Create a client from a fully-specified [`ClientConfig`].
51    ///
52    /// # Errors
53    ///
54    /// Returns [`TesseraError::Network`] when the HTTP client or tokio runtime
55    /// cannot be built.
56    pub fn from_config(config: ClientConfig) -> Result<Self, TesseraError> {
57        let http = reqwest::blocking::Client::builder()
58            .redirect(reqwest::redirect::Policy::none())
59            .default_headers(config.auth_headers())
60            .timeout(config.timeout)
61            .build()
62            .map_err(|err| TesseraError::Network(err.to_string()))?;
63        #[cfg(feature = "polars")]
64        let runtime = tokio::runtime::Builder::new_multi_thread()
65            .enable_all()
66            .build()
67            .map_err(|err| TesseraError::Network(err.to_string()))?;
68        Ok(Self {
69            config,
70            http,
71            #[cfg(feature = "polars")]
72            runtime,
73        })
74    }
75
76    /// The resolved configuration this client was built with.
77    #[must_use]
78    pub fn config(&self) -> &ClientConfig {
79        &self.config
80    }
81
82    /// Close the underlying HTTP connection pool.
83    pub fn close(&mut self) {
84        // reqwest clients tear their pools down on drop; nothing else to do.
85    }
86
87    /// Send a prepared request, retrying transient failures.
88    fn request(
89        &self,
90        prepared: &PreparedRequest,
91    ) -> Result<reqwest::blocking::Response, TesseraError> {
92        for attempt in 0..=self.config.max_retries {
93            let last = attempt == self.config.max_retries;
94            let url = format!("{}{}", self.config.base_url, prepared.path);
95            let sent = self.http.get(url).query(&prepared.params).send();
96            match sent {
97                Err(err) if err.is_connect() || err.is_timeout() || err.is_request() => {
98                    if last {
99                        return Err(TesseraError::Network(format!(
100                            "network error contacting Tessera: {err}"
101                        )));
102                    }
103                    std::thread::sleep(backoff_delay(attempt, None));
104                }
105                Ok(response) if !last && should_retry(response.status().as_u16()) => {
106                    let retry_after = parse_retry_after(response.headers());
107                    std::thread::sleep(backoff_delay(attempt, retry_after));
108                }
109                Ok(response) => {
110                    if response.status().is_success() {
111                        return Ok(response);
112                    }
113                    let status = response.status().as_u16();
114                    let body = response
115                        .bytes()
116                        .map_err(|err| TesseraError::Network(err.to_string()))?;
117                    return Err(error_from_response(status, &body));
118                }
119                Err(err) => {
120                    return Err(TesseraError::Network(format!(
121                        "network error contacting Tessera: {err}"
122                    )));
123                }
124            }
125        }
126        unreachable!("retry loop always returns")
127    }
128
129    /// Parse a success response body as JSON.
130    fn json<T: serde::de::DeserializeOwned>(
131        response: reqwest::blocking::Response,
132    ) -> Result<T, TesseraError> {
133        let body = response
134            .bytes()
135            .map_err(|err| TesseraError::Network(err.to_string()))?;
136        serde_json::from_slice(&body).map_err(|err| TesseraError::Network(err.to_string()))
137    }
138
139    /// List every dataset visible to your entitlement.
140    ///
141    /// # Errors
142    ///
143    /// Returns any [`TesseraError`] the API or transport raises.
144    pub fn datasets(&self) -> Result<DatasetsResponse, TesseraError> {
145        let response = self.request(&datasets_request())?;
146        Self::json(response)
147    }
148
149    /// List the partitions of `asset`, optionally filtered by coin/month.
150    ///
151    /// # Errors
152    ///
153    /// Returns any [`TesseraError`] the API or transport raises.
154    pub fn partitions(
155        &self,
156        asset: &str,
157        coin: Option<&str>,
158        month: Option<&str>,
159    ) -> Result<PartitionsResponse, TesseraError> {
160        let response = self.request(&partitions_request(asset, coin, month))?;
161        Self::json(response)
162    }
163
164    /// Mint presigned download URLs for one partition.
165    ///
166    /// A finalised month is a single object ([`crate::DownloadResponse`]). The
167    /// open month is day-backed and answers with one URL per day
168    /// ([`crate::DayDownloadResponse`]); use [`download_urls`] to flatten either
169    /// shape into URLs.
170    ///
171    /// # Errors
172    ///
173    /// Returns any [`TesseraError`] the API or transport raises.
174    pub fn download_url(
175        &self,
176        asset: &str,
177        coin: &str,
178        month: &str,
179    ) -> Result<DownloadBody, TesseraError> {
180        let response = self.request(&download_request(asset, coin, month))?;
181        Self::json(response)
182    }
183
184    /// Expand `(asset, coins, months)` into concrete partition references.
185    ///
186    /// # Errors
187    ///
188    /// Returns [`TesseraError::InvalidArgument`] on empty/invalid arguments.
189    pub fn partition_refs(
190        &self,
191        asset: &str,
192        coin: impl IntoCoins,
193        month: impl IntoMonths,
194    ) -> Result<Vec<PartitionRef>, TesseraError> {
195        let _ = self;
196        expand_refs(asset, coin, month)
197    }
198
199    /// Resolve presigned URLs for every ref, concurrently and order-preserving.
200    #[cfg(any(feature = "polars", feature = "duckdb"))]
201    fn resolve(&self, refs: &[PartitionRef]) -> Result<Vec<ResolvedPartition>, TesseraError> {
202        resolve_sync(
203            |partition| {
204                download_urls(self.download_url(
205                    &partition.asset,
206                    &partition.coin,
207                    &partition.month,
208                )?)
209            },
210            refs,
211        )
212    }
213
214    /// Lazily scan one or more partitions into a Polars `LazyFrame`.
215    ///
216    /// URLs are minted now but the data is read on `.collect()`. Because
217    /// presigned URLs expire (~15 min), collect promptly; for long-lived
218    /// graphs re-run `scan` to refresh.
219    ///
220    /// # Errors
221    ///
222    /// Returns any [`TesseraError`] the API or transport raises.
223    #[cfg(feature = "polars")]
224    pub fn scan(
225        &self,
226        asset: &str,
227        coin: impl IntoCoins,
228        month: impl IntoMonths,
229        columns: Option<&[&str]>,
230    ) -> Result<LazyFrame, TesseraError> {
231        let parts = self.resolve(&expand_refs(asset, coin, month)?)?;
232        crate::readers::polars::build_lazyframe(&parts, columns)
233    }
234
235    /// Eagerly read one or more partitions into a Polars `DataFrame`.
236    ///
237    /// # Errors
238    ///
239    /// Returns any [`TesseraError`] the API or transport raises, including
240    /// [`TesseraError::PresignExpired`] for rejected presigned URLs.
241    #[cfg(feature = "polars")]
242    pub fn read(
243        &self,
244        asset: &str,
245        coin: impl IntoCoins,
246        month: impl IntoMonths,
247        columns: Option<&[&str]>,
248    ) -> Result<DataFrame, TesseraError> {
249        let parts = self.resolve(&expand_refs(asset, coin, month)?)?;
250        let lazy = crate::readers::polars::build_lazyframe(&parts, columns)?;
251        self.runtime
252            .block_on(async { crate::readers::polars::collect(lazy) })
253    }
254
255    /// Open one or more partitions as an in-memory DuckDB connection exposing
256    /// a `tessera` view for SQL querying.
257    ///
258    /// # Errors
259    ///
260    /// Returns any [`TesseraError`] the API or transport raises.
261    #[cfg(feature = "duckdb")]
262    pub fn to_duckdb(
263        &self,
264        asset: &str,
265        coin: impl IntoCoins,
266        month: impl IntoMonths,
267        columns: Option<&[&str]>,
268    ) -> Result<duckdb::Connection, TesseraError> {
269        let parts = self.resolve(&expand_refs(asset, coin, month)?)?;
270        crate::readers::duckdb::build_relation(&parts, columns)
271    }
272}
273
274impl Drop for TesseraClient {
275    fn drop(&mut self) {
276        self.close();
277    }
278}
279
280impl std::fmt::Debug for TesseraClient {
281    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
282        // Never print the API key.
283        f.debug_struct("TesseraClient")
284            .field("base_url", &self.config.base_url)
285            .field("timeout", &self.config.timeout)
286            .field("max_retries", &self.config.max_retries)
287            .finish_non_exhaustive()
288    }
289}