objectstore_client/expiry.rs
1use std::time::{Duration, SystemTime};
2
3use objectstore_types::metadata::{self, ExpiryAnchor, MetadataUpdate};
4use objectstore_types::time::Timestamp;
5use reqwest::StatusCode;
6
7use crate::instrument::OperationSpan;
8use crate::response::ResponseExt as _;
9use crate::{ObjectKey, Session};
10
11/// A requested minimum expiration deadline.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum ExpiryExtension {
14 /// An absolute deadline, rounded upward to a whole second.
15 At(SystemTime),
16 /// Total lifetime since the object's creation or most recent replacement.
17 ///
18 /// Fractional seconds are truncated when sent to the server.
19 FromCreation(Duration),
20 /// Lifetime from the start of this request on the server.
21 ///
22 /// Fractional seconds are truncated. Retrying establishes a new server-time
23 /// anchor and can extend the deadline further.
24 FromNow(Duration),
25}
26
27impl ExpiryExtension {
28 fn into_update(self) -> crate::Result<MetadataUpdate> {
29 let extend_expiry = match self {
30 Self::At(at) => metadata::ExpiryExtension::At {
31 at: Timestamp::try_from(at)
32 .map_err(metadata::Error::ExpirationTime)?
33 .as_rfc3339(),
34 },
35 Self::FromCreation(after) => metadata::ExpiryExtension::After {
36 after,
37 from: ExpiryAnchor::Creation,
38 },
39 Self::FromNow(after) => metadata::ExpiryExtension::After {
40 after,
41 from: ExpiryAnchor::Now,
42 },
43 };
44 Ok(MetadataUpdate { extend_expiry })
45 }
46}
47
48/// The outcome of a [`Session::extend_expiry`] call.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum ExtendExpiryResponse {
51 /// The deadline was extended or already satisfied the request.
52 ///
53 /// Does not report whether the deadline changed or its stored value.
54 Satisfied,
55 /// The object was observed to be absent or expired.
56 NotFound,
57 /// The extension could not be satisfied.
58 ///
59 /// The object is non-expiring, lacks creation metadata required by a
60 /// creation-relative target, or conflicts with a conditional update.
61 /// A conflict can result from concurrent deletion, so this does not
62 /// guarantee that the object still exists.
63 Rejected,
64}
65
66impl Session {
67 /// Extends an object's expiration deadline while preserving its payload.
68 ///
69 /// An already-sufficient deadline succeeds without being shortened. Relative
70 /// targets are resolved by the server, not added to the existing deadline.
71 /// This requires object-write permission.
72 ///
73 /// Actual extensions adjust TTL duration to approximately match the total lifetime
74 /// since creation; TTI duration remains unchanged.
75 ///
76 /// Returns [`ExtendExpiryResponse`] to distinguish a satisfied request, an
77 /// absent or expired object, and a rejected extension. Other HTTP and transport
78 /// errors are returned through [`crate::Error::Reqwest`].
79 ///
80 /// ```no_run
81 /// # async fn example(session: objectstore_client::Session) -> objectstore_client::Result<()> {
82 /// use std::time::Duration;
83 /// use objectstore_client::{ExpiryExtension, ExtendExpiryResponse};
84 ///
85 /// match session.extend_expiry("key", ExpiryExtension::FromNow(Duration::from_secs(86400)))
86 /// .send().await?
87 /// {
88 /// ExtendExpiryResponse::Satisfied => println!("Deadline satisfied"),
89 /// ExtendExpiryResponse::NotFound => println!("Object is missing or expired"),
90 /// ExtendExpiryResponse::Rejected => println!("Extension was rejected"),
91 /// }
92 /// # Ok(())
93 /// # }
94 /// ```
95 pub fn extend_expiry(&self, key: &str, target: ExpiryExtension) -> ExtendExpiryBuilder {
96 ExtendExpiryBuilder {
97 session: self.clone(),
98 key: key.to_owned(),
99 target,
100 }
101 }
102}
103
104/// A [`Session::extend_expiry`] request builder.
105#[derive(Debug)]
106pub struct ExtendExpiryBuilder {
107 session: Session,
108 key: ObjectKey,
109 target: ExpiryExtension,
110}
111
112impl ExtendExpiryBuilder {
113 /// Sends the extension request, failing locally for an out-of-range timestamp.
114 pub async fn send(self) -> crate::Result<ExtendExpiryResponse> {
115 let span =
116 OperationSpan::storage("objectstore.extend_expiry", &self.session, Some(&self.key));
117 span.instrument(self.execute()).await
118 }
119
120 async fn execute(self) -> crate::Result<ExtendExpiryResponse> {
121 let update = self.target.into_update()?;
122 let response = self
123 .session
124 .request(reqwest::Method::PATCH, &self.key)?
125 .json(&update)
126 .send()
127 .await?;
128 let outcome = match response.status() {
129 StatusCode::NOT_FOUND => ExtendExpiryResponse::NotFound,
130 StatusCode::CONFLICT => ExtendExpiryResponse::Rejected,
131 _ => {
132 response
133 .error_for_status_and_drain()
134 .await?
135 .drain_body()
136 .await;
137 return Ok(ExtendExpiryResponse::Satisfied);
138 }
139 };
140 response.drain_body().await;
141 Ok(outcome)
142 }
143}
144
145#[cfg(test)]
146mod tests {
147 use super::*;
148
149 #[test]
150 fn wire_targets() {
151 for (target, expected) in [
152 (
153 ExpiryExtension::At(SystemTime::UNIX_EPOCH + Duration::from_millis(1500)),
154 metadata::ExpiryExtension::At {
155 at: "1970-01-01T00:00:02Z".parse().unwrap(),
156 },
157 ),
158 (
159 ExpiryExtension::FromCreation(Duration::from_millis(1500)),
160 metadata::ExpiryExtension::After {
161 after: Duration::from_millis(1500),
162 from: ExpiryAnchor::Creation,
163 },
164 ),
165 (
166 ExpiryExtension::FromNow(Duration::ZERO),
167 metadata::ExpiryExtension::After {
168 after: Duration::ZERO,
169 from: ExpiryAnchor::Now,
170 },
171 ),
172 ] {
173 assert_eq!(target.into_update().unwrap().extend_expiry, expected);
174 }
175 }
176
177 #[test]
178 fn rejects_out_of_range_timestamps() {
179 for at in [
180 SystemTime::UNIX_EPOCH - Duration::from_secs(1),
181 SystemTime::UNIX_EPOCH + Duration::from_secs(253_402_300_800),
182 ] {
183 assert!(matches!(
184 ExpiryExtension::At(at).into_update(),
185 Err(crate::Error::Metadata(metadata::Error::ExpirationTime(_)))
186 ));
187 }
188 }
189}