use schemars::{schema::RootSchema, schema_for, JsonSchema};
use serde_json::Value;
#[must_use]
pub fn generate_schema<T>(strict: bool) -> Value
where
T: JsonSchema,
{
let schema = schema_for!(T);
let mut value = serde_json::to_value(schema).unwrap_or(Value::Null);
if strict {
apply_strict_schema(&mut value);
}
value
}
#[must_use]
pub fn generate_schema_with_settings<T>(settings: &SchemaSettings) -> Value
where
T: JsonSchema,
{
let schema = schema_for!(T);
let mut value = serde_json::to_value(schema).unwrap_or(Value::Null);
if settings.strict {
apply_strict_schema(&mut value);
}
value
}
fn apply_strict_schema(value: &mut Value) {
if let Value::Object(map) = value {
if map.contains_key("properties") {
map.insert("additionalProperties".to_owned(), Value::Bool(false));
}
for (_, v) in map.iter_mut() {
apply_strict_schema(v);
}
} else if let Value::Array(arr) = value {
for item in arr.iter_mut() {
apply_strict_schema(item);
}
}
}
#[derive(Debug, Clone, Default)]
pub struct SchemaSettings {
pub strict: bool,
pub title: Option<String>,
pub description: Option<String>,
}
impl SchemaSettings {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn strict(mut self) -> Self {
self.strict = true;
self
}
#[must_use]
pub fn with_title(mut self, title: impl Into<String>) -> Self {
self.title = Some(title.into());
self
}
#[must_use]
pub fn with_description(mut self, description: impl Into<String>) -> Self {
self.description = Some(description.into());
self
}
}
#[derive(Debug, Clone)]
pub struct TaskSchema {
pub name: String,
pub schema: Value,
pub version: i32,
pub schema_type: SchemaType,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SchemaType {
Input,
Output,
}
impl TaskSchema {
#[must_use]
pub fn input<T>(task_name: &str, strict: bool) -> Self
where
T: JsonSchema,
{
Self {
name: format!("{task_name}_input"),
schema: generate_schema::<T>(strict),
version: 1,
schema_type: SchemaType::Input,
}
}
#[must_use]
pub fn output<T>(task_name: &str, strict: bool) -> Self
where
T: JsonSchema,
{
Self {
name: format!("{task_name}_output"),
schema: generate_schema::<T>(strict),
version: 1,
schema_type: SchemaType::Output,
}
}
#[must_use]
pub fn with_version(mut self, version: i32) -> Self {
self.version = version;
self
}
#[must_use]
pub fn to_schema_def(&self) -> crate::models::SchemaDef {
crate::models::SchemaDef::new(self.name.clone(), self.version, self.schema.clone())
}
}
pub trait WorkerSchema {
#[must_use]
fn input_schema(_strict: bool) -> Option<Value> {
None
}
#[must_use]
fn output_schema(_strict: bool) -> Option<Value> {
None
}
}
#[must_use]
pub fn get_root_schema<T>() -> RootSchema
where
T: JsonSchema,
{
schema_for!(T)
}
#[cfg(test)]
mod tests {
use super::*;
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct TestInput {
name: String,
value: i32,
optional: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, JsonSchema)]
struct TestOutput {
result: String,
count: i64,
}
#[test]
fn test_generate_schema() {
let schema = generate_schema::<TestInput>(false);
assert!(schema.is_object());
let obj = schema.as_object().unwrap();
assert!(obj.contains_key("properties"));
let props = obj.get("properties").unwrap().as_object().unwrap();
assert!(props.contains_key("name"));
assert!(props.contains_key("value"));
assert!(props.contains_key("optional"));
}
#[test]
fn test_generate_strict_schema() {
let schema = generate_schema::<TestInput>(true);
let obj = schema.as_object().unwrap();
assert_eq!(obj.get("additionalProperties"), Some(&Value::Bool(false)));
}
#[test]
fn test_task_schema_input() {
let schema = TaskSchema::input::<TestInput>("my_task", false);
assert_eq!(schema.name, "my_task_input");
assert_eq!(schema.schema_type, SchemaType::Input);
assert_eq!(schema.version, 1);
}
#[test]
fn test_task_schema_output() {
let schema = TaskSchema::output::<TestOutput>("my_task", true);
assert_eq!(schema.name, "my_task_output");
assert_eq!(schema.schema_type, SchemaType::Output);
let obj = schema.schema.as_object().unwrap();
assert_eq!(obj.get("additionalProperties"), Some(&Value::Bool(false)));
}
#[test]
fn test_to_schema_def() {
let task_schema = TaskSchema::input::<TestInput>("process_order", false).with_version(2);
let schema_def = task_schema.to_schema_def();
assert_eq!(schema_def.name, "process_order_input");
assert_eq!(schema_def.version, 2);
assert_eq!(schema_def.schema_type, "JSON");
}
}