Skip to main content

mz_repr/
timestamp.rs

1// Copyright Materialize, Inc. and contributors. All rights reserved.
2//
3// Use of this software is governed by the Business Source License
4// included in the LICENSE file.
5//
6// As of the Change Date specified in that file, in accordance with
7// the Business Source License, use of this software will be governed
8// by the Apache License, Version 2.0.
9
10use std::convert::TryFrom;
11use std::num::TryFromIntError;
12use std::time::Duration;
13
14use dec::TryFromDecimalError;
15use mz_proto::{RustType, TryFromProtoError};
16use mz_timely_util::temporal::BucketTimestamp;
17use proptest_derive::Arbitrary;
18use serde::{Deserialize, Serialize, Serializer};
19
20use crate::adt::numeric::Numeric;
21use crate::refresh_schedule::RefreshSchedule;
22use crate::strconv::parse_timestamptz;
23
24include!(concat!(env!("OUT_DIR"), "/mz_repr.timestamp.rs"));
25
26/// System-wide timestamp type.
27#[derive(
28    Clone,
29    // TODO: De-implement Copy, which is widely used.
30    Copy,
31    PartialEq,
32    Eq,
33    PartialOrd,
34    Ord,
35    Hash,
36    Default,
37    Arbitrary,
38    bytemuck::AnyBitPattern,
39    bytemuck::NoUninit,
40)]
41#[repr(transparent)]
42pub struct Timestamp {
43    /// note no `pub`.
44    internal: u64,
45}
46
47impl PartialEq<&Timestamp> for Timestamp {
48    fn eq(&self, other: &&Timestamp) -> bool {
49        self.eq(*other)
50    }
51}
52
53impl PartialEq<Timestamp> for &Timestamp {
54    fn eq(&self, other: &Timestamp) -> bool {
55        self.internal.eq(&other.internal)
56    }
57}
58
59impl RustType<ProtoTimestamp> for Timestamp {
60    fn into_proto(&self) -> ProtoTimestamp {
61        ProtoTimestamp {
62            internal: self.into(),
63        }
64    }
65
66    fn from_proto(proto: ProtoTimestamp) -> Result<Self, TryFromProtoError> {
67        Ok(Timestamp::new(proto.internal))
68    }
69}
70
71mod columnar_timestamp {
72    use crate::Timestamp;
73    use columnar::Columnar;
74    use mz_ore::cast::CastFrom;
75    use std::ops::Range;
76
77    /// A newtype wrapper for a vector of `Timestamp` values.
78    #[derive(Clone, Copy, Default, Debug)]
79    pub struct Timestamps<T>(T);
80    impl<D, T: columnar::Push<D>> columnar::Push<D> for Timestamps<T> {
81        #[inline(always)]
82        fn push(&mut self, item: D) {
83            self.0.push(item)
84        }
85    }
86    impl<T: columnar::Clear> columnar::Clear for Timestamps<T> {
87        #[inline(always)]
88        fn clear(&mut self) {
89            self.0.clear()
90        }
91    }
92    impl<T: columnar::Len> columnar::Len for Timestamps<T> {
93        #[inline(always)]
94        fn len(&self) -> usize {
95            self.0.len()
96        }
97    }
98    impl<'a> columnar::Index for Timestamps<&'a [Timestamp]> {
99        type Ref = Timestamp;
100
101        #[inline(always)]
102        fn get(&self, index: usize) -> Self::Ref {
103            self.0[index]
104        }
105    }
106
107    impl Columnar for Timestamp {
108        #[inline(always)]
109        fn into_owned<'a>(other: columnar::Ref<'a, Self>) -> Self {
110            other
111        }
112        type Container = Timestamps<Vec<Timestamp>>;
113        #[inline(always)]
114        fn reborrow<'b, 'a: 'b>(thing: columnar::Ref<'a, Self>) -> columnar::Ref<'b, Self>
115        where
116            Self: 'a,
117        {
118            thing
119        }
120    }
121
122    impl columnar::Borrow for Timestamps<Vec<Timestamp>> {
123        type Ref<'a> = Timestamp;
124        type Borrowed<'a>
125            = Timestamps<&'a [Timestamp]>
126        where
127            Self: 'a;
128        #[inline(always)]
129        fn borrow<'a>(&'a self) -> Self::Borrowed<'a> {
130            Timestamps(self.0.as_slice())
131        }
132        #[inline(always)]
133        fn reborrow<'b, 'a: 'b>(item: Self::Borrowed<'a>) -> Self::Borrowed<'b>
134        where
135            Self: 'a,
136        {
137            Timestamps(item.0)
138        }
139
140        #[inline(always)]
141        fn reborrow_ref<'b, 'a: 'b>(item: Self::Ref<'a>) -> Self::Ref<'b>
142        where
143            Self: 'a,
144        {
145            item
146        }
147    }
148
149    impl columnar::Container for Timestamps<Vec<Timestamp>> {
150        #[inline(always)]
151        fn extend_from_self(&mut self, other: Self::Borrowed<'_>, range: Range<usize>) {
152            self.0.extend_from_self(other.0, range)
153        }
154        #[inline(always)]
155        fn reserve_for<'a, I>(&mut self, selves: I)
156        where
157            Self: 'a,
158            I: Iterator<Item = Self::Borrowed<'a>> + Clone,
159        {
160            self.0.reserve_for(selves.map(|s| s.0));
161        }
162    }
163
164    impl<'a> columnar::AsBytes<'a> for Timestamps<&'a [Timestamp]> {
165        #[inline(always)]
166        fn as_bytes(&self) -> impl Iterator<Item = (u64, &'a [u8])> {
167            std::iter::once((
168                u64::cast_from(align_of::<Timestamp>()),
169                bytemuck::cast_slice(self.0),
170            ))
171        }
172    }
173    impl<'a> columnar::FromBytes<'a> for Timestamps<&'a [Timestamp]> {
174        const SLICE_COUNT: usize = 1;
175        #[inline(always)]
176        fn from_bytes(bytes: &mut impl Iterator<Item = &'a [u8]>) -> Self {
177            Timestamps(bytemuck::cast_slice(
178                bytes.next().expect("Iterator exhausted prematurely"),
179            ))
180        }
181    }
182}
183
184impl BucketTimestamp for Timestamp {
185    fn advance_by_power_of_two(&self, exponent: u32) -> Option<Self> {
186        let rhs = 1_u64.checked_shl(exponent)?;
187        Some(self.internal.checked_add(rhs)?.into())
188    }
189}
190
191pub trait TimestampManipulation:
192    timely::progress::Timestamp
193    + timely::order::TotalOrder
194    + differential_dataflow::lattice::Lattice
195    + std::fmt::Debug
196    + mz_persist_types::StepForward
197    + Sync
198{
199    /// Advance a timestamp by the least amount possible such that
200    /// `ts.less_than(ts.step_forward())` is true. Panic if unable to do so.
201    fn step_forward(&self) -> Self;
202
203    /// Advance a timestamp forward by the given `amount`. Panic if unable to do so.
204    fn step_forward_by(&self, amount: &Self) -> Self;
205
206    /// Advance a timestamp forward by the given `amount`. Return `None` if unable to do so.
207    fn try_step_forward_by(&self, amount: &Self) -> Option<Self>;
208
209    /// Advance a timestamp by the least amount possible such that `ts.less_than(ts.step_forward())`
210    /// is true. Return `None` if unable to do so.
211    fn try_step_forward(&self) -> Option<Self>;
212
213    /// Retreat a timestamp by the least amount possible such that
214    /// `ts.step_back().unwrap().less_than(ts)` is true. Return `None` if unable,
215    /// which must only happen if the timestamp is `Timestamp::minimum()`.
216    fn step_back(&self) -> Option<Self>;
217
218    /// Return the maximum value for this timestamp.
219    fn maximum() -> Self;
220
221    /// Rounds up the timestamp to the time of the next refresh according to the given schedule.
222    /// Returns None if there is no next refresh.
223    fn round_up(&self, schedule: &RefreshSchedule) -> Option<Self>;
224
225    /// Rounds down `timestamp - 1` to the time of the previous refresh according to the given
226    /// schedule.
227    /// Returns None if there is no previous refresh.
228    fn round_down_minus_1(&self, schedule: &RefreshSchedule) -> Option<Self>;
229}
230
231impl TimestampManipulation for Timestamp {
232    fn step_forward(&self) -> Self {
233        self.step_forward()
234    }
235
236    fn step_forward_by(&self, amount: &Self) -> Self {
237        self.step_forward_by(amount)
238    }
239
240    fn try_step_forward(&self) -> Option<Self> {
241        self.try_step_forward()
242    }
243
244    fn try_step_forward_by(&self, amount: &Self) -> Option<Self> {
245        self.try_step_forward_by(amount)
246    }
247
248    fn step_back(&self) -> Option<Self> {
249        self.step_back()
250    }
251
252    fn maximum() -> Self {
253        Self::MAX
254    }
255
256    fn round_up(&self, schedule: &RefreshSchedule) -> Option<Self> {
257        schedule.round_up_timestamp(*self)
258    }
259
260    fn round_down_minus_1(&self, schedule: &RefreshSchedule) -> Option<Self> {
261        schedule.round_down_timestamp_m1(*self)
262    }
263}
264
265impl mz_persist_types::StepForward for Timestamp {
266    fn step_forward(&self) -> Self {
267        self.step_forward()
268    }
269}
270
271impl Timestamp {
272    pub const MAX: Self = Self { internal: u64::MAX };
273    pub const MIN: Self = Self { internal: u64::MIN };
274
275    pub const fn new(timestamp: u64) -> Self {
276        Self {
277            internal: timestamp,
278        }
279    }
280
281    pub fn to_bytes(&self) -> [u8; 8] {
282        self.internal.to_le_bytes()
283    }
284
285    pub fn from_bytes(bytes: [u8; 8]) -> Self {
286        Self {
287            internal: u64::from_le_bytes(bytes),
288        }
289    }
290
291    pub fn saturating_sub<I: Into<Self>>(self, rhs: I) -> Self {
292        Self {
293            internal: self.internal.saturating_sub(rhs.into().internal),
294        }
295    }
296
297    pub fn saturating_add<I: Into<Self>>(self, rhs: I) -> Self {
298        Self {
299            internal: self.internal.saturating_add(rhs.into().internal),
300        }
301    }
302
303    pub fn saturating_mul<I: Into<Self>>(self, rhs: I) -> Self {
304        Self {
305            internal: self.internal.saturating_mul(rhs.into().internal),
306        }
307    }
308
309    pub fn checked_add<I: Into<Self>>(self, rhs: I) -> Option<Self> {
310        self.internal
311            .checked_add(rhs.into().internal)
312            .map(|internal| Self { internal })
313    }
314
315    pub fn checked_sub<I: Into<Self>>(self, rhs: I) -> Option<Self> {
316        self.internal
317            .checked_sub(rhs.into().internal)
318            .map(|internal| Self { internal })
319    }
320
321    /// Advance a timestamp by the least amount possible such that
322    /// `ts.less_than(ts.step_forward())` is true. Panic if unable to do so.
323    pub fn step_forward(&self) -> Self {
324        match self.checked_add(1) {
325            Some(ts) => ts,
326            None => panic!("could not step forward"),
327        }
328    }
329
330    /// Advance a timestamp forward by the given `amount`. Panic if unable to do so.
331    pub fn step_forward_by(&self, amount: &Self) -> Self {
332        match self.checked_add(*amount) {
333            Some(ts) => ts,
334            None => panic!("could not step {self} forward by {amount}"),
335        }
336    }
337
338    /// Advance a timestamp by the least amount possible such that `ts.less_than(ts.step_forward())`
339    /// is true. Return `None` if unable to do so.
340    pub fn try_step_forward(&self) -> Option<Self> {
341        self.checked_add(1)
342    }
343
344    /// Advance a timestamp forward by the given `amount`. Return `None` if unable to do so.
345    pub fn try_step_forward_by(&self, amount: &Self) -> Option<Self> {
346        self.checked_add(*amount)
347    }
348
349    /// Retreat a timestamp by the least amount possible such that
350    /// `ts.step_back().unwrap().less_than(ts)` is true. Return `None` if unable,
351    /// which must only happen if the timestamp is `Timestamp::minimum()`.
352    pub fn step_back(&self) -> Option<Self> {
353        self.checked_sub(1)
354    }
355}
356
357impl From<u64> for Timestamp {
358    fn from(internal: u64) -> Self {
359        Self { internal }
360    }
361}
362
363impl From<Timestamp> for u64 {
364    fn from(ts: Timestamp) -> Self {
365        ts.internal
366    }
367}
368
369impl From<Timestamp> for u128 {
370    fn from(ts: Timestamp) -> Self {
371        u128::from(ts.internal)
372    }
373}
374
375impl TryFrom<Timestamp> for i64 {
376    type Error = TryFromIntError;
377
378    fn try_from(value: Timestamp) -> Result<Self, Self::Error> {
379        value.internal.try_into()
380    }
381}
382
383impl From<&Timestamp> for u64 {
384    fn from(ts: &Timestamp) -> Self {
385        ts.internal
386    }
387}
388
389impl From<Timestamp> for Numeric {
390    fn from(ts: Timestamp) -> Self {
391        ts.internal.into()
392    }
393}
394
395impl From<Timestamp> for Duration {
396    fn from(ts: Timestamp) -> Self {
397        Duration::from_millis(ts.internal)
398    }
399}
400
401impl std::ops::Rem<Timestamp> for Timestamp {
402    type Output = Timestamp;
403
404    fn rem(self, rhs: Timestamp) -> Self::Output {
405        Self {
406            internal: self.internal % rhs.internal,
407        }
408    }
409}
410
411impl Serialize for Timestamp {
412    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
413    where
414        S: Serializer,
415    {
416        self.internal.serialize(serializer)
417    }
418}
419
420impl<'de> Deserialize<'de> for Timestamp {
421    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
422    where
423        D: serde::Deserializer<'de>,
424    {
425        Ok(Self {
426            internal: u64::deserialize(deserializer)?,
427        })
428    }
429}
430
431impl timely::order::PartialOrder for Timestamp {
432    fn less_equal(&self, other: &Self) -> bool {
433        self.internal.less_equal(&other.internal)
434    }
435}
436
437impl timely::order::PartialOrder<&Timestamp> for Timestamp {
438    fn less_equal(&self, other: &&Self) -> bool {
439        self.internal.less_equal(&other.internal)
440    }
441}
442
443impl timely::order::PartialOrder<Timestamp> for &Timestamp {
444    fn less_equal(&self, other: &Timestamp) -> bool {
445        self.internal.less_equal(&other.internal)
446    }
447}
448
449impl timely::order::TotalOrder for Timestamp {}
450
451impl timely::progress::Timestamp for Timestamp {
452    type Summary = Timestamp;
453
454    fn minimum() -> Self {
455        Self::MIN
456    }
457}
458
459impl timely::progress::PathSummary<Timestamp> for Timestamp {
460    #[inline]
461    fn results_in(&self, src: &Timestamp) -> Option<Timestamp> {
462        self.internal
463            .checked_add(src.internal)
464            .map(|internal| Self { internal })
465    }
466    #[inline]
467    fn followed_by(&self, other: &Timestamp) -> Option<Timestamp> {
468        self.internal
469            .checked_add(other.internal)
470            .map(|internal| Self { internal })
471    }
472}
473
474impl timely::progress::timestamp::Refines<()> for Timestamp {
475    fn to_inner(_: ()) -> Timestamp {
476        Default::default()
477    }
478    fn to_outer(self) -> () {
479        ()
480    }
481    fn summarize(_: <Timestamp as timely::progress::timestamp::Timestamp>::Summary) -> () {
482        ()
483    }
484}
485
486impl differential_dataflow::lattice::Lattice for Timestamp {
487    #[inline]
488    fn join(&self, other: &Self) -> Self {
489        ::std::cmp::max(*self, *other)
490    }
491    #[inline]
492    fn meet(&self, other: &Self) -> Self {
493        ::std::cmp::min(*self, *other)
494    }
495}
496
497impl mz_persist_types::Codec64 for Timestamp {
498    fn codec_name() -> String {
499        u64::codec_name()
500    }
501
502    fn encode(&self) -> [u8; 8] {
503        self.internal.encode()
504    }
505
506    fn decode(buf: [u8; 8]) -> Self {
507        Self {
508            internal: u64::decode(buf),
509        }
510    }
511}
512
513impl std::fmt::Display for Timestamp {
514    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
515        std::fmt::Display::fmt(&self.internal, f)
516    }
517}
518
519impl std::fmt::Debug for Timestamp {
520    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
521        std::fmt::Debug::fmt(&self.internal, f)
522    }
523}
524
525impl std::str::FromStr for Timestamp {
526    type Err = String;
527
528    fn from_str(s: &str) -> Result<Self, Self::Err> {
529        Ok(Self {
530            internal: s
531                .parse::<u64>()
532                .map_err(|_| "could not parse as number of milliseconds since epoch".to_string())
533                .or_else(|err_num_of_millis| {
534                    parse_timestamptz(s)
535                        .map_err(|parse_error| {
536                            format!(
537                                "{}; could not parse as date and time: {}",
538                                err_num_of_millis, parse_error
539                            )
540                        })?
541                        .timestamp_millis()
542                        .try_into()
543                        .map_err(|_| "out of range for mz_timestamp".to_string())
544                })
545                .map_err(|e: String| format!("could not parse mz_timestamp: {}", e))?,
546        })
547    }
548}
549
550impl TryFrom<Duration> for Timestamp {
551    type Error = TryFromIntError;
552
553    fn try_from(value: Duration) -> Result<Self, Self::Error> {
554        Ok(Self {
555            internal: value.as_millis().try_into()?,
556        })
557    }
558}
559
560impl TryFrom<u128> for Timestamp {
561    type Error = TryFromIntError;
562
563    fn try_from(value: u128) -> Result<Self, Self::Error> {
564        Ok(Self {
565            internal: value.try_into()?,
566        })
567    }
568}
569
570impl TryFrom<i64> for Timestamp {
571    type Error = TryFromIntError;
572
573    fn try_from(value: i64) -> Result<Self, Self::Error> {
574        Ok(Self {
575            internal: value.try_into()?,
576        })
577    }
578}
579
580impl TryFrom<Numeric> for Timestamp {
581    type Error = TryFromDecimalError;
582
583    fn try_from(value: Numeric) -> Result<Self, Self::Error> {
584        Ok(Self {
585            internal: value.try_into()?,
586        })
587    }
588}
589
590impl columnation::Columnation for Timestamp {
591    type InnerRegion = columnation::CopyRegion<Timestamp>;
592}