mockforge-core 0.3.115

Shared logic for MockForge - routing, validation, latency, proxy
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
//! Template Library System
//!
//! Provides a system for managing, versioning, and sharing templates.
//! Supports:
//! - Shared template storage
//! - Template versioning
//! - Template marketplace/registry
//! - Template discovery and installation

use crate::{Error, Result};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use tracing::{debug, info, warn};

/// Template metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateMetadata {
    /// Template ID (unique identifier)
    pub id: String,
    /// Template name
    pub name: String,
    /// Template description
    pub description: Option<String>,
    /// Template version (semver format)
    pub version: String,
    /// Template author
    pub author: Option<String>,
    /// Template tags for categorization
    pub tags: Vec<String>,
    /// Template category (e.g., "user", "payment", "auth")
    pub category: Option<String>,
    /// Template content (the actual template string)
    pub content: String,
    /// Example usage
    pub example: Option<String>,
    /// Dependencies (other template IDs this template depends on)
    pub dependencies: Vec<String>,
    /// Creation timestamp
    pub created_at: Option<String>,
    /// Last updated timestamp
    pub updated_at: Option<String>,
}

/// Template version information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateVersion {
    /// Version string (semver)
    pub version: String,
    /// Template content for this version
    pub content: String,
    /// Changelog entry for this version
    pub changelog: Option<String>,
    /// Whether this is a pre-release version
    pub prerelease: bool,
    /// Release date
    pub released_at: String,
}

/// Template library entry (can have multiple versions)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TemplateLibraryEntry {
    /// Template ID
    pub id: String,
    /// Template name
    pub name: String,
    /// Template description
    pub description: Option<String>,
    /// Template author
    pub author: Option<String>,
    /// Template tags
    pub tags: Vec<String>,
    /// Template category
    pub category: Option<String>,
    /// Available versions
    pub versions: Vec<TemplateVersion>,
    /// Latest version
    pub latest_version: String,
    /// Dependencies
    pub dependencies: Vec<String>,
    /// Example usage
    pub example: Option<String>,
    /// Creation timestamp
    pub created_at: Option<String>,
    /// Last updated timestamp
    pub updated_at: Option<String>,
}

/// Template library registry
pub struct TemplateLibrary {
    /// Local storage directory
    storage_dir: PathBuf,
    /// In-memory cache of templates
    templates: HashMap<String, TemplateLibraryEntry>,
}

impl TemplateLibrary {
    /// Create a new template library
    pub fn new(storage_dir: impl AsRef<Path>) -> Result<Self> {
        let storage_dir = storage_dir.as_ref().to_path_buf();

        // Create storage directory if it doesn't exist
        std::fs::create_dir_all(&storage_dir).map_err(|e| {
            Error::io_with_context(
                format!("creating template library directory {}", storage_dir.display()),
                e.to_string(),
            )
        })?;

        let mut library = Self {
            storage_dir,
            templates: HashMap::new(),
        };

        // Load existing templates
        library.load_templates()?;

        Ok(library)
    }

    /// Load templates from storage
    fn load_templates(&mut self) -> Result<()> {
        let templates_dir = self.storage_dir.join("templates");

        if !templates_dir.exists() {
            return Ok(());
        }

        for entry in std::fs::read_dir(&templates_dir)
            .map_err(|e| Error::io_with_context("reading templates directory", e.to_string()))?
        {
            let entry = entry
                .map_err(|e| Error::io_with_context("reading directory entry", e.to_string()))?;

            let path = entry.path();
            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("json") {
                match self.load_template_file(&path) {
                    Ok(Some(template)) => {
                        let id = template.id.clone();
                        self.templates.insert(id, template);
                    }
                    Ok(None) => {
                        // File doesn't contain a valid template, skip
                    }
                    Err(e) => {
                        warn!("Failed to load template from {}: {}", path.display(), e);
                    }
                }
            }
        }

        info!("Loaded {} template(s) from library", self.templates.len());
        Ok(())
    }

    /// Load a template from a file
    fn load_template_file(&self, path: &Path) -> Result<Option<TemplateLibraryEntry>> {
        let content = std::fs::read_to_string(path).map_err(|e| {
            Error::io_with_context(
                format!("reading template file {}", path.display()),
                e.to_string(),
            )
        })?;

        let template: TemplateLibraryEntry = serde_json::from_str(&content).map_err(|e| {
            Error::config(format!("Failed to parse template file {}: {}", path.display(), e))
        })?;

        Ok(Some(template))
    }

    /// Register a template in the library
    pub fn register_template(&mut self, metadata: TemplateMetadata) -> Result<()> {
        let template_id = metadata.id.clone();

        // Check if template already exists
        let entry = if let Some(existing) = self.templates.get_mut(&template_id) {
            // Add new version to existing template
            let version = TemplateVersion {
                version: metadata.version.clone(),
                content: metadata.content.clone(),
                changelog: None,
                prerelease: false,
                released_at: chrono::Utc::now().to_rfc3339(),
            };

            existing.versions.push(version);
            existing.versions.sort_by(|a, b| {
                // Simple version comparison (could use semver crate for better comparison)
                b.version.cmp(&a.version)
            });
            existing.latest_version = metadata.version.clone();
            existing.updated_at = Some(chrono::Utc::now().to_rfc3339());

            existing.clone()
        } else {
            // Create new template entry
            let version = TemplateVersion {
                version: metadata.version.clone(),
                content: metadata.content.clone(),
                changelog: None,
                prerelease: false,
                released_at: chrono::Utc::now().to_rfc3339(),
            };

            TemplateLibraryEntry {
                id: metadata.id.clone(),
                name: metadata.name.clone(),
                description: metadata.description.clone(),
                author: metadata.author.clone(),
                tags: metadata.tags.clone(),
                category: metadata.category.clone(),
                versions: vec![version],
                latest_version: metadata.version.clone(),
                dependencies: metadata.dependencies.clone(),
                example: metadata.example.clone(),
                created_at: Some(chrono::Utc::now().to_rfc3339()),
                updated_at: Some(chrono::Utc::now().to_rfc3339()),
            }
        };

        // Save to disk
        self.save_template(&entry)?;

        // Update in-memory cache
        self.templates.insert(template_id, entry);

        Ok(())
    }

    /// Save a template to disk
    fn save_template(&self, template: &TemplateLibraryEntry) -> Result<()> {
        let templates_dir = self.storage_dir.join("templates");
        std::fs::create_dir_all(&templates_dir)
            .map_err(|e| Error::io_with_context("creating templates directory", e.to_string()))?;

        let file_path = templates_dir.join(format!("{}.json", template.id));
        let json = serde_json::to_string_pretty(template)
            .map_err(|e| Error::config(format!("Failed to serialize template: {}", e)))?;

        std::fs::write(&file_path, json)
            .map_err(|e| Error::io_with_context("writing template file", e.to_string()))?;

        debug!("Saved template {} to {}", template.id, file_path.display());
        Ok(())
    }

    /// Get a template by ID
    pub fn get_template(&self, id: &str) -> Option<&TemplateLibraryEntry> {
        self.templates.get(id)
    }

    /// Get a specific version of a template
    pub fn get_template_version(&self, id: &str, version: &str) -> Option<String> {
        self.templates
            .get(id)
            .and_then(|entry| entry.versions.iter().find(|v| v.version == version))
            .map(|v| v.content.clone())
    }

    /// Get the latest version of a template
    pub fn get_latest_template(&self, id: &str) -> Option<String> {
        self.templates.get(id).map(|entry| {
            entry.versions.first().map(|v| v.content.clone()).unwrap_or_else(|| {
                // Fallback to latest_version field
                self.get_template_version(id, &entry.latest_version).unwrap_or_default()
            })
        })
    }

    /// List all templates
    pub fn list_templates(&self) -> Vec<&TemplateLibraryEntry> {
        self.templates.values().collect()
    }

    /// Search templates by query
    pub fn search_templates(&self, query: &str) -> Vec<&TemplateLibraryEntry> {
        let query_lower = query.to_lowercase();

        self.templates
            .values()
            .filter(|template| {
                template.name.to_lowercase().contains(&query_lower)
                    || template
                        .description
                        .as_ref()
                        .map(|d| d.to_lowercase().contains(&query_lower))
                        .unwrap_or(false)
                    || template.tags.iter().any(|tag| tag.to_lowercase().contains(&query_lower))
                    || template
                        .category
                        .as_ref()
                        .map(|c| c.to_lowercase().contains(&query_lower))
                        .unwrap_or(false)
            })
            .collect()
    }

    /// Search templates by category
    pub fn templates_by_category(&self, category: &str) -> Vec<&TemplateLibraryEntry> {
        self.templates
            .values()
            .filter(|template| {
                template
                    .category
                    .as_ref()
                    .map(|c| c.eq_ignore_ascii_case(category))
                    .unwrap_or(false)
            })
            .collect()
    }

    /// Remove a template
    pub fn remove_template(&mut self, id: &str) -> Result<()> {
        if self.templates.remove(id).is_some() {
            let file_path = self.storage_dir.join("templates").join(format!("{}.json", id));
            if file_path.exists() {
                std::fs::remove_file(&file_path)
                    .map_err(|e| Error::io_with_context("removing template file", e.to_string()))?;
            }
            info!("Removed template: {}", id);
        }
        Ok(())
    }

    /// Remove a specific version of a template
    pub fn remove_template_version(&mut self, id: &str, version: &str) -> Result<()> {
        if let Some(template) = self.templates.get_mut(id) {
            template.versions.retain(|v| v.version != version);

            if template.versions.is_empty() {
                // Remove entire template if no versions left
                self.remove_template(id)?;
            } else {
                // Update latest version
                template.versions.sort_by(|a, b| b.version.cmp(&a.version));
                template.latest_version =
                    template.versions.first().map(|v| v.version.clone()).unwrap_or_default();
                template.updated_at = Some(chrono::Utc::now().to_rfc3339());

                // Clone template to avoid borrow checker issues
                let template_clone = template.clone();
                let _ = template; // Explicitly drop mutable borrow

                // Save updated template
                self.save_template(&template_clone)?;
            }
        }
        Ok(())
    }

    /// Get storage directory
    pub fn storage_dir(&self) -> &Path {
        &self.storage_dir
    }
}

/// Template marketplace/registry (for remote templates)
pub struct TemplateMarketplace {
    /// Registry URL
    registry_url: String,
    /// Authentication token (optional)
    auth_token: Option<String>,
}

impl TemplateMarketplace {
    /// Create a new template marketplace client
    pub fn new(registry_url: String, auth_token: Option<String>) -> Self {
        Self {
            registry_url,
            auth_token,
        }
    }

    /// Search for templates in the marketplace
    pub async fn search(&self, query: &str) -> Result<Vec<TemplateLibraryEntry>> {
        let encoded_query = urlencoding::encode(query);
        let url = format!("{}/api/templates/search?q={}", self.registry_url, encoded_query);

        let mut request = reqwest::Client::new().get(&url);
        if let Some(ref token) = self.auth_token {
            request = request.bearer_auth(token);
        }

        let response = request
            .send()
            .await
            .map_err(|e| Error::internal(format!("Failed to search marketplace: {}", e)))?;

        if !response.status().is_success() {
            return Err(Error::internal(format!(
                "Marketplace search failed with status: {}",
                response.status()
            )));
        }

        let templates: Vec<TemplateLibraryEntry> = response
            .json()
            .await
            .map_err(|e| Error::internal(format!("Failed to parse marketplace response: {}", e)))?;

        Ok(templates)
    }

    /// Get a template from the marketplace
    pub async fn get_template(
        &self,
        id: &str,
        version: Option<&str>,
    ) -> Result<TemplateLibraryEntry> {
        let url = if let Some(version) = version {
            format!("{}/api/templates/{}/{}", self.registry_url, id, version)
        } else {
            format!("{}/api/templates/{}", self.registry_url, id)
        };

        let mut request = reqwest::Client::new().get(&url);
        if let Some(ref token) = self.auth_token {
            request = request.bearer_auth(token);
        }

        let response = request.send().await.map_err(|e| {
            Error::internal(format!("Failed to fetch template from marketplace: {}", e))
        })?;

        if !response.status().is_success() {
            return Err(Error::internal(format!(
                "Failed to fetch template: {}",
                response.status()
            )));
        }

        let template: TemplateLibraryEntry = response
            .json()
            .await
            .map_err(|e| Error::config(format!("Failed to parse template: {}", e)))?;

        Ok(template)
    }

    /// List featured/popular templates
    pub async fn list_featured(&self) -> Result<Vec<TemplateLibraryEntry>> {
        let url = format!("{}/api/templates/featured", self.registry_url);

        let mut request = reqwest::Client::new().get(&url);
        if let Some(ref token) = self.auth_token {
            request = request.bearer_auth(token);
        }

        let response = request
            .send()
            .await
            .map_err(|e| Error::internal(format!("Failed to fetch featured templates: {}", e)))?;

        if !response.status().is_success() {
            return Err(Error::internal(format!(
                "Failed to fetch featured templates: {}",
                response.status()
            )));
        }

        let templates: Vec<TemplateLibraryEntry> = response
            .json()
            .await
            .map_err(|e| Error::config(format!("Failed to parse featured templates: {}", e)))?;

        Ok(templates)
    }

    /// List templates by category
    pub async fn list_by_category(&self, category: &str) -> Result<Vec<TemplateLibraryEntry>> {
        let encoded_category = urlencoding::encode(category);
        let url = format!("{}/api/templates/category/{}", self.registry_url, encoded_category);

        let mut request = reqwest::Client::new().get(&url);
        if let Some(ref token) = self.auth_token {
            request = request.bearer_auth(token);
        }

        let response = request.send().await.map_err(|e| {
            Error::internal(format!("Failed to fetch templates by category: {}", e))
        })?;

        if !response.status().is_success() {
            return Err(Error::internal(format!(
                "Failed to fetch templates by category: {}",
                response.status()
            )));
        }

        let templates: Vec<TemplateLibraryEntry> = response
            .json()
            .await
            .map_err(|e| Error::config(format!("Failed to parse templates: {}", e)))?;

        Ok(templates)
    }
}

/// Template library manager (combines local library and marketplace)
pub struct TemplateLibraryManager {
    /// Local template library
    library: TemplateLibrary,
    /// Marketplace client (optional)
    marketplace: Option<TemplateMarketplace>,
}

impl TemplateLibraryManager {
    /// Create a new template library manager
    pub fn new(storage_dir: impl AsRef<Path>) -> Result<Self> {
        let library = TemplateLibrary::new(storage_dir)?;
        Ok(Self {
            library,
            marketplace: None,
        })
    }

    /// Enable marketplace integration
    pub fn with_marketplace(mut self, registry_url: String, auth_token: Option<String>) -> Self {
        self.marketplace = Some(TemplateMarketplace::new(registry_url, auth_token));
        self
    }

    /// Install a template from marketplace to local library
    pub async fn install_from_marketplace(
        &mut self,
        id: &str,
        version: Option<&str>,
    ) -> Result<()> {
        let marketplace = self
            .marketplace
            .as_ref()
            .ok_or_else(|| Error::config("Marketplace not configured"))?;

        let template = marketplace.get_template(id, version).await?;

        // Convert to metadata and register
        let latest_version = template
            .versions
            .first()
            .ok_or_else(|| Error::not_found("template version", id))?;

        let metadata = TemplateMetadata {
            id: template.id.clone(),
            name: template.name.clone(),
            description: template.description.clone(),
            version: latest_version.version.clone(),
            author: template.author.clone(),
            tags: template.tags.clone(),
            category: template.category.clone(),
            content: latest_version.content.clone(),
            example: template.example.clone(),
            dependencies: template.dependencies.clone(),
            created_at: template.created_at.clone(),
            updated_at: template.updated_at.clone(),
        };

        self.library.register_template(metadata)?;
        info!("Installed template {} from marketplace", id);

        Ok(())
    }

    /// Get local library reference
    pub fn library(&self) -> &TemplateLibrary {
        &self.library
    }

    /// Get mutable local library reference
    pub fn library_mut(&mut self) -> &mut TemplateLibrary {
        &mut self.library
    }

    /// Get marketplace reference
    pub fn marketplace(&self) -> Option<&TemplateMarketplace> {
        self.marketplace.as_ref()
    }
}

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

    #[test]
    fn test_template_metadata() {
        let metadata = TemplateMetadata {
            id: "user-profile".to_string(),
            name: "User Profile Template".to_string(),
            description: Some("Template for user profile data".to_string()),
            version: "1.0.0".to_string(),
            author: Some("Test Author".to_string()),
            tags: vec!["user".to_string(), "profile".to_string()],
            category: Some("user".to_string()),
            content: "{{faker.name}} - {{faker.email}}".to_string(),
            example: Some("John Doe - john@example.com".to_string()),
            dependencies: Vec::new(),
            created_at: None,
            updated_at: None,
        };

        assert_eq!(metadata.id, "user-profile");
        assert_eq!(metadata.version, "1.0.0");
    }

    #[tokio::test]
    async fn test_template_library() {
        let temp_dir = TempDir::new().unwrap();
        let library = TemplateLibrary::new(temp_dir.path()).unwrap();

        let metadata = TemplateMetadata {
            id: "test-template".to_string(),
            name: "Test Template".to_string(),
            description: None,
            version: "1.0.0".to_string(),
            author: None,
            tags: Vec::new(),
            category: None,
            content: "{{uuid}}".to_string(),
            example: None,
            dependencies: Vec::new(),
            created_at: None,
            updated_at: None,
        };

        let mut library = library;
        library.register_template(metadata).unwrap();

        let template = library.get_template("test-template");
        assert!(template.is_some());
        assert_eq!(template.unwrap().name, "Test Template");
    }
}