Skip to main content

postproject_core/
provenance.rs

1//! Extensible production-provenance vocabulary and participant identities.
2
3use std::collections::BTreeSet;
4
5use crate::{
6    ActivityId, Error, ErrorKind, ExternalIdentifier, FingerprintSnapshot, RepresentationId,
7    Result, Timestamp, uri::normalize_uri,
8};
9
10/// Maximum encoded length of an activity-kind identifier.
11pub const MAX_ACTIVITY_KIND_BYTES: usize = 128;
12/// Maximum encoded length of an activity-edge role identifier.
13pub const MAX_ACTIVITY_ROLE_BYTES: usize = 128;
14/// Maximum UTF-8 byte length of a tool or agent display name.
15pub const MAX_PROVENANCE_NAME_BYTES: usize = 256;
16/// Maximum UTF-8 byte length of an optional tool version.
17pub const MAX_TOOL_VERSION_BYTES: usize = 128;
18/// Maximum UTF-8 byte length of an optional tool or vendor URI.
19pub const MAX_PROVENANCE_URI_BYTES: usize = 4_096;
20/// Maximum number of input or output edges on one activity.
21pub const MAX_ACTIVITY_EDGES: usize = 100_000;
22
23/// A namespaced, open-world production activity kind.
24#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
25pub struct ActivityKind(String);
26
27impl ActivityKind {
28    /// Creates a kind such as `org.postproject:transcode`.
29    ///
30    /// # Errors
31    ///
32    /// Returns [`ErrorKind::InvalidArgument`] when the value is not a bounded
33    /// namespaced ASCII identifier.
34    pub fn new(value: impl Into<String>) -> Result<Self> {
35        validate_namespaced_identifier("activity kind", value.into(), MAX_ACTIVITY_KIND_BYTES)
36            .map(Self)
37    }
38
39    /// Returns the exact kind identifier.
40    #[must_use]
41    pub fn as_str(&self) -> &str {
42        &self.0
43    }
44}
45
46/// A namespaced, open-world role for an activity input or output.
47#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
48pub struct ActivityRole(String);
49
50impl ActivityRole {
51    /// Creates a role such as `org.postproject:input.primary-video`.
52    ///
53    /// # Errors
54    ///
55    /// Returns [`ErrorKind::InvalidArgument`] when the value is not a bounded
56    /// namespaced ASCII identifier.
57    pub fn new(value: impl Into<String>) -> Result<Self> {
58        validate_namespaced_identifier("activity role", value.into(), MAX_ACTIVITY_ROLE_BYTES)
59            .map(Self)
60    }
61
62    /// Returns the exact role identifier.
63    #[must_use]
64    pub fn as_str(&self) -> &str {
65        &self.0
66    }
67}
68
69/// The software or service that performed a production activity.
70#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct ToolIdentity {
72    name: String,
73    version: Option<String>,
74    uri: Option<String>,
75}
76
77impl ToolIdentity {
78    /// Creates a bounded tool identity with an optional absolute URI.
79    ///
80    /// # Errors
81    ///
82    /// Returns [`ErrorKind::InvalidArgument`] for empty or oversized text, NUL
83    /// bytes, or an invalid/relative URI.
84    pub fn new(
85        name: impl Into<String>,
86        version: Option<String>,
87        uri: Option<String>,
88    ) -> Result<Self> {
89        let name = name.into();
90        validate_text("tool name", &name, MAX_PROVENANCE_NAME_BYTES)?;
91        if let Some(version) = version.as_deref() {
92            validate_text("tool version", version, MAX_TOOL_VERSION_BYTES)?;
93        }
94        let uri = uri.map(|value| normalize_uri(value, "tool")).transpose()?;
95        if uri
96            .as_ref()
97            .is_some_and(|value| value.len() > MAX_PROVENANCE_URI_BYTES)
98        {
99            return Err(Error::new(
100                ErrorKind::InvalidArgument,
101                format!("tool URI must not exceed {MAX_PROVENANCE_URI_BYTES} UTF-8 bytes"),
102            ));
103        }
104        Ok(Self { name, version, uri })
105    }
106
107    /// Returns the user-facing tool name.
108    #[must_use]
109    pub fn name(&self) -> &str {
110        &self.name
111    }
112
113    /// Returns the optional exact version or build string.
114    #[must_use]
115    pub fn version(&self) -> Option<&str> {
116        self.version.as_deref()
117    }
118
119    /// Returns the optional canonical absolute tool/vendor URI.
120    #[must_use]
121    pub fn uri(&self) -> Option<&str> {
122        self.uri.as_deref()
123    }
124}
125
126/// A person, organization, application instance, or service responsible for an activity.
127#[derive(Clone, Debug, Eq, PartialEq)]
128pub struct AgentIdentity {
129    name: Option<String>,
130    identifier: Option<ExternalIdentifier>,
131}
132
133/// One representation consumed by an activity.
134#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
135pub struct ActivityInput {
136    representation_id: RepresentationId,
137    role: Option<ActivityRole>,
138    snapshot: Option<ActivityEdgeSnapshot>,
139}
140
141impl From<RepresentationId> for ActivityInput {
142    fn from(representation_id: RepresentationId) -> Self {
143        Self::new(representation_id, None)
144    }
145}
146
147impl ActivityInput {
148    /// Creates an activity input with an optional extensible role.
149    #[must_use]
150    pub const fn new(representation_id: RepresentationId, role: Option<ActivityRole>) -> Self {
151        Self {
152            representation_id,
153            role,
154            snapshot: None,
155        }
156    }
157
158    /// Returns the consumed representation.
159    #[must_use]
160    pub const fn representation_id(&self) -> RepresentationId {
161        self.representation_id
162    }
163
164    /// Returns the optional semantic input role.
165    #[must_use]
166    pub const fn role(&self) -> Option<&ActivityRole> {
167        self.role.as_ref()
168    }
169
170    /// Returns the storage-captured input state, or `None` for a migrated edge.
171    #[must_use]
172    pub const fn snapshot(&self) -> Option<&ActivityEdgeSnapshot> {
173        self.snapshot.as_ref()
174    }
175
176    /// Attaches a snapshot loaded by a persistence backend.
177    ///
178    /// Callers do not use this when creating an activity: storage replaces any
179    /// supplied value with a snapshot taken inside the creating transaction.
180    #[doc(hidden)]
181    #[must_use]
182    pub fn with_snapshot(mut self, snapshot: ActivityEdgeSnapshot) -> Self {
183        self.snapshot = Some(snapshot);
184        self
185    }
186}
187
188/// One representation produced by an activity.
189#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
190pub struct ActivityOutput {
191    representation_id: RepresentationId,
192    role: Option<ActivityRole>,
193    snapshot: Option<ActivityEdgeSnapshot>,
194}
195
196impl ActivityOutput {
197    /// Creates an activity output with an optional extensible role.
198    #[must_use]
199    pub const fn new(representation_id: RepresentationId, role: Option<ActivityRole>) -> Self {
200        Self {
201            representation_id,
202            role,
203            snapshot: None,
204        }
205    }
206
207    /// Returns the produced representation.
208    #[must_use]
209    pub const fn representation_id(&self) -> RepresentationId {
210        self.representation_id
211    }
212
213    /// Returns the optional semantic output role.
214    #[must_use]
215    pub const fn role(&self) -> Option<&ActivityRole> {
216        self.role.as_ref()
217    }
218
219    /// Returns the storage-captured output state, or `None` for a migrated edge.
220    #[must_use]
221    pub const fn snapshot(&self) -> Option<&ActivityEdgeSnapshot> {
222        self.snapshot.as_ref()
223    }
224
225    /// Attaches a snapshot loaded by a persistence backend.
226    #[doc(hidden)]
227    #[must_use]
228    pub fn with_snapshot(mut self, snapshot: ActivityEdgeSnapshot) -> Self {
229        self.snapshot = Some(snapshot);
230        self
231    }
232}
233
234/// Fingerprint evidence captured for one activity edge at commit time.
235#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
236pub struct ActivityEdgeSnapshot {
237    revision_sequence: u64,
238    fingerprints: Vec<FingerprintSnapshot>,
239}
240
241impl ActivityEdgeSnapshot {
242    /// Creates a canonical snapshot captured at `revision_sequence`.
243    ///
244    /// An empty fingerprint set explicitly records that the representation had
245    /// no fingerprint evidence. This differs from an absent migrated snapshot.
246    ///
247    /// # Errors
248    ///
249    /// Returns an error for sequence zero or duplicate fingerprint domains.
250    pub fn new(revision_sequence: u64, mut fingerprints: Vec<FingerprintSnapshot>) -> Result<Self> {
251        if revision_sequence == 0 {
252            return Err(Error::new(
253                ErrorKind::InvalidArgument,
254                "activity-edge snapshot revision must be greater than zero",
255            ));
256        }
257        fingerprints.sort_by(|left, right| {
258            (left.algorithm(), left.version()).cmp(&(right.algorithm(), right.version()))
259        });
260        if fingerprints.windows(2).any(|pair| {
261            (pair[0].algorithm(), pair[0].version()) == (pair[1].algorithm(), pair[1].version())
262        }) {
263            return Err(Error::new(
264                ErrorKind::InvalidArgument,
265                "activity-edge snapshot contains a duplicate fingerprint domain",
266            ));
267        }
268        Ok(Self {
269            revision_sequence,
270            fingerprints,
271        })
272    }
273
274    /// Returns the production revision current when storage captured the edge.
275    #[must_use]
276    pub const fn revision_sequence(&self) -> u64 {
277        self.revision_sequence
278    }
279
280    /// Returns captured fingerprint domains in canonical order.
281    #[must_use]
282    pub fn fingerprints(&self) -> &[FingerprintSnapshot] {
283        &self.fingerprints
284    }
285}
286
287/// A production operation connecting input and output representations.
288#[derive(Clone, Debug, Eq, PartialEq)]
289pub struct Activity {
290    id: ActivityId,
291    kind: ActivityKind,
292    started_at: Option<Timestamp>,
293    finished_at: Option<Timestamp>,
294    tool: Option<ToolIdentity>,
295    agent: Option<AgentIdentity>,
296    inputs: Vec<ActivityInput>,
297    outputs: Vec<ActivityOutput>,
298}
299
300impl Activity {
301    /// Creates a complete production activity and canonicalizes its edges.
302    ///
303    /// An activity may have no inputs, but must produce at least one output
304    /// because this model does not expose an in-progress lifecycle state.
305    ///
306    /// # Errors
307    ///
308    /// Returns [`ErrorKind::InvalidArgument`] when edges are empty or
309    /// excessive, an identical edge is duplicated, or one representation
310    /// appears on both sides of the activity.
311    pub fn new(
312        id: ActivityId,
313        kind: ActivityKind,
314        mut inputs: Vec<ActivityInput>,
315        mut outputs: Vec<ActivityOutput>,
316    ) -> Result<Self> {
317        validate_edge_count("input", inputs.len(), true)?;
318        validate_edge_count("output", outputs.len(), false)?;
319        inputs.sort();
320        outputs.sort();
321        if inputs.windows(2).any(|pair| pair[0] == pair[1]) {
322            return Err(Error::new(
323                ErrorKind::InvalidArgument,
324                "activity contains a duplicate input edge",
325            ));
326        }
327        if outputs.windows(2).any(|pair| pair[0] == pair[1]) {
328            return Err(Error::new(
329                ErrorKind::InvalidArgument,
330                "activity contains a duplicate output edge",
331            ));
332        }
333        let input_representations: BTreeSet<_> = inputs
334            .iter()
335            .map(ActivityInput::representation_id)
336            .collect();
337        if outputs
338            .iter()
339            .any(|output| input_representations.contains(&output.representation_id()))
340        {
341            return Err(Error::new(
342                ErrorKind::InvalidArgument,
343                "an activity cannot consume and produce the same representation",
344            ));
345        }
346        Ok(Self {
347            id,
348            kind,
349            started_at: None,
350            finished_at: None,
351            tool: None,
352            agent: None,
353            inputs,
354            outputs,
355        })
356    }
357
358    /// Adds optional activity timing.
359    ///
360    /// # Errors
361    ///
362    /// Returns [`ErrorKind::InvalidArgument`] when both times are present and
363    /// the finish precedes the start.
364    pub fn with_timing(
365        mut self,
366        started_at: Option<Timestamp>,
367        finished_at: Option<Timestamp>,
368    ) -> Result<Self> {
369        if started_at
370            .zip(finished_at)
371            .is_some_and(|(started, finished)| finished < started)
372        {
373            return Err(Error::new(
374                ErrorKind::InvalidArgument,
375                "activity finish time must not precede its start time",
376            ));
377        }
378        self.started_at = started_at;
379        self.finished_at = finished_at;
380        Ok(self)
381    }
382
383    /// Adds the optional tool that performed the activity.
384    #[must_use]
385    pub fn with_tool(mut self, tool: ToolIdentity) -> Self {
386        self.tool = Some(tool);
387        self
388    }
389
390    /// Adds the optional agent responsible for the activity.
391    #[must_use]
392    pub fn with_agent(mut self, agent: AgentIdentity) -> Self {
393        self.agent = Some(agent);
394        self
395    }
396
397    /// Returns the activity's stable identity.
398    #[must_use]
399    pub const fn id(&self) -> ActivityId {
400        self.id
401    }
402
403    /// Returns the extensible activity kind.
404    #[must_use]
405    pub const fn kind(&self) -> &ActivityKind {
406        &self.kind
407    }
408
409    /// Returns the optional start time.
410    #[must_use]
411    pub const fn started_at(&self) -> Option<Timestamp> {
412        self.started_at
413    }
414
415    /// Returns the optional finish time.
416    #[must_use]
417    pub const fn finished_at(&self) -> Option<Timestamp> {
418        self.finished_at
419    }
420
421    /// Returns the optional responsible tool.
422    #[must_use]
423    pub const fn tool(&self) -> Option<&ToolIdentity> {
424        self.tool.as_ref()
425    }
426
427    /// Returns the optional responsible agent.
428    #[must_use]
429    pub const fn agent(&self) -> Option<&AgentIdentity> {
430        self.agent.as_ref()
431    }
432
433    /// Returns inputs in canonical representation/role order.
434    #[must_use]
435    pub fn inputs(&self) -> &[ActivityInput] {
436        &self.inputs
437    }
438
439    /// Returns outputs in canonical representation/role order.
440    #[must_use]
441    pub fn outputs(&self) -> &[ActivityOutput] {
442        &self.outputs
443    }
444}
445
446impl AgentIdentity {
447    /// Creates an agent described by a name, an external identifier, or both.
448    ///
449    /// # Errors
450    ///
451    /// Returns [`ErrorKind::InvalidArgument`] when neither identity is present
452    /// or the name is empty, oversized, or contains NUL.
453    pub fn new(name: Option<String>, identifier: Option<ExternalIdentifier>) -> Result<Self> {
454        if let Some(name) = name.as_deref() {
455            validate_text("agent name", name, MAX_PROVENANCE_NAME_BYTES)?;
456        }
457        if name.is_none() && identifier.is_none() {
458            return Err(Error::new(
459                ErrorKind::InvalidArgument,
460                "agent identity requires a name or external identifier",
461            ));
462        }
463        Ok(Self { name, identifier })
464    }
465
466    /// Returns the optional user-facing agent name.
467    #[must_use]
468    pub fn name(&self) -> Option<&str> {
469        self.name.as_deref()
470    }
471
472    /// Returns the optional external agent identity.
473    #[must_use]
474    pub const fn identifier(&self) -> Option<&ExternalIdentifier> {
475        self.identifier.as_ref()
476    }
477}
478
479fn validate_namespaced_identifier(label: &str, value: String, maximum: usize) -> Result<String> {
480    let valid_bytes = value
481        .bytes()
482        .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
483    let valid_namespace = value
484        .split_once(':')
485        .is_some_and(|(namespace, local)| !namespace.is_empty() && !local.is_empty());
486    if value.len() > maximum || !valid_bytes || !valid_namespace {
487        return Err(Error::new(
488            ErrorKind::InvalidArgument,
489            format!("{label} must be a namespaced identifier of at most {maximum} ASCII bytes"),
490        ));
491    }
492    Ok(value)
493}
494
495fn validate_text(label: &str, value: &str, maximum: usize) -> Result<()> {
496    if value.is_empty() || value.len() > maximum || value.contains('\0') {
497        return Err(Error::new(
498            ErrorKind::InvalidArgument,
499            format!("{label} must contain 1-{maximum} UTF-8 bytes without NUL"),
500        ));
501    }
502    Ok(())
503}
504
505fn validate_edge_count(label: &str, count: usize, may_be_empty: bool) -> Result<()> {
506    if count > MAX_ACTIVITY_EDGES || (!may_be_empty && count == 0) {
507        let minimum = usize::from(!may_be_empty);
508        return Err(Error::new(
509            ErrorKind::InvalidArgument,
510            format!("activity must have {minimum}-{MAX_ACTIVITY_EDGES} {label} edges"),
511        ));
512    }
513    Ok(())
514}
515
516#[cfg(test)]
517mod tests {
518    use super::*;
519    use crate::IdentifierScheme;
520
521    #[test]
522    fn activity_vocabulary_is_extensible_and_namespaced() {
523        let kind = ActivityKind::new("vendor.example:vfx-render").expect("valid kind");
524        let role = ActivityRole::new("vendor.example:input.plate").expect("valid role");
525
526        assert_eq!(kind.as_str(), "vendor.example:vfx-render");
527        assert_eq!(role.as_str(), "vendor.example:input.plate");
528        assert!(ActivityKind::new("transcode").is_err());
529        assert!(ActivityRole::new("vendor.example:bad role").is_err());
530    }
531
532    #[test]
533    fn tool_and_agent_identity_preserve_supplied_detail() {
534        let tool = ToolIdentity::new(
535            "FFmpeg",
536            Some("8.0-custom".to_owned()),
537            Some("https://ffmpeg.org".to_owned()),
538        )
539        .expect("valid tool");
540        let identifier = ExternalIdentifier::new(
541            IdentifierScheme::new("com.example.worker").expect("valid scheme"),
542            "worker-42",
543            None,
544        )
545        .expect("valid identifier");
546        let agent = AgentIdentity::new(Some("Render worker".to_owned()), Some(identifier.clone()))
547            .expect("valid agent");
548
549        assert_eq!(tool.name(), "FFmpeg");
550        assert_eq!(tool.version(), Some("8.0-custom"));
551        assert_eq!(tool.uri(), Some("https://ffmpeg.org/"));
552        assert_eq!(agent.name(), Some("Render worker"));
553        assert_eq!(agent.identifier(), Some(&identifier));
554    }
555
556    #[test]
557    fn participant_identity_is_bounded() {
558        assert!(ToolIdentity::new("", None, None).is_err());
559        assert!(ToolIdentity::new("tool", Some(String::new()), None).is_err());
560        assert!(ToolIdentity::new("tool", None, Some("relative".to_owned())).is_err());
561        let oversized_uri = format!(
562            "https://example.com/{}",
563            "x".repeat(MAX_PROVENANCE_URI_BYTES)
564        );
565        assert!(ToolIdentity::new("tool", None, Some(oversized_uri)).is_err());
566        assert!(AgentIdentity::new(None, None).is_err());
567        assert!(AgentIdentity::new(Some("bad\0name".to_owned()), None).is_err());
568    }
569
570    #[test]
571    fn activity_supports_canonical_fan_in_and_fan_out() {
572        let first_input = RepresentationId::from_bytes([2; 16]);
573        let second_input = RepresentationId::from_bytes([1; 16]);
574        let first_output = RepresentationId::from_bytes([4; 16]);
575        let second_output = RepresentationId::from_bytes([3; 16]);
576        let activity = Activity::new(
577            ActivityId::new(),
578            ActivityKind::new("org.postproject:transcode").expect("valid kind"),
579            vec![
580                ActivityInput::new(first_input, None),
581                ActivityInput::new(second_input, None),
582            ],
583            vec![
584                ActivityOutput::new(first_output, None),
585                ActivityOutput::new(second_output, None),
586            ],
587        )
588        .expect("valid activity")
589        .with_timing(
590            Some(Timestamp::from_unix_micros(10)),
591            Some(Timestamp::from_unix_micros(20)),
592        )
593        .expect("valid timing");
594
595        assert_eq!(activity.inputs()[0].representation_id(), second_input);
596        assert_eq!(activity.inputs()[1].representation_id(), first_input);
597        assert_eq!(activity.outputs()[0].representation_id(), second_output);
598        assert_eq!(activity.outputs()[1].representation_id(), first_output);
599    }
600
601    #[test]
602    fn activity_rejects_incomplete_or_ambiguous_graph_facts() {
603        let representation = RepresentationId::new();
604        let kind = || ActivityKind::new("org.postproject:vfx-render").expect("valid kind");
605        let input = || ActivityInput::new(representation, None);
606        let output = || ActivityOutput::new(representation, None);
607
608        let no_outputs = Activity::new(ActivityId::new(), kind(), vec![input()], Vec::new());
609        assert!(no_outputs.is_err());
610
611        let duplicate = Activity::new(
612            ActivityId::new(),
613            kind(),
614            Vec::new(),
615            vec![output(), output()],
616        );
617        assert!(duplicate.is_err());
618
619        let self_edge = Activity::new(ActivityId::new(), kind(), vec![input()], vec![output()]);
620        assert!(self_edge.is_err());
621
622        let reversed_time = Activity::new(
623            ActivityId::new(),
624            kind(),
625            Vec::new(),
626            vec![ActivityOutput::new(RepresentationId::new(), None)],
627        )
628        .expect("valid activity")
629        .with_timing(
630            Some(Timestamp::from_unix_micros(2)),
631            Some(Timestamp::from_unix_micros(1)),
632        );
633        assert!(reversed_time.is_err());
634    }
635}