Skip to main content

cortex_reflect/
parse.rs

1//! Parsers for reflection JSON contracts.
2
3use schemars::schema_for;
4
5use crate::error::ReflectError;
6use crate::schema::{PrincipleCandidateBatch, SessionReflection};
7
8/// Parse and validate a `SessionReflection` JSON object.
9///
10/// Failures preserve the original input for quarantine. This function performs
11/// syntax validation, serde/schema shape validation, and local invariant checks
12/// such as confidence ranges and candidate index bounds.
13pub fn parse_reflection(input: &str) -> Result<SessionReflection, ReflectError> {
14    let value = parse_value(input)?;
15    let reflection: SessionReflection =
16        serde_json::from_value(value).map_err(|source| ReflectError::InvalidSchema {
17            raw: input.to_string(),
18            message: source.to_string(),
19        })?;
20    reflection
21        .validate()
22        .map_err(|message| ReflectError::InvalidSchema {
23            raw: input.to_string(),
24            message,
25        })?;
26    Ok(reflection)
27}
28
29/// Parse and validate a `PrincipleCandidate` batch JSON object.
30pub fn parse_principle_candidates(input: &str) -> Result<PrincipleCandidateBatch, ReflectError> {
31    let value = parse_value(input)?;
32    let batch: PrincipleCandidateBatch =
33        serde_json::from_value(value).map_err(|source| ReflectError::InvalidSchema {
34            raw: input.to_string(),
35            message: source.to_string(),
36        })?;
37    batch
38        .validate()
39        .map_err(|message| ReflectError::InvalidSchema {
40            raw: input.to_string(),
41            message,
42        })?;
43    Ok(batch)
44}
45
46/// Export the `SessionReflection` JSON Schema as a JSON value.
47#[must_use]
48pub fn session_reflection_json_schema() -> serde_json::Value {
49    serde_json::to_value(schema_for!(SessionReflection)).expect("schema is serializable")
50}
51
52/// Export the `PrincipleCandidateBatch` JSON Schema as a JSON value.
53#[must_use]
54pub fn principle_candidate_batch_json_schema() -> serde_json::Value {
55    serde_json::to_value(schema_for!(PrincipleCandidateBatch)).expect("schema is serializable")
56}
57
58fn parse_value(input: &str) -> Result<serde_json::Value, ReflectError> {
59    serde_json::from_str(input).map_err(|source| ReflectError::InvalidJson {
60        raw: input.to_string(),
61        message: source.to_string(),
62    })
63}