Skip to main content

objectstore_types/
metadata.rs

1//! Per-object metadata types and HTTP header serialization.
2//!
3//! This module defines [`Metadata`], the per-object metadata structure that
4//! travels through the entire system: clients set it via HTTP headers, the
5//! server parses and validates it, the service passes it to backends, and
6//! backends persist it alongside the stored object.
7//!
8//! [`MetadataUpdate`] is the separate JSON request contract for explicit
9//! metadata updates. It is not a persisted metadata representation.
10//!
11//! # Serialization
12//!
13//! Metadata has two serialization formats:
14//!
15//! - **HTTP headers** — used by the public API. [`Metadata::from_headers`] and
16//!   [`Metadata::to_headers`] handle this conversion for public fields only.
17//! - **JSON** — used internally by backends for storage. JSON serialization
18//!   includes additional internal fields that are skipped in the header
19//!   representation.
20//!
21//! # HTTP header prefixes
22//!
23//! Headers use three prefix conventions:
24//!
25//! - Standard HTTP headers where applicable (`Content-Type`, `Content-Encoding`)
26//! - `x-sn-*` for objectstore-specific fields (e.g. `x-sn-expiration`)
27//! - `x-snme-` for custom user metadata (e.g. `x-snme-build_id`)
28//!
29//! Backends that store metadata as object metadata (like GCS) layer their own
30//! prefix on top, so `x-sn-expiration` becomes `x-goog-meta-x-sn-expiration`.
31//! The [`Metadata::from_headers`] and [`Metadata::to_headers`] methods accept
32//! a `prefix` parameter for this purpose.
33//!
34//! # Escaping free-form values
35//!
36//! [`Metadata`] always holds logical strings: [`filename`](Metadata::filename),
37//! [`origin`](Metadata::origin), and [`custom`](Metadata::custom) values may
38//! contain arbitrary Unicode.
39//!
40//! Over the wire, metadata travels in HTTP headers, which have no charset. In
41//! practice anything outside visible ASCII is either rejected outright or
42//! silently reinterpreted.
43//!
44//! The fields are therefore percent-encoded in headers, via
45//! [`headers::encode_header_value`] and [`headers::decode_header_value`].
46//! Encoding is a property of the *transport*, never of the stored value:
47//! anything reading [`Metadata`] sees the logical string.
48
49use std::borrow::Cow;
50use std::collections::BTreeMap;
51use std::fmt;
52use std::num::ParseIntError;
53use std::str::FromStr;
54use std::time::Duration;
55
56use http::header::{self, HeaderMap, HeaderName};
57use serde::{Deserialize, Serialize};
58
59use crate::duration::{ParseDurationError, format_duration, parse_duration};
60use crate::headers;
61use crate::time::{InvalidTimestamp, Rfc3339Timestamp, Timestamp};
62
63/// The custom HTTP header that contains the serialized [`ExpirationPolicy`].
64pub const HEADER_EXPIRATION: &str = "x-sn-expiration";
65/// The custom HTTP header that contains the object creation time.
66pub const HEADER_TIME_CREATED: &str = "x-sn-time-created";
67/// The custom HTTP header that contains the object expiration time.
68pub const HEADER_TIME_EXPIRES: &str = "x-sn-time-expires";
69/// The custom HTTP header that contains the origin of the object.
70pub const HEADER_ORIGIN: &str = "x-sn-origin";
71/// The custom HTTP header that contains the filename of the object.
72pub const HEADER_FILENAME: &str = "x-sn-filename";
73/// The custom HTTP header that contains the size of the stored object in bytes.
74pub const HEADER_SIZE: &str = "x-sn-size";
75/// The prefix for custom HTTP headers containing custom per-object metadata.
76pub const HEADER_META_PREFIX: &str = "x-snme-";
77
78/// The default content type for objects without a known content type.
79pub const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";
80
81/// Upper bound on the TTI debounce window.
82///
83/// The debounce window for TTI bumps is `min(tti / 4, MAX_TTI_DEBOUNCE)`. For
84/// TTI values above 4 days the debounce stays at 24 hours (the historical
85/// constant); shorter TTI values get a proportionally smaller window so that
86/// bumps are not silently suppressed.
87const MAX_TTI_DEBOUNCE: Duration = Duration::from_hours(24);
88
89/// An application-specific JSON request for updating object metadata.
90///
91/// This is intentionally separate from [`Metadata`]: omitted fields are not merge-patch
92/// operations, and metadata headers are not interpreted as updates. Unknown fields are rejected.
93#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
94#[serde(deny_unknown_fields)]
95pub struct MetadataUpdate {
96    /// Extends the existing expiration deadline, adjusting TTL duration to match.
97    pub extend_expiry: ExpiryExtension,
98}
99
100/// A requested minimum expiration deadline.
101///
102/// The absolute form contains `at`. The relative form contains both `after` and `from`.
103/// Mixed, incomplete, and unknown fields are rejected during deserialization.
104#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
105#[serde(untagged, deny_unknown_fields)]
106pub enum ExpiryExtension {
107    /// An RFC3339 deadline, validated during deserialization.
108    At {
109        /// The requested absolute deadline.
110        at: Rfc3339Timestamp,
111    },
112    /// A duration relative to an explicit anchor.
113    After {
114        /// A duration in the format documented by [`crate::duration`].
115        #[serde(with = "crate::duration")]
116        after: Duration,
117        /// The timestamp against which the duration is resolved.
118        from: ExpiryAnchor,
119    },
120}
121
122/// The timestamp against which a relative expiry extension is resolved.
123#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
124#[serde(rename_all = "snake_case")]
125pub enum ExpiryAnchor {
126    /// The object's observed creation time.
127    Creation,
128    /// The request-start time.
129    Now,
130}
131
132/// A content type is not a valid [IANA Media
133/// Type](https://www.iana.org/assignments/media-types/media-types.xhtml).
134///
135/// The message describes which part is malformed. The underlying parser is an implementation
136/// detail and not part of the public API.
137#[derive(Debug, thiserror::Error)]
138#[error(transparent)]
139pub struct InvalidContentType(mediatype::MediaTypeError);
140
141/// Errors that can happen dealing with metadata
142#[derive(Debug, thiserror::Error)]
143pub enum Error {
144    /// Any problems dealing with http headers, essentially converting to/from [`str`].
145    #[error("error dealing with http headers")]
146    Header(#[from] Option<http::Error>),
147    /// The value for the expiration policy is invalid.
148    #[error("invalid expiration policy value")]
149    Expiration(#[from] Option<ParseDurationError>),
150    /// The compression algorithm is invalid.
151    #[error("invalid compression value")]
152    Compression,
153    /// The content type is invalid.
154    #[error("invalid content type")]
155    ContentType(#[from] InvalidContentType),
156    /// The creation time is invalid.
157    #[error("invalid creation time")]
158    CreationTime(#[from] humantime::TimestampError),
159    /// The expiration timestamp is outside the supported range.
160    #[error("invalid expiration time")]
161    ExpirationTime(#[from] InvalidTimestamp),
162    /// The object size is not a valid byte count.
163    #[error("invalid object size")]
164    Size(#[from] ParseIntError),
165    /// A free-form header value did not decode into a logical string.
166    #[error("invalid metadata header value")]
167    Encoding(#[from] crate::headers::DecodeError),
168    /// An internal consistency invariant on the metadata was violated.
169    #[error("invariant violation: {0}")]
170    Invariant(&'static str),
171}
172impl From<header::InvalidHeaderValue> for Error {
173    fn from(err: header::InvalidHeaderValue) -> Self {
174        Self::Header(Some(err.into()))
175    }
176}
177impl From<header::InvalidHeaderName> for Error {
178    fn from(err: header::InvalidHeaderName) -> Self {
179        Self::Header(Some(err.into()))
180    }
181}
182impl From<header::ToStrError> for Error {
183    fn from(_err: header::ToStrError) -> Self {
184        // the error happens when converting a header value back to a `str`
185        Self::Header(None)
186    }
187}
188
189/// The per-object expiration policy.
190///
191/// Controls automatic object cleanup. The policy is set by the client at upload
192/// time via the [`x-sn-expiration`](HEADER_EXPIRATION) header and persisted with
193/// the object.
194///
195/// | Variant      | Wire format | Behavior                                     |
196/// |--------------|-------------|----------------------------------------------|
197/// | `Manual`     | `manual`    | No automatic expiration (default)            |
198/// | `TimeToLive` | `ttl:30s`   | Expires after a fixed duration from creation |
199/// | `TimeToIdle` | `tti:1h`    | Expires after a duration of no access        |
200///
201/// Durations use the [wire format](crate::duration), which is written in days, hours, minutes,
202/// and seconds (e.g. `30s`, `5m`, `1h`, `7d`, `400d 12h`).
203///
204/// **Important:** `Manual` is the default and must remain so — persisted objects
205/// without an explicit policy are deserialized as `Manual`.
206#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
207pub enum ExpirationPolicy {
208    /// Manual expiration, meaning no automatic cleanup.
209    // IMPORTANT: Do not change the default, we rely on this for persisted objects.
210    #[default]
211    Manual,
212    /// Time to live, with expiration after the specified duration.
213    TimeToLive(Duration),
214    /// Time to idle, with expiration once the object has not been accessed within the specified duration.
215    TimeToIdle(Duration),
216}
217impl ExpirationPolicy {
218    /// Returns the duration after which the object expires.
219    pub fn expires_in(&self) -> Option<Duration> {
220        match self {
221            ExpirationPolicy::Manual => None,
222            ExpirationPolicy::TimeToLive(duration) => Some(*duration),
223            ExpirationPolicy::TimeToIdle(duration) => Some(*duration),
224        }
225    }
226
227    /// Returns `true` if this policy indicates time-based expiry.
228    pub fn is_timeout(&self) -> bool {
229        match self {
230            ExpirationPolicy::TimeToLive(_) => true,
231            ExpirationPolicy::TimeToIdle(_) => true,
232            ExpirationPolicy::Manual => false,
233        }
234    }
235
236    /// Returns `true` if this policy is `Manual`.
237    pub fn is_manual(&self) -> bool {
238        *self == ExpirationPolicy::Manual
239    }
240
241    /// Checks whether a TTI deadline needs bumping given the current expiry and access time.
242    ///
243    /// Returns `Some(new_expire_at)` when the current deadline is stale enough
244    /// to justify a write, `None` otherwise. The debounce window scales with the
245    /// TTI duration so short-TTI objects get bumped more frequently.
246    ///
247    /// Returns `None` if the new deadline would exceed the supported timestamp range.
248    pub fn check_tti_bump(
249        &self,
250        time_expires: Option<Timestamp>,
251        access_time: Timestamp,
252    ) -> Option<Timestamp> {
253        let ExpirationPolicy::TimeToIdle(tti) = *self else {
254            return None;
255        };
256
257        let time_expires = time_expires?;
258        let new_expire_at = access_time.checked_add(tti)?;
259        let debounce = (tti / 4).min(MAX_TTI_DEBOUNCE);
260        (new_expire_at.checked_duration_since(time_expires)? > debounce).then_some(new_expire_at)
261    }
262}
263impl fmt::Display for ExpirationPolicy {
264    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
265        match self {
266            ExpirationPolicy::TimeToLive(duration) => {
267                write!(f, "ttl:{}", format_duration(*duration))
268            }
269            ExpirationPolicy::TimeToIdle(duration) => {
270                write!(f, "tti:{}", format_duration(*duration))
271            }
272            ExpirationPolicy::Manual => f.write_str("manual"),
273        }
274    }
275}
276impl FromStr for ExpirationPolicy {
277    type Err = Error;
278
279    fn from_str(s: &str) -> Result<Self, Self::Err> {
280        if s == "manual" {
281            return Ok(ExpirationPolicy::Manual);
282        }
283        if let Some(duration) = s.strip_prefix("ttl:") {
284            return Ok(ExpirationPolicy::TimeToLive(parse_duration(duration)?));
285        }
286        if let Some(duration) = s.strip_prefix("tti:") {
287            return Ok(ExpirationPolicy::TimeToIdle(parse_duration(duration)?));
288        }
289        Err(Error::Expiration(None))
290    }
291}
292
293/// The compression algorithm applied to an object's payload.
294///
295/// Transmitted via the standard `Content-Encoding` HTTP header. Supported
296/// algorithms are Zstandard (`zstd`) and `gzip`.
297#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
298pub enum Compression {
299    /// Compressed using `zstd`.
300    Zstd,
301    /// Compressed using `gzip`.
302    Gzip,
303}
304
305impl Compression {
306    /// Returns a string representation of the compression algorithm.
307    pub fn as_str(&self) -> &str {
308        match self {
309            Compression::Zstd => "zstd",
310            Compression::Gzip => "gzip",
311        }
312    }
313}
314
315impl fmt::Display for Compression {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        f.write_str(self.as_str())
318    }
319}
320
321impl FromStr for Compression {
322    type Err = Error;
323
324    fn from_str(s: &str) -> Result<Self, Self::Err> {
325        match s {
326            "zstd" => Ok(Compression::Zstd),
327            "gzip" => Ok(Compression::Gzip),
328            _ => Err(Error::Compression),
329        }
330    }
331}
332
333/// Per-object metadata.
334///
335/// Includes first-class fields (expiration, compression, timestamps, etc.) and
336/// arbitrary user-provided key-value metadata. See the [module-level
337/// documentation](self) for the HTTP header mapping conventions.
338#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
339#[serde(default)]
340pub struct Metadata {
341    /// The expiration policy of the object (header: `x-sn-expiration`).
342    ///
343    /// Skipped during serialization when set to [`ExpirationPolicy::Manual`].
344    #[serde(skip_serializing_if = "ExpirationPolicy::is_manual")]
345    pub expiration_policy: ExpirationPolicy,
346
347    /// The creation/last replacement time of the object (header: `x-sn-time-created`).
348    ///
349    /// Set by the server every time an object is put, i.e. when objects are first
350    /// created and when existing objects are overwritten.
351    #[serde(skip_serializing_if = "Option::is_none")]
352    pub time_created: Option<Timestamp>,
353
354    /// The resolved expiration timestamp (header: `x-sn-time-expires`).
355    ///
356    /// Initially derived from the [`expiration_policy`](Self::expiration_policy), but may be later
357    /// extended by explicit updates. This timestamp reflects the deadline present *prior to* the
358    /// current access to the object.
359    ///
360    /// Fractional deadlines round up to whole seconds; see [`Timestamp`].
361    #[serde(skip_serializing_if = "Option::is_none")]
362    pub time_expires: Option<Timestamp>,
363
364    /// IANA media type of the object (header: `Content-Type`).
365    ///
366    /// Defaults to [`DEFAULT_CONTENT_TYPE`] (`application/octet-stream`).
367    pub content_type: Cow<'static, str>,
368
369    /// The compression algorithm used for this object (header: `Content-Encoding`).
370    #[serde(skip_serializing_if = "Option::is_none")]
371    pub compression: Option<Compression>,
372
373    /// The origin of the object (header: `x-sn-origin`).
374    ///
375    /// Typically the IP address of the original source. This is an optional but
376    /// encouraged field that tracks where the payload was originally obtained
377    /// from (e.g. the IP of a Sentry SDK or CLI).
378    #[serde(skip_serializing_if = "Option::is_none")]
379    pub origin: Option<String>,
380
381    /// An optional filename associated with this object (header: `x-sn-filename`).
382    ///
383    /// This filename is returned when downloading the object.
384    ///
385    /// This is a logical string and may contain arbitrary Unicode; it is escaped only on the
386    /// wire (see [the module docs](self#escaping-free-form-values)).
387    #[serde(skip_serializing_if = "Option::is_none")]
388    pub filename: Option<String>,
389
390    /// Size of the stored data in bytes, if known (header: `x-sn-size`).
391    ///
392    /// Read-only. This is the size of the complete object, even when only a range of it is
393    /// being returned. It describes the stored bytes, so for a compressed object it is the
394    /// compressed size.
395    #[serde(skip_serializing_if = "Option::is_none")]
396    pub size: Option<usize>,
397
398    /// Arbitrary user-provided key-value metadata (header prefix: `x-snme-`).
399    ///
400    /// Each entry is transmitted as `x-snme-{key}: {value}`.
401    #[serde(skip_serializing_if = "BTreeMap::is_empty")]
402    pub custom: BTreeMap<String, String>,
403}
404
405impl Metadata {
406    /// Parses the metadata headers accepted from writing endpoints.
407    ///
408    /// Unlike [`from_headers`](Self::from_headers), this skips parsing read-only attributes so
409    /// clients cannot set them via headers.
410    ///
411    /// Uses `access_time` to materialize the following attributes:
412    /// - [`time_created`](Self::time_created)
413    /// - [`time_expires`](Self::time_expires)
414    ///
415    /// A prefix can also be provided which is stripped from custom non-standard headers.
416    pub fn from_insert_headers(
417        headers: &HeaderMap,
418        prefix: &str,
419        access_time: Timestamp,
420    ) -> Result<Self, Error> {
421        let mut metadata = Self::parse_headers(headers, prefix, true)?;
422
423        metadata.time_created = Some(access_time);
424        metadata.time_expires = metadata
425            .expiration_policy
426            .expires_in()
427            .map(|ttl| access_time.checked_add(ttl).ok_or(InvalidTimestamp))
428            .transpose()?;
429
430        Ok(metadata)
431    }
432
433    /// Validates internal consistency of the metadata.
434    ///
435    /// A time-based [`expiration_policy`](Self::expiration_policy) must carry a resolved
436    /// [`time_expires`](Self::time_expires); backends rely on this to persist a concrete
437    /// expiration.
438    pub fn validate(&self) -> Result<(), Error> {
439        if self.expiration_policy.is_timeout() && self.time_expires.is_none() {
440            return Err(Error::Invariant(
441                "expiration policy requires a resolved expiration time",
442            ));
443        }
444        if self.expiration_policy.is_manual() && self.time_expires.is_some() {
445            return Err(Error::Invariant(
446                "manual expiration policy must not have a resolved expiration time",
447            ));
448        }
449        Ok(())
450    }
451
452    /// Returns whether the object has expired at the given time.
453    pub fn is_expired(&self, access_time: Timestamp) -> bool {
454        self.time_expires
455            .is_some_and(|deadline| deadline < access_time)
456    }
457
458    /// Checks whether this object's TTI deadline needs bumping.
459    ///
460    /// See [`ExpirationPolicy::check_tti_bump`] for details.
461    pub fn check_tti_bump(&self, access_time: Timestamp) -> Option<Timestamp> {
462        self.expiration_policy
463            .check_tti_bump(self.time_expires, access_time)
464    }
465
466    /// Extracts public API metadata from the given [`HeaderMap`].
467    ///
468    /// A prefix can be also be provided which is being stripped from custom non-standard headers.
469    pub fn from_headers(headers: &HeaderMap, prefix: &str) -> Result<Self, Error> {
470        Self::parse_headers(headers, prefix, false)
471    }
472
473    /// Parses metadata from the given [`HeaderMap`].
474    ///
475    /// When `skip_read_only` is set, read-only attributes are not parsed off the headers, so a
476    /// malformed client-supplied value cannot fail the parse. A prefix can also be provided which
477    /// is stripped from custom non-standard headers.
478    fn parse_headers(
479        headers: &HeaderMap,
480        prefix: &str,
481        skip_read_only: bool,
482    ) -> Result<Self, Error> {
483        let mut metadata = Metadata::default();
484
485        for (name, value) in headers {
486            match *name {
487                // standard HTTP headers
488                header::CONTENT_TYPE => {
489                    let content_type = value.to_str()?;
490                    validate_content_type(content_type)?;
491                    metadata.content_type = content_type.to_owned().into();
492                }
493                header::CONTENT_ENCODING => {
494                    let compression = value.to_str()?;
495                    metadata.compression = Some(Compression::from_str(compression)?);
496                }
497                _ => {
498                    let Some(name) = name.as_str().strip_prefix(prefix) else {
499                        continue;
500                    };
501
502                    match name {
503                        // Objectstore first-class metadata
504                        HEADER_EXPIRATION => {
505                            let expiration_policy = value.to_str()?;
506                            metadata.expiration_policy =
507                                ExpirationPolicy::from_str(expiration_policy)?;
508                        }
509                        HEADER_TIME_CREATED if !skip_read_only => {
510                            let timestamp = value.to_str()?;
511                            let time = Timestamp::from_rfc3339(timestamp)?;
512                            metadata.time_created = Some(time);
513                        }
514                        HEADER_TIME_EXPIRES if !skip_read_only => {
515                            let timestamp = value.to_str()?;
516                            let time = Timestamp::from_rfc3339(timestamp)?;
517                            metadata.time_expires = Some(time);
518                        }
519                        HEADER_ORIGIN => {
520                            metadata.origin = Some(headers::decode_header_value(value)?);
521                        }
522                        HEADER_FILENAME => {
523                            metadata.filename = Some(headers::decode_header_value(value)?);
524                        }
525                        HEADER_SIZE if !skip_read_only => {
526                            let size = value.to_str()?;
527                            metadata.size = Some(size.parse()?);
528                        }
529                        _ => {
530                            // customer-provided metadata
531                            if let Some(name) = name.strip_prefix(HEADER_META_PREFIX) {
532                                let value = headers::decode_header_value(value)?;
533                                metadata.custom.insert(name.into(), value);
534                            }
535                        }
536                    }
537                }
538            }
539        }
540
541        Ok(metadata)
542    }
543
544    /// Turns the metadata into a [`HeaderMap`] for the public API.
545    ///
546    /// It will prefix any non-standard headers with the given `prefix`. GCS-specific headers are
547    /// not emitted; backends handle those separately.
548    pub fn to_headers(&self, prefix: &str) -> Result<HeaderMap, Error> {
549        let Self {
550            content_type,
551            compression,
552            origin,
553            filename,
554            expiration_policy,
555            time_created,
556            time_expires,
557            size,
558            custom,
559        } = self;
560
561        let mut headers = HeaderMap::new();
562
563        // standard headers
564        headers.append(header::CONTENT_TYPE, content_type.parse()?);
565        if let Some(compression) = compression {
566            headers.append(header::CONTENT_ENCODING, compression.as_str().parse()?);
567        }
568
569        // Objectstore first-class metadata
570        if *expiration_policy != ExpirationPolicy::Manual {
571            let name = HeaderName::try_from(format!("{prefix}{HEADER_EXPIRATION}"))?;
572            headers.append(name, expiration_policy.to_string().parse()?);
573        }
574        if let Some(time) = time_created {
575            let name = HeaderName::try_from(format!("{prefix}{HEADER_TIME_CREATED}"))?;
576            let timestamp = time.as_rfc3339();
577            headers.append(name, timestamp.to_string().parse()?);
578        }
579        if let Some(time) = time_expires {
580            let name = HeaderName::try_from(format!("{prefix}{HEADER_TIME_EXPIRES}"))?;
581            let timestamp = time.as_rfc3339();
582            headers.append(name, timestamp.to_string().parse()?);
583        }
584        if let Some(origin) = origin {
585            let name = HeaderName::try_from(format!("{prefix}{HEADER_ORIGIN}"))?;
586            headers.append(name, headers::encode_header_value(origin));
587        }
588        if let Some(filename) = filename {
589            let name = HeaderName::try_from(format!("{prefix}{HEADER_FILENAME}"))?;
590            headers.append(name, headers::encode_header_value(filename));
591        }
592        if let Some(size) = size {
593            let name = HeaderName::try_from(format!("{prefix}{HEADER_SIZE}"))?;
594            headers.append(name, size.to_string().parse()?);
595        }
596
597        // customer-provided metadata
598        for (key, value) in custom {
599            let name = HeaderName::try_from(format!("{prefix}{HEADER_META_PREFIX}{key}"))?;
600            headers.append(name, headers::encode_header_value(value));
601        }
602
603        Ok(headers)
604    }
605}
606
607/// Validates that `content_type` is a valid [IANA Media
608/// Type](https://www.iana.org/assignments/media-types/media-types.xhtml).
609fn validate_content_type(content_type: &str) -> Result<(), Error> {
610    mediatype::MediaType::parse(content_type).map_err(InvalidContentType)?;
611    Ok(())
612}
613
614impl Default for Metadata {
615    fn default() -> Self {
616        Self {
617            expiration_policy: ExpirationPolicy::Manual,
618            time_created: None,
619            time_expires: None,
620            content_type: DEFAULT_CONTENT_TYPE.into(),
621            compression: None,
622            origin: None,
623            filename: None,
624            size: None,
625            custom: BTreeMap::new(),
626        }
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use super::*;
633
634    #[test]
635    fn metadata_update_parses_supported_expiry_extensions() {
636        let cases = [
637            (
638                r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z"}}"#,
639                ExpiryExtension::At {
640                    at: "2026-10-16T12:00:00Z".parse().unwrap(),
641                },
642            ),
643            (
644                r#"{"extend_expiry":{"after":"30d","from":"creation"}}"#,
645                ExpiryExtension::After {
646                    after: Duration::from_secs(30 * 86400),
647                    from: ExpiryAnchor::Creation,
648                },
649            ),
650            (
651                r#"{"extend_expiry":{"after":"0s","from":"now"}}"#,
652                ExpiryExtension::After {
653                    after: Duration::ZERO,
654                    from: ExpiryAnchor::Now,
655                },
656            ),
657        ];
658
659        for (json, expected) in cases {
660            let update: MetadataUpdate = serde_json::from_str(json).unwrap();
661            assert_eq!(update.extend_expiry, expected);
662            assert_eq!(serde_json::to_string(&update).unwrap(), json);
663        }
664    }
665
666    #[test]
667    fn metadata_update_rejects_invalid_structures() {
668        let cases = [
669            r#"{"extend_expiry":{"at":"not a timestamp"}}"#,
670            r#"{"extend_expiry":{"after":"not a duration","from":"now"}}"#,
671            r#"{}"#,
672            r#"{"extend_expiry":null}"#,
673            r#"{"extend_expiry":{}}"#,
674            r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z","after":"30d","from":"now"}}"#,
675            r#"{"extend_expiry":{"after":"30d"}}"#,
676            r#"{"extend_expiry":{"after":"30d","from":"unsupported"}}"#,
677            r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z","unknown":true}}"#,
678            r#"{"extend_expiry":{"after":"30d","from":"now","unknown":true}}"#,
679            r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z"},"content_type":"text/plain"}"#,
680        ];
681
682        for json in cases {
683            assert!(
684                serde_json::from_str::<MetadataUpdate>(json).is_err(),
685                "unexpectedly accepted {json}"
686            );
687        }
688    }
689
690    #[test]
691    fn from_headers_with_origin() {
692        let mut headers = HeaderMap::new();
693        headers.insert("content-type", "text/plain".parse().unwrap());
694        headers.insert(HEADER_ORIGIN, "203.0.113.42".parse().unwrap());
695
696        let metadata = Metadata::from_headers(&headers, "").unwrap();
697        assert_eq!(metadata.origin.as_deref(), Some("203.0.113.42"));
698        assert_eq!(metadata.content_type, "text/plain");
699    }
700
701    #[test]
702    fn from_headers_without_origin() {
703        let mut headers = HeaderMap::new();
704        headers.insert("content-type", "text/plain".parse().unwrap());
705
706        let metadata = Metadata::from_headers(&headers, "").unwrap();
707        assert!(metadata.origin.is_none());
708    }
709
710    #[test]
711    fn to_headers_with_origin() {
712        let metadata = Metadata {
713            origin: Some("203.0.113.42".into()),
714            ..Default::default()
715        };
716
717        let headers = metadata.to_headers("").unwrap();
718        assert_eq!(headers.get(HEADER_ORIGIN).unwrap(), "203.0.113.42");
719    }
720
721    #[test]
722    fn to_headers_without_origin() {
723        let metadata = Metadata::default();
724        let headers = metadata.to_headers("").unwrap();
725        assert!(headers.get(HEADER_ORIGIN).is_none());
726    }
727
728    #[test]
729    fn origin_header_roundtrip() {
730        let metadata = Metadata {
731            origin: Some("203.0.113.42".into()),
732            ..Default::default()
733        };
734
735        let headers = metadata.to_headers("").unwrap();
736        let roundtripped = Metadata::from_headers(&headers, "").unwrap();
737        assert_eq!(roundtripped.origin, metadata.origin);
738    }
739
740    #[test]
741    fn from_headers_with_filename() {
742        let mut headers = HeaderMap::new();
743        headers.insert(HEADER_FILENAME, "report.pdf".parse().unwrap());
744
745        let metadata = Metadata::from_headers(&headers, "").unwrap();
746        assert_eq!(metadata.filename.as_deref(), Some("report.pdf"));
747    }
748
749    #[test]
750    fn from_headers_without_filename() {
751        let headers = HeaderMap::new();
752        let metadata = Metadata::from_headers(&headers, "").unwrap();
753        assert!(metadata.filename.is_none());
754    }
755
756    #[test]
757    fn to_headers_with_filename() {
758        let metadata = Metadata {
759            filename: Some("report.pdf".into()),
760            ..Default::default()
761        };
762
763        let headers = metadata.to_headers("").unwrap();
764        assert_eq!(headers.get(HEADER_FILENAME).unwrap(), "report.pdf");
765    }
766
767    #[test]
768    fn to_headers_without_filename() {
769        let metadata = Metadata::default();
770        let headers = metadata.to_headers("").unwrap();
771        assert!(headers.get(HEADER_FILENAME).is_none());
772    }
773
774    #[test]
775    fn filename_header_roundtrip() {
776        let metadata = Metadata {
777            filename: Some("report.pdf".into()),
778            ..Default::default()
779        };
780
781        let headers = metadata.to_headers("").unwrap();
782        let roundtripped = Metadata::from_headers(&headers, "").unwrap();
783        assert_eq!(roundtripped.filename, metadata.filename);
784    }
785
786    /// Every free-form field is escaped on the way out and decoded on the way back in.
787    ///
788    /// The escaping itself is covered in [`crate::headers`]; this only pins down that each of the
789    /// three fields that needs it actually goes through it, in both directions.
790    #[test]
791    fn free_form_values_are_escaped_on_the_wire() {
792        let metadata = Metadata {
793            origin: Some("Ünknown-源".into()),
794            filename: Some("réport-📄.pdf".into()),
795            custom: BTreeMap::from([("release".to_owned(), "100% vérsion-🚀".to_owned())]),
796            ..Default::default()
797        };
798
799        let headers = metadata.to_headers("").unwrap();
800        assert_eq!(
801            headers.get(HEADER_ORIGIN).unwrap(),
802            "%C3%9Cnknown-%E6%BA%90"
803        );
804        assert_eq!(
805            headers.get(HEADER_FILENAME).unwrap(),
806            "r%C3%A9port-%F0%9F%93%84.pdf",
807        );
808        assert_eq!(
809            headers.get(format!("{HEADER_META_PREFIX}release")).unwrap(),
810            "100%25 v%C3%A9rsion-%F0%9F%9A%80",
811        );
812
813        let roundtripped = Metadata::from_headers(&headers, "").unwrap();
814        assert_eq!(roundtripped.origin, metadata.origin);
815        assert_eq!(roundtripped.filename, metadata.filename);
816        assert_eq!(roundtripped.custom, metadata.custom);
817    }
818
819    #[test]
820    fn from_headers_content_type_and_encoding() {
821        let mut headers = HeaderMap::new();
822        headers.insert("content-type", "application/json".parse().unwrap());
823        headers.insert("content-encoding", "zstd".parse().unwrap());
824
825        let metadata = Metadata::from_headers(&headers, "").unwrap();
826        assert_eq!(metadata.content_type, "application/json");
827        assert_eq!(metadata.compression, Some(Compression::Zstd));
828    }
829
830    #[test]
831    fn from_headers_expiration_policy() {
832        let mut headers = HeaderMap::new();
833        headers.insert(HEADER_EXPIRATION, "ttl:30s".parse().unwrap());
834
835        let metadata = Metadata::from_headers(&headers, "").unwrap();
836        assert_eq!(
837            metadata.expiration_policy,
838            ExpirationPolicy::TimeToLive(Duration::from_secs(30))
839        );
840    }
841
842    #[test]
843    fn expiration_policy_keeps_long_durations_in_days() {
844        let ttl = Duration::from_secs(400 * 86400 + 3600);
845        let policy = ExpirationPolicy::TimeToLive(ttl);
846
847        assert_eq!(policy.to_string(), "ttl:400d 1h");
848        assert_eq!(
849            policy.to_string().parse::<ExpirationPolicy>().unwrap(),
850            policy
851        );
852    }
853
854    #[test]
855    fn expiration_policy_parses_units_that_are_never_emitted() {
856        let policy: ExpirationPolicy = "tti:2weeks".parse().unwrap();
857        assert_eq!(
858            policy,
859            ExpirationPolicy::TimeToIdle(Duration::from_secs(14 * 86400))
860        );
861        // Re-emitting normalizes to the units of the wire format.
862        assert_eq!(policy.to_string(), "tti:14d");
863    }
864
865    #[test]
866    fn from_headers_timestamps() {
867        let mut headers = HeaderMap::new();
868        headers.insert(
869            HEADER_TIME_CREATED,
870            "2024-01-15T12:00:00.123456Z".parse().unwrap(),
871        );
872        headers.insert(
873            HEADER_TIME_EXPIRES,
874            "2024-01-16T12:00:00.123456Z".parse().unwrap(),
875        );
876
877        let metadata = Metadata::from_headers(&headers, "").unwrap();
878        let encoded = metadata.to_headers("").unwrap();
879        assert_eq!(encoded[HEADER_TIME_CREATED], "2024-01-15T12:00:01Z");
880        assert_eq!(encoded[HEADER_TIME_EXPIRES], "2024-01-16T12:00:01Z");
881        let deadline = metadata.time_expires.unwrap();
882        assert!(!metadata.is_expired(deadline - Duration::from_secs(1)));
883        assert!(!metadata.is_expired(deadline));
884        assert!(metadata.is_expired(deadline + Duration::from_secs(1)));
885    }
886
887    #[test]
888    fn from_insert_headers_ignores_read_only_fields() {
889        // Read-only and output attributes must never be taken from an untrusted
890        // client request, even if the client supplies the headers.
891        let forged_created = "2024-01-15T12:00:00.000000Z";
892        let mut headers = HeaderMap::new();
893        headers.insert("content-type", "text/plain".parse().unwrap());
894        headers.insert(HEADER_TIME_CREATED, forged_created.parse().unwrap());
895        headers.insert(
896            HEADER_TIME_EXPIRES,
897            "2024-01-16T12:00:00.000000Z".parse().unwrap(),
898        );
899
900        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
901        // `time_created` is stamped by the server, not the client's forged value.
902        let created = metadata.time_created.unwrap();
903        assert_ne!(created, Timestamp::from_rfc3339(forged_created).unwrap());
904        assert!(metadata.time_expires.is_none());
905        assert!(metadata.size.is_none());
906        // Client-settable fields are still parsed.
907        assert_eq!(metadata.content_type, "text/plain");
908    }
909
910    #[test]
911    fn from_insert_headers_ignores_malformed_read_only_fields() {
912        // A malformed read-only header must not fail the write: it is skipped, not parsed.
913        let mut headers = HeaderMap::new();
914        headers.insert(HEADER_TIME_CREATED, "not-a-timestamp".parse().unwrap());
915        headers.insert(HEADER_TIME_EXPIRES, "not-a-timestamp".parse().unwrap());
916
917        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
918        assert!(metadata.time_created.is_some());
919        assert!(metadata.time_expires.is_none());
920    }
921
922    #[test]
923    fn from_insert_headers_resolves_time_expires_for_ttl() {
924        let mut headers = HeaderMap::new();
925        headers.insert(HEADER_EXPIRATION, "ttl:30s".parse().unwrap());
926
927        let access_time = Timestamp::UNIX_EPOCH;
928        let metadata = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
929        let created = metadata.time_created.unwrap();
930        assert_eq!(created, access_time);
931        let expires = metadata.time_expires.unwrap();
932        assert_eq!(expires, created + Duration::from_secs(30));
933    }
934
935    #[test]
936    fn from_insert_headers_resolves_time_expires_for_tti() {
937        let mut headers = HeaderMap::new();
938        headers.insert(HEADER_EXPIRATION, "tti:1h".parse().unwrap());
939
940        let access_time = Timestamp::UNIX_EPOCH;
941        let metadata = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
942        let created = metadata.time_created.unwrap();
943        assert_eq!(created, access_time);
944        let expires = metadata.time_expires.unwrap();
945        assert_eq!(expires, created + Duration::from_hours(1));
946    }
947
948    #[test]
949    fn from_insert_headers_manual_leaves_time_expires_none() {
950        let headers = HeaderMap::new();
951        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
952        assert_eq!(metadata.expiration_policy, ExpirationPolicy::Manual);
953        assert!(metadata.time_expires.is_none());
954    }
955
956    #[test]
957    fn validate_accepts_resolved_timeout() {
958        let metadata = Metadata {
959            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_secs(30)),
960            time_expires: Some(Timestamp::now() + Duration::from_secs(30)),
961            ..Default::default()
962        };
963        assert!(metadata.validate().is_ok());
964    }
965
966    #[test]
967    fn validate_accepts_manual_without_expiry() {
968        let metadata = Metadata::default();
969        assert!(metadata.validate().is_ok());
970    }
971
972    #[test]
973    fn validate_rejects_timeout_without_expiry() {
974        let metadata = Metadata {
975            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
976            time_expires: None,
977            ..Default::default()
978        };
979        assert!(matches!(metadata.validate(), Err(Error::Invariant(_))));
980    }
981
982    #[test]
983    fn from_headers_custom_metadata_with_prefix() {
984        let mut headers = HeaderMap::new();
985        // Simulate a backend that prefixes headers, e.g. "x-goog-meta-"
986        let prefix = "x-goog-meta-";
987        let expiration_header: HeaderName = format!("{prefix}{HEADER_EXPIRATION}").parse().unwrap();
988        headers.insert(expiration_header, "tti:1h".parse().unwrap());
989
990        let custom_header: HeaderName = format!("{prefix}{HEADER_META_PREFIX}my-key")
991            .parse()
992            .unwrap();
993        headers.insert(custom_header, "my-value".parse().unwrap());
994
995        let metadata = Metadata::from_headers(&headers, prefix).unwrap();
996        assert_eq!(
997            metadata.expiration_policy,
998            ExpirationPolicy::TimeToIdle(Duration::from_hours(1))
999        );
1000        assert_eq!(metadata.custom.get("my-key").unwrap(), "my-value");
1001    }
1002
1003    #[test]
1004    fn from_headers_invalid_content_type() {
1005        let mut headers = HeaderMap::new();
1006        headers.insert("content-type", "not a valid media type!".parse().unwrap());
1007
1008        let err = Metadata::from_headers(&headers, "").unwrap_err();
1009        assert!(matches!(err, Error::ContentType(_)));
1010    }
1011
1012    #[test]
1013    fn from_headers_invalid_compression() {
1014        let mut headers = HeaderMap::new();
1015        headers.insert("content-encoding", "brotli".parse().unwrap());
1016
1017        let err = Metadata::from_headers(&headers, "").unwrap_err();
1018        assert!(matches!(err, Error::Compression));
1019    }
1020
1021    #[test]
1022    fn from_headers_invalid_expiration() {
1023        let mut headers = HeaderMap::new();
1024        headers.insert(HEADER_EXPIRATION, "garbage".parse().unwrap());
1025
1026        let err = Metadata::from_headers(&headers, "").unwrap_err();
1027        assert!(matches!(err, Error::Expiration(_)));
1028    }
1029
1030    #[test]
1031    fn from_headers_invalid_timestamp() {
1032        let mut headers = HeaderMap::new();
1033        headers.insert(HEADER_TIME_CREATED, "not-a-timestamp".parse().unwrap());
1034
1035        let err = Metadata::from_headers(&headers, "").unwrap_err();
1036        assert!(matches!(err, Error::CreationTime(_)));
1037    }
1038
1039    #[test]
1040    fn to_headers_all_fields() {
1041        let metadata = Metadata {
1042            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_mins(1)),
1043            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1044            time_expires: Some(Timestamp::from_unix_secs(1_700_000_060).unwrap()),
1045            content_type: "text/html".into(),
1046            compression: Some(Compression::Zstd),
1047            origin: Some("10.0.0.1".into()),
1048            filename: Some("report.pdf".into()),
1049            size: None,
1050            custom: BTreeMap::from([("foo".into(), "bar".into())]),
1051        };
1052
1053        let headers = metadata.to_headers("pfx-").unwrap();
1054        let map: BTreeMap<_, _> = headers
1055            .iter()
1056            .map(|(k, v)| (k.as_str(), v.to_str().unwrap()))
1057            .collect();
1058
1059        insta::assert_debug_snapshot!(map, @r#"
1060        {
1061            "content-encoding": "zstd",
1062            "content-type": "text/html",
1063            "pfx-x-sn-expiration": "ttl:1m",
1064            "pfx-x-sn-filename": "report.pdf",
1065            "pfx-x-sn-origin": "10.0.0.1",
1066            "pfx-x-sn-time-created": "2023-11-14T22:13:20Z",
1067            "pfx-x-sn-time-expires": "2023-11-14T22:14:20Z",
1068            "pfx-x-snme-foo": "bar",
1069        }
1070        "#);
1071    }
1072
1073    #[test]
1074    fn full_roundtrip_all_fields() {
1075        let prefix = "x-test-";
1076        let metadata = Metadata {
1077            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(2)),
1078            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1079            time_expires: Some(Timestamp::from_unix_secs(1_700_007_200).unwrap()),
1080            content_type: "image/png".into(),
1081            compression: Some(Compression::Zstd),
1082            origin: Some("192.168.1.1".into()),
1083            filename: Some("image.png".into()),
1084            size: None,
1085            custom: BTreeMap::from([
1086                ("key1".into(), "value1".into()),
1087                ("key2".into(), "value2".into()),
1088            ]),
1089        };
1090
1091        let headers = metadata.to_headers(prefix).unwrap();
1092        let roundtripped = Metadata::from_headers(&headers, prefix).unwrap();
1093
1094        assert_eq!(roundtripped.expiration_policy, metadata.expiration_policy);
1095        assert_eq!(roundtripped.content_type, metadata.content_type);
1096        assert_eq!(roundtripped.compression, metadata.compression);
1097        assert_eq!(roundtripped.origin, metadata.origin);
1098        assert_eq!(roundtripped.filename, metadata.filename);
1099        assert_eq!(roundtripped.time_created, metadata.time_created);
1100        assert_eq!(roundtripped.time_expires, metadata.time_expires);
1101        assert_eq!(roundtripped.custom, metadata.custom);
1102    }
1103
1104    #[test]
1105    fn from_headers_empty() {
1106        let headers = HeaderMap::new();
1107        let metadata = Metadata::from_headers(&headers, "x-goog-meta-").unwrap();
1108        assert_eq!(metadata, Metadata::default());
1109    }
1110
1111    #[test]
1112    fn from_headers_invalid_time_expires() {
1113        let mut headers = HeaderMap::new();
1114        let name: HeaderName = format!("x-goog-meta-{HEADER_TIME_EXPIRES}")
1115            .parse()
1116            .unwrap();
1117        headers.insert(name, "not-a-timestamp".parse().unwrap());
1118
1119        // NOTE: This produces InvalidCreationTime even for time_expires because
1120        // both fields share the same humantime::TimestampError #[from] conversion.
1121        assert!(Metadata::from_headers(&headers, "x-goog-meta-").is_err());
1122    }
1123
1124    #[test]
1125    fn serde_roundtrip_default() {
1126        let metadata = Metadata::default();
1127        let json = serde_json::to_string(&metadata).unwrap();
1128        let deserialized: Metadata = serde_json::from_str(&json).unwrap();
1129        assert_eq!(deserialized, metadata);
1130    }
1131
1132    #[test]
1133    fn serde_roundtrip_all_fields() {
1134        let metadata = Metadata {
1135            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1136            time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1137            time_expires: Some(Timestamp::from_unix_secs(1_700_003_600).unwrap()),
1138            content_type: "application/json".into(),
1139            compression: Some(Compression::Zstd),
1140            origin: Some("10.0.0.1".into()),
1141            filename: Some("data.json".into()),
1142            size: Some(1024),
1143            custom: BTreeMap::from([("key".into(), "value".into())]),
1144        };
1145
1146        let json = serde_json::to_string(&metadata).unwrap();
1147        let deserialized: Metadata = serde_json::from_str(&json).unwrap();
1148        assert_eq!(deserialized, metadata);
1149    }
1150
1151    #[test]
1152    fn size_roundtrips_through_headers() {
1153        let metadata = Metadata {
1154            size: Some(42),
1155            ..Default::default()
1156        };
1157
1158        let headers = metadata.to_headers("").unwrap();
1159        assert_eq!(headers.get(HEADER_SIZE).unwrap(), "42");
1160        assert_eq!(Metadata::from_headers(&headers, "").unwrap().size, Some(42));
1161    }
1162
1163    #[test]
1164    fn size_is_prefixed_in_headers() {
1165        let metadata = Metadata {
1166            size: Some(42),
1167            ..Default::default()
1168        };
1169
1170        let headers = metadata.to_headers("x-goog-meta-").unwrap();
1171        assert_eq!(headers.get("x-goog-meta-x-sn-size").unwrap(), "42");
1172    }
1173
1174    #[test]
1175    fn from_insert_headers_ignores_size() {
1176        // Size is materialized by the server; a client-supplied value must never be trusted.
1177        let mut headers = HeaderMap::new();
1178        headers.insert(HEADER_SIZE, "9999".parse().unwrap());
1179
1180        let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1181        assert!(metadata.size.is_none());
1182    }
1183
1184    #[test]
1185    fn from_headers_rejects_malformed_size() {
1186        let mut headers = HeaderMap::new();
1187        headers.insert(HEADER_SIZE, "not-a-number".parse().unwrap());
1188
1189        assert!(matches!(
1190            Metadata::from_headers(&headers, ""),
1191            Err(Error::Size(_))
1192        ));
1193    }
1194
1195    #[test]
1196    fn default_metadata() {
1197        let metadata = Metadata::default();
1198        assert_eq!(metadata.content_type, DEFAULT_CONTENT_TYPE);
1199        assert_eq!(metadata.expiration_policy, ExpirationPolicy::Manual);
1200        assert!(metadata.compression.is_none());
1201        assert!(metadata.origin.is_none());
1202        assert!(metadata.filename.is_none());
1203        assert!(metadata.time_created.is_none());
1204        assert!(metadata.time_expires.is_none());
1205        assert!(metadata.size.is_none());
1206        assert!(metadata.custom.is_empty());
1207    }
1208
1209    #[test]
1210    fn expiration_display_roundtrip() {
1211        let cases = [
1212            ExpirationPolicy::Manual,
1213            ExpirationPolicy::TimeToLive(Duration::from_secs(30)),
1214            ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1215        ];
1216
1217        for policy in cases {
1218            let displayed = policy.to_string();
1219            let parsed: ExpirationPolicy = displayed.parse().unwrap();
1220            assert_eq!(parsed, policy);
1221        }
1222    }
1223
1224    #[test]
1225    fn expiration_parse_invalid() {
1226        assert!(ExpirationPolicy::from_str("garbage").is_err());
1227        assert!(ExpirationPolicy::from_str("ttl:").is_err());
1228        assert!(ExpirationPolicy::from_str("").is_err());
1229    }
1230
1231    #[test]
1232    fn expiration_policy_helpers() {
1233        assert_eq!(ExpirationPolicy::Manual.expires_in(), None);
1234        assert!(ExpirationPolicy::Manual.is_manual());
1235        assert!(!ExpirationPolicy::Manual.is_timeout());
1236
1237        let ttl = ExpirationPolicy::TimeToLive(Duration::from_mins(1));
1238        assert_eq!(ttl.expires_in(), Some(Duration::from_mins(1)));
1239        assert!(ttl.is_timeout());
1240        assert!(!ttl.is_manual());
1241
1242        let tti = ExpirationPolicy::TimeToIdle(Duration::from_mins(2));
1243        assert_eq!(tti.expires_in(), Some(Duration::from_mins(2)));
1244        assert!(tti.is_timeout());
1245        assert!(!tti.is_manual());
1246    }
1247
1248    #[test]
1249    fn compression_display_roundtrip() {
1250        for (compression, expected) in [(Compression::Zstd, "zstd"), (Compression::Gzip, "gzip")] {
1251            let displayed = compression.to_string();
1252            assert_eq!(displayed, expected);
1253            let parsed: Compression = displayed.parse().unwrap();
1254            assert_eq!(parsed, compression);
1255        }
1256    }
1257
1258    #[test]
1259    fn compression_parse_invalid() {
1260        assert!(Compression::from_str("lz4").is_err());
1261        assert!(Compression::from_str("").is_err());
1262    }
1263
1264    #[test]
1265    fn check_tti_bump_returns_none_for_manual() {
1266        let metadata = Metadata::default();
1267        assert!(metadata.check_tti_bump(Timestamp::now()).is_none());
1268    }
1269
1270    #[test]
1271    fn check_tti_bump_returns_none_for_ttl() {
1272        let now = Timestamp::now();
1273        let metadata = Metadata {
1274            expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_hours(1)),
1275            time_expires: Some(now + Duration::from_hours(1)),
1276            ..Default::default()
1277        };
1278        assert!(metadata.check_tti_bump(now).is_none());
1279    }
1280
1281    #[test]
1282    fn check_tti_bump_returns_none_when_fresh() {
1283        let now = Timestamp::now();
1284        let tti = Duration::from_hours(2 * 24);
1285        let metadata = Metadata {
1286            expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1287            time_expires: Some(now + tti),
1288            ..Default::default()
1289        };
1290        assert!(metadata.check_tti_bump(now).is_none());
1291    }
1292
1293    #[test]
1294    fn check_tti_bump_returns_new_deadline_when_stale() {
1295        let now = Timestamp::now();
1296        let tti = Duration::from_hours(2 * 24);
1297        let debounce = tti / 4;
1298        let stale_deadline = now + tti - debounce - Duration::from_mins(1);
1299        let metadata = Metadata {
1300            expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1301            time_expires: Some(stale_deadline),
1302            ..Default::default()
1303        };
1304        let new_deadline = metadata.check_tti_bump(now).unwrap();
1305        assert_eq!(new_deadline, now + tti);
1306    }
1307
1308    #[test]
1309    fn check_tti_bump_short_tti_triggers_bump() {
1310        let now = Timestamp::now();
1311        for tti in [
1312            Duration::from_hours(2),
1313            Duration::from_secs(3),
1314            Duration::from_secs(4),
1315        ] {
1316            let debounce = tti / 4;
1317            let new_deadline = now + tti;
1318            let mut metadata = Metadata {
1319                expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1320                time_expires: Some(new_deadline - Duration::from_secs(debounce.as_secs() + 1)),
1321                ..Default::default()
1322            };
1323            assert_eq!(metadata.check_tti_bump(now), Some(new_deadline));
1324            metadata.time_expires = Some(new_deadline - Duration::from_secs(debounce.as_secs()));
1325            assert!(metadata.check_tti_bump(now).is_none());
1326        }
1327    }
1328
1329    #[test]
1330    fn check_tti_bump_debounce_caps_at_24h() {
1331        let now = Timestamp::now();
1332        let tti = Duration::from_hours(30 * 24);
1333        let capped_debounce = Duration::from_hours(24);
1334        let stale_deadline = now + tti - capped_debounce - Duration::from_mins(1);
1335        let metadata = Metadata {
1336            expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1337            time_expires: Some(stale_deadline),
1338            ..Default::default()
1339        };
1340        assert!(metadata.check_tti_bump(now).is_some());
1341
1342        let fresh_deadline = now + tti - capped_debounce + Duration::from_mins(1);
1343        let metadata = Metadata {
1344            time_expires: Some(fresh_deadline),
1345            ..metadata
1346        };
1347        assert!(metadata.check_tti_bump(now).is_none());
1348    }
1349
1350    #[test]
1351    fn check_tti_bump_returns_none_when_time_expires_missing() {
1352        let metadata = Metadata {
1353            expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1354            time_expires: None,
1355            ..Default::default()
1356        };
1357        assert!(metadata.check_tti_bump(Timestamp::now()).is_none());
1358    }
1359}