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
//! # Token Resolver Plugin Integration
//!
//! This module provides integration between token resolvers and the template engine,
//! allowing plugins to register custom token resolution handlers.

use crate::config::Config;
use async_trait::async_trait;
use mockforge_plugin_core::*;
use once_cell::sync::Lazy;
use regex::Regex;
use std::{collections::HashMap, sync::Arc};
use tokio::sync::RwLock;
use tracing::{debug, error, info, warn};

/// Regex for extracting tokens from templates (e.g., "{{token}}")
static TOKEN_PATTERN: Lazy<Regex> =
    Lazy::new(|| Regex::new(r"\{\{([^}]+)\}\}").expect("Invalid token regex pattern"));

/// Plugin-based token resolver that integrates with the template engine
#[derive(Debug)]
pub struct PluginTokenResolver {
    /// Configuration reference
    config: Arc<Config>,
    /// Registered token resolver plugins
    resolvers: Arc<RwLock<HashMap<String, Arc<dyn TokenResolver>>>>,
    /// Plugin loading context
    plugin_context: Option<Arc<mockforge_plugin_loader::PluginLoadContext>>,
}

impl PluginTokenResolver {
    /// Create a new plugin token resolver
    pub fn new(config: Arc<Config>) -> Self {
        Self {
            config,
            resolvers: Arc::new(RwLock::new(HashMap::new())),
            plugin_context: None,
        }
    }

    /// Set the plugin loading context
    pub fn with_plugin_context(mut self, context: Arc<mockforge_plugin_loader::PluginLoadContext>) -> Self {
        self.plugin_context = Some(context);
        self
    }

    /// Register a token resolver plugin
    pub async fn register_resolver(&self, name: &str, resolver: Arc<dyn TokenResolver>) -> Result<(), PluginError> {
        debug!("Registering token resolver plugin: {}", name);

        // Validate the plugin
        resolver.validate()?;

        // Register it
        let mut resolvers = self.resolvers.write().await;
        resolvers.insert(name.to_string(), resolver);

        info!("Successfully registered token resolver plugin: {}", name);
        Ok(())
    }

    /// Unregister a token resolver plugin
    pub async fn unregister_resolver(&self, name: &str) -> Result<(), PluginError> {
        debug!("Unregistering token resolver plugin: {}", name);

        let mut resolvers = self.resolvers.write().await;
        if resolvers.remove(name).is_some() {
            info!("Successfully unregistered token resolver plugin: {}", name);
            Ok(())
        } else {
            Err(PluginError::config_error(&format!("Resolver '{}' not found", name)))
        }
    }

    /// Resolve a token using registered plugins
    pub async fn resolve_token(&self, token: &str, context: &ResolutionContext) -> Option<String> {
        debug!("Attempting to resolve token: {}", token);

        let resolvers = self.resolvers.read().await;
        let mut best_match: Option<(String, usize)> = None;

        // Find the best matching resolver based on prefix priority
        for (name, resolver) in resolvers.iter() {
            if resolver.can_resolve(token) {
                let priority = self.get_resolver_priority(name);

                match best_match {
                    None => best_match = Some((name.clone(), priority)),
                    Some((_, current_priority)) if priority > current_priority => {
                        best_match = Some((name.clone(), priority));
                    }
                    _ => {}
                }
            }
        }

        if let Some((resolver_name, _)) = best_match {
            if let Some(resolver) = resolvers.get(&resolver_name) {
                match resolver.resolve_token(token, context) {
                    Ok(value) => {
                        debug!("Successfully resolved token '{}' using resolver '{}'", token, resolver_name);
                        return Some(value);
                    }
                    Err(e) => {
                        warn!("Token resolution failed for '{}' using resolver '{}': {}",
                              token, resolver_name, e);
                        return None;
                    }
                }
            }
        }

        debug!("No resolver found for token: {}", token);
        None
    }

    /// Get priority for a resolver (higher is better)
    fn get_resolver_priority(&self, resolver_name: &str) -> usize {
        // Priority order: custom > env > db > time > generic
        match resolver_name {
            name if name.contains("custom") => 100,
            name if name.contains("env") => 90,
            name if name.contains("db") || name.contains("database") => 80,
            name if name.contains("time") || name.contains("datetime") => 70,
            name if name.contains("stats") || name.contains("metrics") => 60,
            _ => 50,
        }
    }

    /// Get metadata about registered resolvers
    pub async fn get_resolver_metadata(&self) -> HashMap<String, PluginMetadata> {
        let mut metadata = HashMap::new();
        let resolvers = self.resolvers.read().await;

        for (name, resolver) in resolvers.iter() {
            metadata.insert(name.clone(), resolver.get_metadata());
        }

        metadata
    }

    /// List registered resolver names
    pub async fn list_resolvers(&self) -> Vec<String> {
        let resolvers = self.resolvers.read().await;
        resolvers.keys().cloned().collect()
    }

    /// Check if a token can be resolved
    pub async fn can_resolve_token(&self, token: &str) -> bool {
        let resolvers = self.resolvers.read().await;
        resolvers.values().any(|resolver| resolver.can_resolve(token))
    }
}

#[async_trait]
impl TokenResolver for PluginTokenResolver {
    fn can_resolve(&self, token: &str) -> bool {
        // This is a sync check - in practice, use can_resolve_token
        // For now, do a simple prefix check
        token.starts_with("{{") && token.ends_with("}}")
    }

    fn resolve_token(&self, token: &str, context: &ResolutionContext) -> Result<String, PluginError> {
        // For async resolution, use the async method
        // This is a limitation of the trait - we'd need to make it async
        Err(PluginError::resolution_failed("Use async resolve_token method for plugin resolution"))
    }

    fn get_metadata(&self) -> PluginMetadata {
        PluginMetadata::new("Plugin-based token resolver with registered plugins")
            .with_capability("token-resolution")
            .with_capability("plugin-integration")
    }
}

/// Integration point for template engine to use plugin resolvers
pub struct TemplatePluginIntegration {
    /// The plugin token resolver
    resolver: Arc<PluginTokenResolver>,
}

impl TemplatePluginIntegration {
    /// Create a new template plugin integration
    pub fn new(resolver: Arc<PluginTokenResolver>) -> Self {
        Self { resolver }
    }

    /// Process a template string with plugin resolution
    pub async fn process_template(
        &self,
        template: &str,
        context: &ResolutionContext,
    ) -> Result<String, PluginError> {
        let mut result = template.to_string();

        // Find all token patterns {{...}}
        let token_pattern = regex::Regex::new(r"\{\{([^}]+)\}\}").map_err(|e| {
            PluginError::config_error(&format!("Invalid regex pattern: {}", e))
        })?;

        // Replace tokens asynchronously
        for capture in token_pattern.captures_iter(template) {
            let token = capture.get(1).unwrap().as_str();

            if let Some(resolved) = self.resolver.resolve_token(token, context).await {
                let token_pattern = format!("{{{{{}}}}}", regex::escape(token));
                if let Ok(replace_regex) = regex::Regex::new(&token_pattern) {
                    result = replace_regex.replace(&result, &resolved).to_string();
                }
            }
        }

        Ok(result)
    }

    /// Extract tokens that need resolution
    pub async fn extract_tokens(&self, template: &str) -> Vec<String> {
        let mut tokens = Vec::new();

        for capture in TOKEN_PATTERN.captures_iter(template) {
            let token = capture.get(1).unwrap().as_str().to_string();
            if self.resolver.can_resolve_token(&token).await {
                tokens.push(token);
            }
        }

        tokens
    }

    /// Get resolution statistics
    pub async fn get_resolution_stats(&self) -> HashMap<String, usize> {
        let resolvers = self.resolver.get_resolver_metadata().await;
        let mut stats = HashMap::new();
        stats.insert("total_resolvers".to_string(), resolvers.len());

        // Count resolvers by type
        let mut types = HashMap::new();
        for metadata in resolvers.values() {
            for prefix in &metadata.supported_prefixes {
                *types.entry(prefix.clone()).or_insert(0) += 1;
            }
        }

        for (prefix, count) in types {
            stats.insert(format!("{}_resolvers", prefix), count);
        }

        stats
    }
}

/// Factory function to create standard token resolvers
pub struct TokenResolverFactory;

impl TokenResolverFactory {
    /// Create an environment variable resolver
    pub fn create_env_resolver() -> Result<Arc<dyn TokenResolver>, PluginError> {
        Ok(Arc::new(EnvironmentResolver::new()?))
    }

    /// Create a time-based resolver
    pub fn create_time_resolver() -> Arc<dyn TokenResolver> {
        Arc::new(TimeResolver::new())
    }

    /// Create a UUID resolver
    pub fn create_uuid_resolver() -> Arc<dyn TokenResolver> {
        Arc::new(UuidResolver::new())
    }

    /// Create a stats resolver
    pub fn create_stats_resolver(stats_store: Option<HashMap<String, serde_json::Value>>) -> Arc<dyn TokenResolver> {
        Arc::new(StatsResolver::new(stats_store.unwrap_or_default()))
    }
}

/// Environment variable token resolver
#[derive(Debug)]
struct EnvironmentResolver {
    // No state needed
}

impl EnvironmentResolver {
    fn new() -> Result<Self, PluginError> {
        Ok(Self {})
    }
}

#[async_trait]
impl TokenResolver for EnvironmentResolver {
    fn can_resolve(&self, token: &str) -> bool {
        token.starts_with("env:") || token.starts_with("ENV:")
    }

    fn resolve_token(&self, token: &str, _context: &ResolutionContext) -> Result<String, PluginError> {
        let env_key = if token.starts_with("env:") {
            &token[4..]
        } else {
            &token[4..]
        };

        std::env::var(env_key).map_err(|_| {
            PluginError::resolution_failed(&format!("Environment variable '{}' not found", env_key))
        })
    }

    fn get_metadata(&self) -> PluginMetadata {
        PluginMetadata::new("Environment variable resolver for config and secrets")
            .with_capability("env-vars")
            .with_prefix("env")
    }
}

/// Time-based token resolver
#[derive(Debug)]
struct TimeResolver {
    // No state needed
}

impl TimeResolver {
    fn new() -> Self {
        Self {}
    }
}

#[async_trait]
impl TokenResolver for TimeResolver {
    fn can_resolve(&self, token: &str) -> bool {
        token.starts_with("time:") || token.starts_with("datetime:")
    }

    fn resolve_token(&self, token: &str, _context: &ResolutionContext) -> Result<String, PluginError> {
        let time_spec = if token.starts_with("time:") {
            &token[5..]
        } else {
            &token[9..]
        };

        let now = chrono::Utc::now();

        match time_spec {
            "iso8601" | "rfc3339" => Ok(now.to_rfc3339()),
            "timestamp" => Ok(now.timestamp().to_string()),
            "unix" => Ok(now.timestamp().to_string()),
            "date" => Ok(now.format("%Y-%m-%d").to_string()),
            "time" => Ok(now.format("%H:%M:%S").to_string()),
            "datetime" => Ok(now.format("%Y-%m-%d %H:%M:%S").to_string()),
            "business-hours" => {
                let hour = now.hour();
                if hour >= 9 && hour < 17 {
                    Ok("Open".to_string())
                } else {
                    Ok("Closed".to_string())
                }
            }
            _ => Err(PluginError::invalid_token(token)),
        }
    }

    fn get_metadata(&self) -> PluginMetadata {
        PluginMetadata::new("Time and date resolver for dynamic timestamps")
            .with_capability("datetime")
            .with_prefix("time")
            .with_prefix("datetime")
    }
}

/// UUID token resolver
#[derive(Debug)]
struct UuidResolver {
    // No state needed
}

impl UuidResolver {
    fn new() -> Self {
        Self {}
    }
}

#[async_trait]
impl TokenResolver for UuidResolver {
    fn can_resolve(&self, token: &str) -> bool {
        token == "uuid:v4" || token == "uuid" || token == "id" || token == "session:id"
    }

    fn resolve_token(&self, token: &str, _context: &ResolutionContext) -> Result<String, PluginError> {
        match token {
            "uuid:v4" | "uuid" | "id" | "session:id" => {
                Ok(uuid::Uuid::new_v4().to_string())
            }
            _ => Err(PluginError::invalid_token(token)),
        }
    }

    fn get_metadata(&self) -> PluginMetadata {
        PluginMetadata::new("UUID generator for unique identifiers")
            .with_capability("uuid-generation")
            .with_prefix("uuid")
            .with_prefix("id")
    }
}

/// Statistics token resolver
#[derive(Debug)]
struct StatsResolver {
    stats_store: HashMap<String, serde_json::Value>,
}

impl StatsResolver {
    fn new(stats_store: HashMap<String, serde_json::Value>) -> Self {
        Self { stats_store }
    }

    fn increment_stat(&mut self, key: &str) {
        let value = self.stats_store.entry(key.to_string())
            .or_insert(serde_json::Value::Number(0.into()));

        if let Some(num) = value.as_i64() {
            *value = serde_json::Value::Number((num + 1).into());
        }
    }
}

#[async_trait]
impl TokenResolver for StatsResolver {
    fn can_resolve(&self, token: &str) -> bool {
        token.starts_with("stats:") ||
        token.starts_with("metrics:") ||
        token.starts_with("counter:")
    }

    fn resolve_token(&self, token: &str, _context: &ResolutionContext) -> Result<String, PluginError> {
        let stat_key = if let Some(key) = token.strip_prefix("stats:") {
            key
        } else if let Some(key) = token.strip_prefix("metrics:") {
            key
        } else if let Some(key) = token.strip_prefix("counter:") {
            key
        } else {
            return Err(PluginError::invalid_token(token));
        };

        match stat_key {
            "requests" | "active-users" | "total-users" => {
                // Mock values for common stats
                match stat_key {
                    "requests" => Ok("15423".to_string()),
                    "active-users" => Ok("89".to_string()),
                    "total-users" => Ok("1274".to_string()),
                    _ => Ok("0".to_string()),
                }
            }
            key if self.stats_store.contains_key(key) => {
                if let Some(value) = self.stats_store.get(key) {
                    Ok(value.to_string())
                } else {
                    Err(PluginError::resolution_failed(&format!("Stat '{}' not found", key)))
                }
            }
            _ => Err(PluginError::resolution_failed(&format!("Unknown stat '{}'", stat_key))),
        }
    }

    fn get_metadata(&self) -> PluginMetadata {
        PluginMetadata::new("Statistics and metrics resolver")
            .with_capability("stats")
            .with_prefix("stats")
            .with_prefix("metrics")
    }
}

/// Convenience functions for creating standard resolvers
pub mod presets {
    use super::*;

    /// Create all standard token resolvers
    pub async fn create_standard_resolvers() -> Vec<(String, Arc<dyn TokenResolver>)> {
        vec![
            ("env-resolver".to_string(), TokenResolverFactory::create_env_resolver().unwrap()),
            ("time-resolver".to_string(), TokenResolverFactory::create_time_resolver()),
            ("uuid-resolver".to_string(), TokenResolverFactory::create_uuid_resolver()),
            ("stats-resolver".to_string(), TokenResolverFactory::create_stats_resolver(None)),
        ]
    }

    /// Create minimal resolvers for basic functionality
    pub fn create_minimal_resolvers() -> Vec<(String, Arc<dyn TokenResolver>)> {
        vec![
            ("env-resolver".to_string(), TokenResolverFactory::create_env_resolver().unwrap()),
            ("time-resolver".to_string(), TokenResolverFactory::create_time_resolver()),
        ]
    }
}

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

    #[test]
    fn test_plugin_token_resolver_creation() {
        let config = Arc::new(Config::default());
        let resolver = PluginTokenResolver::new(config);
        assert!(resolver.list_resolvers().is_empty());
    }

    #[tokio::test]
    async fn test_env_resolver() {
        let resolver = EnvironmentResolver::new().unwrap();

        // Test that it can resolve env tokens
        assert!(resolver.can_resolve("env:PATH"));
        assert!(!resolver.can_resolve("db:users"));

        // Test metadata
        let metadata = resolver.get_metadata();
        assert_eq!(metadata.description, "Environment variable resolver for config and secrets");
        assert!(metadata.supported_prefixes.contains(&"env".to_string()));
    }

    #[tokio::test]
    async fn test_time_resolver() {
        let resolver = TimeResolver::new();

        // Test that it can resolve time tokens
        assert!(resolver.can_resolve("time:iso8601"));
        assert!(resolver.can_resolve("datetime:date"));
        assert!(!resolver.can_resolve("env:PATH"));

        // Test resolution
        let context = ResolutionContext::new();
        let result = resolver.resolve_token("time:iso8601", &context).unwrap();
        assert!(!result.is_empty());
        assert!(result.contains("T")); // ISO 8601 format should contain 'T'
    }

    #[tokio::test]
    async fn test_uuid_resolver() {
        let resolver = UuidResolver::new();

        // Test that it can resolve UUID tokens
        assert!(resolver.can_resolve("uuid:v4"));
        assert!(resolver.can_resolve("id"));
        assert!(!resolver.can_resolve("env:PATH"));

        // Test resolution produces valid UUID
        let context = ResolutionContext::new();
        let result = resolver.resolve_token("uuid:v4", &context).unwrap();
        assert!(uuid::Uuid::parse_str(&result).is_ok());
    }

    #[tokio::test]
    async fn test_stats_resolver() {
        let resolver = StatsResolver::new(HashMap::new());

        // Test that it can resolve stats tokens
        assert!(resolver.can_resolve("stats:requests"));
        assert!(resolver.can_resolve("metrics:active-users"));
        assert!(!resolver.can_resolve("env:PATH"));

        // Test resolution
        let context = ResolutionContext::new();
        let result = resolver.resolve_token("stats:requests", &context).unwrap();
        assert!(result == "15423"); // Mock value
    }
}