use std::cmp::Ordering;
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::frontier::MutableAntichain;
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, PartialEq, Eq, Serialize)]
pub enum CompactionWindow {
#[default]
Default,
DisableCompaction,
Duration(Timestamp),
}
impl Ord for CompactionWindow {
fn cmp(&self, other: &Self) -> Ordering {
self.comparable_timestamp()
.cmp(&other.comparable_timestamp())
}
}
impl PartialOrd for CompactionWindow {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
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 From<CompactionWindow> for ReadCapability<Timestamp> {
fn from(value: CompactionWindow) -> Self {
let policy: ReadPolicy<Timestamp> = value.into();
policy.into()
}
}
impl TryFrom<Duration> for CompactionWindow {
type Error = TryFromIntError;
fn try_from(value: Duration) -> Result<Self, Self::Error> {
Ok(Self::Duration(value.try_into()?))
}
}
#[derive(Debug, Serialize)]
pub struct ReadCapability<T = mz_repr::Timestamp>
where
T: timely::progress::Timestamp,
{
pub base_policy: ReadPolicy<T>,
pub holds: MutableAntichain<T>,
}
impl<T: timely::progress::Timestamp> From<ReadPolicy<T>> for ReadCapability<T> {
fn from(base_policy: ReadPolicy<T>) -> Self {
Self {
base_policy,
holds: MutableAntichain::new(),
}
}
}
impl<T: timely::progress::Timestamp> ReadCapability<T> {
pub fn policy(&self) -> ReadPolicy<T> {
ReadPolicy::Multiple(vec![
ReadPolicy::ValidFrom(self.holds.frontier().to_owned()),
self.base_policy.clone(),
])
}
}