1use std::collections::HashMap;
7use std::fmt;
8use std::str::FromStr;
9use std::time::Duration;
10
11use chrono::Datelike;
12
13use crate::{FORMAT_VERSION, FormatError, FormatVersion, Result, property};
14
15const HOUR_MICROS: i64 = 3_600_000_000;
16const DAY_MICROS: i64 = 24 * HOUR_MICROS;
17const DAY_SECS: u64 = 86_400;
18
19#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
23pub enum Chunk {
24 Hour,
26 Day,
28 Month,
30}
31
32impl Chunk {
33 pub fn as_str(self) -> &'static str {
35 match self {
36 Self::Hour => "hour",
37 Self::Day => "day",
38 Self::Month => "month",
39 }
40 }
41
42 pub fn value(self, micros: i64) -> Result<i32> {
44 let out_of_range = || FormatError::new(format!("timestamp {micros}µs is out of range for {self} partitions"));
45 let t = chrono::DateTime::from_timestamp_micros(micros).ok_or_else(out_of_range)?;
46 let v = match self {
47 Self::Hour => micros.div_euclid(HOUR_MICROS),
48 Self::Day => micros.div_euclid(DAY_MICROS),
49 Self::Month => (i64::from(t.year()) - 1970) * 12 + i64::from(t.month0()),
50 };
51 i32::try_from(v).map_err(|_| out_of_range())
52 }
53
54 pub fn start_micros(self, value: i32) -> Result<i64> {
56 let start = match self {
57 Self::Hour => Some(i64::from(value) * HOUR_MICROS),
58 Self::Day => i64::from(value).checked_mul(DAY_MICROS),
59 Self::Month => {
60 let (year, month0) = (1970 + value.div_euclid(12), value.rem_euclid(12).unsigned_abs());
61 chrono::NaiveDate::from_ymd_opt(year, month0 + 1, 1)
62 .and_then(|d| d.and_hms_opt(0, 0, 0))
63 .map(|t| t.and_utc().timestamp_micros())
64 }
65 };
66 start.ok_or_else(|| self.out_of_range(value))
67 }
68
69 pub fn end_micros(self, value: i32) -> Result<i64> {
71 self.start_micros(value.checked_add(1).ok_or_else(|| self.out_of_range(value))?)
72 }
73
74 pub fn label(self, value: i32) -> String {
77 let Some(t) = self.start_micros(value).ok().and_then(chrono::DateTime::from_timestamp_micros) else {
78 return value.to_string();
79 };
80 let format = match self {
81 Self::Hour => "%Y-%m-%d-%H",
82 Self::Day => "%Y-%m-%d",
83 Self::Month => "%Y-%m",
84 };
85 t.format(format).to_string()
86 }
87
88 fn out_of_range(self, value: i32) -> FormatError {
89 FormatError::new(format!("{self} partition {value} is out of range"))
90 }
91}
92
93impl FromStr for Chunk {
94 type Err = FormatError;
95
96 fn from_str(s: &str) -> Result<Self> {
97 match s.trim().to_ascii_lowercase().as_str() {
98 "hour" | "1h" | "1 hour" => Ok(Self::Hour),
99 "day" | "1d" | "1 day" | "24h" => Ok(Self::Day),
100 "month" | "1 month" => Ok(Self::Month),
101 other => Err(FormatError::new(format!("chunk interval must be hour, day or month, got {other:?}"))),
102 }
103 }
104}
105
106impl fmt::Display for Chunk {
107 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
108 f.write_str(self.as_str())
109 }
110}
111
112#[derive(Clone, Debug, Default)]
115pub struct TableOptions {
116 pub time_column: Option<String>,
118 pub series_key: Vec<String>,
120 pub chunk: Option<Chunk>,
122 pub dedup: Option<bool>,
124 pub retention: Option<Duration>,
126 pub ingest_time: Option<bool>,
128 pub properties: HashMap<String, String>,
130}
131
132#[derive(Clone, Debug)]
134pub struct Contract {
135 pub time_column: Option<String>,
137 pub series_key: Vec<String>,
139 pub chunk: Option<Chunk>,
141 pub dedup: bool,
143 pub ingest_time_column: Option<String>,
145 pub retention: Option<Duration>,
147 pub target_file_size: u64,
149 pub row_group_rows: usize,
151 pub auto_maintain: bool,
153 pub snapshot_retention: Duration,
155 pub min_snapshots: usize,
157 pub max_snapshots: usize,
159 pub compact_min_files: usize,
161 pub compact_cold_after: Option<Duration>,
164 pub read_dedup: bool,
166 pub read_dedup_strategy: String,
168 pub head_format: String,
170 pub head_inline_bytes: u64,
172 pub format_version: FormatVersion,
174 pub keep_snapshots_until: Option<i64>,
176 pub rollups: Vec<String>,
178 pub rollup_routing: bool,
180 pub rollup_refresh_interval: Option<Duration>,
183 pub version_check_interval: Duration,
186 pub data_page_rows: Option<usize>,
188}
189
190impl Contract {
191 const DEFAULT_TARGET_FILE_SIZE: u64 = 256 << 20;
193 const DEFAULT_ROW_GROUP_ROWS: usize = 1 << 20;
194 const DEFAULT_SNAPSHOT_RETENTION: Duration = Duration::from_secs(3600);
195 const DEFAULT_MIN_SNAPSHOTS: usize = 5;
196 const DEFAULT_MAX_SNAPSHOTS: usize = 100;
197 const DEFAULT_COMPACT_MIN_FILES: usize = 8;
198 const DEFAULT_COMPACT_COLD_AFTER: Duration = Duration::from_secs(3600);
199 const DEFAULT_HEAD_FORMAT: &str = "arrow";
200 const DEFAULT_HEAD_INLINE_BYTES: u64 = 1 << 20;
201 const DEFAULT_ROLLUP_REFRESH_INTERVAL: Duration = Duration::from_secs(60);
202 const DEFAULT_VERSION_CHECK_INTERVAL: Duration = Duration::from_secs(1);
203
204 pub fn from_properties(properties: &HashMap<String, String>) -> Result<Self> {
206 let p = Properties(properties);
207 Ok(Self {
208 time_column: p.get(property::TIME_COLUMN).map(str::to_string),
209 series_key: p.list(property::SERIES_KEY),
210 chunk: p.get(property::CHUNK).map(str::parse).transpose()?,
211 dedup: p.flag(property::DEDUP, false)?,
212 ingest_time_column: p.get(property::INGEST_TIME_COLUMN).map(str::to_string),
213 retention: p.duration(property::RETENTION)?,
214 target_file_size: p.number(property::TARGET_FILE_SIZE, Self::DEFAULT_TARGET_FILE_SIZE)?,
215 row_group_rows: p.number(property::ROW_GROUP_ROWS, Self::DEFAULT_ROW_GROUP_ROWS)?,
216 auto_maintain: p.flag(property::AUTO_MAINTAIN, true)?,
217 snapshot_retention: p.duration(property::SNAPSHOT_RETENTION)?.unwrap_or(Self::DEFAULT_SNAPSHOT_RETENTION),
218 min_snapshots: p.number(property::MIN_SNAPSHOTS, Self::DEFAULT_MIN_SNAPSHOTS)?,
219 max_snapshots: p.number(property::MAX_SNAPSHOTS, Self::DEFAULT_MAX_SNAPSHOTS)?,
220 compact_min_files: p.number(property::COMPACT_MIN_FILES, Self::DEFAULT_COMPACT_MIN_FILES)?,
221 compact_cold_after: match p.get(property::COMPACT_COLD_AFTER) {
222 Some(s) if s.eq_ignore_ascii_case("off") => None,
223 Some(s) => Some(parse_duration(s)?),
224 None => Some(Self::DEFAULT_COMPACT_COLD_AFTER),
225 },
226 read_dedup: p.flag(property::READ_DEDUP, p.flag(property::DEDUP, false)?)?,
227 read_dedup_strategy: p.get(property::READ_DEDUP_STRATEGY).unwrap_or("merge").to_ascii_lowercase(),
228 head_format: p.get(property::HEAD_FORMAT).unwrap_or(Self::DEFAULT_HEAD_FORMAT).to_ascii_lowercase(),
229 head_inline_bytes: p.number(property::HEAD_INLINE_BYTES, Self::DEFAULT_HEAD_INLINE_BYTES)?,
230 format_version: p.get(property::FORMAT_VERSION).map_or(Ok(FormatVersion::UNVERSIONED), str::parse)?,
231 keep_snapshots_until: p
232 .get(property::KEEP_SNAPSHOTS_UNTIL)
233 .map(|_| p.number(property::KEEP_SNAPSHOTS_UNTIL, 0))
234 .transpose()?,
235 rollups: p.list(property::ROLLUPS),
236 rollup_routing: p.flag(property::ROLLUP_ROUTING, true)?,
237 rollup_refresh_interval: match p.get(property::ROLLUP_REFRESH_INTERVAL) {
238 Some(s) if s.eq_ignore_ascii_case("off") => None,
239 Some(s) => Some(parse_duration(s)?),
240 None => Some(Self::DEFAULT_ROLLUP_REFRESH_INTERVAL),
241 },
242 version_check_interval: p
243 .duration(property::VERSION_CHECK_INTERVAL)?
244 .unwrap_or(Self::DEFAULT_VERSION_CHECK_INTERVAL),
245 data_page_rows: p
246 .get(property::DATA_PAGE_ROWS)
247 .map(|_| p.number(property::DATA_PAGE_ROWS, 0))
248 .transpose()?,
249 })
250 }
251
252 pub fn check_readable(&self) -> Result<()> {
255 if self.format_version.readable_by(FORMAT_VERSION) {
256 return Ok(());
257 }
258 Err(FormatError::new(format!(
259 "table format {} is newer than this Timelake reads ({FORMAT_VERSION}): upgrade Timelake",
260 self.format_version
261 )))
262 }
263
264 pub fn check_writable(&self) -> Result<()> {
267 if self.format_version.writable_by(FORMAT_VERSION) {
268 return Ok(());
269 }
270 Err(FormatError::new(format!(
271 "table format {} is newer than this Timelake writes ({FORMAT_VERSION}): upgrade Timelake",
272 self.format_version
273 )))
274 }
275
276 pub fn is_time_series(&self) -> bool {
278 self.time_column.is_some()
279 }
280
281 pub fn sort_columns(&self) -> Vec<String> {
283 let mut v = self.series_key.clone();
284 v.extend(self.time_column.clone());
285 v
286 }
287
288 pub fn write_order(&self) -> Vec<String> {
291 let mut v = self.sort_columns();
292 v.extend(self.ingest_time_column.clone());
293 v
294 }
295}
296
297struct Properties<'a>(&'a HashMap<String, String>);
299
300impl Properties<'_> {
301 fn get(&self, key: &str) -> Option<&str> {
302 self.0.get(key).map(|s| s.trim()).filter(|s| !s.is_empty())
303 }
304
305 fn number<T: FromStr>(&self, key: &str, default: T) -> Result<T> {
306 self.get(key).map_or(Ok(default), |s| {
307 s.parse().map_err(|_| FormatError::new(format!("{key} must be a non-negative integer, got {s:?}")))
308 })
309 }
310
311 fn flag(&self, key: &str, default: bool) -> Result<bool> {
312 self.get(key).map_or(Ok(default), |s| {
313 s.to_ascii_lowercase()
314 .parse()
315 .map_err(|_| FormatError::new(format!("{key} must be true or false, got {s:?}")))
316 })
317 }
318
319 fn duration(&self, key: &str) -> Result<Option<Duration>> {
320 self.get(key).map(parse_duration).transpose()
321 }
322
323 fn list(&self, key: &str) -> Vec<String> {
325 self.get(key)
326 .map(|s| s.split(',').map(str::trim).filter(|c| !c.is_empty()).map(str::to_string).collect())
327 .unwrap_or_default()
328 }
329}
330
331pub fn parse_duration(s: &str) -> Result<Duration> {
333 let s = s.trim();
334 let split = s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len());
335 let (n, unit) = s.split_at(split);
336 let n: u64 = n.parse().map_err(|_| FormatError::new(format!("bad duration {s:?}")))?;
337 let unit_secs = match unit.trim().to_ascii_lowercase().as_str() {
338 "s" | "sec" | "secs" | "second" | "seconds" => 1,
339 "m" | "min" | "mins" | "minute" | "minutes" => 60,
340 "h" | "hr" | "hrs" | "hour" | "hours" => 3600,
341 "d" | "day" | "days" => DAY_SECS,
342 "w" | "week" | "weeks" => 7 * DAY_SECS,
343 "y" | "year" | "years" => 365 * DAY_SECS,
344 _ => return Err(FormatError::new(format!("bad duration unit in {s:?} (use s, m, h, d, w, y)"))),
345 };
346 let secs = n.checked_mul(unit_secs).ok_or_else(|| FormatError::new(format!("duration {s:?} is too long")))?;
347 Ok(Duration::from_secs(secs))
348}
349
350pub fn format_duration(d: Duration) -> String {
353 let secs = d.as_secs();
354 match [(DAY_SECS, 'd'), (3600, 'h'), (60, 'm')]
355 .into_iter()
356 .find(|(unit, _)| secs != 0 && secs.is_multiple_of(*unit))
357 {
358 Some((unit, suffix)) => format!("{}{suffix}", secs / unit),
359 None => format!("{secs}s"),
360 }
361}
362
363#[cfg(test)]
364mod tests {
365 use super::*;
366 use crate::property::*;
367
368 const T: i64 = 1_767_225_600_000_000; #[test]
371 fn chunk_values_round_trip() {
372 for c in [Chunk::Hour, Chunk::Day, Chunk::Month] {
373 let v = c.value(T + 1).unwrap();
374 assert_eq!(c.start_micros(v).unwrap(), T, "{c:?}");
375 assert!(c.end_micros(v).unwrap() > T);
376 }
377 assert_eq!(Chunk::Day.label(Chunk::Day.value(T).unwrap()), "2026-01-01");
378 assert_eq!(Chunk::Hour.label(Chunk::Hour.value(T).unwrap()), "2026-01-01-00");
379 assert_eq!(Chunk::Month.label(Chunk::Month.value(T).unwrap()), "2026-01");
380 assert_eq!(Chunk::Month.value(T).unwrap(), (2026 - 1970) * 12);
381 assert_eq!(Chunk::Day.value(-1).unwrap(), -1);
383 assert_eq!(Chunk::Month.value(-1).unwrap(), -1);
384 assert_eq!(Chunk::Month.start_micros(-1).unwrap(), -31 * DAY_MICROS);
385 }
386
387 #[test]
388 fn out_of_range_times_are_errors() {
389 for c in [Chunk::Hour, Chunk::Day, Chunk::Month] {
390 assert!(c.value(i64::MAX).is_err(), "{c:?}");
391 assert!(c.value(i64::MIN).is_err(), "{c:?}");
392 }
393 assert!(Chunk::Day.start_micros(i32::MAX).is_err());
394 assert!(Chunk::Month.start_micros(i32::MAX).is_err());
395 assert!(Chunk::Hour.end_micros(i32::MAX).is_err());
396 assert_eq!(Chunk::Month.label(i32::MAX), i32::MAX.to_string());
397 }
398
399 #[test]
400 fn chunk_parses_and_displays() {
401 for (s, c) in [("hour", Chunk::Hour), (" 1 Day ", Chunk::Day), ("24h", Chunk::Day), ("month", Chunk::Month)] {
402 assert_eq!(s.parse::<Chunk>().unwrap(), c, "{s}");
403 }
404 assert!("week".parse::<Chunk>().is_err());
405 for c in [Chunk::Hour, Chunk::Day, Chunk::Month] {
406 assert_eq!(c.to_string().parse::<Chunk>().unwrap(), c);
407 }
408 }
409
410 #[test]
411 fn durations() {
412 assert_eq!(parse_duration("90d").unwrap().as_secs(), 90 * 86_400);
413 assert_eq!(parse_duration("1h").unwrap().as_secs(), 3600);
414 assert_eq!(parse_duration(" 0s ").unwrap(), Duration::ZERO);
415 assert!(parse_duration("1 parsec").is_err());
416 assert!(parse_duration("d").is_err());
417 assert!(parse_duration("-1d").is_err());
418 }
419
420 #[test]
421 fn durations_accept_singular_and_plural_units() {
422 assert_eq!(parse_duration("1 day").unwrap().as_secs(), 86_400);
423 assert_eq!(parse_duration("1 hour").unwrap().as_secs(), 3600);
424 assert_eq!(parse_duration("1 week").unwrap().as_secs(), 7 * 86_400);
425 assert_eq!(parse_duration("2 Weeks").unwrap().as_secs(), 14 * 86_400);
426 assert_eq!(parse_duration("1 minute").unwrap().as_secs(), 60);
427 assert_eq!(parse_duration("1 year").unwrap().as_secs(), 365 * 86_400);
428 }
429
430 #[test]
431 fn duration_overflow_is_an_error() {
432 assert!(parse_duration("99999999999999999y").is_err());
433 assert!(parse_duration("99999999999999999999s").is_err());
434 }
435
436 #[test]
437 fn durations_format_in_the_largest_exact_unit() {
438 for (secs, s) in [(90 * 86_400, "90d"), (36 * 3600, "36h"), (90, "90s"), (120, "2m"), (0, "0s")] {
439 assert_eq!(format_duration(Duration::from_secs(secs)), s);
440 assert_eq!(parse_duration(s).unwrap().as_secs(), secs);
441 }
442 }
443
444 fn props(kv: &[(&str, &str)]) -> HashMap<String, String> {
445 kv.iter().map(|(k, v)| ((*k).to_string(), (*v).to_string())).collect()
446 }
447
448 #[test]
449 fn contract_defaults() {
450 let c = Contract::from_properties(&HashMap::new()).unwrap();
451 assert!(!c.is_time_series() && !c.dedup && c.auto_maintain);
452 assert_eq!(c.retention, None);
453 assert_eq!(c.snapshot_retention, Duration::from_secs(3600));
454 assert_eq!((c.min_snapshots, c.max_snapshots, c.compact_min_files), (5, 100, 8));
455 assert_eq!(
456 (c.head_format.as_str(), c.head_inline_bytes, c.format_version),
457 ("arrow", 1 << 20, FormatVersion::UNVERSIONED)
458 );
459 assert_eq!((c.compact_cold_after, c.read_dedup), (Some(Duration::from_hours(1)), false));
460 let dedup = Contract::from_properties(&props(&[(property::DEDUP, "true")])).unwrap();
461 assert!(dedup.read_dedup, "read dedup follows dedup");
462 let off =
463 props(&[(property::DEDUP, "true"), (property::READ_DEDUP, "false"), (property::COMPACT_COLD_AFTER, "off")]);
464 let off = Contract::from_properties(&off).unwrap();
465 assert_eq!((off.compact_cold_after, off.read_dedup), (None, false));
466 let cold = Contract::from_properties(&props(&[(property::COMPACT_COLD_AFTER, "6h")])).unwrap();
467 assert_eq!(cold.compact_cold_after, Some(Duration::from_hours(6)));
468 assert_eq!(c.sort_columns(), [] as [String; 0]);
469 }
470
471 #[test]
472 fn contract_parses_properties() {
473 let c = Contract::from_properties(&props(&[
474 (TIME_COLUMN, "time"),
475 (SERIES_KEY, "site, device,"),
476 (CHUNK, "hour"),
477 (DEDUP, "True"),
478 (AUTO_MAINTAIN, "FALSE"),
479 (RETENTION, "1 day"),
480 (MIN_SNAPSHOTS, "3"),
481 (TARGET_FILE_SIZE, " 1024 "),
482 (HEAD_FORMAT, "JSON"),
483 (HEAD_INLINE_BYTES, "0"),
484 ]))
485 .unwrap();
486 assert_eq!((c.head_format.as_str(), c.head_inline_bytes), ("json", 0));
487 assert_eq!(c.sort_columns(), ["site", "device", "time"]);
488 assert_eq!(c.chunk, Some(Chunk::Hour));
489 assert!(c.dedup && !c.auto_maintain);
490 assert_eq!(c.retention, Some(Duration::from_hours(24)));
491 assert_eq!((c.min_snapshots, c.target_file_size), (3, 1024));
492 }
493
494 #[test]
495 fn contract_rejects_bad_values() {
496 for kv in [(DEDUP, "yes"), (AUTO_MAINTAIN, "0"), (CHUNK, "week"), (RETENTION, "forever"), (MAX_SNAPSHOTS, "-1")]
497 {
498 assert!(Contract::from_properties(&props(&[kv])).is_err(), "{kv:?}");
499 }
500 }
501}