Skip to main content

ggen_core/
parallel_generator.rs

1//! Parallel template generation for bulk operations
2//!
3//! **QUICK WIN 2: PARALLEL TEMPLATE GENERATION**
4//! Provides 2-4x speedup for bulk template processing using Rayon.
5
6use crate::utils::error::{Error, Result};
7use rayon::prelude::*;
8use std::path::{Path, PathBuf};
9use tera::Context;
10use walkdir::WalkDir;
11
12use crate::pipeline::Pipeline;
13use crate::streaming_generator::GenerationResult;
14use crate::template_types::Template;
15
16/// Parallel template generator using Rayon for bulk operations
17///
18/// This generator processes multiple templates concurrently, providing
19/// significant speedup for projects with many templates.
20///
21/// # Performance
22///
23/// - **2-4x faster** than sequential processing for bulk operations
24/// - Scales with CPU core count
25/// - Best for projects with 10+ templates
26///
27/// # Examples
28///
29/// ```rust,no_run
30/// use crate::parallel_generator::ParallelGenerator;
31/// use tera::Context;
32/// use std::path::PathBuf;
33///
34/// # fn main() -> crate::utils::error::Result<()> {
35/// let template_dir = PathBuf::from("templates");
36/// let output_dir = PathBuf::from("output");
37/// let vars = Context::new();
38///
39/// let result = ParallelGenerator::generate_all(
40///     &template_dir,
41///     &output_dir,
42///     &vars
43/// )?;
44///
45/// println!("Generated {} files in {:.2}s",
46///     result.success_count,
47///     result.duration.as_secs_f64()
48/// );
49/// # Ok(())
50/// # }
51/// ```
52pub struct ParallelGenerator;
53
54impl ParallelGenerator {
55    /// Generate all templates in parallel
56    ///
57    /// **QUICK WIN 2:** Uses Rayon to process templates concurrently,
58    /// providing 2-4x speedup for bulk operations.
59    pub fn generate_all(
60        template_dir: &Path, output_dir: &Path, vars: &Context,
61    ) -> Result<GenerationResult> {
62        let start = std::time::Instant::now();
63
64        // Collect all template paths
65        let template_paths: Vec<PathBuf> = WalkDir::new(template_dir)
66            .into_iter()
67            .filter_map(|entry| entry.ok())
68            .filter(|entry| entry.file_type().is_file())
69            .filter(|entry| entry.path().extension() == Some(std::ffi::OsStr::new("tmpl")))
70            .map(|entry| entry.path().to_path_buf())
71            .collect();
72
73        // QUICK WIN 2: Process templates in parallel using Rayon
74        let results: Vec<_> = template_paths
75            .par_iter()
76            .map(|template_path| Self::process_template_isolated(template_path, output_dir, vars))
77            .collect();
78
79        // Aggregate results
80        let mut generation_result = GenerationResult::default();
81        for result in results {
82            match result {
83                Ok(output_path) => {
84                    generation_result.success_count += 1;
85                    generation_result.generated_files.push(output_path);
86                }
87                Err(e) => {
88                    generation_result.error_count += 1;
89                    generation_result.errors.push(e.to_string());
90                }
91            }
92        }
93
94        generation_result.duration = start.elapsed();
95        Ok(generation_result)
96    }
97
98    /// Process a single template in isolation (thread-safe)
99    fn process_template_isolated(
100        template_path: &Path, output_dir: &Path, vars: &Context,
101    ) -> Result<PathBuf> {
102        // Create isolated pipeline for this template (thread-safe)
103        let mut pipeline = Pipeline::new()?;
104
105        // Parse template
106        let content = std::fs::read_to_string(template_path).map_err(|e| {
107            Error::with_source(
108                &format!("Failed to read template {}", template_path.display()),
109                Box::new(e),
110            )
111        })?;
112        let mut template = Template::parse(&content)?;
113
114        // Render frontmatter
115        template.render_frontmatter(&mut pipeline.tera, vars)?;
116
117        // QUICK WIN 1: Early check for RDF usage
118        // Process RDF graph only if template actually uses RDF/SPARQL
119        if !template.front.rdf_inline.is_empty()
120            || !template.front.rdf.is_empty()
121            || !template.front.sparql.is_empty()
122        {
123            template.process_graph(&mut pipeline.graph, &mut pipeline.tera, vars, template_path)?;
124        }
125
126        // Render template
127        let rendered = template.render(&mut pipeline.tera, vars, std::path::Path::new(""))?;
128
129        // Determine output path
130        let output_path = if let Some(to_path) = &template.front.to {
131            let rendered_to = pipeline.tera.render_str(to_path, vars)?;
132            output_dir.join(rendered_to)
133        } else {
134            let filename = template_path
135                .file_stem()
136                .ok_or_else(|| Error::new("Template has no filename"))?
137                .to_string_lossy();
138            output_dir.join(format!("{}.out", filename))
139        };
140
141        // Ensure parent directory exists
142        if let Some(parent) = output_path.parent() {
143            std::fs::create_dir_all(parent).map_err(|e| {
144                Error::new(&format!(
145                    "Failed to create output directory {}: {}",
146                    parent.display(),
147                    e
148                ))
149            })?;
150        }
151
152        // Write output file
153        std::fs::write(&output_path, rendered).map_err(|e| {
154            Error::new(&format!(
155                "Failed to write output file {}: {}",
156                output_path.display(),
157                e
158            ))
159        })?;
160
161        Ok(output_path)
162    }
163}
164
165#[cfg(test)]
166mod tests {
167    use super::*;
168    use tempfile::TempDir;
169
170    fn create_test_template(dir: &Path, name: &str, content: &str) -> Result<PathBuf> {
171        let path = dir.join(format!("{}.tmpl", name));
172        std::fs::write(&path, content)
173            .map_err(|e| Error::with_source("Failed to write test template", Box::new(e)))?;
174        Ok(path)
175    }
176
177    #[test]
178    fn test_parallel_generation() -> Result<()> {
179        let temp_dir = TempDir::new()?;
180        let output_dir = TempDir::new()?;
181
182        // Create multiple templates
183        for i in 0..10 {
184            create_test_template(
185                temp_dir.path(),
186                &format!("test_{}", i),
187                &format!(
188                    r#"---
189to: "output_{i}.txt"
190---
191File {i} content"#
192                ),
193            )?;
194        }
195
196        let vars = Context::new();
197        let result = ParallelGenerator::generate_all(temp_dir.path(), output_dir.path(), &vars)?;
198
199        assert_eq!(result.success_count, 10);
200        assert_eq!(result.error_count, 0);
201        assert!(result.throughput() > 0.0);
202
203        Ok(())
204    }
205
206    #[test]
207    fn test_parallel_with_rdf_skip() -> Result<()> {
208        let temp_dir = TempDir::new()?;
209        let output_dir = TempDir::new()?;
210
211        // Create templates WITHOUT RDF (should use Quick Win 1)
212        for i in 0..5 {
213            create_test_template(
214                temp_dir.path(),
215                &format!("no_rdf_{}", i),
216                r#"---
217to: "simple.txt"
218---
219Simple template without RDF"#,
220            )?;
221        }
222
223        let vars = Context::new();
224        let result = ParallelGenerator::generate_all(temp_dir.path(), output_dir.path(), &vars)?;
225
226        assert_eq!(result.success_count, 5);
227        assert_eq!(result.error_count, 0);
228
229        Ok(())
230    }
231}