mockforge_sdk/
admin.rs

1//! Admin API client for runtime mock management
2//!
3//! Provides programmatic access to MockForge's management API for
4//! creating, updating, and managing mocks at runtime.
5
6use crate::{Error, Result};
7use reqwest::Client;
8use serde::{Deserialize, Serialize};
9use std::collections::HashMap;
10
11/// Admin API client for managing mocks
12pub struct AdminClient {
13    base_url: String,
14    client: Client,
15}
16
17/// Mock configuration
18#[derive(Debug, Clone, Serialize, Deserialize)]
19pub struct MockConfig {
20    /// Unique identifier for the mock (auto-generated if empty)
21    #[serde(skip_serializing_if = "String::is_empty")]
22    pub id: String,
23    /// Human-readable name for the mock
24    pub name: String,
25    /// HTTP method (GET, POST, PUT, DELETE, etc.)
26    pub method: String,
27    /// URL path pattern (supports path parameters)
28    pub path: String,
29    /// Response configuration
30    pub response: MockResponse,
31    /// Whether this mock is currently active
32    #[serde(default = "default_true")]
33    pub enabled: bool,
34    /// Optional latency to simulate in milliseconds
35    #[serde(skip_serializing_if = "Option::is_none")]
36    pub latency_ms: Option<u64>,
37    /// HTTP status code to return (default: 200)
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub status_code: Option<u16>,
40    /// Request matching criteria (headers, query params, body patterns)
41    #[serde(skip_serializing_if = "Option::is_none")]
42    pub request_match: Option<RequestMatchCriteria>,
43    /// Priority for mock ordering (higher priority mocks are matched first)
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub priority: Option<i32>,
46    /// Scenario name for stateful mocking
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub scenario: Option<String>,
49    /// Required scenario state for this mock to be active
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub required_scenario_state: Option<String>,
52    /// New scenario state after this mock is matched
53    #[serde(skip_serializing_if = "Option::is_none")]
54    pub new_scenario_state: Option<String>,
55}
56
57fn default_true() -> bool {
58    true
59}
60
61/// Mock response configuration
62#[derive(Debug, Clone, Serialize, Deserialize)]
63pub struct MockResponse {
64    /// Response body (supports JSON values and templates)
65    pub body: serde_json::Value,
66    /// Optional HTTP headers to include in the response
67    #[serde(skip_serializing_if = "Option::is_none")]
68    pub headers: Option<HashMap<String, String>>,
69}
70
71/// Request matching criteria for advanced request matching
72#[derive(Debug, Clone, Serialize, Deserialize, Default)]
73pub struct RequestMatchCriteria {
74    /// Headers that must be present and match (case-insensitive header names)
75    #[serde(skip_serializing_if = "HashMap::is_empty")]
76    pub headers: HashMap<String, String>,
77    /// Query parameters that must be present and match
78    #[serde(skip_serializing_if = "HashMap::is_empty")]
79    pub query_params: HashMap<String, String>,
80    /// Request body pattern (supports exact match or regex)
81    #[serde(skip_serializing_if = "Option::is_none")]
82    pub body_pattern: Option<String>,
83    /// JSONPath expression for JSON body matching
84    #[serde(skip_serializing_if = "Option::is_none")]
85    pub json_path: Option<String>,
86    /// XPath expression for XML body matching
87    #[serde(skip_serializing_if = "Option::is_none")]
88    pub xpath: Option<String>,
89    /// Custom matcher expression (e.g., "headers.content-type == \"application/json\"")
90    #[serde(skip_serializing_if = "Option::is_none")]
91    pub custom_matcher: Option<String>,
92}
93
94/// Server statistics
95#[derive(Debug, Clone, Serialize, Deserialize)]
96pub struct ServerStats {
97    /// Server uptime in seconds
98    pub uptime_seconds: u64,
99    /// Total number of requests served
100    pub total_requests: u64,
101    /// Number of registered mocks (active and inactive)
102    pub active_mocks: usize,
103    /// Number of currently enabled mocks
104    pub enabled_mocks: usize,
105    /// Total number of registered routes
106    pub registered_routes: usize,
107}
108
109/// Server configuration info
110#[derive(Debug, Clone, Serialize, Deserialize)]
111pub struct ServerConfig {
112    /// MockForge version
113    pub version: String,
114    /// HTTP port the server is running on
115    pub port: u16,
116    /// Whether an OpenAPI spec is loaded
117    pub has_openapi_spec: bool,
118    /// Path to the OpenAPI spec file (if loaded)
119    #[serde(skip_serializing_if = "Option::is_none")]
120    pub spec_path: Option<String>,
121}
122
123/// List of mocks with metadata
124#[derive(Debug, Clone, Serialize, Deserialize)]
125pub struct MockList {
126    /// List of mock configurations
127    pub mocks: Vec<MockConfig>,
128    /// Total number of mocks
129    pub total: usize,
130    /// Number of enabled mocks
131    pub enabled: usize,
132}
133
134impl AdminClient {
135    /// Create a new admin client
136    ///
137    /// The base URL should be the root URL of the MockForge server
138    /// (e.g., "http://localhost:3000"). Trailing slashes are automatically removed.
139    ///
140    /// # Examples
141    ///
142    /// ```rust
143    /// use mockforge_sdk::AdminClient;
144    ///
145    /// let client = AdminClient::new("http://localhost:3000");
146    /// // Also works with trailing slash:
147    /// let client = AdminClient::new("http://localhost:3000/");
148    /// ```
149    pub fn new(base_url: impl Into<String>) -> Self {
150        let mut url = base_url.into();
151
152        // Normalize URL: remove trailing slashes
153        while url.ends_with('/') {
154            url.pop();
155        }
156
157        Self {
158            base_url: url,
159            client: Client::new(),
160        }
161    }
162
163    /// List all mocks
164    pub async fn list_mocks(&self) -> Result<MockList> {
165        let url = format!("{}/api/mocks", self.base_url);
166        let response = self
167            .client
168            .get(&url)
169            .send()
170            .await
171            .map_err(|e| Error::General(format!("Failed to list mocks: {}", e)))?;
172
173        if !response.status().is_success() {
174            return Err(Error::General(format!(
175                "Failed to list mocks: HTTP {}",
176                response.status()
177            )));
178        }
179
180        response
181            .json()
182            .await
183            .map_err(|e| Error::General(format!("Failed to parse response: {}", e)))
184    }
185
186    /// Get a specific mock by ID
187    pub async fn get_mock(&self, id: &str) -> Result<MockConfig> {
188        let url = format!("{}/api/mocks/{}", self.base_url, id);
189        let response = self
190            .client
191            .get(&url)
192            .send()
193            .await
194            .map_err(|e| Error::General(format!("Failed to get mock: {}", e)))?;
195
196        if response.status() == reqwest::StatusCode::NOT_FOUND {
197            return Err(Error::General(format!("Mock not found: {}", id)));
198        }
199
200        if !response.status().is_success() {
201            return Err(Error::General(format!("Failed to get mock: HTTP {}", response.status())));
202        }
203
204        response
205            .json()
206            .await
207            .map_err(|e| Error::General(format!("Failed to parse response: {}", e)))
208    }
209
210    /// Create a new mock
211    pub async fn create_mock(&self, mock: MockConfig) -> Result<MockConfig> {
212        let url = format!("{}/api/mocks", self.base_url);
213        let response = self
214            .client
215            .post(&url)
216            .json(&mock)
217            .send()
218            .await
219            .map_err(|e| Error::General(format!("Failed to create mock: {}", e)))?;
220
221        if response.status() == reqwest::StatusCode::CONFLICT {
222            return Err(Error::General(format!("Mock with ID {} already exists", mock.id)));
223        }
224
225        if !response.status().is_success() {
226            return Err(Error::General(format!(
227                "Failed to create mock: HTTP {}",
228                response.status()
229            )));
230        }
231
232        response
233            .json()
234            .await
235            .map_err(|e| Error::General(format!("Failed to parse response: {}", e)))
236    }
237
238    /// Update an existing mock
239    pub async fn update_mock(&self, id: &str, mock: MockConfig) -> Result<MockConfig> {
240        let url = format!("{}/api/mocks/{}", self.base_url, id);
241        let response = self
242            .client
243            .put(&url)
244            .json(&mock)
245            .send()
246            .await
247            .map_err(|e| Error::General(format!("Failed to update mock: {}", e)))?;
248
249        if response.status() == reqwest::StatusCode::NOT_FOUND {
250            return Err(Error::General(format!("Mock not found: {}", id)));
251        }
252
253        if !response.status().is_success() {
254            return Err(Error::General(format!(
255                "Failed to update mock: HTTP {}",
256                response.status()
257            )));
258        }
259
260        response
261            .json()
262            .await
263            .map_err(|e| Error::General(format!("Failed to parse response: {}", e)))
264    }
265
266    /// Delete a mock
267    pub async fn delete_mock(&self, id: &str) -> Result<()> {
268        let url = format!("{}/api/mocks/{}", self.base_url, id);
269        let response = self
270            .client
271            .delete(&url)
272            .send()
273            .await
274            .map_err(|e| Error::General(format!("Failed to delete mock: {}", e)))?;
275
276        if response.status() == reqwest::StatusCode::NOT_FOUND {
277            return Err(Error::General(format!("Mock not found: {}", id)));
278        }
279
280        if !response.status().is_success() {
281            return Err(Error::General(format!(
282                "Failed to delete mock: HTTP {}",
283                response.status()
284            )));
285        }
286
287        Ok(())
288    }
289
290    /// Get server statistics
291    pub async fn get_stats(&self) -> Result<ServerStats> {
292        let url = format!("{}/api/stats", self.base_url);
293        let response = self
294            .client
295            .get(&url)
296            .send()
297            .await
298            .map_err(|e| Error::General(format!("Failed to get stats: {}", e)))?;
299
300        if !response.status().is_success() {
301            return Err(Error::General(format!("Failed to get stats: HTTP {}", response.status())));
302        }
303
304        response
305            .json()
306            .await
307            .map_err(|e| Error::General(format!("Failed to parse response: {}", e)))
308    }
309
310    /// Get server configuration
311    pub async fn get_config(&self) -> Result<ServerConfig> {
312        let url = format!("{}/api/config", self.base_url);
313        let response = self
314            .client
315            .get(&url)
316            .send()
317            .await
318            .map_err(|e| Error::General(format!("Failed to get config: {}", e)))?;
319
320        if !response.status().is_success() {
321            return Err(Error::General(format!(
322                "Failed to get config: HTTP {}",
323                response.status()
324            )));
325        }
326
327        response
328            .json()
329            .await
330            .map_err(|e| Error::General(format!("Failed to parse response: {}", e)))
331    }
332
333    /// Reset all mocks to initial state
334    pub async fn reset(&self) -> Result<()> {
335        let url = format!("{}/api/reset", self.base_url);
336        let response = self
337            .client
338            .post(&url)
339            .send()
340            .await
341            .map_err(|e| Error::General(format!("Failed to reset mocks: {}", e)))?;
342
343        if !response.status().is_success() {
344            return Err(Error::General(format!(
345                "Failed to reset mocks: HTTP {}",
346                response.status()
347            )));
348        }
349
350        Ok(())
351    }
352}
353
354/// Builder for creating mock configurations with fluent API
355///
356/// This builder provides a WireMock-like fluent API for creating mock configurations
357/// with comprehensive request matching and response configuration.
358///
359/// # Examples
360///
361/// ```rust
362/// use mockforge_sdk::admin::MockConfigBuilder;
363/// use serde_json::json;
364///
365/// // Basic mock
366/// let mock = MockConfigBuilder::new("GET", "/api/users")
367///     .name("Get Users")
368///     .status(200)
369///     .body(json!([{"id": 1, "name": "Alice"}]))
370///     .build();
371///
372/// // Advanced matching with headers and query params
373/// let mock = MockConfigBuilder::new("POST", "/api/users")
374///     .name("Create User")
375///     .with_header("Authorization", "Bearer.*")
376///     .with_query_param("role", "admin")
377///     .with_body_pattern(r#"{"name":".*"}"#)
378///     .status(201)
379///     .body(json!({"id": 123, "created": true}))
380///     .priority(10)
381///     .build();
382/// ```
383pub struct MockConfigBuilder {
384    config: MockConfig,
385}
386
387impl MockConfigBuilder {
388    /// Create a new mock configuration builder
389    ///
390    /// # Arguments
391    /// * `method` - HTTP method (GET, POST, PUT, DELETE, etc.)
392    /// * `path` - URL path pattern (supports path parameters like `/users/{id}`)
393    pub fn new(method: impl Into<String>, path: impl Into<String>) -> Self {
394        Self {
395            config: MockConfig {
396                id: String::new(),
397                name: String::new(),
398                method: method.into().to_uppercase(),
399                path: path.into(),
400                response: MockResponse {
401                    body: serde_json::json!({}),
402                    headers: None,
403                },
404                enabled: true,
405                latency_ms: None,
406                status_code: None,
407                request_match: None,
408                priority: None,
409                scenario: None,
410                required_scenario_state: None,
411                new_scenario_state: None,
412            },
413        }
414    }
415
416    /// Set the mock ID
417    pub fn id(mut self, id: impl Into<String>) -> Self {
418        self.config.id = id.into();
419        self
420    }
421
422    /// Set the mock name
423    pub fn name(mut self, name: impl Into<String>) -> Self {
424        self.config.name = name.into();
425        self
426    }
427
428    /// Set the response body (supports templating with {{variables}})
429    pub fn body(mut self, body: serde_json::Value) -> Self {
430        self.config.response.body = body;
431        self
432    }
433
434    /// Set the response status code
435    pub fn status(mut self, status: u16) -> Self {
436        self.config.status_code = Some(status);
437        self
438    }
439
440    /// Set response headers
441    pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
442        self.config.response.headers = Some(headers);
443        self
444    }
445
446    /// Add a single response header
447    pub fn header(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
448        let headers = self.config.response.headers.get_or_insert_with(HashMap::new);
449        headers.insert(key.into(), value.into());
450        self
451    }
452
453    /// Set the latency in milliseconds
454    pub fn latency_ms(mut self, ms: u64) -> Self {
455        self.config.latency_ms = Some(ms);
456        self
457    }
458
459    /// Enable or disable the mock
460    pub fn enabled(mut self, enabled: bool) -> Self {
461        self.config.enabled = enabled;
462        self
463    }
464
465    // ========== Request Matching Methods ==========
466
467    /// Require a specific header to be present and match (supports regex patterns)
468    ///
469    /// # Examples
470    /// ```rust
471    /// MockConfigBuilder::new("GET", "/api/users")
472    ///     .with_header("Authorization", "Bearer.*")
473    ///     .with_header("Content-Type", "application/json")
474    /// ```
475    pub fn with_header(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
476        let match_criteria =
477            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
478        match_criteria.headers.insert(name.into(), value.into());
479        self
480    }
481
482    /// Require multiple headers to be present and match
483    pub fn with_headers(mut self, headers: HashMap<String, String>) -> Self {
484        let match_criteria =
485            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
486        match_criteria.headers.extend(headers);
487        self
488    }
489
490    /// Require a specific query parameter to be present and match
491    ///
492    /// # Examples
493    /// ```rust
494    /// MockConfigBuilder::new("GET", "/api/users")
495    ///     .with_query_param("role", "admin")
496    ///     .with_query_param("limit", "10")
497    /// ```
498    pub fn with_query_param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
499        let match_criteria =
500            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
501        match_criteria.query_params.insert(name.into(), value.into());
502        self
503    }
504
505    /// Require multiple query parameters to be present and match
506    pub fn with_query_params(mut self, params: HashMap<String, String>) -> Self {
507        let match_criteria =
508            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
509        match_criteria.query_params.extend(params);
510        self
511    }
512
513    /// Require the request body to match a pattern (supports exact match or regex)
514    ///
515    /// # Examples
516    /// ```rust
517    /// MockConfigBuilder::new("POST", "/api/users")
518    ///     .with_body_pattern(r#"{"name":".*"}"#)  // Regex pattern
519    ///     .with_body_pattern("exact string match")  // Exact match
520    /// ```
521    pub fn with_body_pattern(mut self, pattern: impl Into<String>) -> Self {
522        let match_criteria =
523            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
524        match_criteria.body_pattern = Some(pattern.into());
525        self
526    }
527
528    /// Require the request body to match a JSONPath expression
529    ///
530    /// # Examples
531    /// ```rust
532    /// MockConfigBuilder::new("POST", "/api/users")
533    ///     .with_json_path("$.name")  // Body must have a 'name' field
534    ///     .with_json_path("$.age > 18")  // Body must have age > 18
535    /// ```
536    pub fn with_json_path(mut self, json_path: impl Into<String>) -> Self {
537        let match_criteria =
538            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
539        match_criteria.json_path = Some(json_path.into());
540        self
541    }
542
543    /// Require the request body to match an XPath expression (for XML)
544    ///
545    /// # Examples
546    /// ```rust
547    /// MockConfigBuilder::new("POST", "/api/users")
548    ///     .with_xpath("/users/user[@id='123']")
549    /// ```
550    pub fn with_xpath(mut self, xpath: impl Into<String>) -> Self {
551        let match_criteria =
552            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
553        match_criteria.xpath = Some(xpath.into());
554        self
555    }
556
557    /// Set a custom matcher expression for advanced matching logic
558    ///
559    /// # Examples
560    /// ```rust
561    /// MockConfigBuilder::new("GET", "/api/users")
562    ///     .with_custom_matcher("headers.content-type == \"application/json\"")
563    ///     .with_custom_matcher("path =~ \"/api/.*\"")
564    /// ```
565    pub fn with_custom_matcher(mut self, expression: impl Into<String>) -> Self {
566        let match_criteria =
567            self.config.request_match.get_or_insert_with(RequestMatchCriteria::default);
568        match_criteria.custom_matcher = Some(expression.into());
569        self
570    }
571
572    // ========== Priority and Scenario Methods ==========
573
574    /// Set the priority for this mock (higher priority mocks are matched first)
575    ///
576    /// Default priority is 0. Higher numbers = higher priority.
577    pub fn priority(mut self, priority: i32) -> Self {
578        self.config.priority = Some(priority);
579        self
580    }
581
582    /// Set the scenario name for stateful mocking
583    ///
584    /// Scenarios allow you to create stateful mock sequences where the response
585    /// depends on previous requests.
586    pub fn scenario(mut self, scenario: impl Into<String>) -> Self {
587        self.config.scenario = Some(scenario.into());
588        self
589    }
590
591    /// Require a specific scenario state for this mock to be active
592    ///
593    /// This mock will only match if the scenario is in the specified state.
594    pub fn when_scenario_state(mut self, state: impl Into<String>) -> Self {
595        self.config.required_scenario_state = Some(state.into());
596        self
597    }
598
599    /// Set the new scenario state after this mock is matched
600    ///
601    /// After this mock responds, the scenario will transition to this state.
602    pub fn will_set_scenario_state(mut self, state: impl Into<String>) -> Self {
603        self.config.new_scenario_state = Some(state.into());
604        self
605    }
606
607    /// Build the mock configuration
608    pub fn build(self) -> MockConfig {
609        self.config
610    }
611}
612
613#[cfg(test)]
614mod tests {
615    use super::*;
616
617    #[test]
618    fn test_mock_config_builder_basic() {
619        let mock = MockConfigBuilder::new("GET", "/api/users")
620            .name("Get Users")
621            .status(200)
622            .body(serde_json::json!([{"id": 1, "name": "Alice"}]))
623            .latency_ms(100)
624            .header("Content-Type", "application/json")
625            .build();
626
627        assert_eq!(mock.method, "GET");
628        assert_eq!(mock.path, "/api/users");
629        assert_eq!(mock.name, "Get Users");
630        assert_eq!(mock.status_code, Some(200));
631        assert_eq!(mock.latency_ms, Some(100));
632        assert!(mock.enabled);
633    }
634
635    #[test]
636    fn test_mock_config_builder_with_matching() {
637        let mut headers = HashMap::new();
638        headers.insert("Authorization".to_string(), "Bearer.*".to_string());
639
640        let mut query_params = HashMap::new();
641        query_params.insert("role".to_string(), "admin".to_string());
642
643        let mock = MockConfigBuilder::new("POST", "/api/users")
644            .name("Create User")
645            .with_headers(headers.clone())
646            .with_query_params(query_params.clone())
647            .with_body_pattern(r#"{"name":".*"}"#)
648            .status(201)
649            .body(serde_json::json!({"id": 123, "created": true}))
650            .priority(10)
651            .build();
652
653        assert_eq!(mock.method, "POST");
654        assert!(mock.request_match.is_some());
655        let match_criteria = mock.request_match.unwrap();
656        assert_eq!(match_criteria.headers.get("Authorization"), Some(&"Bearer.*".to_string()));
657        assert_eq!(match_criteria.query_params.get("role"), Some(&"admin".to_string()));
658        assert_eq!(match_criteria.body_pattern, Some(r#"{"name":".*"}"#.to_string()));
659        assert_eq!(mock.priority, Some(10));
660    }
661
662    #[test]
663    fn test_mock_config_builder_with_scenario() {
664        let mock = MockConfigBuilder::new("GET", "/api/checkout")
665            .name("Checkout Step 1")
666            .scenario("checkout-flow")
667            .when_scenario_state("started")
668            .will_set_scenario_state("payment")
669            .status(200)
670            .body(serde_json::json!({"step": 1}))
671            .build();
672
673        assert_eq!(mock.scenario, Some("checkout-flow".to_string()));
674        assert_eq!(mock.required_scenario_state, Some("started".to_string()));
675        assert_eq!(mock.new_scenario_state, Some("payment".to_string()));
676    }
677
678    #[test]
679    fn test_mock_config_builder_fluent_chaining() {
680        let mock = MockConfigBuilder::new("GET", "/api/users/{id}")
681            .id("user-get-123")
682            .name("Get User by ID")
683            .with_header("Accept", "application/json")
684            .with_query_param("include", "profile")
685            .with_json_path("$.id")
686            .status(200)
687            .body(serde_json::json!({"id": "{{request.path.id}}", "name": "Alice"}))
688            .header("X-Request-ID", "{{uuid}}")
689            .latency_ms(50)
690            .priority(5)
691            .enabled(true)
692            .build();
693
694        assert_eq!(mock.id, "user-get-123");
695        assert_eq!(mock.name, "Get User by ID");
696        assert!(mock.request_match.is_some());
697        let match_criteria = mock.request_match.unwrap();
698        assert!(match_criteria.headers.contains_key("Accept"));
699        assert!(match_criteria.query_params.contains_key("include"));
700        assert_eq!(match_criteria.json_path, Some("$.id".to_string()));
701        assert_eq!(mock.priority, Some(5));
702    }
703}