batch_mode_batch_schema/
batch_message_content.rs

1// ---------------- [ File: src/batch_message_content.rs ]
2crate::ix!();
3
4#[derive(Debug,PartialEq,Eq,Serialize,Deserialize)]
5#[serde(transparent)]
6pub struct BatchMessageContent {
7    content:            String,
8    #[serde(skip)]
9    sanitized_json_str: OnceCell<String>,
10}
11
12impl PartialEq<str> for BatchMessageContent {
13
14    fn eq(&self, other: &str) -> bool{
15        self.as_ref().eq(other)
16    }
17}
18
19impl AsRef<str> for BatchMessageContent {
20    fn as_ref(&self) -> &str {
21        &self.content
22    }
23}
24
25impl BatchMessageContent {
26
27    pub fn as_str(&self) -> &str {
28        &self.content
29    }
30
31    pub fn get_sanitized_json_str(&self) -> &str {
32        self.sanitized_json_str.get_or_init(|| {
33            let json_str = extract_json_from_possible_backticks_block(&self.content);
34            sanitize_json_str(&json_str)
35        })
36    }
37
38    /// Generalized JSON parsing method using JsonParsingStrategy.
39    fn parse_inner_json(&self, strategy: JsonParsingStrategy) -> Result<Value, JsonParseError> {
40        let sanitized_json_str = self.get_sanitized_json_str();
41        match serde_json::from_str(&sanitized_json_str) {
42            Ok(json_value) => Ok(json_value),
43            Err(e) => {
44                warn!(
45                    "Failed to parse JSON string. Will try to repair it. Error: {}",
46                     e
47                );
48
49                match strategy {
50                    JsonParsingStrategy::WithRepair => {
51                        // Attempt to repair the JSON
52                        match repair_json_with_known_capitalized_sentence_fragment_list_items(&sanitized_json_str) {
53                            Ok(repaired_json) => {
54                                warn!("Successfully repaired JSON.");
55                                Ok(repaired_json)
56                            }
57                            Err(e) => {
58                                error!("Failed to repair JSON: {}, Error: {}", sanitized_json_str, e);
59                                Err(e.into())
60                            }
61                        }
62                    }
63                    JsonParsingStrategy::WithoutRepair => Err(e.into()),
64                }
65            }
66        }
67    }
68
69    /// Extracts and parses JSON without attempting repair.
70    pub fn extract_clean_parse_json(&self) -> Result<Value, JsonParseError> {
71        self.parse_inner_json(JsonParsingStrategy::WithoutRepair)
72    }
73
74    /// Extracts and parses JSON, attempting to repair on failure.
75    pub fn extract_clean_parse_json_with_repair(&self) -> Result<Value, JsonParseError> {
76        self.parse_inner_json(JsonParsingStrategy::WithRepair)
77    }
78}