Skip to main content

toolkit_gts/
local.rs

1//! Crate-local GTS declaration collectors for publishing a gear's own documents.
2//! Crate-root declaration macros collect linked declarations process-wide; `local` macros
3//! additionally submit to the declaring crate's collector, using the same inputs.
4//!
5//! ```ignore
6//! // At the crate root:
7//! toolkit_gts::declare_gts_inventory!();
8//!
9//! // Anywhere in that crate:
10//! #[toolkit_gts::local::gts_type_schema(/* same arguments */)]
11//! pub struct MySpecV1 { /* ... */ }
12//! toolkit_gts::local::gts_instance_raw!({ "id": "...", /* ... */ });
13//! ```
14//!
15//! `declare_gts_inventory!()` defines `__toolkit_gts_inventory` and
16//! `pub fn gts_declarations() -> Vec<(String, String)>`: `(GTS id, JSON text)`
17//! pairs using only std types across crate boundaries. A `local` macro without
18//! that declaration fails to compile because the collector is missing.
19//! Listed crates must use `local::*` throughout; collection rejects leftover root
20//! declarations and names their omitted IDs.
21//! Process-wide readers, including an embedded types-registry, still see every
22//! declaration. Merge a gear's crate collectors with [`merge_declarations`]
23//! or [`DeclarationMerge`].
24
25use std::collections::BTreeMap;
26
27use gts::GtsId;
28
29pub use toolkit_gts_macros::{
30    local_gts_instance as gts_instance, local_gts_instance_raw as gts_instance_raw,
31    local_gts_type_schema as gts_type_schema,
32};
33
34pub use crate::declare_gts_inventory;
35
36/// Defines this crate's GTS declaration collector and its
37/// `pub fn gts_declarations() -> Vec<(String, String)>`; see [`crate::local`].
38/// Invoke once, at the crate root.
39#[macro_export]
40macro_rules! declare_gts_inventory {
41    () => {
42        #[doc(hidden)]
43        pub mod __toolkit_gts_inventory {
44            /// A Type Schema declared by this crate.
45            pub struct TypeSchema(pub $crate::InventoryTypeSchema);
46            /// An Instance declared by this crate.
47            pub struct Instance(pub $crate::InventoryInstance);
48            $crate::inventory::collect!(TypeSchema);
49            $crate::inventory::collect!(Instance);
50        }
51
52        /// The GTS Type Schemas and Instances this crate declares, as
53        /// `(GTS id, JSON text)` sorted by id.
54        ///
55        /// # Panics
56        /// If root-macro declarations remain; migrate them to `toolkit_gts::local::*`.
57        #[must_use]
58        pub fn gts_declarations() -> ::std::vec::Vec<(::std::string::String, ::std::string::String)>
59        {
60            $crate::local::__assert_local_declarations(
61                ::std::module_path!(),
62                ::std::env!("CARGO_MANIFEST_DIR"),
63            );
64            $crate::local::__collect(
65                $crate::inventory::iter::<__toolkit_gts_inventory::TypeSchema>
66                    .into_iter()
67                    .map(|entry| &entry.0),
68                $crate::inventory::iter::<__toolkit_gts_inventory::Instance>
69                    .into_iter()
70                    .map(|entry| &entry.0),
71            )
72        }
73    };
74}
75
76/// Global-only declaration provenance; keeps existing inventory record layouts unchanged.
77#[doc(hidden)]
78pub struct GlobalOnlyDeclaration {
79    pub module_path: &'static str,
80    pub manifest_dir: &'static str,
81    pub gts_id: &'static str,
82}
83
84crate::inventory::collect!(GlobalOnlyDeclaration);
85
86/// Reject incomplete migration of a declaring crate to its local collector.
87///
88/// # Panics
89/// If the crate has a root-macro declaration absent from its local collector.
90#[doc(hidden)]
91pub fn __assert_local_declarations(crate_root: &str, manifest_dir: &str) {
92    let mut omitted: Vec<_> = crate::inventory::iter::<GlobalOnlyDeclaration>
93        .into_iter()
94        .filter(|entry| {
95            entry.manifest_dir == manifest_dir
96                && entry.module_path.split("::").next() == Some(crate_root)
97        })
98        .map(|entry| entry.gts_id)
99        .collect();
100    omitted.sort_unstable();
101    omitted.dedup();
102    assert!(
103        omitted.is_empty(),
104        "crate `{crate_root}` has global-only GTS declarations: {}; use \
105         toolkit_gts::local::gts_type_schema, toolkit_gts::local::gts_instance! or \
106         toolkit_gts::local::gts_instance_raw! for every declaration in a published crate",
107        omitted.join(", ")
108    );
109}
110
111/// The body of a generated `gts_declarations()`.
112#[doc(hidden)]
113pub fn __collect<'a>(
114    schemas: impl Iterator<Item = &'a crate::InventoryTypeSchema>,
115    instances: impl Iterator<Item = &'a crate::InventoryInstance>,
116) -> Vec<(String, String)> {
117    let mut out: Vec<(String, String)> = schemas
118        .map(|entry| (entry.type_id.to_owned(), (entry.schema_fn)()))
119        .chain(instances.map(|entry| {
120            (
121                entry.instance_id.to_owned(),
122                (entry.payload_fn)().to_string(),
123            )
124        }))
125        .collect();
126    out.sort();
127    out
128}
129
130/// One source of unparsed declarations for [`DeclarationMerge::add_source`]: a
131/// crate's `gts_declarations()`.
132pub struct DeclarationSource {
133    /// Names the source in diagnostics, e.g. the crate name.
134    pub origin: String,
135    /// `(GTS id, JSON text)` pairs.
136    pub declarations: Vec<(String, String)>,
137}
138
139impl DeclarationSource {
140    #[must_use]
141    pub fn new(origin: impl Into<String>, declarations: Vec<(String, String)>) -> Self {
142        Self {
143            origin: origin.into(),
144            declarations,
145        }
146    }
147}
148
149/// Merge crate collectors ([`Self::add_source`]) and typed runtime documents
150/// ([`Self::add_documents`]) into `(GTS id, content)` pairs sorted by id.
151///
152/// Collector ids are parsed once and compared as text. Equal duplicates collapse
153/// by [`same_canonical_content`]. [`Self::finish`] reports all invalid ids/JSON
154/// and content conflicts together, naming their origins.
155#[derive(Debug, Default)]
156pub struct DeclarationMerge {
157    merged: BTreeMap<String, (GtsId, serde_json::Value, String)>,
158    problems: Vec<String>,
159}
160
161impl DeclarationMerge {
162    /// Adds a crate collector's declarations, parsing each id and JSON text.
163    pub fn add_source(&mut self, source: DeclarationSource) -> &mut Self {
164        for (id, text) in source.declarations {
165            let parsed = match GtsId::try_new(&id) {
166                Ok(parsed) => parsed,
167                Err(e) => {
168                    self.problems
169                        .push(format!("{id} from {}: invalid GTS id: {e}", source.origin));
170                    continue;
171                }
172            };
173            match serde_json::from_str(&text) {
174                Ok(content) => self.insert(parsed, content, &source.origin),
175                Err(e) => self
176                    .problems
177                    .push(format!("{id} from {}: invalid JSON: {e}", source.origin)),
178            }
179        }
180        self
181    }
182
183    /// Adds documents whose ids are already parsed, e.g. a gear's `entities`.
184    pub fn add_documents(
185        &mut self,
186        origin: &str,
187        documents: impl IntoIterator<Item = (GtsId, serde_json::Value)>,
188    ) -> &mut Self {
189        for (id, content) in documents {
190            self.insert(id, content, origin);
191        }
192        self
193    }
194
195    fn insert(&mut self, id: GtsId, content: serde_json::Value, origin: &str) {
196        match self.merged.get(id.id()) {
197            None => {
198                self.merged
199                    .insert(id.id().to_owned(), (id, content, origin.to_owned()));
200            }
201            Some((_, kept, _)) if same_canonical_content(kept, &content) => {}
202            Some((_, _, kept_origin)) => self.problems.push(format!(
203                "{id} is declared with different content by {kept_origin} and {origin}"
204            )),
205        }
206    }
207
208    /// The merged `(GTS id, content)`, sorted by id.
209    ///
210    /// # Errors
211    /// Lists every invalid id or JSON text and every conflicting id.
212    pub fn finish(self) -> anyhow::Result<Vec<(GtsId, serde_json::Value)>> {
213        if !self.problems.is_empty() {
214            anyhow::bail!(
215                "conflicting or invalid GTS declarations:\n- {}",
216                self.problems.join("\n- ")
217            );
218        }
219        Ok(self
220            .merged
221            .into_values()
222            .map(|(id, content, _)| (id, content))
223            .collect())
224    }
225}
226
227/// Merges `sources` with a [`DeclarationMerge`].
228///
229/// # Errors
230/// As [`DeclarationMerge::finish`].
231pub fn merge_declarations(
232    sources: impl IntoIterator<Item = DeclarationSource>,
233) -> anyhow::Result<Vec<(GtsId, serde_json::Value)>> {
234    let mut merge = DeclarationMerge::default();
235    for source in sources {
236        merge.add_source(source);
237    }
238    merge.finish()
239}
240
241/// Whether two documents have the same canonical content, as types-registry
242/// stores and compares it: object key order aside, array order kept, every
243/// number keeps its spelling. `Value` equality would call `0.0` and `-0.0`
244/// equal.
245#[must_use]
246pub fn same_canonical_content(left: &serde_json::Value, right: &serde_json::Value) -> bool {
247    use serde_json::Value;
248    match (left, right) {
249        (Value::Number(l), Value::Number(r)) => l.to_string() == r.to_string(),
250        (Value::Array(l), Value::Array(r)) => {
251            l.len() == r.len() && l.iter().zip(r).all(|(l, r)| same_canonical_content(l, r))
252        }
253        (Value::Object(l), Value::Object(r)) => {
254            l.len() == r.len()
255                && l.iter()
256                    .all(|(key, l)| r.get(key).is_some_and(|r| same_canonical_content(l, r)))
257        }
258        _ => left == right,
259    }
260}
261
262#[cfg(test)]
263#[path = "local_tests.rs"]
264mod local_tests;