1use std::collections::BTreeSet;
4
5use crate::{
6 ActivityId, Error, ErrorKind, ExternalIdentifier, FingerprintSnapshot, RepresentationId,
7 Result, Timestamp, uri::normalize_uri,
8};
9
10pub const MAX_ACTIVITY_KIND_BYTES: usize = 128;
12pub const MAX_ACTIVITY_ROLE_BYTES: usize = 128;
14pub const MAX_PROVENANCE_NAME_BYTES: usize = 256;
16pub const MAX_TOOL_VERSION_BYTES: usize = 128;
18pub const MAX_PROVENANCE_URI_BYTES: usize = 4_096;
20pub const MAX_ACTIVITY_EDGES: usize = 100_000;
22
23#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
25pub struct ActivityKind(String);
26
27impl ActivityKind {
28 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 #[must_use]
41 pub fn as_str(&self) -> &str {
42 &self.0
43 }
44}
45
46#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
48pub struct ActivityRole(String);
49
50impl ActivityRole {
51 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 #[must_use]
64 pub fn as_str(&self) -> &str {
65 &self.0
66 }
67}
68
69#[derive(Clone, Debug, Eq, PartialEq)]
71pub struct ToolIdentity {
72 name: String,
73 version: Option<String>,
74 uri: Option<String>,
75}
76
77impl ToolIdentity {
78 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 #[must_use]
109 pub fn name(&self) -> &str {
110 &self.name
111 }
112
113 #[must_use]
115 pub fn version(&self) -> Option<&str> {
116 self.version.as_deref()
117 }
118
119 #[must_use]
121 pub fn uri(&self) -> Option<&str> {
122 self.uri.as_deref()
123 }
124}
125
126#[derive(Clone, Debug, Eq, PartialEq)]
128pub struct AgentIdentity {
129 name: Option<String>,
130 identifier: Option<ExternalIdentifier>,
131}
132
133#[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 #[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 #[must_use]
160 pub const fn representation_id(&self) -> RepresentationId {
161 self.representation_id
162 }
163
164 #[must_use]
166 pub const fn role(&self) -> Option<&ActivityRole> {
167 self.role.as_ref()
168 }
169
170 #[must_use]
172 pub const fn snapshot(&self) -> Option<&ActivityEdgeSnapshot> {
173 self.snapshot.as_ref()
174 }
175
176 #[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#[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 #[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 #[must_use]
209 pub const fn representation_id(&self) -> RepresentationId {
210 self.representation_id
211 }
212
213 #[must_use]
215 pub const fn role(&self) -> Option<&ActivityRole> {
216 self.role.as_ref()
217 }
218
219 #[must_use]
221 pub const fn snapshot(&self) -> Option<&ActivityEdgeSnapshot> {
222 self.snapshot.as_ref()
223 }
224
225 #[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#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
236pub struct ActivityEdgeSnapshot {
237 revision_sequence: u64,
238 fingerprints: Vec<FingerprintSnapshot>,
239}
240
241impl ActivityEdgeSnapshot {
242 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 #[must_use]
276 pub const fn revision_sequence(&self) -> u64 {
277 self.revision_sequence
278 }
279
280 #[must_use]
282 pub fn fingerprints(&self) -> &[FingerprintSnapshot] {
283 &self.fingerprints
284 }
285}
286
287#[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 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 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 #[must_use]
385 pub fn with_tool(mut self, tool: ToolIdentity) -> Self {
386 self.tool = Some(tool);
387 self
388 }
389
390 #[must_use]
392 pub fn with_agent(mut self, agent: AgentIdentity) -> Self {
393 self.agent = Some(agent);
394 self
395 }
396
397 #[must_use]
399 pub const fn id(&self) -> ActivityId {
400 self.id
401 }
402
403 #[must_use]
405 pub const fn kind(&self) -> &ActivityKind {
406 &self.kind
407 }
408
409 #[must_use]
411 pub const fn started_at(&self) -> Option<Timestamp> {
412 self.started_at
413 }
414
415 #[must_use]
417 pub const fn finished_at(&self) -> Option<Timestamp> {
418 self.finished_at
419 }
420
421 #[must_use]
423 pub const fn tool(&self) -> Option<&ToolIdentity> {
424 self.tool.as_ref()
425 }
426
427 #[must_use]
429 pub const fn agent(&self) -> Option<&AgentIdentity> {
430 self.agent.as_ref()
431 }
432
433 #[must_use]
435 pub fn inputs(&self) -> &[ActivityInput] {
436 &self.inputs
437 }
438
439 #[must_use]
441 pub fn outputs(&self) -> &[ActivityOutput] {
442 &self.outputs
443 }
444}
445
446impl AgentIdentity {
447 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 #[must_use]
468 pub fn name(&self) -> Option<&str> {
469 self.name.as_deref()
470 }
471
472 #[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}