momento_functions_collections_common/lib.rs
1//! Common types shared across Momento Cache collection interfaces.
2
3use std::time::Duration;
4
5/// Represents the desired behavior for managing the TTL on collections.
6///
7/// The first time the collection is created, it needs to set a TTL. For subsequent operations
8/// that modify the collection, you may choose to update the TTL in order to prolong the life
9/// of the cached collection, or to leave the TTL unmodified to ensure the collection expires
10/// at the original TTL.
11#[derive(Copy, Clone, Debug, PartialEq, Eq)]
12pub struct CollectionTtl {
13 ttl: Duration,
14 refresh: bool,
15}
16
17impl CollectionTtl {
18 /// Create a collection TTL with the provided `ttl` and `refresh` settings.
19 pub const fn new(ttl: Duration, refresh: bool) -> Self {
20 Self { ttl, refresh }
21 }
22
23 /// Create a collection TTL that updates the TTL for the collection any time it is
24 /// modified.
25 pub fn refresh_on_update(ttl: impl Into<Duration>) -> Self {
26 Self::new(ttl.into(), true)
27 }
28
29 /// Create a collection TTL that will not refresh the TTL for the collection when
30 /// it is updated.
31 ///
32 /// Use this if you want to be sure that the collection expires at the originally
33 /// specified time, even if you make modifications to the value of the collection.
34 ///
35 /// The TTL will still be used when a new collection is created.
36 pub fn initialize_only(ttl: impl Into<Duration>) -> Self {
37 Self::new(ttl.into(), false)
38 }
39
40 /// Return a new collection TTL which uses the same TTL but refreshes on updates.
41 pub fn with_refresh_on_update(self) -> Self {
42 Self::new(self.ttl(), true)
43 }
44
45 /// Return a new collection TTL which uses the same TTL but does not refresh on
46 /// updates.
47 pub fn with_no_refresh_on_update(self) -> Self {
48 Self::new(self.ttl(), false)
49 }
50
51 /// Return a new collection TTL which has the same refresh behavior but uses the
52 /// provided TTL.
53 pub fn with_ttl(self, ttl: impl Into<Duration>) -> Self {
54 Self::new(ttl.into(), self.refresh())
55 }
56
57 /// Constructs a CollectionTtl with the specified TTL. The TTL for the collection will be
58 /// refreshed any time the collection is modified.
59 pub fn of(ttl: Duration) -> Self {
60 Self::new(ttl, true)
61 }
62
63 /// The [`Duration`] after which the cached collection should be expired from the
64 /// cache.
65 pub fn ttl(&self) -> Duration {
66 self.ttl
67 }
68
69 /// Whether the collection's TTL will be refreshed on every update.
70 ///
71 /// If true, this will extend the time at which the collection would expire when
72 /// an update operation happens. Otherwise, the collection's TTL will only be set
73 /// when it is initially created.
74 pub fn refresh(&self) -> bool {
75 self.refresh
76 }
77}
78
79/// Saturate a Duration to u64 milliseconds, clamping at u64::MAX.
80pub fn saturate_ttl(ttl: Duration) -> u64 {
81 ttl.as_millis().min(u64::MAX as u128) as u64
82}