use std::num::TryFromIntError;
use std::time::Duration;
use mz_repr::{Timestamp, TimestampManipulation};
use mz_storage_types::read_policy::ReadPolicy;
use serde::Serialize;
use timely::progress::{Antichain, Timestamp as TimelyTimestamp};
const DEFAULT_LOGICAL_COMPACTION_WINDOW_MILLIS: u64 = 1000;
pub const DEFAULT_LOGICAL_COMPACTION_WINDOW_DURATION: Duration =
Duration::from_millis(DEFAULT_LOGICAL_COMPACTION_WINDOW_MILLIS);
const DEFAULT_LOGICAL_COMPACTION_WINDOW_TS: Timestamp =
Timestamp::new(DEFAULT_LOGICAL_COMPACTION_WINDOW_MILLIS);
pub const SINCE_GRANULARITY: mz_repr::Timestamp = mz_repr::Timestamp::new(1000);
#[derive(Clone, Default, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Serialize)]
pub enum CompactionWindow {
#[default]
Default,
DisableCompaction,
Duration(Timestamp),
}
impl CompactionWindow {
pub fn lag_from(&self, from: Timestamp) -> Timestamp {
let lag = match self {
CompactionWindow::Default => DEFAULT_LOGICAL_COMPACTION_WINDOW_TS,
CompactionWindow::DisableCompaction => return Timestamp::minimum(),
CompactionWindow::Duration(d) => *d,
};
from.saturating_sub(lag)
}
pub fn comparable_timestamp(&self) -> Timestamp {
match self {
CompactionWindow::Default => DEFAULT_LOGICAL_COMPACTION_WINDOW_TS,
CompactionWindow::DisableCompaction => Timestamp::maximum(),
CompactionWindow::Duration(d) => *d,
}
}
}
impl From<CompactionWindow> for ReadPolicy<Timestamp> {
fn from(value: CompactionWindow) -> Self {
let time = match value {
CompactionWindow::Default => DEFAULT_LOGICAL_COMPACTION_WINDOW_TS,
CompactionWindow::Duration(time) => time,
CompactionWindow::DisableCompaction => {
return ReadPolicy::ValidFrom(Antichain::from_elem(Timestamp::minimum()))
}
};
ReadPolicy::lag_writes_by(time, SINCE_GRANULARITY)
}
}
impl TryFrom<Duration> for CompactionWindow {
type Error = TryFromIntError;
fn try_from(value: Duration) -> Result<Self, Self::Error> {
Ok(Self::Duration(value.try_into()?))
}
}