stepflow_flow/schema.rs
1// Copyright 2025 DataStax Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
4// in compliance with the License. You may obtain a copy of the License at
5//
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software distributed under the License
9// is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
10// or implied. See the License for the specific language governing permissions and limitations under
11// the License.
12
13//! Schema manipulation and validation types.
14
15use crate::json_schema::generate_json_schema;
16use serde::{Deserialize, Serialize};
17use serde_json::Value;
18use std::sync::Arc;
19
20/// A shared reference to a JSON Schema.
21///
22/// This wraps a `serde_json::Value` that represents a JSON Schema.
23/// The value should be either an object or a boolean (the valid top-level
24/// JSON Schema values).
25#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
26#[repr(transparent)]
27pub struct SchemaRef(Arc<Value>);
28
29impl From<Value> for SchemaRef {
30 fn from(value: Value) -> Self {
31 SchemaRef(Arc::new(value))
32 }
33}
34
35impl AsRef<Value> for SchemaRef {
36 fn as_ref(&self) -> &Value {
37 &self.0
38 }
39}
40
41impl schemars::JsonSchema for SchemaRef {
42 fn schema_name() -> std::borrow::Cow<'static, str> {
43 "Schema".into()
44 }
45
46 fn json_schema(_generator: &mut schemars::SchemaGenerator) -> schemars::Schema {
47 schemars::json_schema!({
48 "type": "object",
49 "additionalProperties": true,
50 "description": "A valid JSON Schema object."
51 })
52 }
53}
54
55impl SchemaRef {
56 /// Create a schema reference from a type that implements JsonSchema.
57 pub fn for_type<T: schemars::JsonSchema>() -> Self {
58 let json_schema = generate_json_schema::<T>();
59 json_schema.into()
60 }
61
62 /// Parse a JSON Schema from a JSON string.
63 pub fn parse_json(s: &str) -> Result<Self, serde_json::Error> {
64 let value = serde_json::from_str::<Value>(s)?;
65 Ok(value.into())
66 }
67
68 /// Get the schema as a JSON value reference.
69 pub fn as_value(&self) -> &Value {
70 &self.0
71 }
72}