1use schedr_config::masked::{mask_data, names_secret_in_words};
6use schedr_model::TypeDesc;
7use schedr_model::dag::Params;
8use serde::{Deserialize, Serialize};
9use serde_json::Value;
10use utoipa::ToSchema;
11
12#[cfg(test)]
13mod tests;
14
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)]
17pub struct ParamFieldView {
18 pub name: String,
20 pub kind: ParamKind,
22 pub required: bool,
24 pub nullable: bool,
26 pub secret: bool,
30 #[serde(
33 default,
34 skip_serializing_if = "Option::is_none",
35 deserialize_with = "present"
36 )]
37 #[schema(value_type = Option<Object>)]
38 pub default: Option<Value>,
39 #[serde(default, skip_serializing_if = "Vec::is_empty")]
41 #[schema(value_type = Vec<Object>)]
42 pub choices: Vec<Value>,
43}
44
45fn present<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Option<Value>, D::Error> {
47 Value::deserialize(deserializer).map(Some)
48}
49
50#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, ToSchema)]
52#[serde(rename_all = "snake_case")]
53pub enum ParamKind {
54 Bool,
56 Int,
58 Float,
60 Text,
62 Date,
64 Datetime,
66 Duration,
68 Choice,
70 Json,
73}
74
75impl ParamFieldView {
76 #[must_use]
79 pub fn of(params: &Params) -> Vec<Self> {
80 let required: Vec<&str> = root_object(¶ms.schema)
81 .get("required")
82 .and_then(Value::as_array)
83 .map(|names| names.iter().filter_map(Value::as_str).collect())
84 .unwrap_or_default();
85 let shapes: Vec<(String, Shape)> = match ¶ms.ty {
86 TypeDesc::Dataclass { fields, .. } => fields
87 .iter()
88 .map(|f| (f.name.clone(), Shape::of_type(&f.ty)))
89 .collect(),
90 _ => root_object(¶ms.schema)
91 .get("properties")
92 .and_then(Value::as_object)
93 .map(|properties| {
94 properties
95 .iter()
96 .map(|(name, schema)| {
97 (name.clone(), Shape::of_schema(schema, ¶ms.schema, 0))
98 })
99 .collect()
100 })
101 .unwrap_or_default(),
102 };
103 shapes
104 .into_iter()
105 .map(|(name, shape)| {
106 let default = params.defaults.get(&name).cloned();
107 let secret = names_secret_in_words(&name)
108 || default
109 .iter()
110 .chain(&shape.choices)
111 .any(|v| holds_secret(&name, v));
112 Self {
113 required: default.is_none() && required.contains(&name.as_str()),
114 kind: shape.kind,
115 nullable: shape.nullable,
116 choices: if secret { Vec::new() } else { shape.choices },
118 default: if secret { None } else { default },
119 secret,
120 name,
121 }
122 })
123 .collect()
124 }
125}
126
127fn root_object(root: &Value) -> &Value {
130 root.get("$ref")
131 .and_then(Value::as_str)
132 .and_then(|target| target.strip_prefix('#'))
133 .and_then(|path| root.pointer(path))
134 .unwrap_or(root)
135}
136
137fn holds_secret(name: &str, value: &Value) -> bool {
140 let mut fields = serde_json::Map::new();
141 fields.insert(name.to_owned(), value.clone());
142 let original = Value::Object(fields);
143 let mut masked = original.clone();
144 mask_data(&mut masked);
145 masked != original
146}
147
148struct Shape {
150 kind: ParamKind,
151 nullable: bool,
152 choices: Vec<Value>,
153}
154
155impl Shape {
156 fn plain(kind: ParamKind) -> Self {
157 Self {
158 kind,
159 nullable: false,
160 choices: Vec::new(),
161 }
162 }
163
164 fn choice(values: &[Value]) -> Self {
165 Self {
166 kind: ParamKind::Choice,
167 nullable: values.iter().any(Value::is_null),
168 choices: values.iter().filter(|v| !v.is_null()).cloned().collect(),
169 }
170 }
171
172 fn of_type(ty: &TypeDesc) -> Self {
174 match ty {
175 TypeDesc::Bool => Self::plain(ParamKind::Bool),
176 TypeDesc::Int => Self::plain(ParamKind::Int),
177 TypeDesc::Float => Self::plain(ParamKind::Float),
178 TypeDesc::Str => Self::plain(ParamKind::Text),
179 TypeDesc::Date => Self::plain(ParamKind::Date),
180 TypeDesc::Datetime => Self::plain(ParamKind::Datetime),
181 TypeDesc::Timedelta => Self::plain(ParamKind::Duration),
182 TypeDesc::Literal { values } => Self::choice(values),
183 TypeDesc::Union { variants } => {
184 let others: Vec<&TypeDesc> = variants
185 .iter()
186 .filter(|v| !matches!(v, TypeDesc::None))
187 .collect();
188 match others.as_slice() {
189 [one] if others.len() < variants.len() => {
190 let mut shape = Self::of_type(one);
191 if shape.kind != ParamKind::Json {
192 shape.nullable = true;
193 }
194 shape
195 }
196 _ => Self::plain(ParamKind::Json),
197 }
198 }
199 _ => Self::plain(ParamKind::Json),
200 }
201 }
202
203 fn of_schema(schema: &Value, root: &Value, depth: u8) -> Self {
205 if depth > 8 {
207 return Self::plain(ParamKind::Json);
208 }
209 if let Some(target) = schema.get("$ref").and_then(Value::as_str) {
210 return match target
211 .strip_prefix("#/")
212 .and_then(|path| root.pointer(&format!("/{path}")))
213 {
214 Some(found) => Self::of_schema(found, root, depth + 1),
215 None => Self::plain(ParamKind::Json),
216 };
217 }
218 if let Some(values) = schema.get("enum").and_then(Value::as_array) {
219 return Self::choice(values);
220 }
221 if let Some(value) = schema.get("const") {
222 return Self::choice(std::slice::from_ref(value));
223 }
224 if let Some(variants) = schema.get("anyOf").and_then(Value::as_array) {
225 let others: Vec<&Value> = variants
226 .iter()
227 .filter(|v| v.get("type").and_then(Value::as_str) != Some("null"))
228 .collect();
229 return match others.as_slice() {
230 [one] if others.len() < variants.len() => {
231 let mut shape = Self::of_schema(one, root, depth + 1);
232 if shape.kind != ParamKind::Json {
233 shape.nullable = true;
234 }
235 shape
236 }
237 _ => Self::plain(ParamKind::Json),
238 };
239 }
240 let format = schema.get("format").and_then(Value::as_str);
241 match schema.get("type").and_then(Value::as_str) {
242 Some("boolean") => Self::plain(ParamKind::Bool),
243 Some("integer") => Self::plain(ParamKind::Int),
244 Some("number") => Self::plain(ParamKind::Float),
245 Some("string") => Self::plain(match format {
246 Some("date") => ParamKind::Date,
247 Some("date-time") => ParamKind::Datetime,
248 Some("duration") => ParamKind::Duration,
249 _ => ParamKind::Text,
250 }),
251 _ => Self::plain(ParamKind::Json),
252 }
253 }
254}