Skip to main content

postproject_core/
resource.rs

1//! Storage-level resource identity and access values.
2
3use crate::{
4    Asset, Error, ErrorKind, LocatorId, MediaRoot, Representation, ResourceId, Result,
5    SequenceNaming, Timestamp, uri::normalize_uri,
6};
7
8/// Cheap filesystem facts observed for one resource.
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub struct FileFacts {
11    size_bytes: u64,
12    modified_at: Option<Timestamp>,
13}
14
15impl FileFacts {
16    /// Creates file facts from a byte size and optional modification time.
17    #[must_use]
18    pub const fn new(size_bytes: u64, modified_at: Option<Timestamp>) -> Self {
19        Self {
20            size_bytes,
21            modified_at,
22        }
23    }
24
25    /// Returns the observed file size.
26    #[must_use]
27    pub const fn size_bytes(self) -> u64 {
28        self.size_bytes
29    }
30
31    /// Returns the observed modification time, when available.
32    #[must_use]
33    pub const fn modified_at(self) -> Option<Timestamp> {
34        self.modified_at
35    }
36}
37
38#[derive(Clone, Debug, Eq, PartialEq)]
39struct FingerprintData {
40    algorithm: String,
41    version: u16,
42    value: Vec<u8>,
43}
44
45impl FingerprintData {
46    fn new(algorithm: impl Into<String>, version: u16, value: Vec<u8>) -> Result<Self> {
47        let algorithm = algorithm.into();
48        if algorithm.is_empty()
49            || algorithm.len() > 64
50            || !algorithm
51                .bytes()
52                .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_'))
53        {
54            return Err(Error::new(
55                ErrorKind::InvalidArgument,
56                "fingerprint algorithm must be 1-64 ASCII letters, digits, '-' or '_'",
57            ));
58        }
59        if value.is_empty() {
60            return Err(Error::new(
61                ErrorKind::InvalidArgument,
62                "fingerprint value must not be empty",
63            ));
64        }
65        Ok(Self {
66            algorithm,
67            version,
68            value,
69        })
70    }
71}
72
73macro_rules! typed_fingerprint {
74    ($(#[$metadata:meta])* $name:ident) => {
75        $(#[$metadata])*
76        #[derive(Clone, Debug, Eq, PartialEq)]
77        pub struct $name(FingerprintData);
78
79        impl $name {
80            /// Creates typed fingerprint evidence.
81            ///
82            /// # Errors
83            ///
84            /// Returns an error when the algorithm or value is invalid.
85            pub fn new(
86                algorithm: impl Into<String>,
87                version: u16,
88                value: Vec<u8>,
89            ) -> Result<Self> {
90                FingerprintData::new(algorithm, version, value).map(Self)
91            }
92
93            /// Returns the algorithm identifier.
94            #[must_use]
95            pub fn algorithm(&self) -> &str {
96                &self.0.algorithm
97            }
98
99            /// Returns the algorithm format version.
100            #[must_use]
101            pub const fn version(&self) -> u16 {
102                self.0.version
103            }
104
105            /// Returns the opaque fingerprint bytes.
106            #[must_use]
107            pub fn value(&self) -> &[u8] {
108                &self.0.value
109            }
110        }
111    };
112}
113
114typed_fingerprint!(
115    /// Versioned identity evidence derived from one storage resource.
116    ResourceFingerprint
117);
118typed_fingerprint!(
119    /// Versioned, structure-aware identity evidence for a representation.
120    RepresentationFingerprint
121);
122
123/// One immutable fingerprint value captured at a semantic revision.
124#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
125pub struct FingerprintSnapshot {
126    algorithm: String,
127    version: u16,
128    value: Vec<u8>,
129    observed_revision_sequence: Option<u64>,
130}
131
132impl FingerprintSnapshot {
133    /// Creates a validated snapshot of one fingerprint domain.
134    ///
135    /// `observed_revision_sequence` is absent for fingerprints migrated from a
136    /// schema that did not record observation revisions.
137    ///
138    /// # Errors
139    ///
140    /// Returns an error when the fingerprint algorithm or value is invalid.
141    pub fn new(
142        algorithm: impl Into<String>,
143        version: u16,
144        value: Vec<u8>,
145        observed_revision_sequence: Option<u64>,
146    ) -> Result<Self> {
147        let fingerprint = FingerprintData::new(algorithm, version, value)?;
148        Ok(Self {
149            algorithm: fingerprint.algorithm,
150            version: fingerprint.version,
151            value: fingerprint.value,
152            observed_revision_sequence,
153        })
154    }
155
156    /// Returns the algorithm identifier.
157    #[must_use]
158    pub fn algorithm(&self) -> &str {
159        &self.algorithm
160    }
161
162    /// Returns the algorithm format version.
163    #[must_use]
164    pub const fn version(&self) -> u16 {
165        self.version
166    }
167
168    /// Returns the opaque fingerprint bytes.
169    #[must_use]
170    pub fn value(&self) -> &[u8] {
171        &self.value
172    }
173
174    /// Returns the revision that recorded this value, when known.
175    #[must_use]
176    pub const fn observed_revision_sequence(&self) -> Option<u64> {
177        self.observed_revision_sequence
178    }
179}
180
181/// A storage-level component used to realize a representation.
182#[derive(Clone, Debug, Eq, PartialEq)]
183pub struct Resource {
184    id: ResourceId,
185    fingerprints: Vec<ResourceFingerprint>,
186    file_facts: Option<FileFacts>,
187}
188
189impl Resource {
190    /// Creates a resource from content evidence known at observation time.
191    #[must_use]
192    pub fn new(
193        id: ResourceId,
194        fingerprints: Vec<ResourceFingerprint>,
195        file_facts: Option<FileFacts>,
196    ) -> Self {
197        Self {
198            id,
199            fingerprints,
200            file_facts,
201        }
202    }
203
204    /// Returns the resource's stable identity.
205    #[must_use]
206    pub const fn id(&self) -> ResourceId {
207        self.id
208    }
209
210    /// Returns stored content identity evidence.
211    #[must_use]
212    pub fn fingerprints(&self) -> &[ResourceFingerprint] {
213        &self.fingerprints
214    }
215
216    /// Returns cheap stored file facts, when available.
217    #[must_use]
218    pub const fn file_facts(&self) -> Option<FileFacts> {
219        self.file_facts
220    }
221
222    /// Returns this resource with `fingerprint` as the current observation in
223    /// its algorithm/version domain, replacing any value in that domain.
224    #[must_use]
225    pub fn with_observed_fingerprint(&self, fingerprint: &ResourceFingerprint) -> Self {
226        let mut fingerprints = self
227            .fingerprints
228            .iter()
229            .filter(|current| {
230                current.algorithm() != fingerprint.algorithm()
231                    || current.version() != fingerprint.version()
232            })
233            .cloned()
234            .collect::<Vec<_>>();
235        fingerprints.push(fingerprint.clone());
236        Self::new(self.id, fingerprints, self.file_facts)
237    }
238}
239
240/// Canonical current locator identity used to find known media.
241///
242/// A single-file identity has no sequence naming. An image-sequence identity
243/// combines its directory URI with the exact naming descriptor, so different
244/// sequences in one directory remain distinct.
245#[derive(Clone, Debug, Eq, PartialEq)]
246pub struct LocatorIdentity {
247    uri: String,
248    sequence_naming: Option<SequenceNaming>,
249}
250
251impl LocatorIdentity {
252    /// Creates a canonical locator identity.
253    ///
254    /// # Errors
255    ///
256    /// Returns an error when `uri` is invalid or relative.
257    pub fn new(uri: impl Into<String>, sequence_naming: Option<SequenceNaming>) -> Result<Self> {
258        Ok(Self {
259            uri: normalize_uri(uri, "locator identity")?,
260            sequence_naming,
261        })
262    }
263
264    /// Returns the canonical UTF-8 URI.
265    #[must_use]
266    pub fn uri(&self) -> &str {
267        &self.uri
268    }
269
270    /// Returns the exact sequence naming, when this identifies an image
271    /// sequence.
272    #[must_use]
273    pub const fn sequence_naming(&self) -> Option<&SequenceNaming> {
274        self.sequence_naming.as_ref()
275    }
276}
277
278/// One owning path from known storage evidence to logical production media.
279#[derive(Clone, Debug, Eq, PartialEq)]
280pub struct KnownMediaMatch {
281    asset: Asset,
282    representation: Representation,
283    resource: Resource,
284}
285
286impl KnownMediaMatch {
287    /// Creates a known-media ownership match.
288    #[doc(hidden)]
289    #[must_use]
290    pub fn new(asset: Asset, representation: Representation, resource: Resource) -> Self {
291        Self {
292            asset,
293            representation,
294            resource,
295        }
296    }
297
298    /// Returns the owning logical asset.
299    #[must_use]
300    pub const fn asset(&self) -> &Asset {
301        &self.asset
302    }
303
304    /// Returns the parent representation that uses the resource.
305    #[must_use]
306    pub const fn representation(&self) -> &Representation {
307        &self.representation
308    }
309
310    /// Returns the matching storage resource.
311    #[must_use]
312    pub const fn resource(&self) -> &Resource {
313        &self.resource
314    }
315}
316
317/// The last observed availability of a resource locator.
318#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
319#[non_exhaustive]
320pub enum LocatorAvailability {
321    /// Availability has not been checked.
322    Unknown,
323    /// The locator resolved when last checked.
324    Online,
325    /// The locator did not resolve when last checked.
326    Offline,
327}
328
329/// A URI identifying one access route to a resource.
330///
331/// A locator of an image-sequence resource names its directory and carries
332/// the [`SequenceNaming`] of the files there; no other locator has a naming.
333#[derive(Clone, Debug, Eq, PartialEq)]
334pub struct Locator {
335    id: LocatorId,
336    resource_id: ResourceId,
337    uri: String,
338    last_seen: Option<Timestamp>,
339    availability: LocatorAvailability,
340    media_root: Option<String>,
341    sequence_naming: Option<SequenceNaming>,
342}
343
344impl Locator {
345    /// Creates a locator with a syntactically valid absolute URI.
346    ///
347    /// # Errors
348    ///
349    /// Returns an error when `uri` is invalid or relative.
350    pub fn new(
351        id: LocatorId,
352        resource_id: ResourceId,
353        uri: impl Into<String>,
354        last_seen: Option<Timestamp>,
355        availability: LocatorAvailability,
356    ) -> Result<Self> {
357        let uri = normalize_uri(uri, "locator")?;
358        Ok(Self {
359            id,
360            resource_id,
361            uri,
362            last_seen,
363            availability,
364            media_root: None,
365            sequence_naming: None,
366        })
367    }
368
369    /// Records how the files of the image sequence at this locator are named.
370    #[must_use]
371    pub fn with_sequence_naming(mut self, naming: SequenceNaming) -> Self {
372        self.sequence_naming = Some(naming);
373        self
374    }
375
376    /// Associates this locator with the logical root used to discover it.
377    ///
378    /// # Errors
379    ///
380    /// Returns an invalid-argument error for an invalid logical root name.
381    pub fn with_media_root(mut self, name: impl Into<String>) -> Result<Self> {
382        let name = name.into();
383        MediaRoot::validate_name(&name)?;
384        self.media_root = Some(name);
385        Ok(self)
386    }
387
388    /// Returns the locator's stable identity.
389    #[must_use]
390    pub const fn id(&self) -> LocatorId {
391        self.id
392    }
393
394    /// Returns the resource made accessible by this locator.
395    #[must_use]
396    pub const fn resource_id(&self) -> ResourceId {
397        self.resource_id
398    }
399
400    /// Returns the UTF-8 URI.
401    #[must_use]
402    pub fn uri(&self) -> &str {
403        &self.uri
404    }
405
406    /// Returns when the locator was last observed online.
407    #[must_use]
408    pub const fn last_seen(&self) -> Option<Timestamp> {
409        self.last_seen
410    }
411
412    /// Returns its last observed availability.
413    #[must_use]
414    pub const fn availability(&self) -> LocatorAvailability {
415        self.availability
416    }
417
418    /// Returns the logical media root that located this URI, when recorded.
419    #[must_use]
420    pub fn media_root(&self) -> Option<&str> {
421        self.media_root.as_deref()
422    }
423
424    /// Returns the naming of the sequence files at this locator, present
425    /// exactly for a locator of an image-sequence resource.
426    #[must_use]
427    pub const fn sequence_naming(&self) -> Option<&SequenceNaming> {
428        self.sequence_naming.as_ref()
429    }
430}
431
432#[cfg(test)]
433mod tests {
434    use super::*;
435
436    #[test]
437    fn locator_belongs_to_a_resource() {
438        let resource_id = ResourceId::new();
439        let locator = Locator::new(
440            LocatorId::new(),
441            resource_id,
442            "file:///media/clip.mov",
443            None,
444            LocatorAvailability::Unknown,
445        )
446        .expect("valid locator");
447
448        assert_eq!(locator.resource_id(), resource_id);
449        assert_eq!(locator.uri(), "file:///media/clip.mov");
450    }
451
452    #[test]
453    fn fingerprint_domains_are_explicit() {
454        let resource = ResourceFingerprint::new("blake3", 1, vec![1]).expect("valid");
455        let representation =
456            RepresentationFingerprint::new("tree-blake3", 1, vec![2]).expect("valid");
457
458        assert_eq!(resource.algorithm(), "blake3");
459        assert_eq!(representation.algorithm(), "tree-blake3");
460        assert!(ResourceFingerprint::new("contains spaces", 1, vec![1]).is_err());
461        assert!(RepresentationFingerprint::new("valid", 1, Vec::new()).is_err());
462    }
463}