Skip to main content

mockforge_test/
server.rs

1//! MockForge server management for tests
2
3use crate::config::{ServerConfig, ServerConfigBuilder};
4use crate::error::{Error, Result};
5use crate::health::{HealthCheck, HealthStatus};
6use crate::port_reservation::PortReservation;
7use crate::process::ManagedProcess;
8use crate::scenario::{non_blank, ScenarioManager, MANAGEMENT_TOKEN_ENV};
9use parking_lot::Mutex;
10use serde_json::Value;
11use std::path::Path;
12use std::sync::Arc;
13use tracing::{debug, error, info};
14
15/// A managed MockForge server instance for testing
16pub struct MockForgeServer {
17    process: Arc<Mutex<ManagedProcess>>,
18    health: HealthCheck,
19    scenario: ScenarioManager,
20    http_port: u16,
21    ws_port: Option<u16>,
22    grpc_port: Option<u16>,
23    admin_port: Option<u16>,
24    metrics_port: Option<u16>,
25    management_token: String,
26}
27
28/// Random 64-hex-character management token (two v4 UUIDs, 244 random bits).
29fn generate_management_token() -> String {
30    format!("{}{}", uuid::Uuid::new_v4().simple(), uuid::Uuid::new_v4().simple())
31}
32
33/// Pick the management token for a spawned server and pin it in `env_vars`.
34///
35/// Precedence: `config.management_token`, then `MOCKFORGE_MANAGEMENT_TOKEN` in
36/// `config.env_vars`, then the parent environment, then a freshly generated token.
37fn resolve_management_token(config: &mut ServerConfig) -> String {
38    let from_env_vars = config
39        .env_vars
40        .iter()
41        .rev()
42        .find(|(k, _)| k == MANAGEMENT_TOKEN_ENV)
43        .and_then(|(_, v)| non_blank(Some(v)));
44    let token = non_blank(config.management_token.as_deref())
45        .or(from_env_vars)
46        .or_else(|| non_blank(std::env::var(MANAGEMENT_TOKEN_ENV).ok().as_deref()))
47        .unwrap_or_else(generate_management_token);
48    config.env_vars.retain(|(k, _)| k != MANAGEMENT_TOKEN_ENV);
49    config.env_vars.push((MANAGEMENT_TOKEN_ENV.to_string(), token.clone()));
50    config.management_token = Some(token.clone());
51    token
52}
53
54impl MockForgeServer {
55    /// Create a new builder for MockForgeServer
56    pub fn builder() -> MockForgeServerBuilder {
57        MockForgeServerBuilder::default()
58    }
59
60    /// Start a MockForge server with the given configuration
61    pub async fn start(config: ServerConfig) -> Result<Self> {
62        // Resolve any ports the caller asked us to auto-assign (port == 0).
63        // Without this the SDK would forward `--<service>-port 0` to the CLI,
64        // which leaves the SDK with no way to know the OS-assigned port — and
65        // any test that hardcoded a port (e.g. 9080) would silently talk to a
66        // *different* mockforge process if one happened to be running.
67        let mut resolved_config = config.clone();
68        let mut reservations = Vec::new();
69        let mut reserve_port = || -> Result<u16> {
70            let reservation = PortReservation::new()
71                .map_err(|e| Error::ConfigError(format!("Port reservation failed: {e}")))?;
72            let port = reservation.port();
73            reservations.push(reservation);
74            Ok(port)
75        };
76        if resolved_config.http_port == 0 {
77            resolved_config.http_port = reserve_port()?;
78            info!("Auto-assigned HTTP port: {}", resolved_config.http_port);
79        }
80        if resolved_config.admin_port == Some(0) {
81            let port = reserve_port()?;
82            resolved_config.admin_port = Some(port);
83            info!("Auto-assigned admin port: {}", port);
84        }
85        // Prometheus metrics defaults to `enabled: true, port: 9090` in
86        // the CLI config. If we don't override, every subprocess races
87        // on 9090 and loses — and when the metrics handle errors out,
88        // the server's `tokio::select!` trips and the whole subprocess
89        // exits before HTTP health ever goes ready. Auto-assign whenever
90        // the caller didn't pin a port, so parallel tests never collide.
91        if resolved_config.metrics_port.is_none() || resolved_config.metrics_port == Some(0) {
92            let port = reserve_port()?;
93            resolved_config.metrics_port = Some(port);
94            info!("Auto-assigned metrics port: {}", port);
95        }
96        // The mockforge CLI always starts a WS server (default 3001) and gRPC
97        // server (default 50051) even when not explicitly requested. When
98        // multiple test instances spin up in parallel, all of them race for
99        // those default ports — and lose. Auto-assign whenever the caller
100        // didn't pin them, so each test gets its own private ports.
101        if resolved_config.ws_port.is_none() || resolved_config.ws_port == Some(0) {
102            let port = reserve_port()?;
103            resolved_config.ws_port = Some(port);
104            info!("Auto-assigned WebSocket port: {}", port);
105        }
106        if resolved_config.grpc_port.is_none() || resolved_config.grpc_port == Some(0) {
107            let port = reserve_port()?;
108            resolved_config.grpc_port = Some(port);
109            info!("Auto-assigned gRPC port: {}", port);
110        }
111
112        let management_token = resolve_management_token(&mut resolved_config);
113
114        // Spawn the process
115        let process = ManagedProcess::spawn_reserved(&resolved_config, reservations)?;
116        let http_port = process.http_port();
117
118        info!("MockForge server started on port {}", http_port);
119
120        // Create health check client
121        let health = HealthCheck::new("localhost", http_port);
122
123        // Wait for server to become healthy
124        debug!("Waiting for server to become healthy...");
125        health
126            .wait_until_healthy(resolved_config.health_timeout, resolved_config.health_interval)
127            .await?;
128
129        info!("MockForge server is healthy and ready");
130
131        // Create scenario manager
132        let scenario =
133            ScenarioManager::with_management_token("localhost", http_port, Some(&management_token));
134
135        Ok(Self {
136            process: Arc::new(Mutex::new(process)),
137            health,
138            scenario,
139            http_port,
140            ws_port: resolved_config.ws_port,
141            grpc_port: resolved_config.grpc_port,
142            admin_port: resolved_config.admin_port,
143            metrics_port: resolved_config.metrics_port,
144            management_token,
145        })
146    }
147
148    /// Get the HTTP port the server is running on
149    pub fn http_port(&self) -> u16 {
150        self.http_port
151    }
152
153    /// Management token the server was started with; send it as
154    /// `X-MockForge-Management-Token` on control-plane requests.
155    pub fn management_token(&self) -> &str {
156        &self.management_token
157    }
158
159    /// Get the WebSocket port if configured
160    pub fn ws_port(&self) -> Option<u16> {
161        self.ws_port
162    }
163
164    /// Get the gRPC port if configured
165    pub fn grpc_port(&self) -> Option<u16> {
166        self.grpc_port
167    }
168
169    /// Get the admin UI port if admin was enabled.
170    ///
171    /// When the builder set `.admin_port(0)` this returns the
172    /// auto-assigned port; when the builder set a specific port it
173    /// returns that port; when the builder didn't enable admin at all
174    /// it returns `None`.
175    pub fn admin_port(&self) -> Option<u16> {
176        self.admin_port
177    }
178
179    /// Get the metrics endpoint port if metrics was enabled.
180    pub fn metrics_port(&self) -> Option<u16> {
181        self.metrics_port
182    }
183
184    /// Get the base URL of the server
185    pub fn base_url(&self) -> String {
186        format!("http://localhost:{}", self.http_port)
187    }
188
189    /// Get the WebSocket URL if WebSocket is enabled
190    pub fn ws_url(&self) -> Option<String> {
191        self.ws_port.map(|port| format!("ws://localhost:{}/ws", port))
192    }
193
194    /// Get the process ID
195    pub fn pid(&self) -> u32 {
196        self.process.lock().pid()
197    }
198
199    /// Check if the server is still running
200    pub fn is_running(&self) -> bool {
201        self.process.lock().is_running()
202    }
203
204    /// Perform a health check
205    pub async fn health_check(&self) -> Result<HealthStatus> {
206        self.health.check().await
207    }
208
209    /// Check if the server is ready
210    pub async fn is_ready(&self) -> bool {
211        self.health.is_ready().await
212    }
213
214    /// Switch to a different scenario/workspace
215    ///
216    /// # Arguments
217    ///
218    /// * `scenario_name` - Name of the scenario to switch to
219    ///
220    /// # Example
221    ///
222    /// ```no_run
223    /// # use mockforge_test::MockForgeServer;
224    /// # async fn example() -> Result<(), Box<dyn std::error::Error>> {
225    /// let server = MockForgeServer::builder().build().await?;
226    /// server.scenario("user-auth-success").await?;
227    /// # Ok(())
228    /// # }
229    /// ```
230    pub async fn scenario(&self, scenario_name: &str) -> Result<()> {
231        self.scenario.switch_scenario(scenario_name).await
232    }
233
234    /// Load a workspace configuration from a file
235    pub async fn load_workspace<P: AsRef<Path>>(&self, workspace_file: P) -> Result<()> {
236        self.scenario.load_workspace(workspace_file).await
237    }
238
239    /// Update mock configuration for a specific endpoint
240    pub async fn update_mock(&self, endpoint: &str, config: Value) -> Result<()> {
241        self.scenario.update_mock(endpoint, config).await
242    }
243
244    /// List available fixtures
245    pub async fn list_fixtures(&self) -> Result<Vec<String>> {
246        self.scenario.list_fixtures().await
247    }
248
249    /// Get server statistics
250    pub async fn get_stats(&self) -> Result<Value> {
251        self.scenario.get_stats().await
252    }
253
254    /// Reset all mocks to their initial state
255    pub async fn reset(&self) -> Result<()> {
256        self.scenario.reset().await
257    }
258
259    /// Stop the server
260    pub fn stop(&self) -> Result<()> {
261        info!("Stopping MockForge server (port: {})", self.http_port);
262        self.process.lock().kill()
263    }
264}
265
266impl Drop for MockForgeServer {
267    fn drop(&mut self) {
268        if let Err(e) = self.stop() {
269            error!("Failed to stop MockForge server on drop: {}", e);
270        }
271    }
272}
273
274/// Builder for MockForgeServer
275pub struct MockForgeServerBuilder {
276    config_builder: ServerConfigBuilder,
277}
278
279impl Default for MockForgeServerBuilder {
280    fn default() -> Self {
281        Self {
282            config_builder: ServerConfig::builder(),
283        }
284    }
285}
286
287impl MockForgeServerBuilder {
288    /// Set HTTP port (0 for auto-assign)
289    pub fn http_port(mut self, port: u16) -> Self {
290        self.config_builder = self.config_builder.http_port(port);
291        self
292    }
293
294    /// Set WebSocket port
295    pub fn ws_port(mut self, port: u16) -> Self {
296        self.config_builder = self.config_builder.ws_port(port);
297        self
298    }
299
300    /// Set gRPC port
301    pub fn grpc_port(mut self, port: u16) -> Self {
302        self.config_builder = self.config_builder.grpc_port(port);
303        self
304    }
305
306    /// Set admin UI port
307    pub fn admin_port(mut self, port: u16) -> Self {
308        self.config_builder = self.config_builder.admin_port(port);
309        self
310    }
311
312    /// Set metrics port
313    pub fn metrics_port(mut self, port: u16) -> Self {
314        self.config_builder = self.config_builder.metrics_port(port);
315        self
316    }
317
318    /// Set OpenAPI specification file
319    pub fn spec_file(mut self, path: impl Into<std::path::PathBuf>) -> Self {
320        self.config_builder = self.config_builder.spec_file(path);
321        self
322    }
323
324    /// Set workspace directory
325    pub fn workspace_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
326        self.config_builder = self.config_builder.workspace_dir(path);
327        self
328    }
329
330    /// Set profile name
331    pub fn profile(mut self, profile: impl Into<String>) -> Self {
332        self.config_builder = self.config_builder.profile(profile);
333        self
334    }
335
336    /// Enable admin UI
337    pub fn enable_admin(mut self, enable: bool) -> Self {
338        self.config_builder = self.config_builder.enable_admin(enable);
339        self
340    }
341
342    /// Enable metrics endpoint
343    pub fn enable_metrics(mut self, enable: bool) -> Self {
344        self.config_builder = self.config_builder.enable_metrics(enable);
345        self
346    }
347
348    /// Add extra CLI argument
349    pub fn extra_arg(mut self, arg: impl Into<String>) -> Self {
350        self.config_builder = self.config_builder.extra_arg(arg);
351        self
352    }
353
354    /// Set health check timeout
355    pub fn health_timeout(mut self, timeout: std::time::Duration) -> Self {
356        self.config_builder = self.config_builder.health_timeout(timeout);
357        self
358    }
359
360    /// Set working directory
361    pub fn working_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
362        self.config_builder = self.config_builder.working_dir(path);
363        self
364    }
365
366    /// Add environment variable
367    pub fn env_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
368        self.config_builder = self.config_builder.env_var(key, value);
369        self
370    }
371
372    /// Set path to mockforge binary
373    pub fn binary_path(mut self, path: impl Into<std::path::PathBuf>) -> Self {
374        self.config_builder = self.config_builder.binary_path(path);
375        self
376    }
377
378    /// Set the management token (default: env or a random token)
379    pub fn management_token(mut self, token: impl Into<String>) -> Self {
380        self.config_builder = self.config_builder.management_token(token);
381        self
382    }
383
384    /// Build and start the MockForge server
385    pub async fn build(self) -> Result<MockForgeServer> {
386        let config = self.config_builder.build();
387        MockForgeServer::start(config).await
388    }
389}
390
391// Helper function for use with test frameworks
392/// Create a test server with default configuration
393pub async fn with_mockforge<F, Fut>(test: F) -> Result<()>
394where
395    F: FnOnce(MockForgeServer) -> Fut,
396    Fut: std::future::Future<Output = Result<()>>,
397{
398    let server = MockForgeServer::builder().build().await?;
399    test(server).await
400}
401
402#[cfg(test)]
403mod tests {
404    use super::*;
405    use std::time::Duration;
406
407    #[test]
408    fn test_generated_management_token_is_long_random_hex() {
409        let a = generate_management_token();
410        let b = generate_management_token();
411        assert!(a.len() >= 32);
412        assert!(a.chars().all(|c| c.is_ascii_hexdigit()));
413        assert_ne!(a, b);
414    }
415
416    #[test]
417    fn test_resolve_management_token_prefers_explicit_and_pins_env() {
418        let mut config = ServerConfig::builder()
419            .env_var(MANAGEMENT_TOKEN_ENV, "from-env-vars")
420            .management_token("explicit")
421            .build();
422        assert_eq!(resolve_management_token(&mut config), "explicit");
423        let pinned: Vec<_> =
424            config.env_vars.iter().filter(|(k, _)| k == MANAGEMENT_TOKEN_ENV).collect();
425        assert_eq!(pinned, vec![&(MANAGEMENT_TOKEN_ENV.to_string(), "explicit".to_string())]);
426    }
427
428    #[test]
429    fn test_resolve_management_token_uses_env_vars_entry() {
430        let mut config =
431            ServerConfig::builder().env_var(MANAGEMENT_TOKEN_ENV, "from-env-vars").build();
432        assert_eq!(resolve_management_token(&mut config), "from-env-vars");
433        assert_eq!(config.management_token.as_deref(), Some("from-env-vars"));
434    }
435
436    #[test]
437    fn test_resolve_management_token_never_empty() {
438        let mut config = ServerConfig::builder().management_token("   ").build();
439        let token = resolve_management_token(&mut config);
440        assert!(!token.trim().is_empty());
441        assert!(config.env_vars.iter().any(|(k, v)| k == MANAGEMENT_TOKEN_ENV && v == &token));
442    }
443
444    #[test]
445    fn test_builder_creation() {
446        let builder = MockForgeServer::builder().http_port(3000).enable_admin(true).profile("test");
447        // Verify builder captured the configuration
448        drop(builder);
449    }
450
451    #[test]
452    fn test_builder_default() {
453        let _builder = MockForgeServerBuilder::default();
454        // Default builder should be created
455    }
456
457    #[test]
458    fn test_builder_http_port() {
459        let builder = MockForgeServer::builder().http_port(8080);
460        // Chain continues
461        let _builder = builder.http_port(9090);
462    }
463
464    #[test]
465    fn test_builder_ws_port() {
466        let _builder = MockForgeServer::builder().ws_port(3001);
467    }
468
469    #[test]
470    fn test_builder_grpc_port() {
471        let _builder = MockForgeServer::builder().grpc_port(50051);
472    }
473
474    #[test]
475    fn test_builder_admin_port() {
476        let _builder = MockForgeServer::builder().admin_port(3002);
477    }
478
479    #[test]
480    fn test_builder_metrics_port() {
481        let _builder = MockForgeServer::builder().metrics_port(9090);
482    }
483
484    #[test]
485    fn test_builder_spec_file() {
486        let _builder = MockForgeServer::builder().spec_file("/path/to/spec.yaml");
487    }
488
489    #[test]
490    fn test_builder_workspace_dir() {
491        let _builder = MockForgeServer::builder().workspace_dir("/path/to/workspace");
492    }
493
494    #[test]
495    fn test_builder_profile() {
496        let _builder = MockForgeServer::builder().profile("production");
497    }
498
499    #[test]
500    fn test_builder_enable_admin() {
501        let _builder = MockForgeServer::builder().enable_admin(true);
502        let _builder2 = MockForgeServer::builder().enable_admin(false);
503    }
504
505    #[test]
506    fn test_builder_enable_metrics() {
507        let _builder = MockForgeServer::builder().enable_metrics(true);
508        let _builder2 = MockForgeServer::builder().enable_metrics(false);
509    }
510
511    #[test]
512    fn test_builder_extra_arg() {
513        let _builder = MockForgeServer::builder().extra_arg("--verbose");
514    }
515
516    #[test]
517    fn test_builder_health_timeout() {
518        let _builder = MockForgeServer::builder().health_timeout(Duration::from_secs(60));
519    }
520
521    #[test]
522    fn test_builder_working_dir() {
523        let _builder = MockForgeServer::builder().working_dir("/tmp/test");
524    }
525
526    #[test]
527    fn test_builder_env_var() {
528        let _builder = MockForgeServer::builder().env_var("RUST_LOG", "debug");
529    }
530
531    #[test]
532    fn test_builder_binary_path() {
533        let _builder = MockForgeServer::builder().binary_path("/usr/local/bin/mockforge");
534    }
535
536    #[test]
537    fn test_builder_full_chain() {
538        let _builder = MockForgeServer::builder()
539            .http_port(3000)
540            .ws_port(3001)
541            .grpc_port(50051)
542            .admin_port(3002)
543            .metrics_port(9090)
544            .spec_file("/spec.yaml")
545            .workspace_dir("/workspace")
546            .profile("test")
547            .enable_admin(true)
548            .enable_metrics(true)
549            .extra_arg("--verbose")
550            .health_timeout(Duration::from_secs(30))
551            .working_dir("/working")
552            .env_var("KEY", "VALUE")
553            .binary_path("/bin/mockforge");
554
555        // Full builder chain should compile
556    }
557}