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