Skip to main content

postproject_core/
dependency.rs

1//! Live relationships observed from representation content.
2
3use crate::{AssetId, Error, ErrorKind, RepresentationId, ResourceId, Result};
4
5/// Maximum encoded length of an open-world dependency-kind identifier.
6pub const MAX_DEPENDENCY_KIND_BYTES: usize = 128;
7/// Maximum UTF-8 byte length of an authored reference.
8pub const MAX_AUTHORED_REFERENCE_BYTES: usize = 4_096;
9/// Maximum number of edges in one observed dependency set.
10pub const MAX_DEPENDENCIES_PER_SET: usize = 100_000;
11
12/// An open-world, namespaced dependency kind.
13#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
14pub struct DependencyKind(String);
15
16impl DependencyKind {
17    /// Creates a kind such as `org.openusd:reference`.
18    ///
19    /// # Errors
20    ///
21    /// Returns an invalid-argument error when the value is not a bounded,
22    /// namespaced ASCII identifier.
23    pub fn new(value: impl Into<String>) -> Result<Self> {
24        let value = value.into();
25        let valid_bytes = value
26            .bytes()
27            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'.' | b'_' | b'-' | b':'));
28        let valid_namespace = value
29            .split_once(':')
30            .is_some_and(|(namespace, local)| !namespace.is_empty() && !local.is_empty());
31        if value.len() > MAX_DEPENDENCY_KIND_BYTES || !valid_bytes || !valid_namespace {
32            return Err(Error::new(
33                ErrorKind::InvalidArgument,
34                format!(
35                    "dependency kind must be a namespaced identifier of at most {MAX_DEPENDENCY_KIND_BYTES} ASCII bytes"
36                ),
37            ));
38        }
39        Ok(Self(value))
40    }
41
42    /// Returns the exact kind identifier.
43    #[must_use]
44    pub fn as_str(&self) -> &str {
45        &self.0
46    }
47}
48
49/// The production object named by an authored dependency.
50#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
51#[non_exhaustive]
52pub enum DependencyTarget {
53    /// A floating reference to an asset.
54    Asset(AssetId),
55    /// A reference pinned to one representation.
56    Representation(RepresentationId),
57}
58
59/// One object reached by a bounded dependency or dependent query.
60#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
61pub struct DependencyQueryMatch {
62    target: DependencyTarget,
63    depth: u32,
64}
65
66impl DependencyQueryMatch {
67    /// Constructs one backend-derived query match.
68    #[doc(hidden)]
69    #[must_use]
70    pub const fn new(target: DependencyTarget, depth: u32) -> Self {
71        Self { target, depth }
72    }
73
74    /// Returns the matching asset or representation.
75    #[must_use]
76    pub const fn target(self) -> DependencyTarget {
77        self.target
78    }
79
80    /// Returns the shortest number of dependency edges from the query root.
81    #[must_use]
82    pub const fn depth(self) -> u32 {
83        self.depth
84    }
85}
86
87/// One typed dependency occurrence in a representation's observed set.
88#[derive(Clone, Debug, Eq, PartialEq)]
89pub struct Dependency {
90    source_resource_id: Option<ResourceId>,
91    kind: DependencyKind,
92    target: DependencyTarget,
93    resolved_representation_id: Option<RepresentationId>,
94    required: bool,
95    authored_reference: String,
96}
97
98impl Dependency {
99    /// Creates one dependency occurrence.
100    ///
101    /// The authored reference is preserved exactly and may be empty when the
102    /// source format permits an implicit reference. A resolved representation
103    /// applies only to a floating asset target; a representation target is
104    /// already pinned.
105    ///
106    /// # Errors
107    ///
108    /// Returns an invalid-argument error for oversized or NUL-containing
109    /// reference text, or a resolved representation on a pinned target.
110    pub fn new(
111        source_resource_id: Option<ResourceId>,
112        kind: DependencyKind,
113        target: DependencyTarget,
114        resolved_representation_id: Option<RepresentationId>,
115        required: bool,
116        authored_reference: impl Into<String>,
117    ) -> Result<Self> {
118        let authored_reference = authored_reference.into();
119        if authored_reference.len() > MAX_AUTHORED_REFERENCE_BYTES
120            || authored_reference.contains('\0')
121        {
122            return Err(Error::new(
123                ErrorKind::InvalidArgument,
124                format!(
125                    "authored dependency reference must not contain NUL or exceed {MAX_AUTHORED_REFERENCE_BYTES} UTF-8 bytes"
126                ),
127            ));
128        }
129        if matches!(target, DependencyTarget::Representation(_))
130            && resolved_representation_id.is_some()
131        {
132            return Err(Error::new(
133                ErrorKind::InvalidArgument,
134                "a pinned dependency target must not have a separate resolved representation",
135            ));
136        }
137        Ok(Self {
138            source_resource_id,
139            kind,
140            target,
141            resolved_representation_id,
142            required,
143            authored_reference,
144        })
145    }
146
147    /// Returns the resource that contains this reference, when known.
148    #[must_use]
149    pub const fn source_resource_id(&self) -> Option<ResourceId> {
150        self.source_resource_id
151    }
152
153    /// Returns the exact open-world relationship kind.
154    #[must_use]
155    pub const fn kind(&self) -> &DependencyKind {
156        &self.kind
157    }
158
159    /// Returns the floating or pinned target.
160    #[must_use]
161    pub const fn target(&self) -> DependencyTarget {
162        self.target
163    }
164
165    /// Returns the representation selected for a floating asset target.
166    #[must_use]
167    pub const fn resolved_representation_id(&self) -> Option<RepresentationId> {
168        self.resolved_representation_id
169    }
170
171    /// Returns whether the target is needed whenever the source is used.
172    #[must_use]
173    pub const fn is_required(&self) -> bool {
174        self.required
175    }
176
177    /// Returns the reference text exactly as supplied by the caller.
178    #[must_use]
179    pub fn authored_reference(&self) -> &str {
180        &self.authored_reference
181    }
182}
183
184/// Whether an observed dependency set still describes its source content.
185#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
186#[non_exhaustive]
187pub enum DependencySetStatus {
188    /// The set was recorded for the source's current content observation.
189    Current,
190    /// The source changed and its set must be extracted again.
191    NeedsExtraction,
192}
193
194/// One complete ordered observation of a representation's dependencies.
195#[derive(Clone, Debug, Eq, PartialEq)]
196pub struct DependencySet {
197    source_representation_id: RepresentationId,
198    recorded_at_revision: u64,
199    status: DependencySetStatus,
200    dependencies: Vec<Dependency>,
201}
202
203impl DependencySet {
204    /// Reconstructs a bounded dependency-set observation.
205    ///
206    /// # Errors
207    ///
208    /// Returns an invalid-argument error for revision zero or too many edges.
209    pub fn new(
210        source_representation_id: RepresentationId,
211        recorded_at_revision: u64,
212        status: DependencySetStatus,
213        dependencies: Vec<Dependency>,
214    ) -> Result<Self> {
215        if recorded_at_revision == 0 {
216            return Err(Error::new(
217                ErrorKind::InvalidArgument,
218                "dependency-set revision must be greater than zero",
219            ));
220        }
221        if dependencies.len() > MAX_DEPENDENCIES_PER_SET {
222            return Err(Error::new(
223                ErrorKind::InvalidArgument,
224                format!("dependency set must contain at most {MAX_DEPENDENCIES_PER_SET} edges"),
225            ));
226        }
227        Ok(Self {
228            source_representation_id,
229            recorded_at_revision,
230            status,
231            dependencies,
232        })
233    }
234
235    /// Returns the representation whose content supplied the set.
236    #[must_use]
237    pub const fn source_representation_id(&self) -> RepresentationId {
238        self.source_representation_id
239    }
240
241    /// Returns the revision that committed this complete set.
242    #[must_use]
243    pub const fn recorded_at_revision(&self) -> u64 {
244        self.recorded_at_revision
245    }
246
247    /// Returns whether the set needs extraction after a source change.
248    #[must_use]
249    pub const fn status(&self) -> DependencySetStatus {
250        self.status
251    }
252
253    /// Returns dependency occurrences in authored order.
254    #[must_use]
255    pub fn dependencies(&self) -> &[Dependency] {
256        &self.dependencies
257    }
258}
259
260#[cfg(test)]
261mod tests {
262    use super::*;
263
264    #[test]
265    fn dependency_kinds_are_open_world_namespaced_text() {
266        assert!(DependencyKind::new("org.openusd:reference").is_ok());
267        assert!(DependencyKind::new("studio.example:custom_link").is_ok());
268        assert!(DependencyKind::new("reference").is_err());
269    }
270
271    #[test]
272    fn authored_reference_is_exact_and_pinned_targets_are_unambiguous() {
273        let target = RepresentationId::from_bytes([2; 16]);
274        let dependency = Dependency::new(
275            None,
276            DependencyKind::new("org.openusd:reference").expect("kind"),
277            DependencyTarget::Representation(target),
278            None,
279            true,
280            "  ../Character.usd  ",
281        )
282        .expect("dependency");
283        assert_eq!(dependency.authored_reference(), "  ../Character.usd  ");
284        assert!(
285            Dependency::new(
286                None,
287                DependencyKind::new("org.openusd:reference").expect("kind"),
288                DependencyTarget::Representation(target),
289                Some(target),
290                true,
291                "Character.usd",
292            )
293            .is_err()
294        );
295    }
296
297    #[test]
298    fn dependency_sets_preserve_repeated_authored_order() {
299        let edge = Dependency::new(
300            None,
301            DependencyKind::new("org.postproject:requires").expect("kind"),
302            DependencyTarget::Asset(AssetId::from_bytes([3; 16])),
303            Some(RepresentationId::from_bytes([4; 16])),
304            true,
305            "asset://character",
306        )
307        .expect("dependency");
308        let set = DependencySet::new(
309            RepresentationId::from_bytes([1; 16]),
310            7,
311            DependencySetStatus::Current,
312            vec![edge.clone(), edge],
313        )
314        .expect("set");
315        assert_eq!(set.dependencies().len(), 2);
316    }
317}