tron 2.1.0

A rust based template system built for speed and simplicity.
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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
//! Template caching and performance optimization utilities.
//!
//! This module provides advanced caching mechanisms for templates to improve
//! performance when working with large numbers of templates or frequently
//! accessed template files.

use std::collections::HashMap;
use std::hash::{Hash, Hasher};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant, SystemTime};
use crate::error::{Result, TronError};
use crate::template::TronTemplate;

/// Cache key for templates, combining path and content hash.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CacheKey {
    /// File path (if loaded from file)
    pub path: Option<PathBuf>,
    /// Hash of template content
    pub content_hash: u64,
}

impl CacheKey {
    /// Create a new cache key from a template.
    pub fn from_template(template: &TronTemplate) -> Self {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        template.content().hash(&mut hasher);
        
        Self {
            path: template.path().map(|p| p.to_path_buf()),
            content_hash: hasher.finish(),
        }
    }
    
    /// Create a cache key from content and optional path.
    pub fn from_content(content: &str, path: Option<&std::path::Path>) -> Self {
        let mut hasher = std::collections::hash_map::DefaultHasher::new();
        content.hash(&mut hasher);
        
        Self {
            path: path.map(|p| p.to_path_buf()),
            content_hash: hasher.finish(),
        }
    }
}

/// Cached template entry with metadata.
#[derive(Debug, Clone)]
pub struct CachedTemplate {
    /// The cached template
    pub template: TronTemplate,
    /// When the template was cached
    pub cached_at: Instant,
    /// File modification time (if applicable)
    pub file_modified: Option<SystemTime>,
    /// Access count for LRU eviction
    pub access_count: u32,
    /// Last access time for LRU eviction
    pub last_accessed: Instant,
}

impl CachedTemplate {
    /// Create a new cached template entry.
    pub fn new(template: TronTemplate) -> Self {
        let now = Instant::now();
        let file_modified = if let Some(path) = template.path() {
            std::fs::metadata(path)
                .ok()
                .and_then(|m| m.modified().ok())
        } else {
            None
        };
        
        Self {
            template,
            cached_at: now,
            file_modified,
            access_count: 0,
            last_accessed: now,
        }
    }
    
    /// Mark this template as accessed.
    pub fn mark_accessed(&mut self) {
        self.access_count += 1;
        self.last_accessed = Instant::now();
    }
    
    /// Check if this cached entry is still valid.
    pub fn is_valid(&self, max_age: Option<Duration>) -> bool {
        // Check age limit
        if let Some(max_age) = max_age {
            if self.cached_at.elapsed() > max_age {
                return false;
            }
        }
        
        // Check file modification time
        if let (Some(path), Some(cached_modified)) = (self.template.path(), self.file_modified) {
            if let Ok(metadata) = std::fs::metadata(path) {
                if let Ok(current_modified) = metadata.modified() {
                    if current_modified > cached_modified {
                        return false;
                    }
                }
            }
        }
        
        true
    }
}

/// Configuration for template caching behavior.
#[derive(Debug, Clone)]
pub struct CacheConfig {
    /// Maximum number of templates to cache
    pub max_size: usize,
    /// Maximum age for cached entries
    pub max_age: Option<Duration>,
    /// Whether to enable file modification tracking
    pub track_file_changes: bool,
    /// Cache hit/miss statistics tracking
    pub enable_stats: bool,
}

impl Default for CacheConfig {
    fn default() -> Self {
        Self {
            max_size: 100,
            max_age: Some(Duration::from_secs(300)), // 5 minutes
            track_file_changes: true,
            enable_stats: true,
        }
    }
}

/// Cache statistics for monitoring and debugging.
#[derive(Debug, Clone, Default)]
pub struct CacheStats {
    /// Total cache hits
    pub hits: u64,
    /// Total cache misses
    pub misses: u64,
    /// Total evictions due to size limit
    pub evictions: u64,
    /// Total invalidations due to file changes
    pub invalidations: u64,
}

impl CacheStats {
    /// Calculate cache hit ratio.
    pub fn hit_ratio(&self) -> f64 {
        let total = self.hits + self.misses;
        if total == 0 {
            0.0
        } else {
            self.hits as f64 / total as f64
        }
    }
    
    /// Reset all statistics to zero.
    pub fn reset(&mut self) {
        *self = Self::default();
    }
}

/// High-performance template cache with LRU eviction and file tracking.
///
/// `TemplateCache` provides efficient caching of parsed templates with features like:
/// - LRU (Least Recently Used) eviction when cache is full
/// - Automatic invalidation when source files are modified
/// - Configurable cache size and entry age limits
/// - Detailed statistics for monitoring cache performance
/// - Thread-safe operations for concurrent access
///
/// # Examples
///
/// Basic caching:
///
/// ```
/// use tron::{TemplateCache, TronTemplate};
///
/// let mut cache = TemplateCache::new();
/// 
/// // Load and cache a template
/// let template = TronTemplate::new("Hello @[name]@!").unwrap();
/// cache.insert_template(template.clone());
///
/// // Retrieve from cache
/// if let Some(cached) = cache.get_by_content("Hello @[name]@!") {
///     println!("Cache hit!");
/// }
/// ```
///
/// With custom configuration:
///
/// ```
/// use tron::{TemplateCache, CacheConfig};
/// use std::time::Duration;
///
/// let config = CacheConfig {
///     max_size: 50,
///     max_age: Some(Duration::from_secs(600)), // 10 minutes
///     track_file_changes: true,
///     enable_stats: true,
/// };
///
/// let cache = TemplateCache::with_config(config);
/// ```
pub struct TemplateCache {
    cache: Arc<RwLock<HashMap<CacheKey, CachedTemplate>>>,
    config: CacheConfig,
    stats: Arc<RwLock<CacheStats>>,
}

impl TemplateCache {
    /// Create a new template cache with default configuration.
    pub fn new() -> Self {
        Self::with_config(CacheConfig::default())
    }
    
    /// Create a template cache with custom configuration.
    pub fn with_config(config: CacheConfig) -> Self {
        Self {
            cache: Arc::new(RwLock::new(HashMap::new())),
            config,
            stats: Arc::new(RwLock::new(CacheStats::default())),
        }
    }
    
    /// Insert a template into the cache.
    pub fn insert_template(&self, template: TronTemplate) -> Result<()> {
        let key = CacheKey::from_template(&template);
        let cached_template = CachedTemplate::new(template);
        
        let mut cache = self.cache.write().unwrap();
        
        // Check if we need to evict entries
        if cache.len() >= self.config.max_size {
            self.evict_lru(&mut cache);
        }
        
        cache.insert(key, cached_template);
        Ok(())
    }
    
    /// Get a template from the cache by content.
    pub fn get_by_content(&self, content: &str) -> Option<TronTemplate> {
        let key = CacheKey::from_content(content, None);
        self.get_by_key(&key)
    }
    
    /// Get a template from the cache by file path.
    pub fn get_by_path(&self, path: &std::path::Path) -> Option<TronTemplate> {
        // We need to scan the cache since we don't know the content hash
        let target_path = path.to_path_buf();
        let mut found_key = None;
        let mut is_valid = false;
        let mut template_clone = None;
        
        // First pass: find the key and check validity
        {
            let cache = self.cache.read().unwrap();
            for (cache_key, cached_template) in cache.iter() {
                if cache_key.path.as_ref() == Some(&target_path) {
                    found_key = Some(cache_key.clone());
                    is_valid = cached_template.is_valid(self.config.max_age);
                    if is_valid {
                        template_clone = Some(cached_template.template.clone());
                    }
                    break;
                }
            }
        }
        
        if let Some(key) = found_key {
            if is_valid {
                // Mark as accessed
                {
                    let mut cache = self.cache.write().unwrap();
                    if let Some(entry) = cache.get_mut(&key) {
                        entry.mark_accessed();
                    }
                }
                
                if self.config.enable_stats {
                    let mut stats = self.stats.write().unwrap();
                    stats.hits += 1;
                }
                
                template_clone
            } else {
                // Entry is invalid, remove it
                {
                    let mut cache = self.cache.write().unwrap();
                    cache.remove(&key);
                }
                
                if self.config.enable_stats {
                    let mut stats = self.stats.write().unwrap();
                    stats.invalidations += 1;
                }
                
                None
            }
        } else {
            if self.config.enable_stats {
                let mut stats = self.stats.write().unwrap();
                stats.misses += 1;
            }
            
            None
        }
    }
    
    /// Get a template from the cache by cache key.
    fn get_by_key(&self, key: &CacheKey) -> Option<TronTemplate> {
        let cache = self.cache.read().unwrap();
        
        if let Some(cached_template) = cache.get(key) {
            if cached_template.is_valid(self.config.max_age) {
                // Mark as accessed (need to upgrade to write lock)
                drop(cache);
                let mut cache = self.cache.write().unwrap();
                if let Some(entry) = cache.get_mut(key) {
                    entry.mark_accessed();
                    
                    if self.config.enable_stats {
                        let mut stats = self.stats.write().unwrap();
                        stats.hits += 1;
                    }
                    
                    return Some(entry.template.clone());
                }
            } else {
                // Entry is invalid, remove it
                drop(cache);
                let mut cache = self.cache.write().unwrap();
                cache.remove(key);
                
                if self.config.enable_stats {
                    let mut stats = self.stats.write().unwrap();
                    stats.invalidations += 1;
                }
            }
        }
        
        if self.config.enable_stats {
            let mut stats = self.stats.write().unwrap();
            stats.misses += 1;
        }
        
        None
    }
    
    /// Evict the least recently used entry from the cache.
    fn evict_lru(&self, cache: &mut HashMap<CacheKey, CachedTemplate>) {
        if cache.is_empty() {
            return;
        }
        
        // Find the entry with the oldest last_accessed time
        let oldest_key = cache
            .iter()
            .min_by_key(|(_, entry)| entry.last_accessed)
            .map(|(key, _)| key.clone());
        
        if let Some(key) = oldest_key {
            cache.remove(&key);
            
            if self.config.enable_stats {
                if let Ok(mut stats) = self.stats.write() {
                    stats.evictions += 1;
                }
            }
        }
    }
    
    /// Clear all entries from the cache.
    pub fn clear(&self) {
        let mut cache = self.cache.write().unwrap();
        cache.clear();
    }
    
    /// Get the current number of cached templates.
    pub fn size(&self) -> usize {
        let cache = self.cache.read().unwrap();
        cache.len()
    }
    
    /// Check if the cache is empty.
    pub fn is_empty(&self) -> bool {
        self.size() == 0
    }
    
    /// Check if a template is cached by path.
    ///
    /// # Examples
    ///
    /// ```
    /// use tron::TemplateCache;
    /// use std::path::Path;
    ///
    /// let cache = TemplateCache::new();
    /// let path = Path::new("templates/example.tron");
    /// 
    /// if cache.is_cached(&path) {
    ///     println!("Template is in cache");
    /// }
    /// ```
    pub fn is_cached<P: AsRef<std::path::Path>>(&self, path: P) -> bool {
        let target_path = path.as_ref().to_path_buf();
        let cache = self.cache.read().unwrap();
        
        for cache_key in cache.keys() {
            if cache_key.path.as_ref() == Some(&target_path) {
                return true;
            }
        }
        
        false
    }
    
    /// Get cache statistics (if enabled).
    pub fn stats(&self) -> Option<CacheStats> {
        if self.config.enable_stats {
            let stats = self.stats.read().unwrap();
            Some(stats.clone())
        } else {
            None
        }
    }
    
    /// Reset cache statistics.
    pub fn reset_stats(&self) {
        if self.config.enable_stats {
            let mut stats = self.stats.write().unwrap();
            stats.reset();
        }
    }
    
    /// Remove expired entries from the cache.
    pub fn cleanup_expired(&self) {
        let mut cache = self.cache.write().unwrap();
        let max_age = self.config.max_age;
        
        let expired_keys: Vec<CacheKey> = cache
            .iter()
            .filter_map(|(key, entry)| {
                if !entry.is_valid(max_age) {
                    Some(key.clone())
                } else {
                    None
                }
            })
            .collect();
        
        for key in expired_keys {
            cache.remove(&key);
            
            if self.config.enable_stats {
                if let Ok(mut stats) = self.stats.write() {
                    stats.invalidations += 1;
                }
            }
        }
    }
}

impl Default for TemplateCache {
    fn default() -> Self {
        Self::new()
    }
}

// Thread-safe implementation
unsafe impl Send for TemplateCache {}
unsafe impl Sync for TemplateCache {}

#[cfg(test)]
mod tests {
    use super::*;
    use std::thread;
    use std::time::Duration;
    
    #[test]
    fn test_cache_key_creation() -> Result<()> {
        let template = TronTemplate::new("Hello @[name]@!")?;
        let key1 = CacheKey::from_template(&template);
        let key2 = CacheKey::from_content("Hello @[name]@!", None);
        
        assert_eq!(key1.content_hash, key2.content_hash);
        assert_eq!(key1.path, key2.path);
        Ok(())
    }
    
    #[test]
    fn test_basic_caching() -> Result<()> {
        let cache = TemplateCache::new();
        let template = TronTemplate::new("Hello @[name]@!")?;
        
        // Insert template
        cache.insert_template(template.clone())?;
        assert_eq!(cache.size(), 1);
        
        // Retrieve from cache
        let cached = cache.get_by_content("Hello @[name]@!");
        assert!(cached.is_some());
        assert_eq!(cached.unwrap().content(), template.content());
        
        Ok(())
    }
    
    #[test]
    fn test_cache_miss() {
        let cache = TemplateCache::new();
        let cached = cache.get_by_content("Nonexistent template");
        assert!(cached.is_none());
    }
    
    #[test]
    fn test_cache_stats() -> Result<()> {
        let config = CacheConfig {
            enable_stats: true,
            ..Default::default()
        };
        let cache = TemplateCache::with_config(config);
        let template = TronTemplate::new("Hello @[name]@!")?;
        
        cache.insert_template(template)?;
        
        // Cache hit
        let _ = cache.get_by_content("Hello @[name]@!");
        
        // Cache miss
        let _ = cache.get_by_content("Nonexistent");
        
        let stats = cache.stats().unwrap();
        assert_eq!(stats.hits, 1);
        assert_eq!(stats.misses, 1);
        assert_eq!(stats.hit_ratio(), 0.5);
        
        Ok(())
    }
    
    #[test]
    fn test_cache_eviction() -> Result<()> {
        let config = CacheConfig {
            max_size: 2,
            ..Default::default()
        };
        let cache = TemplateCache::with_config(config);
        
        // Insert three templates (should evict the first one)
        let template1 = TronTemplate::new("Template 1 @[name]@")?;
        let template2 = TronTemplate::new("Template 2 @[name]@")?;
        let template3 = TronTemplate::new("Template 3 @[name]@")?;
        
        cache.insert_template(template1)?;
        cache.insert_template(template2)?;
        cache.insert_template(template3)?;
        
        assert_eq!(cache.size(), 2);
        
        // First template should be evicted
        let cached1 = cache.get_by_content("Template 1 @[name]@");
        assert!(cached1.is_none());
        
        // Other templates should still be there
        let cached2 = cache.get_by_content("Template 2 @[name]@");
        let cached3 = cache.get_by_content("Template 3 @[name]@");
        assert!(cached2.is_some());
        assert!(cached3.is_some());
        
        Ok(())
    }
    
    #[test]
    fn test_cache_clear() -> Result<()> {
        let cache = TemplateCache::new();
        let template = TronTemplate::new("Hello @[name]@!")?;
        
        cache.insert_template(template)?;
        assert_eq!(cache.size(), 1);
        
        cache.clear();
        assert_eq!(cache.size(), 0);
        assert!(cache.is_empty());
        
        Ok(())
    }
    
    #[test]
    fn test_thread_safety() -> Result<()> {
        let cache = Arc::new(TemplateCache::new());
        let mut handles = vec![];
        
        // Spawn multiple threads that insert templates
        for i in 0..10 {
            let cache = Arc::clone(&cache);
            let handle = thread::spawn(move || -> Result<()> {
                let template = TronTemplate::new(&format!("Template {} @[name]@", i))?;
                cache.insert_template(template)?;
                Ok(())
            });
            handles.push(handle);
        }
        
        // Wait for all threads to complete
        for handle in handles {
            handle.join().unwrap()?;
        }
        
        // Cache should contain all templates
        assert_eq!(cache.size(), 10);
        
        Ok(())
    }
    
    #[test]
    fn test_cached_template_validity() -> Result<()> {
        let template = TronTemplate::new("Hello @[name]@!")?;
        let mut cached = CachedTemplate::new(template);
        
        // Should be valid initially
        assert!(cached.is_valid(Some(Duration::from_secs(60))));
        
        // Should be invalid after max age
        assert!(!cached.is_valid(Some(Duration::from_nanos(1))));
        
        // Access tracking
        assert_eq!(cached.access_count, 0);
        cached.mark_accessed();
        assert_eq!(cached.access_count, 1);
        
        Ok(())
    }
}