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        struct_to_gts_schema as upstream_struct_to_gts_schema,
58    };
59}
60
61/// Registration record for a GTS Type Schema contributed to the process-wide
62/// inventory.
63///
64/// Each `#[gts_type_schema(...)]`-annotated type submits one of these via
65/// `inventory::submit!` at macro-expansion time. The `schema_fn` lazily
66/// invokes the macro-generated accessor (`gts_schema_with_refs_as_string`)
67/// to produce the JSON Schema document on demand.
68#[derive(Clone)]
69pub struct InventoryTypeSchema {
70    /// GTS Type Identifier (e.g. `gts.cf.toolkit.authz.permission.v1~`).
71    pub type_id: &'static str,
72    /// Lazy accessor returning the GTS Type Schema as a JSON string.
73    pub schema_fn: fn() -> String,
74}
75
76/// Registration record for a well-known GTS Instance contributed to the
77/// process-wide inventory.
78///
79/// Submitted by the `gts_instance! { ... }` macro. `type_id` is derived at
80/// macro-expansion time from the last `~` in the full instance id.
81#[derive(Clone)]
82pub struct InventoryInstance {
83    /// GTS Type Identifier the Instance conforms to (prefix of the full
84    /// Instance Identifier up to and including the last `~`).
85    pub type_id: &'static str,
86    /// Full GTS Instance Identifier.
87    pub instance_id: &'static str,
88    /// Lazy accessor returning the Instance payload as JSON (with `id`
89    /// auto-injected by the macro).
90    ///
91    /// Two emission paths populate this:
92    /// - `gts_instance! { ... }` (typed) expands to
93    ///   `serde_json::to_value(&Struct { ... }).expect(...)`, which panics
94    ///   only if a custom `Serialize` impl in the struct's transitive
95    ///   field types fails (e.g., a map with non-string keys). In practice
96    ///   our base types — `AuthzPermissionV1`, `PluginV1<P>` — use only
97    ///   primitive / string / `GtsInstanceId` fields, so the panic path is
98    ///   unreachable.
99    /// - `gts_instance_raw! { ... }` expands to `serde_json::json!(...)`
100    ///   on a literal JSON object, which cannot panic at runtime.
101    pub payload_fn: fn() -> serde_json::Value,
102}
103
104inventory::collect!(InventoryTypeSchema);
105inventory::collect!(InventoryInstance);
106
107/// Returns every GTS Type Schema declared via `#[gts_type_schema(...)]` in
108/// any crate linked into the current process.
109///
110/// Source of truth for each Type Schema is its Rust struct via the
111/// macro-generated `gts_schema_with_refs_as_string` accessor — no
112/// hand-written JSON.
113///
114/// # Errors
115///
116/// Returns an error if any registered Type Schema accessor produces invalid
117/// JSON. This should be impossible with a correctly-applied `#[gts_type_schema]`
118/// macro and signals a macro regression.
119pub fn all_inventory_type_schemas() -> anyhow::Result<Vec<serde_json::Value>> {
120    let mut out = Vec::new();
121    for entry in inventory::iter::<InventoryTypeSchema> {
122        let schema_str = (entry.schema_fn)();
123        let value: serde_json::Value = serde_json::from_str(&schema_str).map_err(|e| {
124            anyhow::anyhow!(
125                "invalid GTS Type Schema JSON emitted by GTS type {}: {e}",
126                entry.type_id
127            )
128        })?;
129        out.push(value);
130    }
131    Ok(out)
132}
133
134/// Returns every well-known GTS Instance declared via `gts_instance!` in
135/// any crate linked into the current process.
136///
137/// # Errors
138///
139/// Currently never returns `Err`. Typed `gts_instance!` declarations use
140/// `serde_json::to_value` internally, whose only failure mode is a custom
141/// `Serialize` impl that fails — practically unreachable for our base
142/// types (primitive / string / `GtsInstanceId` fields only). Raw
143/// declarations use `serde_json::json!` on a literal object, which cannot
144/// fail. The `Result` return type is kept for symmetry with
145/// [`all_inventory_type_schemas`] and to leave room for surfacing
146/// per-instance serialization errors without an API break if a future
147/// base type ever introduces a fallible `Serialize` path.
148pub fn all_inventory_instances() -> anyhow::Result<Vec<serde_json::Value>> {
149    Ok(inventory::iter::<InventoryInstance>
150        .into_iter()
151        .map(|entry| (entry.payload_fn)())
152        .collect())
153}
154
155#[cfg(test)]
156mod tests {
157    use super::{
158        InventoryInstance, InventoryTypeSchema, all_inventory_instances, all_inventory_type_schemas,
159    };
160
161    #[test]
162    fn platform_base_schemas_are_registered_and_valid() {
163        let schemas = all_inventory_type_schemas().expect("schemas collect cleanly");
164
165        // Both platform base types shipped by this crate must be present.
166        let ids: Vec<&str> = inventory::iter::<InventoryTypeSchema>
167            .into_iter()
168            .map(|e| e.type_id)
169            .collect();
170        assert!(
171            ids.contains(&"gts.cf.toolkit.plugins.plugin.v1~"),
172            "PluginV1 not registered; got ids: {ids:?}"
173        );
174        assert!(
175            ids.contains(&"gts.cf.toolkit.authz.permission.v1~"),
176            "AuthzPermissionV1 not registered; got ids: {ids:?}"
177        );
178        assert_eq!(
179            schemas.len(),
180            ids.len(),
181            "iter vs aggregated count mismatch (did all entries collect cleanly?)"
182        );
183
184        for (idx, s) in schemas.iter().enumerate() {
185            assert!(s.is_object(), "schema #{idx} is not a JSON object: {s}");
186            assert!(s.get("$id").is_some(), "schema #{idx} missing $id: {s}");
187            assert!(
188                s.get("type").is_some(),
189                "schema #{idx} missing top-level type: {s}"
190            );
191        }
192    }
193
194    #[test]
195    fn inventory_instances_registry_is_consistent() {
196        // No instances ship from this crate, but the collector path must
197        // still run. (External crates may contribute instances; this crate
198        // only checks self-consistency.)
199        let instances = all_inventory_instances().expect("instances collect cleanly");
200        let ids: Vec<&str> = inventory::iter::<InventoryInstance>
201            .into_iter()
202            .map(|e| e.instance_id)
203            .collect();
204        assert_eq!(
205            instances.len(),
206            ids.len(),
207            "iter vs aggregated count mismatch"
208        );
209    }
210}