Skip to main content

google_cloud_spanner/
timestamp_bound.rs

1// Copyright 2026 Google LLC
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use crate::model::transaction_options::read_only::TimestampBound as ReadOnlyTimestampBound;
16use std::time::Duration as StdDuration;
17use wkt::Duration;
18use wkt::Timestamp;
19
20/// Use a timestamp bound to specify how to choose a timestamp at which a query should read data.
21///
22/// # Example
23/// ```
24/// # use google_cloud_spanner::client::Spanner;
25/// # use google_cloud_spanner::transaction::TimestampBound;
26/// # async fn test_doc() -> Result<(), Box<dyn std::error::Error>> {
27/// let client = Spanner::builder().build().await?;
28/// let db = client.database_client("projects/p/instances/i/databases/d").build().await?;
29///
30/// let tx = db.single_use().set_timestamp_bound(TimestampBound::strong()).build();
31/// # Ok(())
32/// # }
33/// ```
34///
35/// See <https://cloud.google.com/spanner/docs/timestamp-bounds> for more information.
36#[derive(Clone, Debug, PartialEq)]
37pub struct TimestampBound(pub(crate) ReadOnlyTimestampBound);
38
39impl Default for TimestampBound {
40    fn default() -> Self {
41        Self::strong()
42    }
43}
44
45impl TimestampBound {
46    /// Returns a strong timestamp bound. Strong reads are guaranteed to see the
47    /// effects of all transactions that have committed before the start of the read.
48    ///
49    /// See [timestamp_bound_strong] for more information.
50    ///
51    /// [timestamp_bound_strong]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#strong
52    pub fn strong() -> Self {
53        Self(ReadOnlyTimestampBound::Strong(true))
54    }
55
56    /// Returns a timestamp bound for an exact timestamp. The data will be read as it was at the given timestamp.
57    ///
58    /// For fallible conversion from types such as RFC 3339 strings, [`std::time::SystemTime`],
59    /// or [`time::OffsetDateTime`], use [`try_read_timestamp`](Self::try_read_timestamp).
60    ///
61    /// See [timestamp_bound_read_timestamp] for more information.
62    ///
63    /// [timestamp_bound_read_timestamp]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#read_timestamp
64    pub fn read_timestamp(timestamp: Timestamp) -> Self {
65        Self(ReadOnlyTimestampBound::ReadTimestamp(Box::new(timestamp)))
66    }
67
68    /// Returns a timestamp bound for an exact timestamp, returning an error if the timestamp is out of range.
69    ///
70    /// See [timestamp_bound_read_timestamp] for more information.
71    ///
72    /// [timestamp_bound_read_timestamp]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#read_timestamp
73    pub fn try_read_timestamp<T>(timestamp: T) -> Result<Self, T::Error>
74    where
75        T: TryInto<Timestamp>,
76    {
77        let timestamp = timestamp.try_into()?;
78        Ok(Self::read_timestamp(timestamp))
79    }
80
81    /// Returns a timestamp bound for a minimum read timestamp. The data will be read as it was at the
82    /// given timestamp or later.
83    ///
84    /// For fallible conversion from types such as RFC 3339 strings, [`std::time::SystemTime`],
85    /// or [`time::OffsetDateTime`], use [`try_min_read_timestamp`](Self::try_min_read_timestamp).
86    ///
87    /// See [timestamp_bound_bounded_staleness] for more information.
88    ///
89    /// [timestamp_bound_bounded_staleness]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#bounded_staleness
90    pub fn min_read_timestamp(timestamp: Timestamp) -> Self {
91        Self(ReadOnlyTimestampBound::MinReadTimestamp(Box::new(
92            timestamp,
93        )))
94    }
95
96    /// Returns a timestamp bound for a minimum read timestamp, returning an error if the timestamp is out of range.
97    ///
98    /// See [timestamp_bound_bounded_staleness] for more information.
99    ///
100    /// [timestamp_bound_bounded_staleness]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#bounded_staleness
101    pub fn try_min_read_timestamp<T>(timestamp: T) -> Result<Self, T::Error>
102    where
103        T: TryInto<Timestamp>,
104    {
105        let timestamp = timestamp.try_into()?;
106        Ok(Self::min_read_timestamp(timestamp))
107    }
108
109    /// Returns a timestamp bound for an exact staleness. The data will be read as it was at the given timestamp
110    /// calculated by the current server time minus the given duration.
111    ///
112    /// For fallible conversion from types such as [`wkt::Duration`], use
113    /// [`try_exact_staleness`](Self::try_exact_staleness).
114    ///
115    /// See [timestamp_bound_exact_staleness] for more information.
116    ///
117    /// [timestamp_bound_exact_staleness]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#exact_staleness
118    pub fn exact_staleness(duration: StdDuration) -> Self {
119        Self(ReadOnlyTimestampBound::ExactStaleness(Box::new(
120            to_clamped_duration(duration),
121        )))
122    }
123
124    /// Returns a timestamp bound for an exact staleness, returning an error if the duration is out of range.
125    ///
126    /// See [timestamp_bound_exact_staleness] for more information.
127    ///
128    /// [timestamp_bound_exact_staleness]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#exact_staleness
129    pub fn try_exact_staleness<T>(duration: T) -> Result<Self, T::Error>
130    where
131        T: TryInto<Duration>,
132    {
133        let duration = duration.try_into()?;
134        Ok(Self(ReadOnlyTimestampBound::ExactStaleness(Box::new(
135            duration,
136        ))))
137    }
138
139    /// Returns a timestamp bound for a maximum staleness. The data will be read as it was at the
140    /// current server time minus the given duration or later.
141    ///
142    /// For fallible conversion from types such as [`wkt::Duration`], use
143    /// [`try_max_staleness`](Self::try_max_staleness).
144    ///
145    /// See [timestamp_bound_bounded_staleness] for more information.
146    ///
147    /// [timestamp_bound_bounded_staleness]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#bounded_staleness
148    pub fn max_staleness(duration: StdDuration) -> Self {
149        Self(ReadOnlyTimestampBound::MaxStaleness(Box::new(
150            to_clamped_duration(duration),
151        )))
152    }
153
154    /// Returns a timestamp bound for a maximum staleness, returning an error if the duration is out of range.
155    ///
156    /// See [timestamp_bound_bounded_staleness] for more information.
157    ///
158    /// [timestamp_bound_bounded_staleness]: https://docs.cloud.google.com/spanner/docs/timestamp-bounds#bounded_staleness
159    pub fn try_max_staleness<T>(duration: T) -> Result<Self, T::Error>
160    where
161        T: TryInto<Duration>,
162    {
163        let duration = duration.try_into()?;
164        Ok(Self(ReadOnlyTimestampBound::MaxStaleness(Box::new(
165            duration,
166        ))))
167    }
168}
169
170fn to_clamped_duration(duration: StdDuration) -> Duration {
171    let seconds = i64::try_from(duration.as_secs()).unwrap_or(i64::MAX);
172    let nanos = duration.subsec_nanos() as i32;
173    Duration::clamp(seconds, nanos)
174}
175
176#[cfg(test)]
177mod tests {
178    use super::*;
179    use std::fmt::Debug;
180    use std::time::Duration as StdDuration;
181    use std::time::SystemTime;
182    use time::macros::datetime;
183    use wkt::Timestamp;
184
185    #[test]
186    fn test_auto_traits() {
187        static_assertions::assert_impl_all!(TimestampBound: Clone, Debug, Default, PartialEq, Send, Sync);
188    }
189
190    #[test]
191    fn test_strong() {
192        let bound = TimestampBound::strong();
193        assert!(matches!(bound.0, ReadOnlyTimestampBound::Strong(true)));
194        assert_eq!(bound, TimestampBound::default());
195    }
196
197    #[test]
198    fn test_read_timestamp_methods() {
199        let ts = datetime!(2026-03-09 18:00:00 UTC);
200
201        // 1. OffsetDateTime
202        #[cfg(feature = "unstable-time")]
203        {
204            let try_read = TimestampBound::try_read_timestamp(ts).expect("valid OffsetDateTime");
205            assert!(matches!(
206                try_read.0,
207                ReadOnlyTimestampBound::ReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
208            ));
209        }
210
211        // 2. wkt::Timestamp
212        let timestamp = Timestamp::clamp(ts.unix_timestamp(), ts.nanosecond() as i32);
213        let read = TimestampBound::read_timestamp(timestamp);
214        assert!(matches!(
215            read.0,
216            ReadOnlyTimestampBound::ReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
217        ));
218
219        let try_read = TimestampBound::try_read_timestamp(timestamp).expect("valid wkt timestamp");
220        assert!(matches!(
221            try_read.0,
222            ReadOnlyTimestampBound::ReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
223        ));
224
225        // 3. SystemTime
226        let system_time = SystemTime::from(ts);
227        let try_read = TimestampBound::try_read_timestamp(system_time).expect("valid SystemTime");
228        assert!(matches!(
229            try_read.0,
230            ReadOnlyTimestampBound::ReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
231        ));
232    }
233
234    #[test]
235    fn test_min_read_timestamp_methods() {
236        let ts = datetime!(2026-03-09 18:00:00 UTC);
237
238        // 1. OffsetDateTime
239        #[cfg(feature = "unstable-time")]
240        {
241            let try_min_read =
242                TimestampBound::try_min_read_timestamp(ts).expect("valid OffsetDateTime");
243            assert!(matches!(
244                try_min_read.0,
245                ReadOnlyTimestampBound::MinReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
246            ));
247        }
248
249        // 2. wkt::Timestamp
250        let timestamp = Timestamp::clamp(ts.unix_timestamp(), ts.nanosecond() as i32);
251        let min_read = TimestampBound::min_read_timestamp(timestamp);
252        assert!(matches!(
253            min_read.0,
254            ReadOnlyTimestampBound::MinReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
255        ));
256
257        let try_min_read =
258            TimestampBound::try_min_read_timestamp(timestamp).expect("valid wkt timestamp");
259        assert!(matches!(
260            try_min_read.0,
261            ReadOnlyTimestampBound::MinReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
262        ));
263
264        // 3. SystemTime
265        let system_time = SystemTime::from(ts);
266        let try_min_read =
267            TimestampBound::try_min_read_timestamp(system_time).expect("valid SystemTime");
268        assert!(matches!(
269            try_min_read.0,
270            ReadOnlyTimestampBound::MinReadTimestamp(ref t) if t.seconds() == ts.unix_timestamp() && t.nanos() == ts.nanosecond() as i32
271        ));
272    }
273
274    #[test]
275    fn test_exact_staleness_methods() {
276        let d = StdDuration::from_secs(60);
277
278        // 1. std::time::Duration
279        let exact = TimestampBound::exact_staleness(d);
280        assert!(matches!(
281            exact.0,
282            ReadOnlyTimestampBound::ExactStaleness(ref t) if t.seconds() == 60 && t.nanos() == 0
283        ));
284
285        let try_exact = TimestampBound::try_exact_staleness(d).expect("valid std::time::Duration");
286        assert!(matches!(
287            try_exact.0,
288            ReadOnlyTimestampBound::ExactStaleness(ref t) if t.seconds() == 60 && t.nanos() == 0
289        ));
290
291        // 2. wkt::Duration
292        let wkt_d = Duration::clamp(60, 0);
293        let try_exact = TimestampBound::try_exact_staleness(wkt_d).expect("valid wkt::Duration");
294        assert!(matches!(
295            try_exact.0,
296            ReadOnlyTimestampBound::ExactStaleness(ref t) if t.seconds() == 60 && t.nanos() == 0
297        ));
298    }
299
300    #[test]
301    fn test_max_staleness_methods() {
302        let d = StdDuration::from_secs(120);
303
304        // 1. std::time::Duration
305        let max = TimestampBound::max_staleness(d);
306        assert!(matches!(
307            max.0,
308            ReadOnlyTimestampBound::MaxStaleness(ref t) if t.seconds() == 120 && t.nanos() == 0
309        ));
310
311        let try_max = TimestampBound::try_max_staleness(d).expect("valid std::time::Duration");
312        assert!(matches!(
313            try_max.0,
314            ReadOnlyTimestampBound::MaxStaleness(ref t) if t.seconds() == 120 && t.nanos() == 0
315        ));
316
317        // 2. wkt::Duration
318        let wkt_d = Duration::clamp(120, 0);
319        let try_max = TimestampBound::try_max_staleness(wkt_d).expect("valid wkt::Duration");
320        assert!(matches!(
321            try_max.0,
322            ReadOnlyTimestampBound::MaxStaleness(ref t) if t.seconds() == 120 && t.nanos() == 0
323        ));
324    }
325
326    #[test]
327    fn test_out_of_range() {
328        let out_of_range_time = SystemTime::UNIX_EPOCH
329            .checked_sub(StdDuration::from_secs(100_000_000_000))
330            .expect("valid SystemTime");
331        assert!(
332            TimestampBound::try_read_timestamp(out_of_range_time).is_err(),
333            "expected try_read_timestamp to fail for out-of-range timestamp"
334        );
335        assert!(
336            TimestampBound::try_min_read_timestamp(out_of_range_time).is_err(),
337            "expected try_min_read_timestamp to fail for out-of-range timestamp"
338        );
339
340        let out_of_range_duration = StdDuration::from_secs(u64::MAX);
341        assert!(
342            TimestampBound::try_exact_staleness(out_of_range_duration).is_err(),
343            "expected try_exact_staleness to fail for out-of-range duration"
344        );
345        assert!(
346            TimestampBound::try_max_staleness(out_of_range_duration).is_err(),
347            "expected try_max_staleness to fail for out-of-range duration"
348        );
349
350        let clamped_exact = TimestampBound::exact_staleness(out_of_range_duration);
351        assert!(
352            matches!(
353                clamped_exact.0,
354                ReadOnlyTimestampBound::ExactStaleness(ref d)
355                    if d.seconds() == Duration::MAX_SECONDS && d.nanos() == 0
356            ),
357            "expected exact_staleness to clamp to MAX_SECONDS"
358        );
359        let clamped_max = TimestampBound::max_staleness(out_of_range_duration);
360        assert!(
361            matches!(
362                clamped_max.0,
363                ReadOnlyTimestampBound::MaxStaleness(ref d)
364                    if d.seconds() == Duration::MAX_SECONDS && d.nanos() == 0
365            ),
366            "expected max_staleness to clamp to MAX_SECONDS"
367        );
368    }
369}