Skip to main content

code_system_graph_core/
incremental.rs

1use code_system_graph_model::{
2    ArtifactChange, ArtifactChangeKind, ArtifactFingerprint, CheckoutId, NativePath, RepoId
3};
4
5type ArtifactKey<'a> = (&'a RepoId, &'a CheckoutId, &'a NativePath, &'a str);
6
7/// Deterministic incremental plan for extractor-relevant artifacts.
8///
9/// Only artifacts that require extraction or deletion are listed; every current artifact absent
10/// from [`Self::changes`] is unchanged.
11#[derive(Debug, Clone, PartialEq, Eq)]
12pub struct IncrementalPlan {
13    /// Changes sorted by repository, checkout, path, and extractor.
14    pub changes: Vec<ArtifactChange>,
15}
16
17impl IncrementalPlan {
18    /// Returns whether any artifact requires add, modify, or delete processing.
19    #[must_use]
20    pub fn has_changes(&self) -> bool {
21        !self.changes.is_empty()
22    }
23
24    /// Returns the number of artifacts requiring extractor or deletion work.
25    #[must_use]
26    pub fn changed_count(&self) -> usize {
27        self.changes.len()
28    }
29}
30
31/// Compares current artifact fingerprints with the previous published snapshot.
32#[must_use]
33pub fn plan_incremental_scan(
34    previous: &[ArtifactFingerprint],
35    current: &[ArtifactFingerprint],
36) -> IncrementalPlan {
37    let previous = fingerprint_map(previous);
38    let current = fingerprint_map(current);
39    let added_or_modified = current.iter().filter_map(|(key, after)| {
40        let kind = match previous.get(key) {
41            None => ArtifactChangeKind::Added,
42            Some(before) if before.content_hash != after.content_hash => {
43                ArtifactChangeKind::Modified
44            }
45            Some(_) => return None,
46        };
47        Some((*key, kind))
48    });
49    let deleted = previous
50        .keys()
51        .filter(|key| !current.contains_key(*key))
52        .map(|key| (*key, ArtifactChangeKind::Deleted));
53    let mut changes = added_or_modified
54        .chain(deleted)
55        .map(|(key, kind)| ArtifactChange {
56            repo_id: key.0.clone(),
57            checkout_id: key.1.clone(),
58            path: key.2.clone(),
59            extractor: key.3.to_owned(),
60            kind,
61        })
62        .collect::<Vec<_>>();
63    changes.sort_by(|left, right| {
64        (
65            &left.repo_id,
66            &left.checkout_id,
67            &left.path,
68            &left.extractor,
69        )
70            .cmp(&(
71                &right.repo_id,
72                &right.checkout_id,
73                &right.path,
74                &right.extractor,
75            ))
76    });
77    IncrementalPlan { changes }
78}
79
80fn fingerprint_map(
81    fingerprints: &[ArtifactFingerprint],
82) -> foldhash::HashMap<ArtifactKey<'_>, &ArtifactFingerprint> {
83    fingerprints
84        .iter()
85        .map(|fingerprint| {
86            (
87                (
88                    &fingerprint.repo_id,
89                    &fingerprint.checkout_id,
90                    &fingerprint.path,
91                    fingerprint.extractor.as_str(),
92                ),
93                fingerprint,
94            )
95        })
96        .collect()
97}
98
99#[cfg(test)]
100mod tests {
101    use code_system_graph_model::{
102        ArtifactChangeKind, ArtifactFingerprint, CheckoutId, NativePath, NativePathEncoding, RepoId
103    };
104
105    use super::plan_incremental_scan;
106
107    fn fingerprint(path: &str, hash: &str) -> ArtifactFingerprint {
108        ArtifactFingerprint {
109            repo_id: RepoId::new("repo:api"),
110            checkout_id: CheckoutId::new("checkout:api"),
111            path: NativePath {
112                encoding: NativePathEncoding::Utf8,
113                bytes: path.as_bytes().to_vec(),
114                display: path.to_owned(),
115            },
116            extractor: "openapi".to_owned(),
117            content_hash: hash.to_owned(),
118            size_bytes: 1,
119        }
120    }
121
122    #[test]
123    fn plan_should_list_only_added_deleted_and_modified_artifacts_in_key_order() {
124        let previous = vec![
125            fingerprint("deleted.yaml", "a"),
126            fingerprint("modified.yaml", "a"),
127            fingerprint("same.yaml", "a"),
128        ];
129        let current = vec![
130            fingerprint("added.yaml", "a"),
131            fingerprint("modified.yaml", "b"),
132            fingerprint("same.yaml", "a"),
133        ];
134
135        let plan = plan_incremental_scan(&previous, &current);
136        let changes = plan
137            .changes
138            .iter()
139            .map(|change| (change.path.display.as_str(), change.kind))
140            .collect::<Vec<_>>();
141
142        assert_eq!(
143            changes,
144            vec![
145                ("added.yaml", ArtifactChangeKind::Added),
146                ("deleted.yaml", ArtifactChangeKind::Deleted),
147                ("modified.yaml", ArtifactChangeKind::Modified),
148            ]
149        );
150        assert_eq!(plan.changed_count(), 3);
151    }
152
153    #[test]
154    fn plan_should_report_no_changes_for_identical_artifact_sets() {
155        let fingerprints = vec![fingerprint("same.yaml", "a")];
156
157        let plan = plan_incremental_scan(&fingerprints, &fingerprints);
158
159        assert!(!plan.has_changes());
160    }
161}