Skip to main content

rigorix_schemas/
lib.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Canonical Rigorix contracts as a consumable crate.
3//!
4//! @canonical schemas/README.md — the contract corpus this crate embeds
5//! (strategy freeze D-1: `schemas/` is the single source of truth; D-2:
6//! schemas + verifiers). ADR-0001 freezes the `rigorix.*` catalog within it.
7//!
8//! This crate embeds the entire [`schemas/`] corpus — the JSON Schemas
9//! (`envelope.json`, `claims.json`, `policy.json`, `api/*.json`, …) **and** the
10//! conformance fixture corpus (`fixtures/**`) — at build time, and exposes it
11//! by relative path. It is the distributable form of the single source of
12//! truth (strategy freeze D-1/D-2), consumed by `rigorix-verifier`, the
13//! Python/TypeScript verifiers, and both servers — one copy, no vendoring.
14//!
15//! The crate is data + lookup: no engine dependency, no runtime filesystem
16//! access. The embedded table is generated by `build.rs` from the repo-root
17//! `schemas/` (a symlink to it lives in this crate so `cargo package` ships the
18//! dereferenced corpus); a sync test fails if the embedded set diverges from
19//! the on-disk contract.
20//!
21//! ```no_run
22//! use rigorix_schemas::{fixture, schema, schema_by_id};
23//!
24//! let envelope = schema("envelope.json").expect("envelope schema");
25//! let chain = fixture("integrity/chain.json").expect("integrity fixture");
26//! let id = schema_by_id("https://rigorix.eu/schemas/envelope-v2.json");
27//! assert_eq!(id, Some("envelope.json"));
28//! # let _ = (envelope, chain);
29//! ```
30
31include!(concat!(env!("OUT_DIR"), "/embedded.rs"));
32
33/// Return the embedded contract at `rel_path`, relative to `schemas/`
34/// (e.g. `"envelope.json"`, `"api/catalog.json"`,
35/// `"fixtures/integrity/chain.json"`).
36pub fn schema(rel_path: &str) -> Option<&'static str> {
37    FILES
38        .binary_search_by(|(path, _)| (*path).cmp(rel_path))
39        .ok()
40        .map(|index| FILES[index].1)
41}
42
43/// Every embedded path, sorted (`NAMES[i]` corresponds to `FILES[i].0`).
44pub fn schema_names() -> &'static [&'static str] {
45    NAMES
46}
47
48/// Return the embedded conformance fixture at `rel_path`, relative to
49/// `fixtures/` (e.g. `"integrity/chain.json"`, `"envelope/envelope-rich-signed.json"`).
50///
51/// Equivalent to `schema(&format!("fixtures/{rel_path}"))`.
52pub fn fixture(rel_path: &str) -> Option<&'static str> {
53    let mut key = String::with_capacity("fixtures/".len() + rel_path.len());
54    key.push_str("fixtures/");
55    key.push_str(rel_path);
56    schema(&key)
57}
58
59/// Resolve a schema `$id` (e.g. `https://rigorix.eu/schemas/envelope-v2.json`)
60/// to its embedded path — for registering cross-file `$ref` resources.
61pub fn schema_by_id(id: &str) -> Option<&'static str> {
62    IDS.iter()
63        .find(|(schema_id, _)| *schema_id == id)
64        .map(|(_, path)| *path)
65}
66
67/// The `$id -> path` map exposed by the corpus.
68pub fn schema_ids() -> &'static [(&'static str, &'static str)] {
69    IDS
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use std::collections::BTreeMap;
76    use std::path::{Path, PathBuf};
77
78    /// The canonical on-disk corpus: prefer the repo-root `schemas/` (the
79    /// single source of truth); fall back to the in-crate symlink.
80    fn disk_root() -> PathBuf {
81        let manifest = Path::new(env!("CARGO_MANIFEST_DIR"));
82        let repo_root = manifest.join("../../schemas");
83        if repo_root.is_dir() {
84            repo_root
85        } else {
86            manifest.join("schemas")
87        }
88    }
89
90    fn walk(root: &Path, dir: &Path, out: &mut BTreeMap<String, Vec<u8>>) {
91        for entry in std::fs::read_dir(dir).expect("read schemas dir") {
92            let path = entry.expect("dir entry").path();
93            if path.is_dir() {
94                walk(root, &path, out);
95            } else {
96                let rel = path
97                    .strip_prefix(root)
98                    .expect("path under schemas root")
99                    .to_string_lossy()
100                    .replace('\\', "/");
101                out.insert(rel, std::fs::read(&path).expect("read schema file"));
102            }
103        }
104    }
105
106    #[test]
107    fn embedded_corpus_matches_disk() {
108        let root = disk_root();
109        let mut on_disk = BTreeMap::new();
110        walk(&root, &root, &mut on_disk);
111
112        assert!(
113            on_disk.len() >= 25,
114            "expected the frozen corpus (>= 25 files), found {} under {}",
115            on_disk.len(),
116            root.display()
117        );
118        assert!(
119            on_disk.contains_key("fixtures/integrity/chain.json"),
120            "the ADR-016 integrity fixtures must be part of the corpus"
121        );
122
123        let mut seen = std::collections::HashSet::new();
124        for (path, _) in FILES {
125            assert!(seen.insert(*path), "duplicate embedded path `{path}`");
126        }
127        assert_eq!(schema_names().len(), FILES.len());
128
129        // Every on-disk file is embedded, byte-equal.
130        for (rel, bytes) in &on_disk {
131            let embedded =
132                schema(rel).unwrap_or_else(|| panic!("`{rel}` is not embedded in the crate"));
133            assert_eq!(
134                embedded.as_bytes(),
135                bytes.as_slice(),
136                "embedded `{rel}` diverges from the on-disk contract"
137            );
138        }
139        // No extra embedded files.
140        for (rel, _) in FILES {
141            assert!(
142                on_disk.contains_key(*rel),
143                "embedded `{rel}` is not present on disk"
144            );
145        }
146    }
147
148    #[test]
149    fn exposes_schemas_fixtures_and_ids() {
150        assert!(schema("envelope.json").is_some());
151        assert!(schema("api/catalog.json").is_some());
152        assert!(schema("fixtures/integrity/chain.json").is_some());
153
154        // `fixture()` is relative to `fixtures/`.
155        assert!(fixture("integrity/chain.json").is_some());
156        assert!(fixture("envelope/envelope-rich-signed.json").is_some());
157        assert!(fixture("does/not/exist.json").is_none());
158
159        assert_eq!(
160            schema_by_id("https://rigorix.eu/schemas/envelope-v2.json"),
161            Some("envelope.json")
162        );
163        assert_eq!(
164            schema_by_id("https://rigorix.eu/schemas/claims.json"),
165            Some("claims.json")
166        );
167        assert!(schema_ids()
168            .iter()
169            .any(|(id, path)| id.ends_with("/envelope-v2.json") && *path == "envelope.json"));
170    }
171}