use std::time::{Duration, Instant};
use kafka_client_core::{Deadline, Moment};
use super::{ClockError, OperationDeadline};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) struct DeadlineCapture {
now: Moment,
deadline: OperationDeadline,
}
impl DeadlineCapture {
pub(crate) const fn now(self) -> Moment {
self.now
}
pub(crate) const fn deadline(self) -> Deadline {
self.deadline.core()
}
pub(crate) const fn operation_deadline(self) -> OperationDeadline {
self.deadline
}
}
#[derive(Debug)]
pub(crate) struct MonotonicClock {
epoch: Instant,
}
impl MonotonicClock {
pub(crate) fn new() -> Self {
Self::from_epoch(Instant::now())
}
pub(crate) fn now(&self) -> Result<Moment, ClockError> {
self.moment_at(Instant::now())
}
pub(crate) fn capture_deadline_after(
&self,
timeout: Duration,
) -> Result<DeadlineCapture, ClockError> {
let boundary = Instant::now();
self.capture_deadline_at(boundary, timeout)
}
pub(crate) fn operation_deadline(
&self,
deadline: Deadline,
) -> Result<OperationDeadline, ClockError> {
let offset = Duration::from_nanos(deadline.tick());
let transport = self
.epoch
.checked_add(offset)
.ok_or(ClockError::InstantOverflow)?;
Ok(OperationDeadline::from_boundary_parts(deadline, transport))
}
pub(super) const fn from_epoch(epoch: Instant) -> Self {
Self { epoch }
}
pub(super) fn moment_at(&self, instant: Instant) -> Result<Moment, ClockError> {
let elapsed = instant
.checked_duration_since(self.epoch)
.ok_or(ClockError::BeforeEpoch)?;
Ok(Moment::from_tick(duration_ticks(elapsed)?))
}
pub(super) fn capture_deadline_at(
&self,
boundary: Instant,
timeout: Duration,
) -> Result<DeadlineCapture, ClockError> {
let absolute_instant = absolute_instant_after(boundary, timeout)?;
let now = self.moment_at(boundary)?;
let deadline = deadline_after_moment(now, timeout)?;
Ok(DeadlineCapture {
now,
deadline: OperationDeadline::from_boundary_parts(deadline, absolute_instant),
})
}
}
impl Default for MonotonicClock {
fn default() -> Self {
Self::new()
}
}
pub(super) fn duration_ticks(duration: Duration) -> Result<u64, ClockError> {
u64::try_from(duration.as_nanos()).map_err(|_overflow| ClockError::TickOverflow)
}
pub(super) fn deadline_after_moment(
now: Moment,
timeout: Duration,
) -> Result<Deadline, ClockError> {
let ticks = duration_ticks(timeout)?;
now.checked_deadline_after(ticks)
.ok_or(ClockError::DeadlineOverflow)
}
pub(super) fn absolute_instant_after(
boundary: Instant,
timeout: Duration,
) -> Result<Instant, ClockError> {
boundary
.checked_add(timeout)
.ok_or(ClockError::InstantOverflow)
}