Skip to main content

stateknot_runtime/
service_schema.rs

1// Copyright 2026 StateKnot contributors
2// SPDX-License-Identifier: Apache-2.0
3
4//! Versioned public-safe journal schema for Agent service control mutations.
5
6use serde_json::Value;
7use stateknot_core::{Digest, SchemaId, SchemaIdError, SchemaReference, Version};
8use thiserror::Error;
9
10use crate::{JsonSchemaRegistryBuilder, JsonSchemaRegistryError};
11
12/// Stable identity of the v1 Agent service control event-data schema.
13pub const STANDARD_AGENT_SERVICE_CONTROL_EVENT_SCHEMA_ID: &str =
14    "https://stknot.com/schemas/runtime/agent-service-control-event/1.0.0";
15
16const DOCUMENT: &str = include_str!("../schemas/agent-service-control-event-1.0.0.json");
17
18/// Returns the immutable reference and owned JSON Schema document shipped with
19/// this runtime release.
20///
21/// # Errors
22///
23/// Returns [`StandardAgentServiceControlSchemaError`] only when the embedded
24/// release artifact is internally malformed.
25pub fn standard_agent_service_control_event_schema()
26-> Result<(SchemaReference, Value), StandardAgentServiceControlSchemaError> {
27    let document = serde_json::from_str::<Value>(DOCUMENT)
28        .map_err(|_| StandardAgentServiceControlSchemaError::EmbeddedDocument)?;
29    let canonical = serde_json_canonicalizer::to_vec(&document)
30        .map_err(|_| StandardAgentServiceControlSchemaError::Canonicalization)?;
31    let id = STANDARD_AGENT_SERVICE_CONTROL_EVENT_SCHEMA_ID
32        .parse::<SchemaId>()
33        .map_err(StandardAgentServiceControlSchemaError::identifier)?;
34    let reference = SchemaReference::new(id, Version::new(1, 0, 0), Digest::sha256(canonical));
35    Ok((reference, document))
36}
37
38/// Registers the standard Agent service control schema in a startup registry.
39///
40/// # Errors
41///
42/// Returns an embedded-definition error or the registry's duplicate, resource,
43/// dialect, digest, and reference-resolution failures.
44pub fn register_standard_agent_service_control_event_schema(
45    builder: &mut JsonSchemaRegistryBuilder,
46) -> Result<SchemaReference, StandardAgentServiceControlSchemaRegistrationError> {
47    let (reference, document) = standard_agent_service_control_event_schema()?;
48    builder.register(reference.clone(), document)?;
49    Ok(reference)
50}
51
52/// Internal release-artifact failure for the embedded standard schema.
53#[derive(Clone, Debug, Eq, Error, PartialEq)]
54#[non_exhaustive]
55pub enum StandardAgentServiceControlSchemaError {
56    /// The embedded JSON document cannot be parsed.
57    #[error("embedded Agent service control event schema is invalid JSON")]
58    EmbeddedDocument,
59    /// The embedded document cannot be represented as RFC 8785 bytes.
60    #[error("embedded Agent service control event schema cannot be canonicalized")]
61    Canonicalization,
62    /// The embedded stable HTTPS identifier is invalid.
63    #[error("embedded Agent service control event schema identifier is invalid: {source}")]
64    Identifier {
65        /// Exact identifier validation error.
66        #[source]
67        source: SchemaIdError,
68    },
69}
70
71impl StandardAgentServiceControlSchemaError {
72    const fn identifier(source: SchemaIdError) -> Self {
73        Self::Identifier { source }
74    }
75}
76
77/// Startup failure while adding the standard Agent service control schema.
78#[derive(Clone, Debug, Eq, Error, PartialEq)]
79#[non_exhaustive]
80pub enum StandardAgentServiceControlSchemaRegistrationError {
81    /// The embedded release artifact was malformed.
82    #[error(transparent)]
83    Definition(#[from] StandardAgentServiceControlSchemaError),
84    /// The target registry rejected the immutable resource.
85    #[error(transparent)]
86    Registry(#[from] JsonSchemaRegistryError),
87}
88
89#[cfg(test)]
90mod tests {
91    use serde_json::json;
92    use stateknot_core::BoundedJson;
93
94    use super::*;
95    use crate::JsonSchemaRegistryLimits;
96
97    #[test]
98    fn standard_schema_is_digest_pinned_closed_and_registry_valid() {
99        let (reference, document) = standard_agent_service_control_event_schema().unwrap();
100        assert_eq!(
101            reference.id().as_str(),
102            STANDARD_AGENT_SERVICE_CONTROL_EVENT_SCHEMA_ID
103        );
104        assert_eq!(reference.version(), Version::new(1, 0, 0));
105
106        let mut builder = JsonSchemaRegistryBuilder::new(JsonSchemaRegistryLimits::default());
107        builder.register(reference.clone(), document).unwrap();
108        let registry = builder.build().unwrap();
109        let valid = json!({
110            "operation": "agent_cancellation_requested",
111            "admission_digest": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
112            "policy_digest": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb",
113            "decision_digest": "cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc",
114            "failure_id": "01912345-6789-7abc-8def-0123456789ab"
115        });
116        registry
117            .validate_bounded(
118                &reference,
119                &BoundedJson::try_from_value(valid.clone()).unwrap(),
120            )
121            .unwrap();
122
123        let mut leaked = valid;
124        leaked["principal"] = json!("private-user");
125        assert!(
126            registry
127                .validate_bounded(&reference, &BoundedJson::try_from_value(leaked).unwrap())
128                .is_err()
129        );
130    }
131}