1use std::borrow::Cow;
62use std::collections::BTreeMap;
63use std::fmt;
64use std::num::ParseIntError;
65use std::str::FromStr;
66use std::time::Duration;
67
68use http::header::{self, HeaderMap, HeaderName};
69use serde::{Deserialize, Serialize};
70
71use crate::duration::{ParseDurationError, format_duration, parse_duration};
72use crate::headers;
73use crate::time::{InvalidTimestamp, Rfc3339Timestamp, Timestamp};
74
75pub const HEADER_EXPIRATION: &str = "x-sn-expiration";
77pub const HEADER_TIME_CREATED: &str = "x-sn-time-created";
79pub const HEADER_TIME_EXPIRES: &str = "x-sn-time-expires";
81pub const HEADER_ORIGIN: &str = "x-sn-origin";
83pub const HEADER_FILENAME: &str = "x-sn-filename";
85pub const HEADER_SIZE: &str = "x-sn-size";
87pub const HEADER_META_PREFIX: &str = "x-snme-";
89
90pub const DEFAULT_CONTENT_TYPE: &str = "application/octet-stream";
92
93const MAX_TTI_DEBOUNCE: Duration = Duration::from_hours(24);
100
101#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
106#[serde(deny_unknown_fields)]
107pub struct MetadataUpdate {
108 pub extend_expiry: ExpiryExtension,
110}
111
112#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
117#[serde(untagged, deny_unknown_fields)]
118pub enum ExpiryExtension {
119 At {
121 at: Rfc3339Timestamp,
123 },
124 After {
126 #[serde(with = "crate::duration")]
128 after: Duration,
129 from: ExpiryAnchor,
131 },
132}
133
134#[derive(Clone, Copy, Debug, Deserialize, Serialize, PartialEq, Eq)]
136#[serde(rename_all = "snake_case")]
137pub enum ExpiryAnchor {
138 Creation,
140 Now,
142}
143
144#[derive(Debug, thiserror::Error)]
150#[error(transparent)]
151pub struct InvalidContentType(mediatype::MediaTypeError);
152
153#[derive(Debug, thiserror::Error)]
155pub enum Error {
156 #[error("error dealing with http headers")]
158 Header(#[from] Option<http::Error>),
159 #[error("invalid expiration policy value")]
161 Expiration(#[from] Option<ParseDurationError>),
162 #[error("invalid compression value")]
164 Compression,
165 #[error("invalid content type")]
167 ContentType(#[from] InvalidContentType),
168 #[error("invalid creation time")]
170 CreationTime(#[from] humantime::TimestampError),
171 #[error("invalid expiration time")]
173 ExpirationTime(#[from] InvalidTimestamp),
174 #[error("invalid object size")]
176 Size(#[from] ParseIntError),
177 #[error("invalid metadata header value")]
179 Encoding(#[from] crate::headers::DecodeError),
180 #[error("invalid custom metadata key {0:?}")]
184 CustomKey(String),
185 #[error("invariant violation: {0}")]
187 Invariant(&'static str),
188}
189impl From<header::InvalidHeaderValue> for Error {
190 fn from(err: header::InvalidHeaderValue) -> Self {
191 Self::Header(Some(err.into()))
192 }
193}
194impl From<header::InvalidHeaderName> for Error {
195 fn from(err: header::InvalidHeaderName) -> Self {
196 Self::Header(Some(err.into()))
197 }
198}
199impl From<header::ToStrError> for Error {
200 fn from(_err: header::ToStrError) -> Self {
201 Self::Header(None)
203 }
204}
205
206#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
224pub enum ExpirationPolicy {
225 #[default]
228 Manual,
229 TimeToLive(Duration),
231 TimeToIdle(Duration),
233}
234impl ExpirationPolicy {
235 pub fn expires_in(&self) -> Option<Duration> {
237 match self {
238 ExpirationPolicy::Manual => None,
239 ExpirationPolicy::TimeToLive(duration) => Some(*duration),
240 ExpirationPolicy::TimeToIdle(duration) => Some(*duration),
241 }
242 }
243
244 pub fn is_timeout(&self) -> bool {
246 match self {
247 ExpirationPolicy::TimeToLive(_) => true,
248 ExpirationPolicy::TimeToIdle(_) => true,
249 ExpirationPolicy::Manual => false,
250 }
251 }
252
253 pub fn is_manual(&self) -> bool {
255 *self == ExpirationPolicy::Manual
256 }
257
258 pub fn check_tti_bump(
266 &self,
267 time_expires: Option<Timestamp>,
268 access_time: Timestamp,
269 ) -> Option<Timestamp> {
270 let ExpirationPolicy::TimeToIdle(tti) = *self else {
271 return None;
272 };
273
274 let time_expires = time_expires?;
275 let new_expire_at = access_time.checked_add(tti)?;
276 let debounce = (tti / 4).min(MAX_TTI_DEBOUNCE);
277 (new_expire_at.checked_duration_since(time_expires)? > debounce).then_some(new_expire_at)
278 }
279}
280impl fmt::Display for ExpirationPolicy {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 match self {
283 ExpirationPolicy::TimeToLive(duration) => {
284 write!(f, "ttl:{}", format_duration(*duration))
285 }
286 ExpirationPolicy::TimeToIdle(duration) => {
287 write!(f, "tti:{}", format_duration(*duration))
288 }
289 ExpirationPolicy::Manual => f.write_str("manual"),
290 }
291 }
292}
293impl FromStr for ExpirationPolicy {
294 type Err = Error;
295
296 fn from_str(s: &str) -> Result<Self, Self::Err> {
297 if s == "manual" {
298 return Ok(ExpirationPolicy::Manual);
299 }
300 if let Some(duration) = s.strip_prefix("ttl:") {
301 return Ok(ExpirationPolicy::TimeToLive(parse_duration(duration)?));
302 }
303 if let Some(duration) = s.strip_prefix("tti:") {
304 return Ok(ExpirationPolicy::TimeToIdle(parse_duration(duration)?));
305 }
306 Err(Error::Expiration(None))
307 }
308}
309
310#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
315pub enum Compression {
316 Zstd,
318 Gzip,
320}
321
322impl Compression {
323 pub fn as_str(&self) -> &str {
325 match self {
326 Compression::Zstd => "zstd",
327 Compression::Gzip => "gzip",
328 }
329 }
330}
331
332impl fmt::Display for Compression {
333 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334 f.write_str(self.as_str())
335 }
336}
337
338impl FromStr for Compression {
339 type Err = Error;
340
341 fn from_str(s: &str) -> Result<Self, Self::Err> {
342 match s {
343 "zstd" => Ok(Compression::Zstd),
344 "gzip" => Ok(Compression::Gzip),
345 _ => Err(Error::Compression),
346 }
347 }
348}
349
350#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)]
356#[serde(default)]
357pub struct Metadata {
358 #[serde(skip_serializing_if = "ExpirationPolicy::is_manual")]
362 pub expiration_policy: ExpirationPolicy,
363
364 #[serde(skip_serializing_if = "Option::is_none")]
369 pub time_created: Option<Timestamp>,
370
371 #[serde(skip_serializing_if = "Option::is_none")]
379 pub time_expires: Option<Timestamp>,
380
381 pub content_type: Cow<'static, str>,
385
386 #[serde(skip_serializing_if = "Option::is_none")]
388 pub compression: Option<Compression>,
389
390 #[serde(skip_serializing_if = "Option::is_none")]
396 pub origin: Option<String>,
397
398 #[serde(skip_serializing_if = "Option::is_none")]
405 pub filename: Option<String>,
406
407 #[serde(skip_serializing_if = "Option::is_none")]
413 pub size: Option<usize>,
414
415 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
422 pub custom: BTreeMap<String, String>,
423}
424
425impl Metadata {
426 pub fn from_insert_headers(
437 headers: &HeaderMap,
438 prefix: &str,
439 access_time: Timestamp,
440 ) -> Result<Self, Error> {
441 let mut metadata = Self::parse_headers(headers, prefix, true)?;
442 metadata.materialize_write_times(access_time)?;
443 Ok(metadata)
444 }
445
446 fn materialize_write_times(&mut self, access_time: Timestamp) -> Result<(), Error> {
448 self.time_created = Some(access_time);
449 self.time_expires = self
450 .expiration_policy
451 .expires_in()
452 .map(|ttl| access_time.checked_add(ttl).ok_or(InvalidTimestamp))
453 .transpose()?;
454 Ok(())
455 }
456
457 pub fn validate(&self) -> Result<(), Error> {
463 if self.expiration_policy.is_timeout() && self.time_expires.is_none() {
464 return Err(Error::Invariant(
465 "expiration policy requires a resolved expiration time",
466 ));
467 }
468 if self.expiration_policy.is_manual() && self.time_expires.is_some() {
469 return Err(Error::Invariant(
470 "manual expiration policy must not have a resolved expiration time",
471 ));
472 }
473 Ok(())
474 }
475
476 pub fn is_expired(&self, access_time: Timestamp) -> bool {
478 self.time_expires
479 .is_some_and(|deadline| deadline < access_time)
480 }
481
482 pub fn check_tti_bump(&self, access_time: Timestamp) -> Option<Timestamp> {
486 self.expiration_policy
487 .check_tti_bump(self.time_expires, access_time)
488 }
489
490 pub fn from_headers(headers: &HeaderMap, prefix: &str) -> Result<Self, Error> {
494 Self::parse_headers(headers, prefix, false)
495 }
496
497 fn parse_headers(
503 headers: &HeaderMap,
504 prefix: &str,
505 skip_read_only: bool,
506 ) -> Result<Self, Error> {
507 let mut metadata = Metadata::default();
508
509 for (name, value) in headers {
510 match *name {
511 header::CONTENT_TYPE => {
513 let content_type = value.to_str()?;
514 validate_content_type(content_type)?;
515 metadata.content_type = content_type.to_owned().into();
516 }
517 header::CONTENT_ENCODING => {
518 let compression = value.to_str()?;
519 metadata.compression = Some(Compression::from_str(compression)?);
520 }
521 _ => {
522 let Some(name) = name.as_str().strip_prefix(prefix) else {
523 continue;
524 };
525
526 match name {
527 HEADER_EXPIRATION => {
529 let expiration_policy = value.to_str()?;
530 metadata.expiration_policy =
531 ExpirationPolicy::from_str(expiration_policy)?;
532 }
533 HEADER_TIME_CREATED if !skip_read_only => {
534 let timestamp = value.to_str()?;
535 let time = Timestamp::from_rfc3339(timestamp)?;
536 metadata.time_created = Some(time);
537 }
538 HEADER_TIME_EXPIRES if !skip_read_only => {
539 let timestamp = value.to_str()?;
540 let time = Timestamp::from_rfc3339(timestamp)?;
541 metadata.time_expires = Some(time);
542 }
543 HEADER_ORIGIN => {
544 metadata.origin = Some(headers::decode_header_value(value)?);
545 }
546 HEADER_FILENAME => {
547 metadata.filename = Some(headers::decode_header_value(value)?);
548 }
549 HEADER_SIZE if !skip_read_only => {
550 let size = value.to_str()?;
551 metadata.size = Some(size.parse()?);
552 }
553 _ => {
554 if let Some(name) = name.strip_prefix(HEADER_META_PREFIX) {
556 let key = headers::decode_header_str_lossy(name);
557 let key = if skip_read_only {
559 normalize_custom_key(&key)?
560 } else {
561 key.into_owned()
562 };
563 let value = headers::decode_header_value(value)?;
564 metadata.custom.insert(key, value);
565 }
566 }
567 }
568 }
569 }
570 }
571
572 Ok(metadata)
573 }
574
575 pub fn to_headers(&self, prefix: &str) -> Result<HeaderMap, Error> {
580 let Self {
581 content_type,
582 compression,
583 origin,
584 filename,
585 expiration_policy,
586 time_created,
587 time_expires,
588 size,
589 custom,
590 } = self;
591
592 let mut headers = HeaderMap::new();
593
594 headers.append(header::CONTENT_TYPE, content_type.parse()?);
596 if let Some(compression) = compression {
597 headers.append(header::CONTENT_ENCODING, compression.as_str().parse()?);
598 }
599
600 if *expiration_policy != ExpirationPolicy::Manual {
602 let name = HeaderName::try_from(format!("{prefix}{HEADER_EXPIRATION}"))?;
603 headers.append(name, expiration_policy.to_string().parse()?);
604 }
605 if let Some(time) = time_created {
606 let name = HeaderName::try_from(format!("{prefix}{HEADER_TIME_CREATED}"))?;
607 let timestamp = time.as_rfc3339();
608 headers.append(name, timestamp.to_string().parse()?);
609 }
610 if let Some(time) = time_expires {
611 let name = HeaderName::try_from(format!("{prefix}{HEADER_TIME_EXPIRES}"))?;
612 let timestamp = time.as_rfc3339();
613 headers.append(name, timestamp.to_string().parse()?);
614 }
615 if let Some(origin) = origin {
616 let name = HeaderName::try_from(format!("{prefix}{HEADER_ORIGIN}"))?;
617 headers.append(name, headers::encode_header_value(origin));
618 }
619 if let Some(filename) = filename {
620 let name = HeaderName::try_from(format!("{prefix}{HEADER_FILENAME}"))?;
621 headers.append(name, headers::encode_header_value(filename));
622 }
623 if let Some(size) = size {
624 let name = HeaderName::try_from(format!("{prefix}{HEADER_SIZE}"))?;
625 headers.append(name, size.to_string().parse()?);
626 }
627
628 for (key, value) in custom {
630 let key = encode_custom_key(key);
631 let name = HeaderName::try_from(format!("{prefix}{HEADER_META_PREFIX}{key}"))?;
632 headers.append(name, headers::encode_header_value(value));
633 }
634
635 Ok(headers)
636 }
637}
638
639pub fn normalize_custom_key(key: &str) -> Result<String, Error> {
660 let is_allowed = |ch: char| {
661 ch.is_ascii_alphanumeric()
662 || matches!(
663 ch,
664 '_' | '-' | '|' | '~' | '%' | '$' | '#' | '+' | '.' | ':'
665 )
666 };
667
668 if key.is_empty() || !key.chars().all(is_allowed) {
669 return Err(Error::CustomKey(key.to_owned()));
670 }
671 Ok(key.to_ascii_lowercase())
672}
673
674pub fn encode_custom_key(key: &str) -> Cow<'_, str> {
691 if !key.contains(['%', ':']) {
692 return Cow::Borrowed(key);
693 }
694
695 let mut encoded = String::with_capacity(key.len() + 4);
696 for ch in key.chars() {
697 match ch {
698 '%' => encoded.push_str("%25"),
699 ':' => encoded.push_str("%3a"),
700 other => encoded.push(other),
701 }
702 }
703 Cow::Owned(encoded)
704}
705
706fn validate_content_type(content_type: &str) -> Result<(), Error> {
709 mediatype::MediaType::parse(content_type).map_err(InvalidContentType)?;
710 Ok(())
711}
712
713impl Default for Metadata {
714 fn default() -> Self {
715 Self {
716 expiration_policy: ExpirationPolicy::Manual,
717 time_created: None,
718 time_expires: None,
719 content_type: DEFAULT_CONTENT_TYPE.into(),
720 compression: None,
721 origin: None,
722 filename: None,
723 size: None,
724 custom: BTreeMap::new(),
725 }
726 }
727}
728
729#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
734#[serde(default)]
735#[non_exhaustive]
736pub struct WriteMetadata {
737 #[serde(skip_serializing_if = "Option::is_none")]
739 pub content_type: Option<String>,
740 #[serde(skip_serializing_if = "Option::is_none")]
742 pub content_encoding: Option<String>,
743 #[serde(skip_serializing_if = "Option::is_none")]
745 pub expiration: Option<String>,
746 #[serde(skip_serializing_if = "Option::is_none")]
748 pub origin: Option<String>,
749 #[serde(skip_serializing_if = "Option::is_none")]
751 pub filename: Option<String>,
752 #[serde(skip_serializing_if = "BTreeMap::is_empty")]
754 pub custom: BTreeMap<String, String>,
755}
756
757impl WriteMetadata {
758 pub fn into_metadata(self, access_time: Timestamp) -> Result<Metadata, Error> {
768 if let Some(content_type) = &self.content_type {
769 validate_content_type(content_type)?;
770 }
771
772 let custom = self
773 .custom
774 .into_iter()
775 .map(|(key, value)| Ok((normalize_custom_key(&key)?, value)))
776 .collect::<Result<_, Error>>()?;
777
778 let expiration_policy = self.expiration.as_deref().map(str::parse).transpose()?;
779 let mut metadata = Metadata {
780 expiration_policy: expiration_policy.unwrap_or_default(),
781 content_type: self
782 .content_type
783 .map_or(DEFAULT_CONTENT_TYPE.into(), Into::into),
784 compression: self
785 .content_encoding
786 .as_deref()
787 .map(str::parse)
788 .transpose()?,
789 origin: self.origin,
790 filename: self.filename,
791 custom,
792 ..Default::default()
793 };
794 metadata.materialize_write_times(access_time)?;
795 Ok(metadata)
796 }
797}
798
799impl From<Metadata> for WriteMetadata {
800 fn from(metadata: Metadata) -> Self {
801 Self {
802 content_type: (metadata.content_type != DEFAULT_CONTENT_TYPE)
803 .then(|| metadata.content_type.into_owned()),
804 content_encoding: metadata.compression.map(|c| c.to_string()),
805 expiration: (!metadata.expiration_policy.is_manual())
806 .then(|| metadata.expiration_policy.to_string()),
807 origin: metadata.origin,
808 filename: metadata.filename,
809 custom: metadata.custom,
810 }
811 }
812}
813
814#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
819#[non_exhaustive]
820pub struct ReadMetadata {
821 pub content_type: String,
823 #[serde(skip_serializing_if = "Option::is_none")]
825 pub content_encoding: Option<String>,
826 #[serde(skip_serializing_if = "Option::is_none")]
828 pub expiration: Option<String>,
829 #[serde(skip_serializing_if = "Option::is_none")]
831 pub origin: Option<String>,
832 #[serde(skip_serializing_if = "Option::is_none")]
834 pub filename: Option<String>,
835 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
837 pub custom: BTreeMap<String, String>,
838 #[serde(skip_serializing_if = "Option::is_none")]
840 pub time_created: Option<Rfc3339Timestamp>,
841 #[serde(skip_serializing_if = "Option::is_none")]
843 pub time_expires: Option<Rfc3339Timestamp>,
844 #[serde(skip_serializing_if = "Option::is_none")]
846 pub size: Option<usize>,
847}
848
849impl From<Metadata> for ReadMetadata {
850 fn from(metadata: Metadata) -> Self {
851 Self {
852 content_type: metadata.content_type.into_owned(),
853 content_encoding: metadata.compression.map(|c| c.to_string()),
854 expiration: (!metadata.expiration_policy.is_manual())
855 .then(|| metadata.expiration_policy.to_string()),
856 origin: metadata.origin,
857 filename: metadata.filename,
858 custom: metadata.custom,
859 time_created: metadata.time_created.map(Timestamp::as_rfc3339),
860 time_expires: metadata.time_expires.map(Timestamp::as_rfc3339),
861 size: metadata.size,
862 }
863 }
864}
865
866impl TryFrom<ReadMetadata> for Metadata {
867 type Error = Error;
868
869 fn try_from(object: ReadMetadata) -> Result<Self, Error> {
870 let expiration_policy = object.expiration.as_deref().map(str::parse).transpose()?;
871 Ok(Self {
872 expiration_policy: expiration_policy.unwrap_or_default(),
873 time_created: object.time_created.map(Rfc3339Timestamp::into_inner),
874 time_expires: object.time_expires.map(Rfc3339Timestamp::into_inner),
875 content_type: object.content_type.into(),
876 compression: object
877 .content_encoding
878 .as_deref()
879 .map(str::parse)
880 .transpose()?,
881 origin: object.origin,
882 filename: object.filename,
883 size: object.size,
884 custom: object.custom,
885 })
886 }
887}
888
889#[cfg(test)]
890mod tests {
891 use super::*;
892
893 #[test]
894 fn metadata_update_parses_supported_expiry_extensions() {
895 let cases = [
896 (
897 r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z"}}"#,
898 ExpiryExtension::At {
899 at: "2026-10-16T12:00:00Z".parse().unwrap(),
900 },
901 ),
902 (
903 r#"{"extend_expiry":{"after":"30d","from":"creation"}}"#,
904 ExpiryExtension::After {
905 after: Duration::from_secs(30 * 86400),
906 from: ExpiryAnchor::Creation,
907 },
908 ),
909 (
910 r#"{"extend_expiry":{"after":"0s","from":"now"}}"#,
911 ExpiryExtension::After {
912 after: Duration::ZERO,
913 from: ExpiryAnchor::Now,
914 },
915 ),
916 ];
917
918 for (json, expected) in cases {
919 let update: MetadataUpdate = serde_json::from_str(json).unwrap();
920 assert_eq!(update.extend_expiry, expected);
921 assert_eq!(serde_json::to_string(&update).unwrap(), json);
922 }
923 }
924
925 #[test]
926 fn metadata_update_rejects_invalid_structures() {
927 let cases = [
928 r#"{"extend_expiry":{"at":"not a timestamp"}}"#,
929 r#"{"extend_expiry":{"after":"not a duration","from":"now"}}"#,
930 r#"{}"#,
931 r#"{"extend_expiry":null}"#,
932 r#"{"extend_expiry":{}}"#,
933 r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z","after":"30d","from":"now"}}"#,
934 r#"{"extend_expiry":{"after":"30d"}}"#,
935 r#"{"extend_expiry":{"after":"30d","from":"unsupported"}}"#,
936 r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z","unknown":true}}"#,
937 r#"{"extend_expiry":{"after":"30d","from":"now","unknown":true}}"#,
938 r#"{"extend_expiry":{"at":"2026-10-16T12:00:00Z"},"content_type":"text/plain"}"#,
939 ];
940
941 for json in cases {
942 assert!(
943 serde_json::from_str::<MetadataUpdate>(json).is_err(),
944 "unexpectedly accepted {json}"
945 );
946 }
947 }
948
949 #[test]
950 fn from_headers_with_origin() {
951 let mut headers = HeaderMap::new();
952 headers.insert("content-type", "text/plain".parse().unwrap());
953 headers.insert(HEADER_ORIGIN, "203.0.113.42".parse().unwrap());
954
955 let metadata = Metadata::from_headers(&headers, "").unwrap();
956 assert_eq!(metadata.origin.as_deref(), Some("203.0.113.42"));
957 assert_eq!(metadata.content_type, "text/plain");
958 }
959
960 #[test]
961 fn from_headers_without_origin() {
962 let mut headers = HeaderMap::new();
963 headers.insert("content-type", "text/plain".parse().unwrap());
964
965 let metadata = Metadata::from_headers(&headers, "").unwrap();
966 assert!(metadata.origin.is_none());
967 }
968
969 #[test]
970 fn to_headers_with_origin() {
971 let metadata = Metadata {
972 origin: Some("203.0.113.42".into()),
973 ..Default::default()
974 };
975
976 let headers = metadata.to_headers("").unwrap();
977 assert_eq!(headers.get(HEADER_ORIGIN).unwrap(), "203.0.113.42");
978 }
979
980 #[test]
981 fn to_headers_without_origin() {
982 let metadata = Metadata::default();
983 let headers = metadata.to_headers("").unwrap();
984 assert!(headers.get(HEADER_ORIGIN).is_none());
985 }
986
987 #[test]
988 fn origin_header_roundtrip() {
989 let metadata = Metadata {
990 origin: Some("203.0.113.42".into()),
991 ..Default::default()
992 };
993
994 let headers = metadata.to_headers("").unwrap();
995 let roundtripped = Metadata::from_headers(&headers, "").unwrap();
996 assert_eq!(roundtripped.origin, metadata.origin);
997 }
998
999 #[test]
1000 fn from_headers_with_filename() {
1001 let mut headers = HeaderMap::new();
1002 headers.insert(HEADER_FILENAME, "report.pdf".parse().unwrap());
1003
1004 let metadata = Metadata::from_headers(&headers, "").unwrap();
1005 assert_eq!(metadata.filename.as_deref(), Some("report.pdf"));
1006 }
1007
1008 #[test]
1009 fn from_headers_without_filename() {
1010 let headers = HeaderMap::new();
1011 let metadata = Metadata::from_headers(&headers, "").unwrap();
1012 assert!(metadata.filename.is_none());
1013 }
1014
1015 #[test]
1016 fn to_headers_with_filename() {
1017 let metadata = Metadata {
1018 filename: Some("report.pdf".into()),
1019 ..Default::default()
1020 };
1021
1022 let headers = metadata.to_headers("").unwrap();
1023 assert_eq!(headers.get(HEADER_FILENAME).unwrap(), "report.pdf");
1024 }
1025
1026 #[test]
1027 fn to_headers_without_filename() {
1028 let metadata = Metadata::default();
1029 let headers = metadata.to_headers("").unwrap();
1030 assert!(headers.get(HEADER_FILENAME).is_none());
1031 }
1032
1033 #[test]
1034 fn filename_header_roundtrip() {
1035 let metadata = Metadata {
1036 filename: Some("report.pdf".into()),
1037 ..Default::default()
1038 };
1039
1040 let headers = metadata.to_headers("").unwrap();
1041 let roundtripped = Metadata::from_headers(&headers, "").unwrap();
1042 assert_eq!(roundtripped.filename, metadata.filename);
1043 }
1044
1045 #[test]
1050 fn free_form_values_are_escaped_on_the_wire() {
1051 let metadata = Metadata {
1052 origin: Some("Ünknown-源".into()),
1053 filename: Some("réport-📄.pdf".into()),
1054 custom: BTreeMap::from([("release".to_owned(), "100% vérsion-🚀".to_owned())]),
1055 ..Default::default()
1056 };
1057
1058 let headers = metadata.to_headers("").unwrap();
1059 assert_eq!(
1060 headers.get(HEADER_ORIGIN).unwrap(),
1061 "%C3%9Cnknown-%E6%BA%90"
1062 );
1063 assert_eq!(
1064 headers.get(HEADER_FILENAME).unwrap(),
1065 "r%C3%A9port-%F0%9F%93%84.pdf",
1066 );
1067 assert_eq!(
1068 headers.get(format!("{HEADER_META_PREFIX}release")).unwrap(),
1069 "100%25 v%C3%A9rsion-%F0%9F%9A%80",
1070 );
1071
1072 let roundtripped = Metadata::from_headers(&headers, "").unwrap();
1073 assert_eq!(roundtripped.origin, metadata.origin);
1074 assert_eq!(roundtripped.filename, metadata.filename);
1075 assert_eq!(roundtripped.custom, metadata.custom);
1076 }
1077
1078 #[test]
1079 fn from_headers_content_type_and_encoding() {
1080 let mut headers = HeaderMap::new();
1081 headers.insert("content-type", "application/json".parse().unwrap());
1082 headers.insert("content-encoding", "zstd".parse().unwrap());
1083
1084 let metadata = Metadata::from_headers(&headers, "").unwrap();
1085 assert_eq!(metadata.content_type, "application/json");
1086 assert_eq!(metadata.compression, Some(Compression::Zstd));
1087 }
1088
1089 #[test]
1090 fn from_headers_expiration_policy() {
1091 let mut headers = HeaderMap::new();
1092 headers.insert(HEADER_EXPIRATION, "ttl:30s".parse().unwrap());
1093
1094 let metadata = Metadata::from_headers(&headers, "").unwrap();
1095 assert_eq!(
1096 metadata.expiration_policy,
1097 ExpirationPolicy::TimeToLive(Duration::from_secs(30))
1098 );
1099 }
1100
1101 #[test]
1102 fn expiration_policy_keeps_long_durations_in_days() {
1103 let ttl = Duration::from_secs(400 * 86400 + 3600);
1104 let policy = ExpirationPolicy::TimeToLive(ttl);
1105
1106 assert_eq!(policy.to_string(), "ttl:400d 1h");
1107 assert_eq!(
1108 policy.to_string().parse::<ExpirationPolicy>().unwrap(),
1109 policy
1110 );
1111 }
1112
1113 #[test]
1114 fn expiration_policy_parses_units_that_are_never_emitted() {
1115 let policy: ExpirationPolicy = "tti:2weeks".parse().unwrap();
1116 assert_eq!(
1117 policy,
1118 ExpirationPolicy::TimeToIdle(Duration::from_secs(14 * 86400))
1119 );
1120 assert_eq!(policy.to_string(), "tti:14d");
1122 }
1123
1124 #[test]
1125 fn from_headers_timestamps() {
1126 let mut headers = HeaderMap::new();
1127 headers.insert(
1128 HEADER_TIME_CREATED,
1129 "2024-01-15T12:00:00.123456Z".parse().unwrap(),
1130 );
1131 headers.insert(
1132 HEADER_TIME_EXPIRES,
1133 "2024-01-16T12:00:00.123456Z".parse().unwrap(),
1134 );
1135
1136 let metadata = Metadata::from_headers(&headers, "").unwrap();
1137 let encoded = metadata.to_headers("").unwrap();
1138 assert_eq!(encoded[HEADER_TIME_CREATED], "2024-01-15T12:00:01Z");
1139 assert_eq!(encoded[HEADER_TIME_EXPIRES], "2024-01-16T12:00:01Z");
1140 let deadline = metadata.time_expires.unwrap();
1141 assert!(!metadata.is_expired(deadline - Duration::from_secs(1)));
1142 assert!(!metadata.is_expired(deadline));
1143 assert!(metadata.is_expired(deadline + Duration::from_secs(1)));
1144 }
1145
1146 #[test]
1147 fn from_insert_headers_ignores_read_only_fields() {
1148 let forged_created = "2024-01-15T12:00:00.000000Z";
1151 let mut headers = HeaderMap::new();
1152 headers.insert("content-type", "text/plain".parse().unwrap());
1153 headers.insert(HEADER_TIME_CREATED, forged_created.parse().unwrap());
1154 headers.insert(
1155 HEADER_TIME_EXPIRES,
1156 "2024-01-16T12:00:00.000000Z".parse().unwrap(),
1157 );
1158
1159 let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1160 let created = metadata.time_created.unwrap();
1162 assert_ne!(created, Timestamp::from_rfc3339(forged_created).unwrap());
1163 assert!(metadata.time_expires.is_none());
1164 assert!(metadata.size.is_none());
1165 assert_eq!(metadata.content_type, "text/plain");
1167 }
1168
1169 #[test]
1170 fn from_insert_headers_ignores_malformed_read_only_fields() {
1171 let mut headers = HeaderMap::new();
1173 headers.insert(HEADER_TIME_CREATED, "not-a-timestamp".parse().unwrap());
1174 headers.insert(HEADER_TIME_EXPIRES, "not-a-timestamp".parse().unwrap());
1175
1176 let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1177 assert!(metadata.time_created.is_some());
1178 assert!(metadata.time_expires.is_none());
1179 }
1180
1181 #[test]
1182 fn from_insert_headers_resolves_time_expires_for_ttl() {
1183 let mut headers = HeaderMap::new();
1184 headers.insert(HEADER_EXPIRATION, "ttl:30s".parse().unwrap());
1185
1186 let access_time = Timestamp::UNIX_EPOCH;
1187 let metadata = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
1188 let created = metadata.time_created.unwrap();
1189 assert_eq!(created, access_time);
1190 let expires = metadata.time_expires.unwrap();
1191 assert_eq!(expires, created + Duration::from_secs(30));
1192 }
1193
1194 #[test]
1195 fn from_insert_headers_resolves_time_expires_for_tti() {
1196 let mut headers = HeaderMap::new();
1197 headers.insert(HEADER_EXPIRATION, "tti:1h".parse().unwrap());
1198
1199 let access_time = Timestamp::UNIX_EPOCH;
1200 let metadata = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
1201 let created = metadata.time_created.unwrap();
1202 assert_eq!(created, access_time);
1203 let expires = metadata.time_expires.unwrap();
1204 assert_eq!(expires, created + Duration::from_hours(1));
1205 }
1206
1207 #[test]
1208 fn from_insert_headers_manual_leaves_time_expires_none() {
1209 let headers = HeaderMap::new();
1210 let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1211 assert_eq!(metadata.expiration_policy, ExpirationPolicy::Manual);
1212 assert!(metadata.time_expires.is_none());
1213 }
1214
1215 #[test]
1216 fn validate_accepts_resolved_timeout() {
1217 let metadata = Metadata {
1218 expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_secs(30)),
1219 time_expires: Some(Timestamp::now() + Duration::from_secs(30)),
1220 ..Default::default()
1221 };
1222 assert!(metadata.validate().is_ok());
1223 }
1224
1225 #[test]
1226 fn validate_accepts_manual_without_expiry() {
1227 let metadata = Metadata::default();
1228 assert!(metadata.validate().is_ok());
1229 }
1230
1231 #[test]
1232 fn validate_rejects_timeout_without_expiry() {
1233 let metadata = Metadata {
1234 expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1235 time_expires: None,
1236 ..Default::default()
1237 };
1238 assert!(matches!(metadata.validate(), Err(Error::Invariant(_))));
1239 }
1240
1241 #[test]
1242 fn from_headers_custom_metadata_with_prefix() {
1243 let mut headers = HeaderMap::new();
1244 let prefix = "x-goog-meta-";
1246 let expiration_header: HeaderName = format!("{prefix}{HEADER_EXPIRATION}").parse().unwrap();
1247 headers.insert(expiration_header, "tti:1h".parse().unwrap());
1248
1249 let custom_header: HeaderName = format!("{prefix}{HEADER_META_PREFIX}my-key")
1250 .parse()
1251 .unwrap();
1252 headers.insert(custom_header, "my-value".parse().unwrap());
1253
1254 let metadata = Metadata::from_headers(&headers, prefix).unwrap();
1255 assert_eq!(
1256 metadata.expiration_policy,
1257 ExpirationPolicy::TimeToIdle(Duration::from_hours(1))
1258 );
1259 assert_eq!(metadata.custom.get("my-key").unwrap(), "my-value");
1260 }
1261
1262 #[test]
1263 fn normalize_custom_key_accepts_allowed_characters_and_lowercases() {
1264 let allowed = "abcdefghijklmnopqrstuvwxyz0123456789_-|~%$#+.:";
1265 for ch in allowed.chars() {
1266 let key = format!("k{ch}k");
1267 assert_eq!(normalize_custom_key(&key).unwrap(), key, "rejected {ch:?}");
1268 }
1269 assert_eq!(normalize_custom_key(allowed).unwrap(), allowed);
1270 assert_eq!(normalize_custom_key("Build_ID:X").unwrap(), "build_id:x");
1271 }
1272
1273 #[test]
1274 fn normalize_custom_key_rejects_empty_and_other_characters() {
1275 let rejected = [
1276 "", "a b", "a\tb", "a!b", "a\"b", "a&b", "a'b", "a(b", "a)b", "a*b", "a,b", "a/b",
1277 "a;b", "a<b", "a=b", "a>b", "a?b", "a@b", "a[b", "a\\b", "a]b", "a^b", "a`b", "a{b",
1278 "a}b", "a\nb", "a\x7fb", "kéy", "键", "k🚀",
1279 ];
1280 for key in rejected {
1281 std::assert_matches!(
1282 normalize_custom_key(key),
1283 Err(Error::CustomKey(_)),
1284 "accepted {key:?}"
1285 );
1286 }
1287 }
1288
1289 #[test]
1290 fn custom_key_header_name_encoding_roundtrips() {
1291 assert_eq!(encode_custom_key("plain-key_1"), "plain-key_1");
1292 assert_eq!(encode_custom_key("a:b"), "a%3ab");
1293 assert_eq!(encode_custom_key("a%b"), "a%25b");
1294 assert_eq!(encode_custom_key("a%3ab"), "a%253ab");
1295 std::assert_matches!(encode_custom_key("plain"), Cow::Borrowed(_));
1296
1297 assert_eq!(headers::decode_header_str_lossy("a%3ab"), "a:b");
1298 assert_eq!(headers::decode_header_str_lossy("a%3Ab"), "a:b");
1299 assert_eq!(headers::decode_header_str_lossy("a%61"), "aa");
1300 assert_eq!(headers::decode_header_str_lossy("a%253ab"), "a%3ab");
1301 std::assert_matches!(headers::decode_header_str_lossy("plain"), Cow::Borrowed(_));
1302
1303 for key in ["a:b", "a%b", "a%3ab", "a%253ab", "%:%", "a%25", "x:y%z"] {
1304 assert_eq!(
1305 headers::decode_header_str_lossy(&encode_custom_key(key)),
1306 key
1307 );
1308 }
1309 }
1310
1311 #[test]
1312 fn custom_key_header_name_decoding_is_lenient() {
1313 for literal in ["100%", "a%", "a%3", "a%zz", "a%%b", "%2", "50%off"] {
1315 assert_eq!(headers::decode_header_str_lossy(literal), literal);
1316 }
1317 assert_eq!(headers::decode_header_str_lossy("a%ffb"), "a\u{FFFD}b");
1319 }
1320
1321 #[test]
1322 fn custom_keys_with_colon_and_percent_roundtrip_through_headers() {
1323 let metadata = Metadata {
1324 custom: BTreeMap::from([
1325 ("a:b".to_owned(), "colon".to_owned()),
1326 ("a%3ab".to_owned(), "encoded-looking".to_owned()),
1327 ("100%".to_owned(), "percent".to_owned()),
1328 ]),
1329 ..Default::default()
1330 };
1331
1332 for prefix in ["", "x-goog-meta-"] {
1333 let headers = metadata.to_headers(prefix).unwrap();
1334 assert_eq!(
1335 headers.get(format!("{prefix}x-snme-a%3ab")).unwrap(),
1336 "colon"
1337 );
1338 assert_eq!(
1339 headers.get(format!("{prefix}x-snme-a%253ab")).unwrap(),
1340 "encoded-looking"
1341 );
1342
1343 let roundtripped = Metadata::from_headers(&headers, prefix).unwrap();
1344 assert_eq!(roundtripped.custom, metadata.custom);
1345
1346 let access_time = Timestamp::from_unix_secs(1_700_000_000).unwrap();
1347 let inserted = Metadata::from_insert_headers(&headers, prefix, access_time).unwrap();
1348 assert_eq!(inserted.custom, metadata.custom);
1349 }
1350 }
1351
1352 #[test]
1353 fn from_headers_does_not_validate_custom_keys() {
1354 let mut headers = HeaderMap::new();
1355 headers.insert("x-snme-a*b", "v".parse().unwrap());
1356 headers.insert("x-snme-100%", "legacy".parse().unwrap());
1357 headers.insert("x-snme-", "empty".parse().unwrap());
1358 let metadata = Metadata::from_headers(&headers, "").unwrap();
1359 assert_eq!(metadata.custom.get("a*b").unwrap(), "v");
1360 assert_eq!(metadata.custom.get("100%").unwrap(), "legacy");
1361 assert_eq!(metadata.custom.get("").unwrap(), "empty");
1362 }
1363
1364 #[test]
1365 fn from_insert_headers_rejects_invalid_custom_keys() {
1366 let access_time = Timestamp::from_unix_secs(1_700_000_000).unwrap();
1367 for name in [
1368 "x-snme-a*b",
1369 "x-snme-a!b",
1370 "x-snme-a%ffb",
1371 "x-snme-a%20b",
1372 "x-snme-",
1373 ] {
1374 let mut headers = HeaderMap::new();
1375 headers.insert(name, "v".parse().unwrap());
1376 std::assert_matches!(
1377 Metadata::from_insert_headers(&headers, "", access_time),
1378 Err(Error::CustomKey(_)),
1379 "accepted {name}"
1380 );
1381 }
1382 }
1383
1384 #[test]
1385 fn from_headers_invalid_content_type() {
1386 let mut headers = HeaderMap::new();
1387 headers.insert("content-type", "not a valid media type!".parse().unwrap());
1388
1389 let err = Metadata::from_headers(&headers, "").unwrap_err();
1390 assert!(matches!(err, Error::ContentType(_)));
1391 }
1392
1393 #[test]
1394 fn from_headers_invalid_compression() {
1395 let mut headers = HeaderMap::new();
1396 headers.insert("content-encoding", "brotli".parse().unwrap());
1397
1398 let err = Metadata::from_headers(&headers, "").unwrap_err();
1399 assert!(matches!(err, Error::Compression));
1400 }
1401
1402 #[test]
1403 fn from_headers_invalid_expiration() {
1404 let mut headers = HeaderMap::new();
1405 headers.insert(HEADER_EXPIRATION, "garbage".parse().unwrap());
1406
1407 let err = Metadata::from_headers(&headers, "").unwrap_err();
1408 assert!(matches!(err, Error::Expiration(_)));
1409 }
1410
1411 #[test]
1412 fn from_headers_invalid_timestamp() {
1413 let mut headers = HeaderMap::new();
1414 headers.insert(HEADER_TIME_CREATED, "not-a-timestamp".parse().unwrap());
1415
1416 let err = Metadata::from_headers(&headers, "").unwrap_err();
1417 assert!(matches!(err, Error::CreationTime(_)));
1418 }
1419
1420 #[test]
1421 fn to_headers_all_fields() {
1422 let metadata = Metadata {
1423 expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_mins(1)),
1424 time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1425 time_expires: Some(Timestamp::from_unix_secs(1_700_000_060).unwrap()),
1426 content_type: "text/html".into(),
1427 compression: Some(Compression::Zstd),
1428 origin: Some("10.0.0.1".into()),
1429 filename: Some("report.pdf".into()),
1430 size: None,
1431 custom: BTreeMap::from([("foo".into(), "bar".into())]),
1432 };
1433
1434 let headers = metadata.to_headers("pfx-").unwrap();
1435 let map: BTreeMap<_, _> = headers
1436 .iter()
1437 .map(|(k, v)| (k.as_str(), v.to_str().unwrap()))
1438 .collect();
1439
1440 insta::assert_debug_snapshot!(map, @r#"
1441 {
1442 "content-encoding": "zstd",
1443 "content-type": "text/html",
1444 "pfx-x-sn-expiration": "ttl:1m",
1445 "pfx-x-sn-filename": "report.pdf",
1446 "pfx-x-sn-origin": "10.0.0.1",
1447 "pfx-x-sn-time-created": "2023-11-14T22:13:20Z",
1448 "pfx-x-sn-time-expires": "2023-11-14T22:14:20Z",
1449 "pfx-x-snme-foo": "bar",
1450 }
1451 "#);
1452 }
1453
1454 #[test]
1455 fn full_roundtrip_all_fields() {
1456 let prefix = "x-test-";
1457 let metadata = Metadata {
1458 expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(2)),
1459 time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1460 time_expires: Some(Timestamp::from_unix_secs(1_700_007_200).unwrap()),
1461 content_type: "image/png".into(),
1462 compression: Some(Compression::Zstd),
1463 origin: Some("192.168.1.1".into()),
1464 filename: Some("image.png".into()),
1465 size: None,
1466 custom: BTreeMap::from([
1467 ("key1".into(), "value1".into()),
1468 ("key2".into(), "value2".into()),
1469 ]),
1470 };
1471
1472 let headers = metadata.to_headers(prefix).unwrap();
1473 let roundtripped = Metadata::from_headers(&headers, prefix).unwrap();
1474
1475 assert_eq!(roundtripped.expiration_policy, metadata.expiration_policy);
1476 assert_eq!(roundtripped.content_type, metadata.content_type);
1477 assert_eq!(roundtripped.compression, metadata.compression);
1478 assert_eq!(roundtripped.origin, metadata.origin);
1479 assert_eq!(roundtripped.filename, metadata.filename);
1480 assert_eq!(roundtripped.time_created, metadata.time_created);
1481 assert_eq!(roundtripped.time_expires, metadata.time_expires);
1482 assert_eq!(roundtripped.custom, metadata.custom);
1483 }
1484
1485 #[test]
1486 fn from_headers_empty() {
1487 let headers = HeaderMap::new();
1488 let metadata = Metadata::from_headers(&headers, "x-goog-meta-").unwrap();
1489 assert_eq!(metadata, Metadata::default());
1490 }
1491
1492 #[test]
1493 fn from_headers_invalid_time_expires() {
1494 let mut headers = HeaderMap::new();
1495 let name: HeaderName = format!("x-goog-meta-{HEADER_TIME_EXPIRES}")
1496 .parse()
1497 .unwrap();
1498 headers.insert(name, "not-a-timestamp".parse().unwrap());
1499
1500 assert!(Metadata::from_headers(&headers, "x-goog-meta-").is_err());
1503 }
1504
1505 #[test]
1506 fn serde_roundtrip_default() {
1507 let metadata = Metadata::default();
1508 let json = serde_json::to_string(&metadata).unwrap();
1509 let deserialized: Metadata = serde_json::from_str(&json).unwrap();
1510 assert_eq!(deserialized, metadata);
1511 }
1512
1513 #[test]
1514 fn serde_roundtrip_all_fields() {
1515 let metadata = Metadata {
1516 expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1517 time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1518 time_expires: Some(Timestamp::from_unix_secs(1_700_003_600).unwrap()),
1519 content_type: "application/json".into(),
1520 compression: Some(Compression::Zstd),
1521 origin: Some("10.0.0.1".into()),
1522 filename: Some("data.json".into()),
1523 size: Some(1024),
1524 custom: BTreeMap::from([("key".into(), "value".into())]),
1525 };
1526
1527 let json = serde_json::to_string(&metadata).unwrap();
1528 let deserialized: Metadata = serde_json::from_str(&json).unwrap();
1529 assert_eq!(deserialized, metadata);
1530 }
1531
1532 #[test]
1533 fn size_roundtrips_through_headers() {
1534 let metadata = Metadata {
1535 size: Some(42),
1536 ..Default::default()
1537 };
1538
1539 let headers = metadata.to_headers("").unwrap();
1540 assert_eq!(headers.get(HEADER_SIZE).unwrap(), "42");
1541 assert_eq!(Metadata::from_headers(&headers, "").unwrap().size, Some(42));
1542 }
1543
1544 #[test]
1545 fn size_is_prefixed_in_headers() {
1546 let metadata = Metadata {
1547 size: Some(42),
1548 ..Default::default()
1549 };
1550
1551 let headers = metadata.to_headers("x-goog-meta-").unwrap();
1552 assert_eq!(headers.get("x-goog-meta-x-sn-size").unwrap(), "42");
1553 }
1554
1555 #[test]
1556 fn from_insert_headers_ignores_size() {
1557 let mut headers = HeaderMap::new();
1559 headers.insert(HEADER_SIZE, "9999".parse().unwrap());
1560
1561 let metadata = Metadata::from_insert_headers(&headers, "", Timestamp::now()).unwrap();
1562 assert!(metadata.size.is_none());
1563 }
1564
1565 #[test]
1566 fn from_headers_rejects_malformed_size() {
1567 let mut headers = HeaderMap::new();
1568 headers.insert(HEADER_SIZE, "not-a-number".parse().unwrap());
1569
1570 assert!(matches!(
1571 Metadata::from_headers(&headers, ""),
1572 Err(Error::Size(_))
1573 ));
1574 }
1575
1576 #[test]
1577 fn default_metadata() {
1578 let metadata = Metadata::default();
1579 assert_eq!(metadata.content_type, DEFAULT_CONTENT_TYPE);
1580 assert_eq!(metadata.expiration_policy, ExpirationPolicy::Manual);
1581 assert!(metadata.compression.is_none());
1582 assert!(metadata.origin.is_none());
1583 assert!(metadata.filename.is_none());
1584 assert!(metadata.time_created.is_none());
1585 assert!(metadata.time_expires.is_none());
1586 assert!(metadata.size.is_none());
1587 assert!(metadata.custom.is_empty());
1588 }
1589
1590 #[test]
1591 fn expiration_display_roundtrip() {
1592 let cases = [
1593 ExpirationPolicy::Manual,
1594 ExpirationPolicy::TimeToLive(Duration::from_secs(30)),
1595 ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1596 ];
1597
1598 for policy in cases {
1599 let displayed = policy.to_string();
1600 let parsed: ExpirationPolicy = displayed.parse().unwrap();
1601 assert_eq!(parsed, policy);
1602 }
1603 }
1604
1605 #[test]
1606 fn expiration_parse_invalid() {
1607 assert!(ExpirationPolicy::from_str("garbage").is_err());
1608 assert!(ExpirationPolicy::from_str("ttl:").is_err());
1609 assert!(ExpirationPolicy::from_str("").is_err());
1610 }
1611
1612 #[test]
1613 fn expiration_policy_helpers() {
1614 assert_eq!(ExpirationPolicy::Manual.expires_in(), None);
1615 assert!(ExpirationPolicy::Manual.is_manual());
1616 assert!(!ExpirationPolicy::Manual.is_timeout());
1617
1618 let ttl = ExpirationPolicy::TimeToLive(Duration::from_mins(1));
1619 assert_eq!(ttl.expires_in(), Some(Duration::from_mins(1)));
1620 assert!(ttl.is_timeout());
1621 assert!(!ttl.is_manual());
1622
1623 let tti = ExpirationPolicy::TimeToIdle(Duration::from_mins(2));
1624 assert_eq!(tti.expires_in(), Some(Duration::from_mins(2)));
1625 assert!(tti.is_timeout());
1626 assert!(!tti.is_manual());
1627 }
1628
1629 #[test]
1630 fn compression_display_roundtrip() {
1631 for (compression, expected) in [(Compression::Zstd, "zstd"), (Compression::Gzip, "gzip")] {
1632 let displayed = compression.to_string();
1633 assert_eq!(displayed, expected);
1634 let parsed: Compression = displayed.parse().unwrap();
1635 assert_eq!(parsed, compression);
1636 }
1637 }
1638
1639 #[test]
1640 fn compression_parse_invalid() {
1641 assert!(Compression::from_str("lz4").is_err());
1642 assert!(Compression::from_str("").is_err());
1643 }
1644
1645 #[test]
1646 fn check_tti_bump_returns_none_for_manual() {
1647 let metadata = Metadata::default();
1648 assert!(metadata.check_tti_bump(Timestamp::now()).is_none());
1649 }
1650
1651 #[test]
1652 fn check_tti_bump_returns_none_for_ttl() {
1653 let now = Timestamp::now();
1654 let metadata = Metadata {
1655 expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_hours(1)),
1656 time_expires: Some(now + Duration::from_hours(1)),
1657 ..Default::default()
1658 };
1659 assert!(metadata.check_tti_bump(now).is_none());
1660 }
1661
1662 #[test]
1663 fn check_tti_bump_returns_none_when_fresh() {
1664 let now = Timestamp::now();
1665 let tti = Duration::from_hours(2 * 24);
1666 let metadata = Metadata {
1667 expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1668 time_expires: Some(now + tti),
1669 ..Default::default()
1670 };
1671 assert!(metadata.check_tti_bump(now).is_none());
1672 }
1673
1674 #[test]
1675 fn check_tti_bump_returns_new_deadline_when_stale() {
1676 let now = Timestamp::now();
1677 let tti = Duration::from_hours(2 * 24);
1678 let debounce = tti / 4;
1679 let stale_deadline = now + tti - debounce - Duration::from_mins(1);
1680 let metadata = Metadata {
1681 expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1682 time_expires: Some(stale_deadline),
1683 ..Default::default()
1684 };
1685 let new_deadline = metadata.check_tti_bump(now).unwrap();
1686 assert_eq!(new_deadline, now + tti);
1687 }
1688
1689 #[test]
1690 fn check_tti_bump_short_tti_triggers_bump() {
1691 let now = Timestamp::now();
1692 for tti in [
1693 Duration::from_hours(2),
1694 Duration::from_secs(3),
1695 Duration::from_secs(4),
1696 ] {
1697 let debounce = tti / 4;
1698 let new_deadline = now + tti;
1699 let mut metadata = Metadata {
1700 expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1701 time_expires: Some(new_deadline - Duration::from_secs(debounce.as_secs() + 1)),
1702 ..Default::default()
1703 };
1704 assert_eq!(metadata.check_tti_bump(now), Some(new_deadline));
1705 metadata.time_expires = Some(new_deadline - Duration::from_secs(debounce.as_secs()));
1706 assert!(metadata.check_tti_bump(now).is_none());
1707 }
1708 }
1709
1710 #[test]
1711 fn check_tti_bump_debounce_caps_at_24h() {
1712 let now = Timestamp::now();
1713 let tti = Duration::from_hours(30 * 24);
1714 let capped_debounce = Duration::from_hours(24);
1715 let stale_deadline = now + tti - capped_debounce - Duration::from_mins(1);
1716 let metadata = Metadata {
1717 expiration_policy: ExpirationPolicy::TimeToIdle(tti),
1718 time_expires: Some(stale_deadline),
1719 ..Default::default()
1720 };
1721 assert!(metadata.check_tti_bump(now).is_some());
1722
1723 let fresh_deadline = now + tti - capped_debounce + Duration::from_mins(1);
1724 let metadata = Metadata {
1725 time_expires: Some(fresh_deadline),
1726 ..metadata
1727 };
1728 assert!(metadata.check_tti_bump(now).is_none());
1729 }
1730
1731 #[test]
1732 fn check_tti_bump_returns_none_when_time_expires_missing() {
1733 let metadata = Metadata {
1734 expiration_policy: ExpirationPolicy::TimeToIdle(Duration::from_hours(1)),
1735 time_expires: None,
1736 ..Default::default()
1737 };
1738 assert!(metadata.check_tti_bump(Timestamp::now()).is_none());
1739 }
1740
1741 fn write_json(json: &str) -> Result<Metadata, Error> {
1744 let insert: WriteMetadata = serde_json::from_str(json).unwrap();
1745 insert.into_metadata(Timestamp::from_unix_secs(1_700_000_000).unwrap())
1746 }
1747
1748 fn full_metadata() -> Metadata {
1749 Metadata {
1750 expiration_policy: ExpirationPolicy::TimeToLive(Duration::from_hours(30 * 24)),
1751 time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1752 time_expires: Some(Timestamp::from_unix_secs(1_702_592_000).unwrap()),
1753 content_type: "image/png".into(),
1754 compression: Some(Compression::Zstd),
1755 origin: Some("203.0.113.42".into()),
1756 filename: Some("résumé.png".into()),
1757 size: Some(1024),
1758 custom: BTreeMap::from([("build".into(), "123".into())]),
1759 }
1760 }
1761
1762 #[test]
1763 fn write_metadata_minimal() {
1764 let metadata = write_json("{}").unwrap();
1765 assert_eq!(
1766 metadata,
1767 Metadata {
1768 time_created: Some(Timestamp::from_unix_secs(1_700_000_000).unwrap()),
1769 ..Default::default()
1770 }
1771 );
1772
1773 let json = serde_json::to_string(&WriteMetadata::from(Metadata::default())).unwrap();
1774 assert_eq!(json, "{}");
1775 }
1776
1777 #[test]
1778 fn write_metadata_full() {
1779 let expected = Metadata {
1780 size: None,
1781 ..full_metadata()
1782 };
1783
1784 let json = serde_json::to_string(&WriteMetadata::from(full_metadata())).unwrap();
1785 assert_eq!(
1786 json,
1787 r#"{"content_type":"image/png","content_encoding":"zstd","expiration":"ttl:30d","origin":"203.0.113.42","filename":"résumé.png","custom":{"build":"123"}}"#
1788 );
1789 assert_eq!(write_json(&json).unwrap(), expected);
1790 }
1791
1792 #[test]
1793 fn write_metadata_odd_cases() {
1794 let json = r#"{
1797 "future": 1,
1798 "size": 9,
1799 "time_created": "2020-01-01T00:00:00Z",
1800 "filename": "50%41.txt",
1801 "custom": {"Build": "100%25"}
1802 }"#;
1803 let metadata = write_json(json).unwrap();
1804 assert_eq!(
1805 metadata.time_created,
1806 Some(Timestamp::from_unix_secs(1_700_000_000).unwrap())
1807 );
1808 assert_eq!(metadata.size, None);
1809 assert_eq!(metadata.filename.as_deref(), Some("50%41.txt"));
1810 assert_eq!(metadata.custom["build"], "100%25");
1811
1812 for json in [
1813 r#"{"content_type":"not a media type!"}"#,
1814 r#"{"content_encoding":"brotli"}"#,
1815 r#"{"expiration":"garbage"}"#,
1816 r#"{"custom":{"a b":"v"}}"#,
1817 ] {
1818 assert!(write_json(json).is_err(), "unexpectedly accepted {json}");
1819 }
1820 }
1821
1822 #[test]
1823 fn write_metadata_matches_insert_headers() {
1824 let access_time = Timestamp::from_unix_secs(1_700_000_000).unwrap();
1825 for expiration in ["manual", "ttl:30d", "tti:1h"] {
1826 let mut headers = HeaderMap::new();
1827 headers.insert("content-type", "text/plain".parse().unwrap());
1828 headers.insert(HEADER_EXPIRATION, expiration.parse().unwrap());
1829 let from_headers = Metadata::from_insert_headers(&headers, "", access_time).unwrap();
1830
1831 let json = format!(r#"{{"content_type":"text/plain","expiration":"{expiration}"}}"#);
1832 assert_eq!(write_json(&json).unwrap(), from_headers, "{expiration}");
1833 }
1834 }
1835
1836 #[test]
1837 fn read_metadata_minimal() {
1838 let json = serde_json::to_string(&ReadMetadata::from(Metadata::default())).unwrap();
1839 assert_eq!(json, r#"{"content_type":"application/octet-stream"}"#);
1840
1841 let object: ReadMetadata = serde_json::from_str(&json).unwrap();
1842 assert_eq!(Metadata::try_from(object).unwrap(), Metadata::default());
1843 }
1844
1845 #[test]
1846 fn read_metadata_full() {
1847 let json = serde_json::to_string_pretty(&ReadMetadata::from(full_metadata())).unwrap();
1848 insta::assert_snapshot!(json, @r#"
1849 {
1850 "content_type": "image/png",
1851 "content_encoding": "zstd",
1852 "expiration": "ttl:30d",
1853 "origin": "203.0.113.42",
1854 "filename": "résumé.png",
1855 "custom": {
1856 "build": "123"
1857 },
1858 "time_created": "2023-11-14T22:13:20Z",
1859 "time_expires": "2023-12-14T22:13:20Z",
1860 "size": 1024
1861 }
1862 "#);
1863
1864 let object: ReadMetadata = serde_json::from_str(&json).unwrap();
1865 assert_eq!(Metadata::try_from(object).unwrap(), full_metadata());
1866 }
1867
1868 #[test]
1869 fn read_metadata_odd_cases() {
1870 let json = r#"{"content_type":"text/plain","future":1,"custom":{"a*b":"v"}}"#;
1872 let object: ReadMetadata = serde_json::from_str(json).unwrap();
1873 assert_eq!(Metadata::try_from(object).unwrap().custom["a*b"], "v");
1874
1875 let json = r#"{"content_type":"text/plain","expiration":"garbage"}"#;
1876 let object: ReadMetadata = serde_json::from_str(json).unwrap();
1877 assert!(Metadata::try_from(object).is_err());
1878 }
1879}