Skip to main content

tessera/
models.rs

1//! Public data models.
2//!
3//! Response models ([`DatasetsResponse`], [`PartitionsResponse`], …) are
4//! generated from the vendored OpenAPI spec at build time (`build.rs` — the
5//! generated code lives in `$OUT_DIR`, so it can never drift from the spec).
6//! This module re-exports them alongside hand-written ergonomic helpers
7//! ([`PartitionRef`], [`MonthSpan`]).
8
9/// Generated OpenAPI response models, exempted from lint scrutiny.
10#[allow(dead_code, clippy::all, clippy::pedantic)]
11mod generated {
12    include!(concat!(env!("OUT_DIR"), "/tessera_generated.rs"));
13}
14
15pub use generated::{
16    DatasetSummary, DatasetsResponse, DayDownload, DayDownloadResponse, DownloadBody,
17    DownloadResponse, ErrorBody, MonthRange, Partition, PartitionsResponse,
18};
19
20use crate::error::TesseraError;
21
22/// Flatten a download body into presigned URLs, oldest object first.
23///
24/// A finalised month is a single object and yields one URL. The open month is
25/// day-backed: it yields one URL per day, ordered by the `YYYY-MM-DD` day they
26/// cover, so concatenating them in order stays chronological.
27///
28/// # Errors
29///
30/// Returns [`TesseraError::UnexpectedResponse`] when a day-backed partition
31/// carries no day objects.
32pub fn download_urls(body: DownloadBody) -> Result<Vec<String>, TesseraError> {
33    match body {
34        DownloadBody::DownloadResponse(single) => Ok(vec![single.url]),
35        DownloadBody::DayDownloadResponse(day_backed) => {
36            let DayDownloadResponse {
37                asset,
38                coin,
39                mut days,
40                month,
41                ..
42            } = day_backed;
43            days.sort_by(|left, right| left.date.cmp(&right.date));
44            if days.is_empty() {
45                return Err(TesseraError::UnexpectedResponse(format!(
46                    "download of day-backed partition {asset}/{}/{month} returned no day objects",
47                    coin.as_deref().unwrap_or("-")
48                )));
49            }
50            Ok(days.into_iter().map(|day| day.url).collect())
51        }
52    }
53}
54
55/// Validate a `YYYY-MM` month string.
56///
57/// Matches the Python SDK's `^\d{4}-(0[1-9]|1[0-2])$` regex: a four-digit
58/// year, a hyphen, and a month in `01..=12`.
59pub(crate) fn validate_month(month: &str) -> Result<(), TesseraError> {
60    let digits = |bytes: &[u8]| bytes.iter().all(u8::is_ascii_digit);
61    let valid = month.len() == 7
62        && month.as_bytes()[4] == b'-'
63        && digits(&month.as_bytes()[0..4])
64        && digits(&month.as_bytes()[5..7]);
65    if !valid {
66        return Err(TesseraError::InvalidArgument(format!(
67            "month must be in YYYY-MM format, got {month:?}"
68        )));
69    }
70    let m: u8 = month[5..7].parse().expect("digits checked above");
71    if !(1..=12).contains(&m) {
72        return Err(TesseraError::InvalidArgument(format!(
73            "month must be in YYYY-MM format, got {month:?}"
74        )));
75    }
76    Ok(())
77}
78
79/// A fully-qualified reference to a single partition.
80///
81/// A partition is one `(asset, coin, month)` slice, e.g. `gold_ohlcv_1m` /
82/// `BTC` / `2025-09`. A finalised month is one Parquet object; the open month is
83/// day-backed and resolves to one object per day.
84#[derive(Debug, Clone, PartialEq, Eq, Hash)]
85pub struct PartitionRef {
86    /// Dataset name, e.g. `gold_ohlcv_1m`.
87    pub asset: String,
88    /// Coin symbol, e.g. `BTC`.
89    pub coin: String,
90    /// Partition month, `YYYY-MM`.
91    pub month: String,
92}
93
94impl PartitionRef {
95    /// Create a reference, validating the month format.
96    ///
97    /// # Errors
98    ///
99    /// Returns [`TesseraError::InvalidArgument`] when `month` is not `YYYY-MM`.
100    pub fn new(
101        asset: impl Into<String>,
102        coin: impl Into<String>,
103        month: impl Into<String>,
104    ) -> Result<Self, TesseraError> {
105        let month = month.into();
106        validate_month(&month)?;
107        Ok(Self {
108            asset: asset.into(),
109            coin: coin.into(),
110            month,
111        })
112    }
113
114    /// The object-storage key layout: `{asset}/coin={COIN}/month={YYYY-MM}.parquet`.
115    #[must_use]
116    pub fn object_key(&self) -> String {
117        format!(
118            "{}/coin={}/month={}.parquet",
119            self.asset, self.coin, self.month
120        )
121    }
122}
123
124/// An inclusive range of months, e.g. `MonthSpan::new("2025-01", "2025-09")?`.
125///
126/// Pass it anywhere a `month` argument is accepted to expand to every month
127/// in the range (inclusive of both endpoints).
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct MonthSpan {
130    /// First month in the span, inclusive.
131    pub start: String,
132    /// Last month in the span, inclusive.
133    pub end: String,
134}
135
136impl MonthSpan {
137    /// Create a span, validating both months and their ordering.
138    ///
139    /// # Errors
140    ///
141    /// Returns [`TesseraError::InvalidArgument`] when either endpoint is not
142    /// `YYYY-MM`, or when `start` is after `end`.
143    pub fn new(start: impl Into<String>, end: impl Into<String>) -> Result<Self, TesseraError> {
144        let start = start.into();
145        let end = end.into();
146        validate_month(&start)?;
147        validate_month(&end)?;
148        if start > end {
149            return Err(TesseraError::InvalidArgument(format!(
150                "MonthSpan start {start:?} is after end {end:?}"
151            )));
152        }
153        Ok(Self { start, end })
154    }
155
156    /// Return the months in the span as a list of `YYYY-MM` strings.
157    #[must_use]
158    pub fn months(&self) -> Vec<String> {
159        let (mut year, mut month) = parse_ym(&self.start);
160        let (end_year, end_month) = parse_ym(&self.end);
161        let mut months = Vec::new();
162        while (year, month) <= (end_year, end_month) {
163            months.push(format!("{year:04}-{month:02}"));
164            month += 1;
165            if month > 12 {
166                month = 1;
167                year += 1;
168            }
169        }
170        months
171    }
172}
173
174impl IntoIterator for MonthSpan {
175    type Item = String;
176    type IntoIter = std::vec::IntoIter<String>;
177
178    /// Iterate the span's months (inclusive, crossing year boundaries).
179    fn into_iter(self) -> Self::IntoIter {
180        self.months().into_iter()
181    }
182}
183
184/// Parse `YYYY-MM` into `(year, month)` integers.
185///
186/// Callers must have run [`validate_month`] first; numeric parsing is
187/// infallible on validated input.
188fn parse_ym(month: &str) -> (i32, i32) {
189    (
190        month[0..4]
191            .parse()
192            .expect("validated month has a numeric year"),
193        month[5..7]
194            .parse()
195            .expect("validated month has a numeric month"),
196    )
197}
198
199/// Accepted shapes for a `coin` argument: one symbol or any iterable of them.
200pub trait IntoCoins {
201    /// Coerce into a non-empty list of coin symbols.
202    ///
203    /// # Errors
204    ///
205    /// Returns [`TesseraError::InvalidArgument`] when the result is empty.
206    fn into_coins(self) -> Result<Vec<String>, TesseraError>;
207}
208
209/// Accepted shapes for a `month` argument: one month, a [`MonthSpan`], or any
210/// iterable of months.
211pub trait IntoMonths {
212    /// Coerce into a non-empty, validated list of `YYYY-MM` strings.
213    ///
214    /// # Errors
215    ///
216    /// Returns [`TesseraError::InvalidArgument`] when the result is empty or
217    /// any entry is not in `YYYY-MM` format.
218    fn into_months(self) -> Result<Vec<String>, TesseraError>;
219}
220
221impl IntoCoins for &str {
222    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
223        Ok(vec![self.to_string()])
224    }
225}
226
227impl IntoCoins for String {
228    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
229        Ok(vec![self])
230    }
231}
232
233impl IntoCoins for &String {
234    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
235        self.as_str().into_coins()
236    }
237}
238
239impl<C: AsRef<str>> IntoCoins for Vec<C> {
240    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
241        self.as_slice().into_coins()
242    }
243}
244
245impl<C: AsRef<str>> IntoCoins for &Vec<C> {
246    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
247        self.as_slice().into_coins()
248    }
249}
250
251impl<C: AsRef<str>, const N: usize> IntoCoins for [C; N] {
252    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
253        self.as_slice().into_coins()
254    }
255}
256
257impl<C: AsRef<str>, const N: usize> IntoCoins for &[C; N] {
258    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
259        self.as_slice().into_coins()
260    }
261}
262
263impl IntoMonths for &str {
264    fn into_months(self) -> Result<Vec<String>, TesseraError> {
265        validate_month(self)?;
266        Ok(vec![self.to_string()])
267    }
268}
269
270impl IntoMonths for String {
271    fn into_months(self) -> Result<Vec<String>, TesseraError> {
272        validate_month(&self)?;
273        Ok(vec![self])
274    }
275}
276
277impl IntoMonths for &String {
278    fn into_months(self) -> Result<Vec<String>, TesseraError> {
279        self.as_str().into_months()
280    }
281}
282
283impl IntoMonths for MonthSpan {
284    fn into_months(self) -> Result<Vec<String>, TesseraError> {
285        Ok(self.months())
286    }
287}
288
289impl<C: AsRef<str>> IntoMonths for &[C] {
290    fn into_months(self) -> Result<Vec<String>, TesseraError> {
291        let months: Vec<String> = self.iter().map(|m| m.as_ref().to_string()).collect();
292        if months.is_empty() {
293            return Err(TesseraError::InvalidArgument(
294                "at least one month is required".to_string(),
295            ));
296        }
297        for m in &months {
298            validate_month(m)?;
299        }
300        Ok(months)
301    }
302}
303
304impl<C: AsRef<str>> IntoMonths for Vec<C> {
305    fn into_months(self) -> Result<Vec<String>, TesseraError> {
306        self.as_slice().into_months()
307    }
308}
309
310impl<C: AsRef<str>> IntoMonths for &Vec<C> {
311    fn into_months(self) -> Result<Vec<String>, TesseraError> {
312        self.as_slice().into_months()
313    }
314}
315
316impl<C: AsRef<str>, const N: usize> IntoMonths for [C; N] {
317    fn into_months(self) -> Result<Vec<String>, TesseraError> {
318        self.as_slice().into_months()
319    }
320}
321
322impl<C: AsRef<str>, const N: usize> IntoMonths for &[C; N] {
323    fn into_months(self) -> Result<Vec<String>, TesseraError> {
324        self.as_slice().into_months()
325    }
326}
327
328impl<C: AsRef<str>> IntoCoins for &[C] {
329    fn into_coins(self) -> Result<Vec<String>, TesseraError> {
330        let coins: Vec<String> = self.iter().map(|c| c.as_ref().to_string()).collect();
331        if coins.is_empty() {
332            return Err(TesseraError::InvalidArgument(
333                "at least one coin is required".to_string(),
334            ));
335        }
336        Ok(coins)
337    }
338}