ic_utils/call/
expiry.rs

1use std::time::{Duration, SystemTime};
2
3use ic_agent::agent::{QueryBuilder, UpdateBuilder};
4use time::OffsetDateTime;
5
6/// An expiry value. Either not specified (the default), a delay relative to the time the
7/// call is made, or a specific date time.
8#[derive(Clone, Debug, Ord, PartialOrd, Eq, PartialEq, Default)]
9pub enum Expiry {
10    /// Unspecified. Will not try to override the Agent's value, which might itself have
11    /// its own default value.
12    #[default]
13    Unspecified,
14
15    /// A duration that will be added to the system time when the call is made.
16    Delay(Duration),
17
18    /// A specific date and time to use for the expiry of the request.
19    DateTime(OffsetDateTime),
20}
21
22impl Expiry {
23    /// Create an expiry that happens after a duration.
24    #[inline]
25    pub fn after(d: Duration) -> Self {
26        Self::Delay(d)
27    }
28
29    /// Set the expiry field to a specific date and time.
30    #[inline]
31    pub fn at(dt: impl Into<OffsetDateTime>) -> Self {
32        Self::DateTime(dt.into())
33    }
34
35    pub(crate) fn apply_to_update(self, u: UpdateBuilder<'_>) -> UpdateBuilder<'_> {
36        match self {
37            Expiry::Unspecified => u,
38            Expiry::Delay(d) => u.expire_after(d),
39            Expiry::DateTime(dt) => u.expire_at(dt),
40        }
41    }
42
43    pub(crate) fn apply_to_query(self, u: QueryBuilder<'_>) -> QueryBuilder<'_> {
44        match self {
45            Expiry::Unspecified => u,
46            Expiry::Delay(d) => u.expire_after(d),
47            Expiry::DateTime(dt) => u.expire_at(dt),
48        }
49    }
50}
51
52impl From<Duration> for Expiry {
53    fn from(d: Duration) -> Self {
54        Self::Delay(d)
55    }
56}
57
58impl From<SystemTime> for Expiry {
59    fn from(dt: SystemTime) -> Self {
60        Self::DateTime(dt.into())
61    }
62}
63
64impl From<OffsetDateTime> for Expiry {
65    fn from(dt: OffsetDateTime) -> Self {
66        Self::DateTime(dt)
67    }
68}