1use crate::{
3 Decimal,
4 definition::{BackendReq, Predicate},
5 generation::{CostLimit, GenerateScreen, Repair, ScreenOutput, TemplateRef, Vocabulary},
6};
7use serde::{Deserialize, Deserializer, Serialize};
8use std::collections::{BTreeMap, BTreeSet};
9
10#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
11#[serde(deny_unknown_fields)]
12pub struct Extract {
13 pub for_each: NoneOnly,
14 pub template: TemplateRef,
15 #[serde(deserialize_with = "projection")]
16 pub projection: Vec<String>,
17 pub vocabularies: BTreeMap<String, ExtractionVocabulary>,
18 pub output: ExtractionSchema,
19 pub distributions: Distributions,
20 pub repair: Repair,
21 pub screen: GenerateScreen,
22 pub limits: ExtractionLimits,
23 pub backend: BackendReq,
24 pub fallback: Fallback,
25}
26impl<'de> Deserialize<'de> for Extract {
27 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
28 #[derive(Deserialize)]
29 #[serde(remote = "Extract", deny_unknown_fields)]
30 struct Wire {
31 pub for_each: NoneOnly,
32 pub template: TemplateRef,
33 #[serde(deserialize_with = "projection")]
34 pub projection: Vec<String>,
35 pub vocabularies: BTreeMap<String, ExtractionVocabulary>,
36 pub output: ExtractionSchema,
37 pub distributions: Distributions,
38 pub repair: Repair,
39 pub screen: GenerateScreen,
40 pub limits: ExtractionLimits,
41 pub backend: BackendReq,
42 pub fallback: Fallback,
43 }
44 let v = Wire::deserialize(d)?;
45 if v.repair.max_attempts != 0 || v.screen.output != ScreenOutput::None {
46 return Err(serde::de::Error::custom(
47 "extraction requires no repair or output screening",
48 ));
49 }
50 fn declared(ty: &ExtractionType, vocab: &BTreeMap<String, ExtractionVocabulary>) -> bool {
51 match ty {
52 ExtractionType::Enum { vocabulary } => vocab.contains_key(vocabulary),
53 ExtractionType::List { item, .. } => declared(item, vocab),
54 ExtractionType::Record { fields } => fields.iter().all(|f| declared(&f.ty, vocab)),
55 _ => true,
56 }
57 }
58 if !v
59 .output
60 .fields
61 .iter()
62 .all(|f| declared(&f.ty, &v.vocabularies))
63 {
64 return Err(serde::de::Error::custom("undeclared extraction vocabulary"));
65 }
66 Ok(v)
67 }
68}
69#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
70#[serde(rename_all = "snake_case")]
71pub enum NoneOnly {
72 None,
73}
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
75#[serde(untagged, deny_unknown_fields)]
79pub enum ExtractionVocabulary {
80 Envelope(Vocabulary),
81 Input {
82 #[serde(deserialize_with = "input_ref")]
83 input: String,
84 },
85}
86#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
87#[serde(rename_all = "snake_case")]
88pub enum Distributions {
89 None,
90 WhenAvailable,
91}
92#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
93#[serde(deny_unknown_fields)]
94pub struct ExtractionLimits {
95 #[serde(deserialize_with = "crate::generation::deadline_share")]
96 pub deadline_share: Decimal,
97 pub max_cost_units: CostLimit,
98}
99#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
100#[serde(rename_all = "snake_case", deny_unknown_fields)]
101pub enum Fallback {
102 None,
103 #[serde(untagged)]
104 Rules(#[serde(deserialize_with = "crate::generation::object")] ExtractionRules),
105}
106#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
107#[serde(deny_unknown_fields)]
108pub struct ExtractionRules {
109 #[serde(deserialize_with = "rules_program")]
110 pub rules_program: String,
111 pub fill: Fill,
112 #[serde(
116 default,
117 skip_serializing_if = "Option::is_none",
118 deserialize_with = "crate::screening::present"
119 )]
120 pub required: Option<Vec<String>>,
121}
122#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
123#[serde(rename_all = "snake_case")]
124pub enum Fill {
125 RequestFailure,
126 AbsentFields,
127 RulesFirst,
129}
130#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
131#[serde(deny_unknown_fields)]
132pub struct ExtractionSchema {
133 #[serde(deserialize_with = "fields::<_, 32>")]
134 pub fields: Vec<ExtractionField>,
135}
136#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
137#[serde(deny_unknown_fields)]
138pub struct ExtractionField {
139 pub name: String,
140 #[serde(rename = "type")]
141 pub ty: ExtractionType,
142}
143#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
144#[serde(rename_all = "snake_case", deny_unknown_fields)]
145pub enum ExtractionType {
146 Bool {},
147 Integer {
148 #[serde(deserialize_with = "integer_bounds")]
149 bounds: [i64; 2],
150 },
151 Decimal(DecimalBounds),
152 Text {
153 #[serde(deserialize_with = "crate::generation::bound::<_, 4096>")]
154 max_bytes: u64,
155 },
156 Date {},
157 Enum {
158 vocabulary: String,
159 },
160 List {
161 #[serde(deserialize_with = "list_item")]
162 item: Box<ExtractionType>,
163 #[serde(deserialize_with = "crate::generation::bound::<_, 64>")]
164 max_items: u64,
165 },
166 Record {
167 #[serde(deserialize_with = "record_fields")]
168 fields: Vec<ExtractionField>,
169 },
170}
171#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
172#[serde(deny_unknown_fields)]
173pub struct DecimalBounds {
174 pub bounds: [String; 2],
175 pub scale: u32,
176}
177impl<'de> Deserialize<'de> for DecimalBounds {
178 fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
179 #[derive(Deserialize)]
180 #[serde(remote = "DecimalBounds", deny_unknown_fields)]
181 struct Wire {
182 bounds: [String; 2],
183 scale: u32,
184 }
185 let v = Wire::deserialize(d)?;
186 let [lo, hi] = [&v.bounds[0], &v.bounds[1]].map(|s| Decimal::parse(s));
187 if v.scale > 9
188 || v.bounds.iter().any(|s| {
189 s.split_once('.')
190 .is_some_and(|(_, f)| f.len() > v.scale as usize)
191 })
192 || !matches!((lo, hi), (Ok(lo), Ok(hi)) if lo <= hi)
193 {
194 return Err(serde::de::Error::custom(
195 "invalid extraction decimal bounds or scale",
196 ));
197 }
198 Ok(v)
199 }
200}
201#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
202#[serde(deny_unknown_fields)]
203pub struct AcceptModelDerived {
204 #[serde(deserialize_with = "field_ref")]
205 pub field: String,
206 pub validate: Validation,
207 pub min_mass: MinMass,
208 pub on_fail: OnFail,
209}
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
211#[serde(rename_all = "snake_case", deny_unknown_fields)]
212pub enum Validation {
213 None,
214 Predicate(Predicate),
215}
216#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
217#[serde(rename_all = "snake_case", deny_unknown_fields)]
218pub enum MinMass {
219 None,
220 #[serde(untagged)]
221 Threshold(#[serde(deserialize_with = "crate::generation::object")] MassThreshold),
222}
223#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
224#[serde(deny_unknown_fields)]
225pub struct MassThreshold {
226 pub option: String,
227 #[serde(deserialize_with = "probability_threshold")]
228 pub at_least: Decimal,
229 pub basis: MassBasis,
230}
231#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
232#[serde(rename_all = "snake_case", deny_unknown_fields)]
233pub enum MassBasis {
234 Calibration(String),
235 UncalibratedThreshold(#[serde(deserialize_with = "uncalibrated_reason")] String),
236}
237fn probability_threshold<'de, D: Deserializer<'de>>(d: D) -> Result<Decimal, D::Error> {
238 let v = Decimal::deserialize(d)?;
239 if v < Decimal::ZERO || v > Decimal::from_i64(1) {
240 return Err(serde::de::Error::custom(
241 "a probability threshold is in [0, 1]",
242 ));
243 }
244 Ok(v)
245}
246fn uncalibrated_reason<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
247 let v = String::deserialize(d)?;
248 if v.is_empty() {
249 return Err(serde::de::Error::custom(
250 "an uncalibrated threshold states its reason",
251 ));
252 }
253 Ok(v)
254}
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
256#[serde(rename_all = "snake_case", deny_unknown_fields)]
257pub enum OnFail {
258 DropField {
259 #[serde(deserialize_with = "notice")]
260 notice: String,
261 },
262 Unresolved,
263}
264#[derive(
265 Debug,
266 Clone,
267 Copy,
268 PartialEq,
269 Eq,
270 PartialOrd,
271 Ord,
272 Hash,
273 Serialize,
274 Deserialize,
275 schemars::JsonSchema,
276)]
277#[serde(rename_all = "snake_case", deny_unknown_fields)]
278pub enum AbsenceReason {
279 Missing,
280 WrongType,
281 TooLong,
282 ControlCharacter,
283 NotInVocabulary,
284 DuplicateItem,
285 TooManyItems,
286 OutOfBounds,
287 InvalidDate,
288 VocabularyUnavailable,
289 SourceUnavailable,
290 ScreenBlocked,
291 ScreenUnavailable,
292 RequestFailed { reason: RequestFailure },
293 FallbackNoMatch,
294 FallbackInvalid,
295}
296#[derive(
297 Debug,
298 Clone,
299 Copy,
300 PartialEq,
301 Eq,
302 PartialOrd,
303 Ord,
304 Hash,
305 Serialize,
306 Deserialize,
307 schemars::JsonSchema,
308)]
309#[serde(rename_all = "snake_case")]
310pub enum RequestFailure {
311 BackendUnavailable,
312 InvalidBackendOutput,
313 DeadlineExceeded,
314 BudgetExhausted,
315 Cancelled,
316}
317fn fields<'de, D: Deserializer<'de>, const MAX: usize>(
318 d: D,
319) -> Result<Vec<ExtractionField>, D::Error> {
320 let v = Vec::<ExtractionField>::deserialize(d)?;
321 let mut names = BTreeSet::new();
322 if !(1..=MAX).contains(&v.len())
323 || v.iter()
324 .any(|f| !crate::parameter::is_parameter_name(&f.name) || !names.insert(&f.name))
325 {
326 return Err(serde::de::Error::custom(
327 "invalid extraction field count or names",
328 ));
329 }
330 Ok(v)
331}
332fn record_fields<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<ExtractionField>, D::Error> {
333 let v = fields::<D, 16>(d)?;
334 if v.iter().any(|f| {
335 matches!(
336 f.ty,
337 ExtractionType::List { .. } | ExtractionType::Record { .. }
338 )
339 }) {
340 return Err(serde::de::Error::custom("record subfields must be scalar"));
341 }
342 Ok(v)
343}
344fn list_item<'de, D: Deserializer<'de>>(d: D) -> Result<Box<ExtractionType>, D::Error> {
345 let v = ExtractionType::deserialize(d)?;
346 if !matches!(v, ExtractionType::Text { .. } | ExtractionType::Enum { .. }) {
347 return Err(serde::de::Error::custom("list items must be text or enum"));
348 }
349 Ok(Box::new(v))
350}
351fn integer_bounds<'de, D: Deserializer<'de>>(d: D) -> Result<[i64; 2], D::Error> {
352 let v = <[i64; 2]>::deserialize(d)?;
353 if v[0] > v[1] {
354 return Err(serde::de::Error::custom("reversed integer bounds"));
355 }
356 Ok(v)
357}
358fn notice<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
359 let v = String::deserialize(d)?;
360 if !crate::parameter::is_parameter_name(&v) {
361 return Err(serde::de::Error::custom("invalid notice code"));
362 }
363 Ok(v)
364}
365fn valid_ref(s: &str, prefix: &str, min: usize, max: usize) -> bool {
366 s.strip_prefix(prefix).is_some_and(|s| {
367 let parts: Vec<_> = s.split('/').collect();
368 (min..=max).contains(&parts.len())
369 && parts
370 .iter()
371 .all(|p| !p.is_empty() && !p.contains(':') && !p.chars().any(char::is_whitespace))
372 })
373}
374pub(crate) fn input_ref<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
375 let v = String::deserialize(d)?;
376 if !valid_ref(&v, "input:", 1, 2) {
377 return Err(serde::de::Error::custom("invalid input reference"));
378 }
379 Ok(v)
380}
381fn field_ref<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
382 let v = String::deserialize(d)?;
383 if !valid_ref(&v, "input:", 1, 2) && !valid_ref(&v, "step:", 2, 2) {
384 return Err(serde::de::Error::custom(
385 "invalid acceptance field reference",
386 ));
387 }
388 Ok(v)
389}
390fn projection<'de, D: Deserializer<'de>>(d: D) -> Result<Vec<String>, D::Error> {
391 let v = Vec::<String>::deserialize(d)?;
392 if !(1..=8).contains(&v.len())
393 || v.iter()
394 .any(|s| !valid_ref(s, "input:", 1, 2) && !valid_ref(s, "step:", 1, 3))
395 {
396 return Err(serde::de::Error::custom("invalid extraction projection"));
397 }
398 Ok(v)
399}
400fn rules_program<'de, D: Deserializer<'de>>(d: D) -> Result<String, D::Error> {
401 let v = String::deserialize(d)?;
402 if !v
403 .split_once('@')
404 .is_some_and(|(n, ver)| !n.is_empty() && !ver.is_empty() && !ver.contains('@'))
405 || v.chars().any(char::is_whitespace)
406 {
407 return Err(serde::de::Error::custom(
408 "expected rules program name@version",
409 ));
410 }
411 Ok(v)
412}