1use std::collections::{BTreeMap, BTreeSet};
3
4use serde::{Deserialize, Serialize};
5
6use crate::extraction::ExtractionSchema;
7use crate::ids::{ContentDigest, PromptTemplateId};
8
9#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
10#[serde(deny_unknown_fields)]
11pub struct ExtractRules {
12 pub schema: String,
13 pub name: String,
14 pub version: String,
15 pub sources: Vec<ExtractionSource>,
16 #[serde(
19 default,
20 skip_serializing_if = "Option::is_none",
21 deserialize_with = "crate::screening::present"
22 )]
23 pub month_tables: Option<BTreeMap<String, Vec<Vec<String>>>>,
24 pub fields: Vec<FieldRules>,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
28#[serde(deny_unknown_fields)]
29pub struct ExtractionSource {
30 pub name: String,
31 #[serde(rename = "ref", deserialize_with = "crate::extraction::input_ref")]
32 pub reference: String,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
36#[serde(deny_unknown_fields)]
37pub struct FieldRules {
38 pub field: String,
39 pub rules: Vec<ExtractionRule>,
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
43#[serde(deny_unknown_fields)]
44pub struct ExtractionRule {
45 pub name: String,
46 pub when: ExtractionCondition,
47 pub then: ExtractionValue,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
51#[serde(rename_all = "snake_case", deny_unknown_fields)]
52pub enum ExtractionCondition {
53 Always,
54 ContainsAny {
55 source: String,
56 terms: Vec<String>,
57 },
58 ContainsAll {
59 source: String,
60 terms: Vec<String>,
61 },
62 All(Vec<ExtractionCondition>),
63 Any(Vec<ExtractionCondition>),
64 Not(Box<ExtractionCondition>),
65 Equals {
67 source: String,
68 value: Scalar,
69 },
70 OneOf {
72 source: String,
73 values: Vec<Scalar>,
74 },
75}
76
77#[derive(
80 Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema,
81)]
82#[serde(untagged)]
83pub enum Scalar {
84 Bool(bool),
85 Integer(i64),
86 Text(String),
87}
88
89#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
92#[serde(rename_all = "snake_case", deny_unknown_fields)]
93pub enum ByteClass {
94 Upper,
95 Lower,
96 Digit,
97 Range([String; 2]),
98}
99
100#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
103#[serde(rename_all = "snake_case", deny_unknown_fields)]
104pub enum ShapeElement {
105 Repeat {
106 class: Vec<ByteClass>,
107 min: u8,
108 max: u8,
109 },
110 OptionalSpace,
111 Byte(String),
112}
113
114#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
116#[serde(rename_all = "snake_case")]
117pub enum DateFormat {
118 YmdDash,
119 DmyName,
120 MdyName,
121 DmySlash,
122 MdySlash,
123 DmyDot,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
127#[serde(rename_all = "snake_case", deny_unknown_fields)]
128pub enum ExtractionValue {
129 Literal(serde_json::Value),
130 IntegerAfter {
131 source: String,
132 terms: Vec<String>,
133 max_digits: u8,
134 },
135 DateIso {
136 source: String,
137 occurrence: u8,
138 },
139 Record(BTreeMap<String, ExtractionValue>),
140 TokenAfter {
142 source: String,
143 terms: Vec<String>,
144 charset: Vec<ByteClass>,
145 min_len: u8,
146 max_len: u8,
147 },
148 TokenMatching {
151 source: String,
152 shape: Vec<ShapeElement>,
153 #[serde(
154 default,
155 skip_serializing_if = "Option::is_none",
156 deserialize_with = "crate::screening::present"
157 )]
158 occurrence: Option<u8>,
159 },
160 Date {
162 source: String,
163 format: DateFormat,
164 #[serde(
165 default,
166 skip_serializing_if = "Option::is_none",
167 deserialize_with = "crate::screening::present"
168 )]
169 months: Option<String>,
170 occurrence: u8,
171 },
172 VocabularyAfter {
174 source: String,
175 terms: Vec<String>,
176 vocabulary: String,
177 },
178}
179
180crate::document::versioned_document!(
181 ExtractRules,
182 [
183 crate::schema::EXTRACT_RULES,
184 crate::schema::EXTRACT_RULES_V2
185 ],
186 "rustev.extract-rules/1 or rustev.extract-rules/2",
187 crate::limits::DESCRIPTOR_V1,
188 check = ExtractRules::validate
189);
190
191impl crate::Identified for ExtractRules {
192 type Id = ContentDigest;
193 fn wrap(digest: String) -> ContentDigest {
194 ContentDigest::from_digest(digest)
195 }
196
197 fn id(&self) -> Result<ContentDigest, crate::canonical::CanonicalError> {
200 Ok(Self::wrap(crate::canonical::tagged_digest(
201 &self.schema,
202 &crate::Document::canonical(self)?,
203 )))
204 }
205}
206
207impl ExtractRules {
208 pub fn is_v2(&self) -> bool {
210 self.schema == crate::schema::EXTRACT_RULES_V2
211 }
212}
213
214fn terms(v: &[String]) -> Result<(), String> {
215 if v.len() > 64 || v.iter().any(|s| s.is_empty() || s.len() > 64) {
219 return Err("extraction terms require at most 64 entries of 1 to 64 bytes".into());
220 }
221 Ok(())
222}
223
224fn terms_v2(v: &[String]) -> Result<(), String> {
226 if v.is_empty() {
227 return Err("a version 2 extractor must have 1 to 64 terms".into());
228 }
229 terms(v)
230}
231
232fn classes(v: &[ByteClass]) -> Result<(), String> {
235 if !(1..=8).contains(&v.len()) {
236 return Err("a byte class list must have 1 to 8 entries".into());
237 }
238 for c in v {
239 if let ByteClass::Range([lo, hi]) = c {
240 match (printable_byte(lo), printable_byte(hi)) {
241 (Some(lo), Some(hi)) if lo <= hi => {}
242 _ => {
243 return Err(
244 "a byte range must be two one-byte strings from ! to ~ with lo <= hi"
245 .into(),
246 );
247 }
248 }
249 }
250 }
251 Ok(())
252}
253
254pub fn printable_byte(s: &str) -> Option<u8> {
256 match s.as_bytes() {
257 [b] if (0x21..=0x7e).contains(b) => Some(*b),
258 _ => None,
259 }
260}
261
262fn scalar(v: &Scalar) -> Result<(), String> {
263 match v {
264 Scalar::Text(s) if s.len() > 256 => {
265 Err("a condition text value must be at most 256 bytes".into())
266 }
267 _ => Ok(()),
268 }
269}
270
271impl ExtractionCondition {
272 fn validate(&self, depth: usize) -> Result<(), String> {
273 if depth > 8 {
274 return Err("extraction condition depth exceeds 8".into());
275 }
276 match self {
277 Self::Always => Ok(()),
278 Self::ContainsAny { terms: t, .. } | Self::ContainsAll { terms: t, .. } => terms(t),
279 Self::All(v) | Self::Any(v) => v.iter().try_for_each(|c| c.validate(depth + 1)),
280 Self::Not(c) => c.validate(depth + 1),
281 Self::Equals { value, .. } => scalar(value),
282 Self::OneOf { values, .. } => {
283 if !(1..=256).contains(&values.len())
284 || values.iter().collect::<BTreeSet<_>>().len() != values.len()
285 {
286 return Err("one_of must have 1 to 256 distinct values".into());
287 }
288 values.iter().try_for_each(scalar)
289 }
290 }
291 }
292
293 fn v2_member(&self) -> Option<&'static str> {
295 match self {
296 Self::Always | Self::ContainsAny { .. } | Self::ContainsAll { .. } => None,
297 Self::All(v) | Self::Any(v) => v.iter().find_map(Self::v2_member),
298 Self::Not(c) => c.v2_member(),
299 Self::Equals { .. } => Some("equals"),
300 Self::OneOf { .. } => Some("one_of"),
301 }
302 }
303}
304
305fn shape(v: &[ShapeElement]) -> Result<(), String> {
306 if !(1..=16).contains(&v.len()) {
307 return Err("a shape must have 1 to 16 elements".into());
308 }
309 if matches!(v.first(), Some(ShapeElement::OptionalSpace))
310 || matches!(v.last(), Some(ShapeElement::OptionalSpace))
311 {
312 return Err("optional_space must not be the first or the last element".into());
313 }
314 let mut min_len = 0u32;
315 for e in v {
316 match e {
317 ShapeElement::Repeat { class, min, max } => {
318 classes(class)?;
319 if min > max || !(1..=16).contains(max) {
320 return Err("a repeat must have 0 <= min <= max and 1 <= max <= 16".into());
321 }
322 min_len += u32::from(*min);
323 }
324 ShapeElement::OptionalSpace => {}
325 ShapeElement::Byte(b) => {
326 printable_byte(b).ok_or("a shape byte must be one byte from ! to ~")?;
327 min_len += 1;
328 }
329 }
330 }
331 if min_len == 0 {
332 return Err("a shape's minimum length must be at least 1".into());
333 }
334 Ok(())
335}
336
337fn occurrence(n: u8) -> Result<(), String> {
338 if !(1..=2).contains(&n) {
339 return Err("occurrence must be 1 or 2".into());
340 }
341 Ok(())
342}
343
344impl ExtractionValue {
345 fn validate(&self) -> Result<(), String> {
346 match self {
347 Self::Literal(_) => Ok(()),
348 Self::IntegerAfter {
349 terms: t,
350 max_digits,
351 ..
352 } => {
353 terms(t)?;
354 if !(1..=18).contains(max_digits) {
355 return Err("max_digits must be 1 to 18".into());
356 }
357 Ok(())
358 }
359 Self::DateIso { occurrence: n, .. } | Self::Date { occurrence: n, .. } => {
360 occurrence(*n)
361 }
362 Self::Record(v) => v.values().try_for_each(|value| {
363 if matches!(value, Self::Record(_)) {
364 return Err("a record value's subfields are scalar".into());
365 }
366 value.validate()
367 }),
368 Self::TokenAfter {
369 terms: t,
370 charset,
371 min_len,
372 max_len,
373 ..
374 } => {
375 terms_v2(t)?;
376 classes(charset)?;
377 if !(1 <= *min_len && min_len <= max_len && *max_len <= 64) {
378 return Err("token_after must have 1 <= min_len <= max_len <= 64".into());
379 }
380 Ok(())
381 }
382 Self::TokenMatching {
383 shape: v,
384 occurrence: n,
385 ..
386 } => {
387 shape(v)?;
388 n.map_or(Ok(()), occurrence)
389 }
390 Self::VocabularyAfter { terms: t, .. } => terms_v2(t),
391 }
392 }
393
394 fn v2_member(&self) -> Option<&'static str> {
396 match self {
397 Self::Literal(_) | Self::IntegerAfter { .. } | Self::DateIso { .. } => None,
398 Self::Record(v) => v.values().find_map(Self::v2_member),
399 Self::TokenAfter { .. } => Some("token_after"),
400 Self::TokenMatching { .. } => Some("token_matching"),
401 Self::Date { .. } => Some("date"),
402 Self::VocabularyAfter { .. } => Some("vocabulary_after"),
403 }
404 }
405}
406
407fn table_name(s: &str) -> bool {
409 let b = s.as_bytes();
410 (1..=16).contains(&b.len())
411 && b[0].is_ascii_lowercase()
412 && b[1..]
413 .iter()
414 .all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || *c == b'_')
415}
416
417fn month_tables(tables: &BTreeMap<String, Vec<Vec<String>>>) -> Result<(), String> {
418 if !(1..=4).contains(&tables.len()) {
419 return Err("month_tables must have 1 to 4 tables".into());
420 }
421 for (name, months) in tables {
422 if !table_name(name) {
423 return Err(format!("invalid month table name {name:?}"));
424 }
425 if months.len() != 12 {
426 return Err(format!("month table {name} must have exactly 12 entries"));
427 }
428 let mut seen = BTreeSet::new();
429 for names in months {
430 if !(1..=4).contains(&names.len()) {
431 return Err(format!("a month of table {name} must have 1 to 4 names"));
432 }
433 for n in names {
434 if !(1..=16).contains(&n.len())
435 || n.bytes().any(|b| {
436 b.is_ascii_control()
437 || b.is_ascii_digit()
438 || matches!(b, b' ' | b',' | b'.' | b'/' | b'-')
439 })
440 {
441 return Err(format!("invalid month name {n:?} in table {name}"));
442 }
443 if !seen.insert(n.to_ascii_lowercase()) {
444 return Err(format!("month name {n:?} repeats in table {name}"));
445 }
446 }
447 }
448 }
449 Ok(())
450}
451
452impl ExtractRules {
453 fn validate(&self) -> Result<(), String> {
454 if !self.is_v2() {
457 let member = self
458 .month_tables
459 .as_ref()
460 .map(|_| "month_tables")
461 .or_else(|| {
462 self.fields
463 .iter()
464 .flat_map(|f| &f.rules)
465 .find_map(|r| r.when.v2_member().or_else(|| r.then.v2_member()))
466 });
467 if let Some(member) = member {
468 return Err(format!(
469 "unknown member {member} in {}",
470 crate::schema::EXTRACT_RULES
471 ));
472 }
473 }
474 if let Some(tables) = &self.month_tables {
475 month_tables(tables)?;
476 }
477 if self.fields.len() > 32 {
478 return Err("extraction program exceeds 32 fields".into());
479 }
480 for f in &self.fields {
481 if f.rules.len() > 128 {
482 return Err("extraction field exceeds 128 rules".into());
483 }
484 for r in &f.rules {
485 r.when.validate(1)?;
486 r.then.validate()?;
487 }
488 }
489 Ok(())
490 }
491}
492
493#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
495#[serde(deny_unknown_fields)]
496pub struct ExtractRequest {
497 pub schema: String,
498 pub step: String,
499 pub template: String,
500 pub template_id: PromptTemplateId,
501 pub instructions: String,
502 pub projection: BTreeMap<String, serde_json::Value>,
503 pub output: ExtractionSchema,
504 pub schema_digest: ContentDigest,
505 pub vocabularies: BTreeMap<String, Vec<String>>,
506}
507
508crate::document::versioned_document!(
509 ExtractRequest,
510 [crate::schema::EXTRACT_REQUEST],
511 "rustev.extract-request/1",
512 crate::limits::RECORD_V1,
513 check = ExtractRequest::validate
514);
515
516impl ExtractRequest {
517 fn validate(&self) -> Result<(), String> {
518 if self.schema_digest
519 != extraction_schema_digest(&self.output).map_err(|e| e.to_string())?
520 {
521 return Err("extraction schema digest disagrees with output".into());
522 }
523 Ok(())
524 }
525}
526
527pub fn extraction_schema_digest(
530 schema: &ExtractionSchema,
531) -> Result<ContentDigest, crate::canonical::CanonicalError> {
532 crate::generation_result::generation_value_digest(schema)
533}