clnrm-template 1.3.0

Cleanroom Testing Framework - Template Engine
Documentation
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
//! Template caching and hot-reload system
//!
//! Provides caching for compiled templates and hot-reload functionality
//! for development and dynamic template loading.

use crate::context::TemplateContext;
use crate::error::Result;
use crate::renderer::TemplateRenderer;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::{Duration, SystemTime};

/// Template cache for compiled templates and metadata
///
/// Caches compiled Tera templates and tracks file modification times
/// for hot-reload functionality.
#[derive(Debug)]
pub struct TemplateCache {
    /// Cached compiled templates (template_name -> compiled_template)
    templates: Arc<RwLock<HashMap<String, CachedTemplate>>>,
    /// File modification times for hot-reload
    file_mtimes: Arc<RwLock<HashMap<PathBuf, SystemTime>>>,
    /// Cache statistics
    stats: Arc<RwLock<CacheStats>>,
    /// Hot-reload enabled
    hot_reload: bool,
    /// Cache TTL (time-to-live)
    ttl: Duration,
}

/// Cached template with metadata
#[derive(Debug, Clone)]
struct CachedTemplate {
    /// Template content
    content: String,
    /// Last modification time
    #[allow(dead_code)]
    modified: SystemTime,
    /// Compilation time
    compiled_at: SystemTime,
    /// Template size (for cache management)
    size: usize,
}

/// Cache statistics for monitoring and optimization
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Total cache hits
    pub hits: u64,
    /// Total cache misses
    pub misses: u64,
    /// Templates evicted due to TTL
    pub evictions: u64,
    /// Total cache size (bytes)
    pub total_size: usize,
    /// Number of templates in cache
    pub template_count: usize,
}

impl TemplateCache {
    /// Create new template cache
    ///
    /// # Arguments
    /// * `hot_reload` - Enable hot-reload for file changes
    /// * `ttl` - Cache time-to-live duration
    pub fn new(hot_reload: bool, ttl: Duration) -> Self {
        Self {
            templates: Arc::new(RwLock::new(HashMap::new())),
            file_mtimes: Arc::new(RwLock::new(HashMap::new())),
            stats: Arc::new(RwLock::new(CacheStats::default())),
            hot_reload,
            ttl,
        }
    }

    /// Create cache with common settings (1 hour TTL, hot-reload enabled)
    pub fn with_defaults() -> Self {
        Self::new(true, Duration::from_secs(3600))
    }

    /// Get template from cache or compile if not cached/missing
    ///
    /// # Arguments
    /// * `template_name` - Name of template
    /// * `template_content` - Template content
    /// * `file_path` - Optional file path for hot-reload
    pub fn get_or_compile(
        &self,
        template_name: &str,
        template_content: &str,
        file_path: Option<&Path>,
    ) -> Result<String> {
        // Check if template is in cache and still valid
        if let Some(cached) = self.templates.read().unwrap().get(template_name) {
            if self.is_cache_valid(cached, file_path)? {
                // Cache hit
                self.record_hit();
                return Ok(cached.content.clone());
            }
        }

        // Cache miss or invalid - compile template
        self.record_miss();

        let compiled = self.compile_template(template_content)?;

        // Cache the compiled template
        self.cache_template(template_name, template_content, &compiled)?;

        // Update file modification time for hot-reload
        if let Some(path) = file_path {
            if let Ok(metadata) = std::fs::metadata(path) {
                if let Ok(mtime) = metadata.modified() {
                    self.file_mtimes
                        .write()
                        .unwrap()
                        .insert(path.to_path_buf(), mtime);
                }
            }
        }

        Ok(compiled)
    }

    /// Check if cached template is still valid
    fn is_cache_valid(&self, cached: &CachedTemplate, file_path: Option<&Path>) -> Result<bool> {
        // Check TTL
        let age = SystemTime::now()
            .duration_since(cached.compiled_at)
            .unwrap_or(Duration::from_secs(0));

        if age > self.ttl {
            return Ok(false);
        }

        // Check file modification time if hot-reload is enabled
        if self.hot_reload {
            if let Some(path) = file_path {
                if let Ok(metadata) = std::fs::metadata(path) {
                    if let Ok(mtime) = metadata.modified() {
                        if let Some(cached_mtime) = self.file_mtimes.read().unwrap().get(path) {
                            if mtime > *cached_mtime {
                                return Ok(false); // File was modified
                            }
                        }
                    }
                }
            }
        }

        Ok(true)
    }

    /// Compile template content
    fn compile_template(&self, content: &str) -> Result<String> {
        // For now, just return the content as-is
        // In a real implementation, this would compile Tera templates
        Ok(content.to_string())
    }

    /// Cache compiled template
    fn cache_template(&self, name: &str, _content: &str, compiled: &str) -> Result<()> {
        let now = SystemTime::now();
        let cached = CachedTemplate {
            content: compiled.to_string(),
            modified: now,
            compiled_at: now,
            size: compiled.len(),
        };

        // Update cache
        self.templates
            .write()
            .unwrap()
            .insert(name.to_string(), cached);

        // Update stats
        let mut stats = self.stats.write().unwrap();
        stats.total_size += compiled.len();
        stats.template_count += 1;

        Ok(())
    }

    /// Record cache hit
    fn record_hit(&self) {
        self.stats.write().unwrap().hits += 1;
    }

    /// Record cache miss
    fn record_miss(&self) {
        self.stats.write().unwrap().misses += 1;
    }

    /// Get cache statistics
    pub fn stats(&self) -> CacheStats {
        self.stats.read().unwrap().clone()
    }

    /// Clear cache
    pub fn clear(&self) {
        self.templates.write().unwrap().clear();
        self.file_mtimes.write().unwrap().clear();

        let mut stats = self.stats.write().unwrap();
        stats.total_size = 0;
        stats.template_count = 0;
        stats.evictions = 0;
    }

    /// Evict expired templates
    pub fn evict_expired(&self) -> usize {
        let now = SystemTime::now();
        let mut templates = self.templates.write().unwrap();
        let mut file_mtimes = self.file_mtimes.write().unwrap();
        let mut stats = self.stats.write().unwrap();

        let initial_count = templates.len();
        templates.retain(|_name, cached| {
            let age = now
                .duration_since(cached.compiled_at)
                .unwrap_or(Duration::from_secs(0));
            if age > self.ttl {
                // Template expired
                stats.total_size -= cached.size;
                stats.evictions += 1;
                false
            } else {
                true
            }
        });

        // Clean up file modification times for non-existent templates
        file_mtimes.retain(|path, _| {
            // Check if file still exists
            path.exists()
        });

        stats.template_count = templates.len();
        initial_count - templates.len()
    }
}

/// Cached template renderer with hot-reload support
///
/// Combines TemplateRenderer with TemplateCache for optimal performance
/// and development experience.
pub struct CachedRenderer {
    /// Base template renderer
    renderer: TemplateRenderer,
    /// Template cache
    cache: TemplateCache,
}

impl CachedRenderer {
    /// Create new cached renderer
    ///
    /// # Arguments
    /// * `context` - Template context
    /// * `hot_reload` - Enable hot-reload
    pub fn new(context: TemplateContext, hot_reload: bool) -> Result<Self> {
        let renderer = TemplateRenderer::new()?.with_context(context);
        let cache = TemplateCache::new(hot_reload, Duration::from_secs(3600));

        Ok(Self { renderer, cache })
    }

    /// Render template with caching
    ///
    /// # Arguments
    /// * `template` - Template content
    /// * `name` - Template name for caching
    /// * `file_path` - Optional file path for hot-reload
    pub fn render_cached(
        &mut self,
        template: &str,
        name: &str,
        file_path: Option<&Path>,
    ) -> Result<String> {
        // Try to get from cache first
        if let Ok(cached) = self.cache.get_or_compile(name, template, file_path) {
            return Ok(cached);
        }

        // Fall back to direct rendering if caching fails
        self.renderer.render_str(template, name)
    }

    /// Get cache statistics
    pub fn cache_stats(&self) -> CacheStats {
        self.cache.stats()
    }

    /// Clear template cache
    pub fn clear_cache(&self) {
        self.cache.clear();
    }

    /// Evict expired templates from cache
    pub fn evict_expired(&self) -> usize {
        self.cache.evict_expired()
    }

    /// Access the underlying template renderer
    pub fn renderer(&self) -> &TemplateRenderer {
        &self.renderer
    }

    /// Access the underlying template renderer mutably
    pub fn renderer_mut(&mut self) -> &mut TemplateRenderer {
        &mut self.renderer
    }
}

/// Hot-reload watcher for template files
///
/// Monitors template directories for file changes and triggers cache invalidation.
/// Useful for development environments where templates change frequently.
pub struct HotReloadWatcher {
    /// Watched directories
    watched_dirs: Vec<PathBuf>,
    /// Cache to invalidate
    #[allow(dead_code)]
    cache: Arc<TemplateCache>,
    /// File watcher (simplified implementation)
    _watcher: Option<Box<dyn Watcher>>,
}

impl HotReloadWatcher {
    /// Create new hot-reload watcher
    ///
    /// # Arguments
    /// * `cache` - Template cache to invalidate on changes
    pub fn new(cache: Arc<TemplateCache>) -> Self {
        Self {
            watched_dirs: Vec::new(),
            cache,
            _watcher: None,
        }
    }

    /// Add directory to watch
    ///
    /// # Arguments
    /// * `path` - Directory path to watch for template changes
    pub fn watch_directory<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.watched_dirs.push(path.as_ref().to_path_buf());
        self
    }

    /// Start watching for file changes
    ///
    /// This is a simplified implementation. In a real implementation,
    /// this would use a proper file watcher like `notify` or `inotify`.
    pub fn start(self) -> Result<()> {
        // For now, just log that we're watching
        // Real implementation would set up file system watchers
        Ok(())
    }

    /// Stop watching (no-op in simplified implementation)
    pub fn stop(&self) -> Result<()> {
        Ok(())
    }
}

// Placeholder trait for file watcher
trait Watcher {}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    #[test]
    fn test_template_cache_basic() {
        let cache = TemplateCache::default();
        let template = "Hello {{ name }}";

        // First access should be a miss
        let result = cache.get_or_compile("test", template, None).unwrap();
        assert_eq!(result, template);

        let stats = cache.stats();
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hits, 0);

        // Second access should be a hit
        let result = cache.get_or_compile("test", template, None).unwrap();
        assert_eq!(result, template);

        let stats = cache.stats();
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hits, 1);
    }

    #[test]
    fn test_cached_renderer() {
        let context = TemplateContext::with_defaults();
        let mut renderer = CachedRenderer::new(context, false).unwrap();

        let template = "service = \"{{ svc }}\"";
        let result = renderer.render_cached(template, "test", None).unwrap();
        assert_eq!(result, template);

        let stats = renderer.cache_stats();
        assert_eq!(stats.misses, 1);
    }

    #[test]
    fn test_cache_eviction() {
        let cache = TemplateCache::new(false, Duration::from_millis(1));

        // Add template
        cache.get_or_compile("test", "Hello", None).unwrap();

        // Wait for TTL to expire
        std::thread::sleep(Duration::from_millis(10));

        // Should be evicted
        let evicted = cache.evict_expired();
        assert_eq!(evicted, 1);
    }
}