Skip to main content

postproject_core/
model.rs

1//! Core media identity and locator value types.
2
3use std::{
4    collections::BTreeSet,
5    time::{SystemTime, UNIX_EPOCH},
6};
7
8use crate::{
9    AssetId, ContentStructure, Error, ErrorKind, Locator, MediaRootId, ProductionId,
10    RepresentationFingerprint, RepresentationId, Resource, Result, uri::normalize_uri,
11};
12
13/// A UTC instant represented as microseconds since the Unix epoch.
14///
15/// The representation is independent of SQLite and has sufficient precision for
16/// filesystem and domain bookkeeping without exposing a third-party time type.
17#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
18pub struct Timestamp(i64);
19
20impl Timestamp {
21    /// Creates a timestamp from signed Unix microseconds.
22    #[must_use]
23    pub const fn from_unix_micros(micros: i64) -> Self {
24        Self(micros)
25    }
26
27    /// Returns the signed Unix-microsecond representation.
28    #[must_use]
29    pub const fn as_unix_micros(self) -> i64 {
30        self.0
31    }
32
33    /// Reads the current system time.
34    ///
35    /// # Errors
36    ///
37    /// Returns [`ErrorKind::Internal`] if the platform clock predates the Unix
38    /// epoch or cannot be represented in signed microseconds.
39    pub fn now() -> Result<Self> {
40        let duration = SystemTime::now()
41            .duration_since(UNIX_EPOCH)
42            .map_err(|error| {
43                Error::new(
44                    ErrorKind::Internal,
45                    format!("system clock is before the Unix epoch: {error}"),
46                )
47            })?;
48        let micros = i64::try_from(duration.as_micros()).map_err(|error| {
49            Error::new(
50                ErrorKind::Internal,
51                format!("system clock is outside the supported range: {error}"),
52            )
53        })?;
54        Ok(Self(micros))
55    }
56}
57
58/// Production identity and header metadata; mutable collections use read queries.
59#[derive(Clone, Debug, Eq, PartialEq)]
60pub struct Production {
61    id: ProductionId,
62    schema_version: u32,
63    created_at: Timestamp,
64    display_name: Option<String>,
65}
66
67impl Production {
68    /// Creates an in-memory production value.
69    #[must_use]
70    pub fn new(
71        id: ProductionId,
72        schema_version: u32,
73        created_at: Timestamp,
74        display_name: Option<String>,
75    ) -> Self {
76        Self {
77            id,
78            schema_version,
79            created_at,
80            display_name,
81        }
82    }
83
84    /// Returns the production's stable identity.
85    #[must_use]
86    pub const fn id(&self) -> ProductionId {
87        self.id
88    }
89
90    /// Returns the persistence schema version used to load this production.
91    #[must_use]
92    pub const fn schema_version(&self) -> u32 {
93        self.schema_version
94    }
95
96    /// Returns when the production was created.
97    #[must_use]
98    pub const fn created_at(&self) -> Timestamp {
99        self.created_at
100    }
101
102    /// Returns the optional user-facing name.
103    #[must_use]
104    pub fn display_name(&self) -> Option<&str> {
105        self.display_name.as_deref()
106    }
107}
108
109/// Logical identity for one piece of production media.
110#[derive(Clone, Debug, Eq, PartialEq)]
111pub struct Asset {
112    id: AssetId,
113    created_at: Timestamp,
114    display_name: Option<String>,
115    import_source: Option<String>,
116}
117
118impl Asset {
119    /// Creates an asset value. Paths belong to locators, not assets.
120    #[must_use]
121    pub fn new(
122        id: AssetId,
123        created_at: Timestamp,
124        display_name: Option<String>,
125        import_source: Option<String>,
126    ) -> Self {
127        Self {
128            id,
129            created_at,
130            display_name,
131            import_source,
132        }
133    }
134
135    /// Returns the asset's stable identity.
136    #[must_use]
137    pub const fn id(&self) -> AssetId {
138        self.id
139    }
140
141    /// Returns when the asset was created.
142    #[must_use]
143    pub const fn created_at(&self) -> Timestamp {
144        self.created_at
145    }
146
147    /// Returns the optional user-facing name.
148    #[must_use]
149    pub fn display_name(&self) -> Option<&str> {
150        self.display_name.as_deref()
151    }
152
153    /// Returns optional application-supplied import provenance.
154    #[must_use]
155    pub fn import_source(&self) -> Option<&str> {
156        self.import_source.as_deref()
157    }
158}
159
160/// The semantic role of an asset representation.
161#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
162#[non_exhaustive]
163pub enum RepresentationKind {
164    /// Source media as imported.
165    Original,
166    /// A lower-cost representation intended for interactive work.
167    Proxy,
168    /// A representation optimized for a particular workflow.
169    Optimized,
170    /// Media derived from another production operation.
171    Derived,
172}
173
174/// One encoded or derived form of an asset.
175#[derive(Clone, Debug, Eq, PartialEq)]
176pub struct Representation {
177    id: RepresentationId,
178    asset_id: AssetId,
179    kind: RepresentationKind,
180    content_structure: ContentStructure,
181    fingerprints: Vec<RepresentationFingerprint>,
182}
183
184impl Representation {
185    /// Creates a representation value.
186    #[must_use]
187    pub fn new(
188        id: RepresentationId,
189        asset_id: AssetId,
190        kind: RepresentationKind,
191        content_structure: ContentStructure,
192        fingerprints: Vec<RepresentationFingerprint>,
193    ) -> Self {
194        Self {
195            id,
196            asset_id,
197            kind,
198            content_structure,
199            fingerprints,
200        }
201    }
202
203    /// Returns the representation's stable identity.
204    #[must_use]
205    pub const fn id(&self) -> RepresentationId {
206        self.id
207    }
208
209    /// Returns the owning asset identity.
210    #[must_use]
211    pub const fn asset_id(&self) -> AssetId {
212        self.asset_id
213    }
214
215    /// Returns the representation's semantic role.
216    #[must_use]
217    pub const fn kind(&self) -> RepresentationKind {
218        self.kind
219    }
220
221    /// Returns how storage resources realize this representation.
222    #[must_use]
223    pub const fn content_structure(&self) -> &ContentStructure {
224        &self.content_structure
225    }
226
227    /// Returns structure-aware identity evidence for this representation.
228    #[must_use]
229    pub fn fingerprints(&self) -> &[RepresentationFingerprint] {
230        &self.fingerprints
231    }
232}
233
234/// A validated representation and the storage resources that realize it.
235#[derive(Clone, Debug, Eq, PartialEq)]
236pub struct RepresentationImport {
237    representation: Representation,
238    resources: Vec<Resource>,
239    locators: Vec<Locator>,
240}
241
242impl RepresentationImport {
243    /// Creates an import aggregate whose resource relationships are consistent.
244    ///
245    /// # Errors
246    ///
247    /// Returns [`ErrorKind::InvalidArgument`] if a referenced resource is absent
248    /// or duplicated, an extra resource is supplied, any resource lacks a
249    /// locator, or a locator has a sequence naming although it does not locate
250    /// the image-sequence resource, or lacks one although it does.
251    pub fn new(
252        representation: Representation,
253        resources: Vec<Resource>,
254        locators: Vec<Locator>,
255    ) -> Result<Self> {
256        let expected: BTreeSet<_> = representation
257            .content_structure()
258            .resource_ids()
259            .into_iter()
260            .collect();
261        let supplied: BTreeSet<_> = resources.iter().map(Resource::id).collect();
262        if expected != supplied || supplied.len() != resources.len() {
263            return Err(Error::new(
264                ErrorKind::InvalidArgument,
265                "representation resources do not exactly match the content structure",
266            ));
267        }
268        if locators
269            .iter()
270            .any(|locator| !supplied.contains(&locator.resource_id()))
271            || supplied.iter().any(|resource_id| {
272                !locators
273                    .iter()
274                    .any(|item| item.resource_id() == *resource_id)
275            })
276        {
277            return Err(Error::new(
278                ErrorKind::InvalidArgument,
279                "every representation resource must own at least one supplied locator",
280            ));
281        }
282        let sequence_resource = representation
283            .content_structure()
284            .image_sequence_descriptor()
285            .map(crate::ImageSequenceDescriptor::resource_id);
286        if locators.iter().any(|locator| {
287            locator.sequence_naming().is_some()
288                != (Some(locator.resource_id()) == sequence_resource)
289        }) {
290            return Err(Error::new(
291                ErrorKind::InvalidArgument,
292                "exactly the locators of an image-sequence resource must carry a sequence naming",
293            ));
294        }
295        Ok(Self {
296            representation,
297            resources,
298            locators,
299        })
300    }
301
302    /// Returns the representation being imported.
303    #[must_use]
304    pub const fn representation(&self) -> &Representation {
305        &self.representation
306    }
307
308    /// Returns the storage resources realizing the representation.
309    #[must_use]
310    pub fn resources(&self) -> &[Resource] {
311        &self.resources
312    }
313
314    /// Returns the known access routes for the imported resources.
315    #[must_use]
316    pub fn locators(&self) -> &[Locator] {
317        &self.locators
318    }
319
320    /// Splits the aggregate into persistable domain values.
321    #[must_use]
322    pub fn into_parts(self) -> (Representation, Vec<Resource>, Vec<Locator>) {
323        (self.representation, self.resources, self.locators)
324    }
325}
326
327/// A validated aggregate representing an imported asset and original media.
328#[derive(Clone, Debug, Eq, PartialEq)]
329pub struct OriginalMediaImport {
330    asset: Asset,
331    media: RepresentationImport,
332}
333
334impl OriginalMediaImport {
335    /// Creates an import aggregate whose ownership relationships are consistent.
336    ///
337    /// # Errors
338    ///
339    /// Returns [`ErrorKind::InvalidArgument`] if ownership is inconsistent, a
340    /// referenced resource is absent or duplicated, an extra resource is
341    /// supplied, any resource lacks a locator, or a sequence naming is
342    /// misplaced as [`RepresentationImport::new`] describes.
343    pub fn new(
344        asset: Asset,
345        representation: Representation,
346        resources: Vec<Resource>,
347        locators: Vec<Locator>,
348    ) -> Result<Self> {
349        if representation.asset_id() != asset.id() {
350            return Err(Error::new(
351                ErrorKind::InvalidArgument,
352                "import representation does not belong to its asset",
353            ));
354        }
355        if representation.kind() != RepresentationKind::Original {
356            return Err(Error::new(
357                ErrorKind::InvalidArgument,
358                "initial import representation must be original media",
359            ));
360        }
361        let media = RepresentationImport::new(representation, resources, locators)?;
362        Ok(Self { asset, media })
363    }
364
365    /// Returns the logical asset.
366    #[must_use]
367    pub const fn asset(&self) -> &Asset {
368        &self.asset
369    }
370
371    /// Returns the original representation.
372    #[must_use]
373    pub const fn representation(&self) -> &Representation {
374        self.media.representation()
375    }
376
377    /// Returns the storage resources realizing the representation.
378    #[must_use]
379    pub fn resources(&self) -> &[Resource] {
380        self.media.resources()
381    }
382
383    /// Returns the known access routes for the imported resources.
384    #[must_use]
385    pub fn locators(&self) -> &[Locator] {
386        self.media.locators()
387    }
388
389    /// Splits the aggregate into persistable domain values.
390    #[must_use]
391    pub fn into_parts(self) -> (Asset, Representation, Vec<Resource>, Vec<Locator>) {
392        let (representation, resources, locators) = self.media.into_parts();
393        (self.asset, representation, resources, locators)
394    }
395}
396
397/// An ordered filesystem or URI boundary searched by the resolver.
398#[derive(Clone, Debug, Eq, PartialEq)]
399pub struct MediaRoot {
400    id: MediaRootId,
401    name: String,
402    label: Option<String>,
403    legacy_uri: Option<String>,
404    priority: i32,
405    enabled: bool,
406}
407
408impl MediaRoot {
409    /// Validates a production-portable logical root name.
410    ///
411    /// # Errors
412    ///
413    /// Returns [`ErrorKind::InvalidArgument`] when `name` is empty, oversized,
414    /// path-shaped, contains control characters, or has surrounding whitespace.
415    pub fn validate_name(name: &str) -> Result<()> {
416        if name.is_empty()
417            || name.len() > 128
418            || name.trim() != name
419            || name
420                .chars()
421                .any(|character| character.is_control() || matches!(character, '/' | '\\'))
422        {
423            return Err(Error::new(
424                ErrorKind::InvalidArgument,
425                "media-root name must be 1-128 UTF-8 bytes without surrounding whitespace, control characters, or path separators",
426            ));
427        }
428        Ok(())
429    }
430
431    /// Creates a configured logical media root.
432    ///
433    /// # Errors
434    ///
435    /// Returns [`ErrorKind::InvalidArgument`] when `name` is not a bounded,
436    /// portable root name or when `legacy_uri` is invalid or relative.
437    pub fn new(
438        id: MediaRootId,
439        name: impl Into<String>,
440        label: Option<String>,
441        legacy_uri: Option<String>,
442        priority: i32,
443        enabled: bool,
444    ) -> Result<Self> {
445        let name = name.into();
446        Self::validate_name(&name)?;
447        let legacy_uri = legacy_uri
448            .map(|uri| normalize_uri(uri, "legacy media-root"))
449            .transpose()?;
450        Ok(Self {
451            id,
452            name,
453            label,
454            legacy_uri,
455            priority,
456            enabled,
457        })
458    }
459
460    /// Returns the root's stable identity.
461    #[must_use]
462    pub const fn id(&self) -> MediaRootId {
463        self.id
464    }
465
466    /// Returns the production-portable logical root name.
467    #[must_use]
468    pub fn name(&self) -> &str {
469        &self.name
470    }
471
472    /// Returns the optional user-facing label.
473    #[must_use]
474    pub fn label(&self) -> Option<&str> {
475        self.label.as_deref()
476    }
477
478    /// Returns the absolute URI retained while migrating a pre-version-6 root.
479    ///
480    /// New roots do not carry this machine-local fallback.
481    #[must_use]
482    pub fn legacy_uri(&self) -> Option<&str> {
483        self.legacy_uri.as_deref()
484    }
485
486    /// Returns the resolver priority; lower values are considered first.
487    #[must_use]
488    pub const fn priority(&self) -> i32 {
489        self.priority
490    }
491
492    /// Returns whether this root participates in resolution.
493    #[must_use]
494    pub const fn is_enabled(&self) -> bool {
495        self.enabled
496    }
497}
498
499#[cfg(test)]
500mod tests {
501    use super::*;
502    use crate::{LocatorAvailability, LocatorId, ResourceId};
503
504    #[test]
505    fn rejects_invalid_root_names() {
506        let root = MediaRoot::new(MediaRootId::new(), "path/name", None, None, 0, true);
507
508        assert_eq!(
509            root.expect_err("path-shaped name must fail").kind(),
510            ErrorKind::InvalidArgument
511        );
512    }
513
514    #[test]
515    fn import_aggregate_enforces_ownership() {
516        let asset = Asset::new(AssetId::new(), Timestamp::from_unix_micros(0), None, None);
517        let resource_id = ResourceId::new();
518        let representation = Representation::new(
519            RepresentationId::new(),
520            AssetId::new(),
521            RepresentationKind::Original,
522            ContentStructure::single_resource(resource_id),
523            Vec::new(),
524        );
525        let resource = Resource::new(resource_id, Vec::new(), None);
526        let locator = Locator::new(
527            LocatorId::new(),
528            resource_id,
529            "file:///media.mov",
530            None,
531            LocatorAvailability::Online,
532        )
533        .expect("valid locator");
534
535        assert_eq!(
536            OriginalMediaImport::new(asset, representation, vec![resource], vec![locator])
537                .expect_err("mismatched ownership must fail")
538                .kind(),
539            ErrorKind::InvalidArgument
540        );
541    }
542
543    #[test]
544    fn representation_import_accepts_non_original_media() {
545        let asset_id = AssetId::new();
546        let resource_id = ResourceId::new();
547        let representation = Representation::new(
548            RepresentationId::new(),
549            asset_id,
550            RepresentationKind::Proxy,
551            ContentStructure::single_resource(resource_id),
552            Vec::new(),
553        );
554        let resource = Resource::new(resource_id, Vec::new(), None);
555        let locator = Locator::new(
556            LocatorId::new(),
557            resource_id,
558            "file:///proxy.mov",
559            None,
560            LocatorAvailability::Online,
561        )
562        .expect("valid locator");
563
564        let imported =
565            RepresentationImport::new(representation.clone(), vec![resource], vec![locator])
566                .expect("valid representation import");
567
568        assert_eq!(imported.representation(), &representation);
569        assert_eq!(imported.representation().asset_id(), asset_id);
570        assert_eq!(imported.representation().kind(), RepresentationKind::Proxy);
571    }
572
573    #[test]
574    fn representation_import_requires_a_locator_for_every_resource() {
575        let resource_id = ResourceId::new();
576        let representation = Representation::new(
577            RepresentationId::new(),
578            AssetId::new(),
579            RepresentationKind::Derived,
580            ContentStructure::single_resource(resource_id),
581            Vec::new(),
582        );
583
584        assert_eq!(
585            RepresentationImport::new(
586                representation,
587                vec![Resource::new(resource_id, Vec::new(), None)],
588                Vec::new(),
589            )
590            .expect_err("missing locator must fail")
591            .kind(),
592            ErrorKind::InvalidArgument
593        );
594    }
595
596    #[test]
597    fn exactly_sequence_locators_carry_a_naming() {
598        let resource_id = ResourceId::new();
599        let descriptor = crate::ImageSequenceDescriptor::new(
600            resource_id,
601            crate::FrameRange::new(1, 3, 1).expect("valid range"),
602            crate::RationalRate::new(24, 1).expect("valid rate"),
603            Vec::new(),
604        )
605        .expect("valid descriptor");
606        let sequence = Representation::new(
607            RepresentationId::new(),
608            AssetId::new(),
609            RepresentationKind::Derived,
610            ContentStructure::image_sequence(descriptor),
611            Vec::new(),
612        );
613        let file = Representation::new(
614            RepresentationId::new(),
615            AssetId::new(),
616            RepresentationKind::Derived,
617            ContentStructure::single_resource(resource_id),
618            Vec::new(),
619        );
620        let resource = Resource::new(resource_id, Vec::new(), None);
621        let unnamed = Locator::new(
622            LocatorId::new(),
623            resource_id,
624            "file:///plates/",
625            None,
626            LocatorAvailability::Online,
627        )
628        .expect("valid locator");
629        let named = unnamed.clone().with_sequence_naming(
630            crate::SequenceNaming::new("shot_", ".png", 4).expect("valid naming"),
631        );
632
633        let import = |representation: &Representation, locator: &Locator| {
634            RepresentationImport::new(
635                representation.clone(),
636                vec![resource.clone()],
637                vec![locator.clone()],
638            )
639        };
640        assert!(import(&sequence, &named).is_ok());
641        assert!(import(&sequence, &unnamed).is_err());
642        assert!(import(&file, &named).is_err());
643        assert!(import(&file, &unnamed).is_ok());
644    }
645}