predsync_compiler/
validate.rs1use predsync_schema::{
4 MAX_ENUM_VARIANTS, MAX_FIELDS, MAX_MESSAGES, MAX_WINDOW, MessageSchema, ParsedSchema,
5 PredictorKind, SchemaError, SchemaSet, Warning, WarningKind, is_identifier,
6};
7use std::string::String;
8use std::vec::Vec;
9
10pub fn validate(messages: Vec<MessageSchema>) -> Result<ParsedSchema, SchemaError> {
12 if messages.len() > MAX_MESSAGES {
13 return Err(SchemaError::Unsupported("too many messages".into()));
14 }
15 let mut warnings = Vec::new();
16 for message in &messages {
17 validate_message(message, &mut warnings)?;
18 }
19 Ok(ParsedSchema {
20 set: SchemaSet { messages },
21 warnings,
22 })
23}
24
25fn validate_message(
26 message: &MessageSchema,
27 warnings: &mut Vec<Warning>,
28) -> Result<(), SchemaError> {
29 if !is_identifier(&message.name) {
30 return Err(SchemaError::InvalidIdentifier(message.name.clone()));
31 }
32 if let Some(namespace) = &message.namespace
33 && !is_identifier(namespace)
34 {
35 return Err(SchemaError::InvalidIdentifier(namespace.clone()));
36 }
37 validate_enums(message)?;
38 if message.fields.len() > MAX_FIELDS {
39 return Err(SchemaError::TooManyFields(message.fields.len()));
40 }
41
42 let mut names = Vec::with_capacity(message.fields.len());
43 for (index, field) in message.fields.iter().enumerate() {
44 if !is_identifier(&field.name) {
45 return Err(SchemaError::InvalidIdentifier(field.name.clone()));
46 }
47 if names.contains(&field.name) {
48 return Err(SchemaError::DuplicateField(index));
49 }
50 names.push(field.name.clone());
51 validate_field(message, field, index, warnings)?;
52 }
53 Ok(())
54}
55
56fn validate_enums(message: &MessageSchema) -> Result<(), SchemaError> {
57 let mut names = Vec::with_capacity(message.enums.len());
58 for (index, enum_def) in message.enums.iter().enumerate() {
59 if !is_identifier(&enum_def.name) {
60 return Err(SchemaError::InvalidIdentifier(enum_def.name.clone()));
61 }
62 if names.contains(&enum_def.name) {
63 return Err(SchemaError::DuplicateEnum(index));
64 }
65 names.push(enum_def.name.clone());
66 if enum_def.variants.is_empty() {
67 return Err(SchemaError::EnumNoVariants(index));
68 }
69 if enum_def.variants.len() > MAX_ENUM_VARIANTS {
70 return Err(SchemaError::EnumTooLarge(index));
71 }
72 let mut variants = Vec::with_capacity(enum_def.variants.len());
73 for variant in &enum_def.variants {
74 if !is_identifier(variant) {
75 return Err(SchemaError::InvalidIdentifier(variant.clone()));
76 }
77 if variants.contains(variant) {
78 return Err(SchemaError::DuplicateVariant(index));
79 }
80 variants.push(variant.clone());
81 }
82 }
83 Ok(())
84}
85
86fn validate_field(
87 message: &MessageSchema,
88 field: &predsync_schema::FieldSchema,
89 index: usize,
90 warnings: &mut Vec<Warning>,
91) -> Result<(), SchemaError> {
92 validate_max_len(field, index)?;
93 validate_quantise(field, index)?;
94 validate_range(field, index)?;
95 validate_predictor_and_tolerance(field, index)?;
96 validate_periods(message, field, index, warnings)
97}
98
99fn validate_max_len(field: &predsync_schema::FieldSchema, index: usize) -> Result<(), SchemaError> {
100 if field.ty.requires_max_len() {
101 match field.max_len {
102 None => return Err(SchemaError::MissingMaxLen(index)),
103 Some(0) => return Err(SchemaError::ZeroMaxLen(index)),
104 Some(_) => {}
105 }
106 } else if field.max_len.is_some() {
107 return Err(SchemaError::MaxLenOnFixedType(index));
108 }
109 Ok(())
110}
111
112fn validate_quantise(
113 field: &predsync_schema::FieldSchema,
114 index: usize,
115) -> Result<(), SchemaError> {
116 if let Some(step) = field.quantise {
117 if !step.is_finite() || step <= 0.0 {
118 return Err(SchemaError::QuantiseNotPositive(index));
119 }
120 if !field.ty.is_numeric() {
121 return Err(SchemaError::QuantiseNotAllowedForType(index));
122 }
123 }
124 Ok(())
125}
126
127fn validate_range(field: &predsync_schema::FieldSchema, index: usize) -> Result<(), SchemaError> {
128 if let Some((low, high)) = field.range {
129 if field.quantise.is_none() {
130 return Err(SchemaError::RangeWithoutQuantise(index));
131 }
132 if !low.is_finite() || !high.is_finite() || low >= high {
133 return Err(SchemaError::InvalidRange(index));
134 }
135 }
136 Ok(())
137}
138
139fn validate_predictor_and_tolerance(
140 field: &predsync_schema::FieldSchema,
141 index: usize,
142) -> Result<(), SchemaError> {
143 if let Some(predictor) = &field.predictor
144 && field.ty.is_opaque()
145 && !matches!(predictor.kind, PredictorKind::HoldLast)
146 {
147 return Err(SchemaError::PredictorNotAllowedForType(index));
148 }
149 if let Some(predictor) = &field.predictor
150 && matches!(predictor.kind, PredictorKind::Custom(_))
151 && predictor.window.is_none()
152 {
153 return Err(SchemaError::MissingPredictorParam(String::from("window")));
154 }
155 if let Some(predictor) = &field.predictor
156 && matches!(predictor.kind, PredictorKind::Ewma)
157 {
158 match predictor.alpha {
159 None => return Err(SchemaError::MissingPredictorParam(String::from("alpha"))),
160 Some(alpha) if !alpha.is_finite() || alpha <= 0.0 || alpha > 1.0 => {
161 return Err(SchemaError::Unsupported(
162 "alpha must be finite and in (0, 1]".into(),
163 ));
164 }
165 Some(_) => {}
166 }
167 }
168
169 if let Some(predictor) = &field.predictor {
170 if predictor.kind.needs_window() && predictor.window.is_none() {
171 return Err(SchemaError::MissingPredictorParam(String::from("window")));
172 }
173 if let Some(window) = predictor.window {
174 if window > MAX_WINDOW {
175 return Err(SchemaError::WindowTooLarge(index));
176 }
177 if window < predictor.kind.min_samples() {
178 return Err(SchemaError::WindowTooSmall(index));
179 }
180 }
181 }
182
183 if field.tolerance.is_some() && field.ty.is_opaque() {
184 return Err(SchemaError::ToleranceNotAllowedForType(index));
185 }
186 if field.predictor.is_some() && field.tolerance.is_none() && !field.ty.is_opaque() {
187 return Err(SchemaError::PredictorWithoutTolerance(index));
188 }
189 if field.tolerance.is_some() && field.predictor.is_none() {
190 return Err(SchemaError::ToleranceWithoutPredictor(index));
191 }
192
193 if let Some(tolerance) = &field.tolerance {
194 if tolerance.abs.is_none() && tolerance.rel.is_none() {
195 return Err(SchemaError::NoToleranceBound(index));
196 }
197 if let (Some(step), Some(abs)) = (field.quantise, tolerance.abs)
198 && abs < step
199 {
200 return Err(SchemaError::ToleranceBelowQuantiseStep(index));
201 }
202 }
203 Ok(())
204}
205
206fn validate_periods(
207 message: &MessageSchema,
208 field: &predsync_schema::FieldSchema,
209 index: usize,
210 warnings: &mut Vec<Warning>,
211) -> Result<(), SchemaError> {
212 let refresh = field.refresh.or_else(|| message.sync.as_ref()?.refresh);
213 let reset = field.reset.or_else(|| message.sync.as_ref()?.reset);
214 if refresh == Some(0) || reset == Some(0) {
215 return Err(SchemaError::ZeroPeriod(index));
216 }
217 if let (Some(refresh), Some(reset)) = (refresh, reset)
218 && reset % refresh != 0
219 {
220 return Err(SchemaError::ResetNotMultipleOfRefresh(index));
221 }
222 if let (Some(predictor), Some(window), Some(refresh)) = (
223 &field.predictor,
224 field.predictor.as_ref().and_then(|p| p.window),
225 refresh,
226 ) && predictor.kind.needs_window()
227 && refresh < u32::from(window)
228 {
229 return Err(SchemaError::RefreshBelowWindow(index));
230 }
231 if field.predictor.is_some() && refresh.is_none() && reset.is_none() {
232 warnings.push(Warning {
233 kind: WarningKind::NoRecoveryConfigured,
234 message: String::from("no recovery on a one-way link beyond the startup Reset"),
235 });
236 }
237 Ok(())
238}