swls_core/revisions.rs
1//! Change tracking for data shared by all documents.
2//!
3//! Most derived data belongs to one document and is recomputed when that
4//! document's triples change (`Changed<Triples>`). Some data is shared:
5//! ontologies loaded in the background, the class hierarchy, SHACL shapes,
6//! configured sources. It usually arrives *after* the documents that use it
7//! were opened, and a change to it can affect every open document.
8//!
9//! [`Revisions`] counts changes to each kind of shared data:
10//!
11//! - **producers** bump a counter when (and only when) their data changed,
12//! - **consumers** remember the revision they last processed in a
13//! `Local<Seen>`; when it moved they process every open document, otherwise
14//! only documents whose own triples changed.
15//!
16//! ```ignore
17//! fn consumer(
18//! docs: Query<(Ref<Triples>, …), With<Open>>,
19//! revisions: Res<Revisions>,
20//! mut seen: Local<Seen>,
21//! ) {
22//! let all = seen.update(revisions.shapes);
23//! for (triples, …) in &docs {
24//! if !all && !triples.is_changed() { continue; }
25//! …
26//! }
27//! }
28//! ```
29
30use bevy_ecs::prelude::*;
31
32/// Revision counters of data shared by all documents. See the module docs.
33#[derive(Resource, Debug, Default, Clone, Copy, PartialEq, Eq)]
34pub struct Revisions {
35 /// Triples in the shared store (background documents) changed.
36 pub store: u64,
37 /// Known classes and properties ([`Ontologies`](crate::prelude::Ontologies)) changed.
38 pub ontologies: u64,
39 /// The class hierarchy ([`TypeHierarchy`](crate::prelude::TypeHierarchy)) changed.
40 pub hierarchy: u64,
41 /// SHACL shapes were added, changed or removed.
42 pub shapes: u64,
43 /// Configured ontology sources were added.
44 pub sources: u64,
45}
46
47/// The revision a consumer last processed. Use as `Local<Seen>`, one per
48/// counter the system depends on.
49#[derive(Debug, Default)]
50pub struct Seen(Option<u64>);
51
52impl Seen {
53 /// Whether `revision` is new to this consumer, and remember it.
54 ///
55 /// The first call returns `true` only when something already changed
56 /// (`revision > 0`), so a consumer does not redo all documents at startup.
57 pub fn update(&mut self, revision: u64) -> bool {
58 let new = self.0.map_or(revision > 0, |seen| seen != revision);
59 self.0 = Some(revision);
60 new
61 }
62}
63
64#[cfg(test)]
65mod tests {
66 use super::*;
67
68 #[test]
69 fn seen_reports_each_new_revision_once() {
70 let mut seen = Seen::default();
71 assert!(!seen.update(0));
72 assert!(!seen.update(0));
73 assert!(seen.update(1));
74 assert!(!seen.update(1));
75 assert!(seen.update(3));
76
77 let mut late = Seen::default();
78 assert!(late.update(2), "a consumer that starts late catches up");
79 }
80}