1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
use std::collections::HashMap;
use std::error::Error;
use std::ffi::OsStr;
use std::fmt::{Debug, Display, Formatter};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use log::{debug, info, trace};
use regex::{Captures, Regex};
use kjp_generator_plugin::json_path_to_object_key;
use crate::processors::ProcessorGenerationError::{GeneratorUnknown, RequiredConfigNotFound};
use crate::Stream;

#[derive(Eq, PartialEq, Debug)]
pub struct Processor {
    pub function_name: String,
    pub function_body: String,
}

#[derive(Debug, Eq, PartialEq)]
pub enum ProcessorGenerationError {
    RequiredConfigNotFound {
        function_name: String,
        field_name: String,
        description: Option<String>,
    },
    GeneratorUnknown {
        name: String,
    },
    GeneratorError {
        description: String,
    }
}

impl Display for ProcessorGenerationError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            RequiredConfigNotFound { function_name, field_name, description } =>
                write!(f, "Processor required config that was missing in template. Function: {}, missing field: {}. Description: {}",
                       function_name, field_name, description.clone().unwrap_or_else(|| "N/A".to_string())
                ),
            GeneratorUnknown { name } =>
                write!(f, "Failed to generate function. Generator is unknown: {name}"),
            ProcessorGenerationError::GeneratorError { description } =>
                write!(f, "Failed to generate function. {description}"),
        }
    }
}

impl Error for ProcessorGenerationError {}

/// Creates a map of code generators from given path.
///
/// This creates a dictionary of all available processor types.
/// Each generator is a program that generates a processor function body,
/// which will be used for processing JSON messages in a given stream.
///
/// This function will scan given path for files. Each file will be treated as a separate generator.
/// Each generator will have the name of corresponding file, but without extension.
/// In case of name conflict, last found generator will overwrite previous ones.
///
/// Please be careful what directory you use, as the generation process runs executables from the directory.
pub fn create_processor_generators<P: AsRef<Path>>(generators_path: P) -> Result<HashMap<String, PathBuf>, Box<dyn Error>> {
    info!("Loading available generators from: {:?}", generators_path.as_ref());

    let m: HashMap<String, PathBuf> = fs::read_dir(&generators_path)?
        .into_iter()
        .filter_map(|entry| entry.map_err(|err|  {
            info!("Cannot read file in [{:?}]: {}", generators_path.as_ref(), err);
            err
        }).ok())
        .filter(|entry| entry.file_type()
            .map(|e| e.is_file())
            .unwrap_or(false)
        )
        .filter_map(|entry| {
            let generator_name = entry.path().file_stem()?.to_str()?.to_string();
            let generator_path = entry.path();
            info!("Generator found: {} [{:?}]", generator_name, generator_path);

            Some((generator_name, generator_path))
        })
        .collect();

    Ok(m)
}

pub const FIELD_KEY: &str = "field";
pub const GENERATOR_KEY: &str = "generator";

/// Generates code for all processors in a stream.
///
/// This function generates a vec of [`Processor`], which contains function name and function source.
/// Each element represents a processor function which will be running as a part of the stream
/// in the target JSON processor executable.
pub fn generate_processors(stream: Stream, generators: &HashMap<String, PathBuf>) -> Result<Vec<Processor>, Box<dyn Error>> {
    debug!("Generating processors...");
    stream.processors.iter()
        .enumerate()
        .map(|(index, config)| {
            let generator_name = config.get(GENERATOR_KEY)
                .ok_or_else(|| RequiredConfigNotFound {
                    function_name: generate_function_name(&stream, index, "UNKNOWN"),
                    field_name: GENERATOR_KEY.to_string(),
                    description: None
                })?;

            let generator_path = generators.get(generator_name)
                .ok_or_else(|| GeneratorUnknown {
                    name: generator_name.to_string()
                })?;

            let function_name = generate_function_name(&stream, index, generator_name);
            debug!("Generating processor [{}] (generator: {})", function_name, generator_name);
            Ok(Processor {
                function_name: function_name.clone(),
                function_body: generate_source(generator_path, &function_name, config)?,
            })
        })
        .collect()
}

fn generate_function_name(stream: &Stream, index: usize, generator_name: &str) -> String {
    format!("{}_{}_{}_{}", stream.input_topic, stream.output_topic, index, generator_name)
}

fn generate_source<P: AsRef<OsStr>>(generator_path: P, function_name: &str, config: &HashMap<String, String>)
    -> Result<String, ProcessorGenerationError> {

    let generator_path_str = generator_path.as_ref().to_str().unwrap_or("");

    let mut args = vec![function_name];
    config.iter()
        .for_each(|(key, value)| {
            args.push(key);
            args.push(value);
        });

    trace!("Running [{:?}] with arguments {:?}", generator_path.as_ref(), args);

    let output = Command::new(&generator_path)
        .args(args)
        .stdout(Stdio::piped())
        .stderr(Stdio::inherit())
        .output()
        .map_err(|err| ProcessorGenerationError::GeneratorError {
            description: format!("Generator error process failed [{generator_path_str}]: {err}"),
        })?;

    let result = String::from_utf8(output.stdout)
        .map_err(|err| ProcessorGenerationError::GeneratorError {
            description: format!("Cannot read output of [{generator_path_str}] (not a valid UTF-8 string): {err}"),
        })?;

    if !output.status.success() {
        return Err(ProcessorGenerationError::GeneratorError {
            description: format!("[{}] Process finished without success (status: [{}], output: [{}])",
                generator_path_str, output.status, result
            )
        })
    }

    trace!("[{} output] {}", generator_path_str, result);

    let jsonpath_regex = Regex::new("(##JSONPATH\\(.*\\)##)").unwrap();

    interpret_child_output(generator_path_str, result)
        .map(|source| {
            jsonpath_regex.replace_all(&source, |caps: &Captures| {
                trace!("Replacing {} with actual object tree accessor.", &caps[1]);
                let capture = &caps[1];
                let capture = &capture["##JSONPATH(".len()..capture.len()-")##".len()];
                json_path_to_object_key(capture)
            }).to_string()
        })
}

fn interpret_child_output(generator_path_str: &str, output: String) -> Result<String, ProcessorGenerationError> {
    if output.is_empty() {
        return Err(ProcessorGenerationError::GeneratorError {
            description: format!("[{generator_path_str}] Process output is empty."),
        })
    }

    let string: String = output.lines()
        .skip(1)
        .collect::<Vec<&str>>()
        .join("\n");

    if output.starts_with("OK") {
        Ok(string)
    } else {
        Err(ProcessorGenerationError::GeneratorError {
            description: format!("[{generator_path_str}] {string}."),
        })
    }
}


#[cfg(test)]
mod test {
    use std::collections::HashMap;
    use std::path::PathBuf;
    use crate::{generate_processors, Stream};
    use crate::processors::Processor;

    #[test]
    fn should_generate_function() {
        let stream = Stream {
            input_topic: "abc".to_string(),
            output_topic: "def".to_string(),
            processors: vec![
                HashMap::from([
                    ("generator".to_string(), "test_generator".to_string()),
                    ("field".to_string(), "static_field0".to_string()),
                    ("value".to_string(), "hello world".to_string()),
                ])
            ]
        };
        let mut generators: HashMap<String, PathBuf> = HashMap::new();
        generators.insert("test_generator".to_string(), PathBuf::from("../kjp-generator-generators/static_field.sh"));

        let result = generate_processors(stream, &generators);
        match result {
            Ok(actual) =>
                assert_eq!(vec![
                    Processor {
                        function_name: "abc_def_0_test_generator".to_string(),
                        function_body: r#"fn abc_def_0_test_generator(_input: &Value, message: &mut OutputMessage) -> Result<(), ProcessingError> {
    message.insert_val(&[Key("static_field0".to_string())], Value::String("hello world".to_string()))?;
    Ok(())
}
"#.to_string()
                    },
                ], actual),
            Err(e) =>
                assert_eq!("Ok(_)", &format!("Err({e})")),
        }
    }
}