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