Skip to main content

postproject_core/
query.rs

1//! Bounded keyset pagination shared by named domain queries.
2
3use crate::{
4    ActivityKind, ArtifactEvaluationLimits, Error, ErrorKind, MetadataProperty, MetadataValue,
5    MetadataValueKind, RepresentationId, Result, ToolIdentity,
6};
7
8/// Maximum number of values returned by one query page.
9pub const MAX_QUERY_PAGE_SIZE: u32 = 1_000;
10/// Maximum encoded size of an opaque continuation cursor.
11pub const MAX_QUERY_CURSOR_BYTES: usize = 2_048;
12/// Maximum depth accepted by a dependency traversal query.
13pub const MAX_DEPENDENCY_QUERY_DEPTH: u32 = 64;
14/// Maximum representations visited by a dependency traversal query.
15pub const MAX_DEPENDENCY_QUERY_REPRESENTATIONS: u32 = 1_000;
16/// Maximum depth accepted by a provenance traversal query.
17pub const MAX_PROVENANCE_QUERY_DEPTH: u32 = 64;
18/// Maximum representations visited by a provenance traversal query.
19pub const MAX_PROVENANCE_QUERY_REPRESENTATIONS: u32 = 1_000;
20
21/// Opaque, query-scoped keyset continuation token.
22#[derive(Clone, Debug, Eq, Hash, PartialEq)]
23pub struct QueryCursor(String);
24
25impl QueryCursor {
26    /// Copies a cursor returned by an earlier page.
27    ///
28    /// # Errors
29    ///
30    /// Returns an invalid-argument error for an empty, oversized, or
31    /// NUL-containing token.
32    pub fn new(token: impl Into<String>) -> Result<Self> {
33        let token = token.into();
34        if token.is_empty() || token.len() > MAX_QUERY_CURSOR_BYTES || token.contains('\0') {
35            return Err(Error::new(
36                ErrorKind::InvalidArgument,
37                format!(
38                    "query cursor must contain 1-{MAX_QUERY_CURSOR_BYTES} UTF-8 bytes without NUL"
39                ),
40            ));
41        }
42        Ok(Self(token))
43    }
44
45    /// Returns the opaque token for copying to the next request.
46    #[must_use]
47    pub fn as_str(&self) -> &str {
48        &self.0
49    }
50}
51
52/// Page size and optional continuation supplied to a named query.
53#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct QueryPageRequest {
55    limit: u32,
56    cursor: Option<QueryCursor>,
57}
58
59impl QueryPageRequest {
60    /// Creates a bounded page request.
61    ///
62    /// # Errors
63    ///
64    /// Returns an invalid-argument error when `limit` is zero or greater than
65    /// [`MAX_QUERY_PAGE_SIZE`].
66    pub fn new(limit: u32, cursor: Option<QueryCursor>) -> Result<Self> {
67        if limit == 0 || limit > MAX_QUERY_PAGE_SIZE {
68            return Err(Error::new(
69                ErrorKind::InvalidArgument,
70                format!("query page size must be between 1 and {MAX_QUERY_PAGE_SIZE}"),
71            ));
72        }
73        Ok(Self { limit, cursor })
74    }
75
76    /// Returns the maximum number of values in the page.
77    #[must_use]
78    pub const fn limit(&self) -> u32 {
79        self.limit
80    }
81
82    /// Returns the preceding page's continuation token, when present.
83    #[must_use]
84    pub const fn cursor(&self) -> Option<&QueryCursor> {
85        self.cursor.as_ref()
86    }
87}
88
89/// One bounded page returned by a named domain query.
90#[derive(Clone, Debug, Eq, PartialEq)]
91pub struct QueryPage<T> {
92    items: Vec<T>,
93    next_cursor: Option<QueryCursor>,
94    traversal_truncated: bool,
95}
96
97impl<T> QueryPage<T> {
98    /// Constructs a backend query page.
99    #[doc(hidden)]
100    #[must_use]
101    pub fn new(items: Vec<T>, next_cursor: Option<QueryCursor>, traversal_truncated: bool) -> Self {
102        Self {
103            items,
104            next_cursor,
105            traversal_truncated,
106        }
107    }
108
109    /// Returns the values in stable key order.
110    #[must_use]
111    pub fn items(&self) -> &[T] {
112        &self.items
113    }
114
115    /// Returns the token for the next page, when another page exists.
116    #[must_use]
117    pub const fn next_cursor(&self) -> Option<&QueryCursor> {
118        self.next_cursor.as_ref()
119    }
120
121    /// Returns whether an explicit traversal bound made the result incomplete.
122    #[must_use]
123    pub const fn traversal_truncated(&self) -> bool {
124        self.traversal_truncated
125    }
126
127    /// Consumes the page and returns its values.
128    #[must_use]
129    pub fn into_items(self) -> Vec<T> {
130        self.items
131    }
132}
133
134/// Bounds for a direct or transitive dependency query.
135#[derive(Clone, Copy, Debug, Eq, PartialEq)]
136pub struct DependencyQueryLimits {
137    max_depth: u32,
138    max_representations: u32,
139}
140
141impl DependencyQueryLimits {
142    /// Creates explicit graph-traversal bounds.
143    ///
144    /// # Errors
145    ///
146    /// Returns an invalid-argument error when either bound is zero or exceeds
147    /// its documented maximum.
148    pub fn new(max_depth: u32, max_representations: u32) -> Result<Self> {
149        if max_depth == 0 || max_depth > MAX_DEPENDENCY_QUERY_DEPTH {
150            return Err(Error::new(
151                ErrorKind::InvalidArgument,
152                format!(
153                    "dependency query depth must be between 1 and {MAX_DEPENDENCY_QUERY_DEPTH}"
154                ),
155            ));
156        }
157        if max_representations == 0 || max_representations > MAX_DEPENDENCY_QUERY_REPRESENTATIONS {
158            return Err(Error::new(
159                ErrorKind::InvalidArgument,
160                format!(
161                    "dependency query representation bound must be between 1 and {MAX_DEPENDENCY_QUERY_REPRESENTATIONS}"
162                ),
163            ));
164        }
165        Ok(Self {
166            max_depth,
167            max_representations,
168        })
169    }
170
171    /// Returns the maximum number of dependency edges followed in one path.
172    #[must_use]
173    pub const fn max_depth(self) -> u32 {
174        self.max_depth
175    }
176
177    /// Returns the maximum number of representations traversed.
178    #[must_use]
179    pub const fn max_representations(self) -> u32 {
180        self.max_representations
181    }
182}
183
184/// Optional exact scalar predicate for a metadata-property query.
185#[derive(Clone, Debug, Eq, PartialEq)]
186pub struct MetadataQuery {
187    property: MetadataProperty,
188    exact_value: Option<MetadataValue>,
189}
190
191impl MetadataQuery {
192    /// Creates a property query with an optional exact scalar value.
193    ///
194    /// # Errors
195    ///
196    /// Returns an invalid-argument error when the predicate is a collection.
197    pub fn new(property: MetadataProperty, exact_value: Option<MetadataValue>) -> Result<Self> {
198        if exact_value.as_ref().is_some_and(|value| {
199            matches!(
200                value.kind(),
201                MetadataValueKind::List | MetadataValueKind::Struct
202            )
203        }) {
204            return Err(Error::new(
205                ErrorKind::InvalidArgument,
206                "metadata query exact-value predicates must be scalar",
207            ));
208        }
209        Ok(Self {
210            property,
211            exact_value,
212        })
213    }
214
215    /// Returns the required metadata property.
216    #[must_use]
217    pub const fn property(&self) -> &MetadataProperty {
218        &self.property
219    }
220
221    /// Returns the optional exact scalar value.
222    #[must_use]
223    pub const fn exact_value(&self) -> Option<&MetadataValue> {
224        self.exact_value.as_ref()
225    }
226}
227
228/// Filter selecting activity outputs by exact activity or tool identity.
229#[derive(Clone, Debug, Eq, PartialEq)]
230#[non_exhaustive]
231pub enum ActivityOutputQuery {
232    /// Outputs produced by one open-world activity kind.
233    Kind(ActivityKind),
234    /// Outputs produced by one exact tool identity.
235    Tool(ToolIdentity),
236}
237
238/// Bounds for a provenance ancestor or descendant query.
239#[derive(Clone, Copy, Debug, Eq, PartialEq)]
240pub struct ProvenanceQueryLimits {
241    max_depth: u32,
242    max_representations: u32,
243}
244
245impl ProvenanceQueryLimits {
246    /// Creates explicit provenance traversal bounds.
247    ///
248    /// # Errors
249    ///
250    /// Returns an invalid-argument error when either bound is zero or exceeds
251    /// its documented maximum.
252    pub fn new(max_depth: u32, max_representations: u32) -> Result<Self> {
253        if max_depth == 0 || max_depth > MAX_PROVENANCE_QUERY_DEPTH {
254            return Err(Error::new(
255                ErrorKind::InvalidArgument,
256                format!(
257                    "provenance query depth must be between 1 and {MAX_PROVENANCE_QUERY_DEPTH}"
258                ),
259            ));
260        }
261        if max_representations == 0 || max_representations > MAX_PROVENANCE_QUERY_REPRESENTATIONS {
262            return Err(Error::new(
263                ErrorKind::InvalidArgument,
264                format!(
265                    "provenance query representation bound must be between 1 and {MAX_PROVENANCE_QUERY_REPRESENTATIONS}"
266                ),
267            ));
268        }
269        Ok(Self {
270            max_depth,
271            max_representations,
272        })
273    }
274
275    /// Returns the maximum number of activity edges followed in one path.
276    #[must_use]
277    pub const fn max_depth(self) -> u32 {
278        self.max_depth
279    }
280
281    /// Returns the maximum number of representations visited.
282    #[must_use]
283    pub const fn max_representations(self) -> u32 {
284        self.max_representations
285    }
286}
287
288/// One representation reached by a provenance traversal.
289#[derive(Clone, Copy, Debug, Eq, PartialEq)]
290pub struct ProvenanceQueryMatch {
291    representation_id: RepresentationId,
292    depth: u32,
293}
294
295impl ProvenanceQueryMatch {
296    /// Creates one shortest-depth provenance result.
297    #[doc(hidden)]
298    #[must_use]
299    pub const fn new(representation_id: RepresentationId, depth: u32) -> Self {
300        Self {
301            representation_id,
302            depth,
303        }
304    }
305
306    /// Returns the reached representation.
307    #[must_use]
308    pub const fn representation_id(self) -> RepresentationId {
309        self.representation_id
310    }
311
312    /// Returns the shortest number of provenance steps from the query root.
313    #[must_use]
314    pub const fn depth(self) -> u32 {
315        self.depth
316    }
317}
318
319/// Filters a paginated stale-artifact query.
320#[derive(Clone, Copy, Debug, Eq, PartialEq)]
321pub struct StaleArtifactQuery {
322    source: Option<RepresentationId>,
323    evaluation_limits: ArtifactEvaluationLimits,
324}
325
326impl StaleArtifactQuery {
327    /// Creates a stale-artifact query, optionally restricted to descendants.
328    #[must_use]
329    pub const fn new(
330        source: Option<RepresentationId>,
331        evaluation_limits: ArtifactEvaluationLimits,
332    ) -> Self {
333        Self {
334            source,
335            evaluation_limits,
336        }
337    }
338
339    /// Returns the optional provenance source restriction.
340    #[must_use]
341    pub const fn source(self) -> Option<RepresentationId> {
342        self.source
343    }
344
345    /// Returns the bounds used to evaluate each candidate artifact.
346    #[must_use]
347    pub const fn evaluation_limits(self) -> ArtifactEvaluationLimits {
348        self.evaluation_limits
349    }
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    #[test]
357    fn page_requests_and_cursors_are_bounded() {
358        assert!(QueryPageRequest::new(1, None).is_ok());
359        assert!(QueryPageRequest::new(MAX_QUERY_PAGE_SIZE, None).is_ok());
360        assert!(QueryPageRequest::new(0, None).is_err());
361        assert!(QueryPageRequest::new(MAX_QUERY_PAGE_SIZE + 1, None).is_err());
362        assert!(QueryCursor::new("").is_err());
363        assert!(QueryCursor::new("x".repeat(MAX_QUERY_CURSOR_BYTES + 1)).is_err());
364    }
365
366    #[test]
367    fn dependency_query_limits_are_explicit() {
368        assert!(DependencyQueryLimits::new(1, 1).is_ok());
369        assert!(
370            DependencyQueryLimits::new(
371                MAX_DEPENDENCY_QUERY_DEPTH,
372                MAX_DEPENDENCY_QUERY_REPRESENTATIONS,
373            )
374            .is_ok()
375        );
376        assert!(DependencyQueryLimits::new(0, 1).is_err());
377        assert!(DependencyQueryLimits::new(1, 0).is_err());
378    }
379
380    #[test]
381    fn metadata_predicates_are_scalar() {
382        let property = MetadataProperty::new(
383            crate::VocabularyId::new("test").expect("vocabulary"),
384            crate::PropertyId::new("value").expect("property"),
385        );
386        assert!(MetadataQuery::new(property.clone(), Some(MetadataValue::i64(3))).is_ok());
387        assert!(
388            MetadataQuery::new(
389                property,
390                Some(MetadataValue::list(vec![MetadataValue::i64(3)]).expect("list")),
391            )
392            .is_err()
393        );
394    }
395
396    #[test]
397    fn provenance_query_limits_are_explicit() {
398        assert!(ProvenanceQueryLimits::new(1, 1).is_ok());
399        assert!(ProvenanceQueryLimits::new(0, 1).is_err());
400        assert!(ProvenanceQueryLimits::new(1, 0).is_err());
401    }
402}