Skip to main content

toolkit_gts/
lib.rs

1#![cfg_attr(coverage_nightly, feature(coverage_attribute))]
2//! `ToolKit` GTS integration.
3//!
4//! This crate bridges Rust types to the [Global Type System] (GTS) used by
5//! Gears. It provides three things:
6//!
7//! 1. **Link-time inventory** of GTS Type Schemas and well-known Instances —
8//!    collectors populated at link time via the `inventory` crate. Any crate
9//!    in the process that uses the declaration macros contributes to the same
10//!    global inventory. `types-registry` consumes the inventory at startup,
11//!    so there is no per-gear registration code for entries known at
12//!    compile time.
13//! 2. **Thin proc-macro wrappers** that delegate to upstream `gts-macros`
14//!    for schema generation and optional inventory registration:
15//!    - `#[gts_type_schema(...)]` — wraps `gts_macros::struct_to_gts_schema`.
16//!    - `#[gts_type_schema_template(...)]` — schema generation without inventory.
17//!    - `gts_instance!` — wraps `gts_macros::gts_instance!`.
18//!    - `gts_instance_raw!` — wraps `gts_macros::gts_instance_raw!`.
19//! 3. **Platform base types** — a small shipped set of GTS base Type Schemas
20//!    ([`PluginV1`], [`AuthzPermissionV1`]) used across the platform.
21//!
22//! ## Adding a new entry
23//!
24//! For a new platform base Type Schema, put a `#[gts_type_schema(...)]`-annotated
25//! struct into this crate and add `mod your_gear;` below. For a Type Schema
26//! or Instance owned by a specific gear, use the same macros from that
27//! gear's crate — the inventory is process-global, so entries land in
28//! `types-registry` regardless of which crate declares them.
29//!
30//! A crate whose gear publishes its own declarations declares a collector of
31//! its own and uses the [`local`] macros instead; see that module.
32//!
33//! [Global Type System]: https://github.com/hypernetix/gts-spec
34
35pub mod local;
36pub mod permission;
37pub mod plugin;
38
39pub use permission::AuthzPermissionV1;
40pub use plugin::PluginV1;
41
42// Re-export GTS primitives used by the wrapper macros and downstream
43// callers. Keeps `toolkit_gts::*` self-sufficient at the top level.
44pub use gts::{GTS_ID_PREFIX, GTS_ID_URI_PREFIX, GtsId, GtsInstanceId, GtsSchema};
45
46// Re-export `inventory` so the macro expansions can emit
47// `<crate>::inventory::submit!` without requiring consumer crates to add
48// `inventory` as a direct dep.
49#[doc(hidden)]
50pub use inventory;
51
52// Re-export the companion proc-macros so consumers need only one crate dep.
53pub use gts_macros::GtsTraitsSchema;
54pub use toolkit_gts_macros::{
55    gts_id, gts_instance, gts_instance_raw, gts_type_schema, gts_type_schema_template, gts_uri,
56};
57
58/// Hidden re-exports used by the `cf-gears-toolkit-gts-macros` proc-macro
59/// expansions to reach the upstream construction macros without forcing
60/// consumers to take a direct dependency on `gts-macros`.
61#[doc(hidden)]
62pub mod __private {
63    pub use ::gts_macros::{
64        gts_id as upstream_gts_id, gts_instance as upstream_gts_instance,
65        gts_instance_raw as upstream_gts_instance_raw,
66        struct_to_gts_schema as upstream_struct_to_gts_schema,
67    };
68}
69
70/// Registration record for a GTS Type Schema contributed to the process-wide
71/// inventory.
72///
73/// Each `#[gts_type_schema(...)]`-annotated type submits one of these via
74/// `inventory::submit!` at macro-expansion time. The `schema_fn` lazily
75/// invokes the macro-generated accessor (`gts_schema_with_refs_as_string`)
76/// to produce the JSON Schema document on demand.
77#[derive(Clone)]
78pub struct InventoryTypeSchema {
79    /// GTS Type Identifier (e.g. `gts.cf.toolkit.authz.permission.v1~`).
80    pub type_id: &'static str,
81    /// Lazy accessor returning the GTS Type Schema as a JSON string.
82    pub schema_fn: fn() -> String,
83}
84
85/// Registration record for a well-known GTS Instance contributed to the
86/// process-wide inventory.
87///
88/// Submitted by the `gts_instance! { ... }` macro. `type_id` is derived at
89/// macro-expansion time from the last `~` in the full instance id.
90#[derive(Clone)]
91pub struct InventoryInstance {
92    /// GTS Type Identifier the Instance conforms to (prefix of the full
93    /// Instance Identifier up to and including the last `~`).
94    pub type_id: &'static str,
95    /// Full GTS Instance Identifier.
96    pub instance_id: &'static str,
97    /// Lazy accessor returning the Instance payload as JSON (with `id`
98    /// auto-injected by the macro).
99    ///
100    /// Two emission paths populate this:
101    /// - `gts_instance! { ... }` (typed) expands to
102    ///   `serde_json::to_value(&Struct { ... }).expect(...)`, which panics
103    ///   only if a custom `Serialize` impl in the struct's transitive
104    ///   field types fails (e.g., a map with non-string keys). In practice
105    ///   our base types — `AuthzPermissionV1`, `PluginV1<P>` — use only
106    ///   primitive / string / `GtsInstanceId` fields, so the panic path is
107    ///   unreachable.
108    /// - `gts_instance_raw! { ... }` expands to `serde_json::json!(...)`
109    ///   on a literal JSON object, which cannot panic at runtime.
110    pub payload_fn: fn() -> serde_json::Value,
111}
112
113inventory::collect!(InventoryTypeSchema);
114inventory::collect!(InventoryInstance);
115
116/// Returns every GTS Type Schema declared via `#[gts_type_schema(...)]` in
117/// any crate linked into the current process.
118///
119/// Source of truth for each Type Schema is its Rust struct via the
120/// macro-generated `gts_schema_with_refs_as_string` accessor — no
121/// hand-written JSON.
122///
123/// # Errors
124///
125/// Returns an error if any registered Type Schema accessor produces invalid
126/// JSON. This should be impossible with a correctly-applied `#[gts_type_schema]`
127/// macro and signals a macro regression.
128pub fn all_inventory_type_schemas() -> anyhow::Result<Vec<serde_json::Value>> {
129    let mut out = Vec::new();
130    for entry in inventory::iter::<InventoryTypeSchema> {
131        let schema_str = (entry.schema_fn)();
132        let value: serde_json::Value = serde_json::from_str(&schema_str).map_err(|e| {
133            anyhow::anyhow!(
134                "invalid GTS Type Schema JSON emitted by GTS type {}: {e}",
135                entry.type_id
136            )
137        })?;
138        out.push(value);
139    }
140    Ok(out)
141}
142
143/// Returns every well-known GTS Instance declared via `gts_instance!` in
144/// any crate linked into the current process.
145///
146/// # Errors
147///
148/// Currently never returns `Err`. Typed `gts_instance!` declarations use
149/// `serde_json::to_value` internally, whose only failure mode is a custom
150/// `Serialize` impl that fails — practically unreachable for our base
151/// types (primitive / string / `GtsInstanceId` fields only). Raw
152/// declarations use `serde_json::json!` on a literal object, which cannot
153/// fail. The `Result` return type is kept for symmetry with
154/// [`all_inventory_type_schemas`] and to leave room for surfacing
155/// per-instance serialization errors without an API break if a future
156/// base type ever introduces a fallible `Serialize` path.
157pub fn all_inventory_instances() -> anyhow::Result<Vec<serde_json::Value>> {
158    Ok(inventory::iter::<InventoryInstance>
159        .into_iter()
160        .map(|entry| (entry.payload_fn)())
161        .collect())
162}
163
164#[cfg(test)]
165mod tests {
166    use super::{
167        InventoryInstance, InventoryTypeSchema, all_inventory_instances, all_inventory_type_schemas,
168    };
169
170    #[test]
171    fn platform_base_schemas_are_registered_and_valid() {
172        let schemas = all_inventory_type_schemas().expect("schemas collect cleanly");
173
174        // Both platform base types shipped by this crate must be present.
175        let ids: Vec<&str> = inventory::iter::<InventoryTypeSchema>
176            .into_iter()
177            .map(|e| e.type_id)
178            .collect();
179        assert!(
180            ids.contains(&crate::gts_id!("cf.toolkit.plugins.plugin.v1~")),
181            "PluginV1 not registered; got ids: {ids:?}"
182        );
183        assert!(
184            ids.contains(&crate::gts_id!("cf.toolkit.authz.permission.v1~")),
185            "AuthzPermissionV1 not registered; got ids: {ids:?}"
186        );
187        assert_eq!(
188            schemas.len(),
189            ids.len(),
190            "iter vs aggregated count mismatch (did all entries collect cleanly?)"
191        );
192
193        for (idx, s) in schemas.iter().enumerate() {
194            assert!(s.is_object(), "schema #{idx} is not a JSON object: {s}");
195            assert!(s.get("$id").is_some(), "schema #{idx} missing $id: {s}");
196            assert!(
197                s.get("type").is_some(),
198                "schema #{idx} missing top-level type: {s}"
199            );
200        }
201    }
202
203    #[test]
204    fn inventory_instances_registry_is_consistent() {
205        // No instances ship from this crate, but the collector path must
206        // still run. (External crates may contribute instances; this crate
207        // only checks self-consistency.)
208        let instances = all_inventory_instances().expect("instances collect cleanly");
209        let ids: Vec<&str> = inventory::iter::<InventoryInstance>
210            .into_iter()
211            .map(|e| e.instance_id)
212            .collect();
213        assert_eq!(
214            instances.len(),
215            ids.len(),
216            "iter vs aggregated count mismatch"
217        );
218    }
219}