tarzi 0.2.3

Rust-native lite search for AI applications
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
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
//! Web Driver Manager for browser automation
//!
//! This module provides a comprehensive web driver management system that supports
//! multiple browser drivers (chromedriver, geckodriver, etc.) with lifecycle management,
//! status checking, and automatic cleanup.

use crate::{
    Result, TarziError,
    constants::{CHROMEDRIVER_DEFAULT_PORT, DEFAULT_TIMEOUT_SECS},
};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::process::{Child, Command, Stdio};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
use tracing::warn;

/// Supported web driver types
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum DriverType {
    /// ChromeDriver for Chrome and Chromium browsers
    Chrome,
    /// GeckoDriver for Firefox browser
    Firefox,
    /// Generic driver type for future extensions
    Generic(String),
}

impl std::fmt::Display for DriverType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            DriverType::Chrome => write!(f, "chromedriver"),
            DriverType::Firefox => write!(f, "geckodriver"),
            DriverType::Generic(name) => write!(f, "{name}"),
        }
    }
}

impl std::str::FromStr for DriverType {
    type Err = TarziError;

    fn from_str(s: &str) -> Result<Self> {
        match s.to_lowercase().as_str() {
            "chromedriver" | "chrome" => Ok(DriverType::Chrome),
            "geckodriver" | "firefox" => Ok(DriverType::Firefox),
            _ => Ok(DriverType::Generic(s.to_string())),
        }
    }
}

/// Configuration for a web driver
#[derive(Debug, Clone)]
pub struct DriverConfig {
    /// Type of driver
    pub driver_type: DriverType,
    /// Port to run the driver on
    pub port: u16,
    /// Additional command line arguments
    pub args: Vec<String>,
    /// Timeout for driver operations (in seconds)
    pub timeout: Duration,
    /// Whether to enable verbose logging
    pub verbose: bool,
}

impl Default for DriverConfig {
    fn default() -> Self {
        Self {
            driver_type: DriverType::Chrome,
            port: CHROMEDRIVER_DEFAULT_PORT,
            args: Vec::new(),
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            verbose: false,
        }
    }
}

/// Status of a web driver process
#[derive(Debug, Clone, PartialEq)]
pub enum DriverStatus {
    /// Driver is not running
    Stopped,
    /// Driver is starting up
    Starting,
    /// Driver is running and ready
    Running,
    /// Driver has failed
    Failed(String),
}

/// Information about a running driver
#[derive(Debug, Clone)]
pub struct DriverInfo {
    /// Configuration used to start the driver
    pub config: DriverConfig,
    /// Current status of the driver
    pub status: DriverStatus,
    /// Process ID of the driver
    pub pid: Option<u32>,
    /// Time when the driver was started
    pub started_at: Instant,
    /// WebDriver endpoint URL
    pub endpoint: String,
}

/// A running web driver process
#[derive(Debug)]
struct DriverProcess {
    /// The child process
    child: Child,
    /// Configuration
    config: DriverConfig,
    /// Start time
    started_at: Instant,
}

/// Web Driver Manager
///
/// Manages the lifecycle of web driver processes, supporting multiple driver types
/// and providing status monitoring, health checks, and automatic cleanup.
#[derive(Debug)]
pub struct DriverManager {
    /// Map of running drivers by port
    drivers: Arc<Mutex<HashMap<u16, DriverProcess>>>,
    /// Default configuration
    default_config: DriverConfig,
}

impl DriverManager {
    /// Create a new driver manager with default configuration
    pub fn new() -> Self {
        Self {
            drivers: Arc::new(Mutex::new(HashMap::new())),
            default_config: DriverConfig::default(),
        }
    }

    /// Create a new driver manager with custom default configuration
    pub fn with_config(config: DriverConfig) -> Self {
        Self {
            drivers: Arc::new(Mutex::new(HashMap::new())),
            default_config: config,
        }
    }

    /// Start a web driver with default configuration
    pub fn start_driver(&self) -> Result<DriverInfo> {
        self.start_driver_with_config(self.default_config.clone())
    }

    /// Start a web driver with custom configuration
    pub fn start_driver_with_config(&self, config: DriverConfig) -> Result<DriverInfo> {
        // Check if driver binary exists
        self.check_driver_binary(&config.driver_type)?;

        // Check if port is already in use
        if self.is_port_in_use(config.port) {
            return Err(TarziError::Driver(format!(
                "Port {} is already in use",
                config.port
            )));
        }

        // Build command
        let mut cmd = Command::new(self.get_driver_binary_name(&config.driver_type));
        cmd.arg(format!("--port={}", config.port));

        // Add driver-specific arguments
        self.add_driver_specific_args(&mut cmd, &config);

        // Add custom arguments
        for arg in &config.args {
            cmd.arg(arg);
        }

        // Set up process stdio
        cmd.stdout(Stdio::piped())
            .stderr(Stdio::piped())
            .stdin(Stdio::null());

        // Start the process
        let child = cmd.spawn().map_err(|e| {
            TarziError::DriverProcess(format!(
                "Failed to start {} driver: {}",
                config.driver_type, e
            ))
        })?;

        self.create_and_store_driver_process(child, config)
    }

    /// Stop a driver by port
    pub fn stop_driver(&self, port: u16) -> Result<()> {
        let mut drivers = self.drivers.lock().unwrap();

        if let Some(mut driver_process) = drivers.remove(&port) {
            // Try to terminate gracefully first
            if let Err(e) = driver_process.child.kill() {
                log::warn!("Failed to kill driver process: {e}");
            }

            // Wait for process to exit
            if let Err(e) = driver_process.child.wait() {
                log::warn!("Failed to wait for driver process to exit: {e}");
            }

            log::info!(
                "Stopped {} driver on port {}",
                driver_process.config.driver_type,
                port
            );
            Ok(())
        } else {
            Err(TarziError::Driver(format!(
                "No driver running on port {port}"
            )))
        }
    }

    /// Stop all running drivers
    pub fn stop_all_drivers(&self) -> Result<()> {
        let ports: Vec<u16> = {
            let drivers = self.drivers.lock().unwrap();
            drivers.keys().cloned().collect()
        };

        for port in ports {
            if let Err(e) = self.stop_driver(port) {
                log::warn!("Failed to stop driver on port {port}: {e}");
            }
        }

        Ok(())
    }

    /// Get information about a running driver
    pub fn get_driver_info(&self, port: u16) -> Option<DriverInfo> {
        let drivers = self.drivers.lock().unwrap();

        drivers.get(&port).map(|driver_process| {
            let status = if self.is_driver_healthy(&format!("http://127.0.0.1:{port}")) {
                DriverStatus::Running
            } else {
                DriverStatus::Failed("Driver not responding".to_string())
            };

            DriverInfo {
                config: driver_process.config.clone(),
                status,
                pid: Some(driver_process.child.id()),
                started_at: driver_process.started_at,
                endpoint: format!("http://127.0.0.1:{port}"),
            }
        })
    }

    /// List all running drivers
    pub fn list_drivers(&self) -> Vec<DriverInfo> {
        let drivers = self.drivers.lock().unwrap();

        drivers
            .iter()
            .map(|(port, driver_process)| {
                let status = if self.is_driver_healthy(&format!("http://127.0.0.1:{}", *port)) {
                    DriverStatus::Running
                } else {
                    DriverStatus::Failed("Driver not responding".to_string())
                };

                DriverInfo {
                    config: driver_process.config.clone(),
                    status,
                    pid: Some(driver_process.child.id()),
                    started_at: driver_process.started_at,
                    endpoint: format!("http://127.0.0.1:{port}"),
                }
            })
            .collect()
    }

    /// Check if a driver binary is installed
    pub fn check_driver_binary(&self, driver_type: &DriverType) -> Result<()> {
        let binary_name = self.get_driver_binary_name(driver_type);

        // Try to find the binary in PATH
        match which::which(&binary_name) {
            Ok(path) => {
                log::debug!("Found {binary_name} at {path:?}");
                Ok(())
            }
            Err(_) => Err(TarziError::DriverNotFound(
                self.create_driver_not_found_message(driver_type, &binary_name),
            )),
        }
    }

    /// Check if a port is in use by this manager
    pub fn is_port_in_use(&self, port: u16) -> bool {
        let drivers = self.drivers.lock().unwrap();
        drivers.contains_key(&port)
    }

    /// Perform a health check on a driver
    pub fn is_driver_healthy(&self, endpoint: &str) -> bool {
        // Use a simple TCP connection check instead of HTTP to avoid blocking runtime issues
        use std::net::TcpStream;

        let addr_str = endpoint.replace("http://", "");
        match addr_str.parse::<std::net::SocketAddr>() {
            Ok(addr) => match TcpStream::connect_timeout(&addr, Duration::from_secs(3)) {
                Ok(stream) => {
                    let _ = stream.shutdown(std::net::Shutdown::Both);
                    true
                }
                Err(_) => false,
            },
            Err(_) => {
                warn!("Failed to parse endpoint address: {}", addr_str);
                false
            }
        }
    }

    /// Wait for a driver to be ready
    fn wait_for_driver_ready(&self, endpoint: &str, timeout: Duration) -> Result<()> {
        let start = Instant::now();

        while start.elapsed() < timeout {
            if self.is_driver_healthy(endpoint) {
                return Ok(());
            }

            thread::sleep(Duration::from_millis(500));
        }

        Err(TarziError::Driver(format!(
            "Driver failed to become ready within {timeout:?}"
        )))
    }

    /// Create and store driver process, then wait for it to be ready
    fn create_and_store_driver_process(
        &self,
        child: Child,
        config: DriverConfig,
    ) -> Result<DriverInfo> {
        let pid = child.id();
        let started_at = Instant::now();
        let endpoint = format!("http://127.0.0.1:{}", config.port);

        // Store the driver process
        let driver_process = DriverProcess {
            child,
            config: config.clone(),
            started_at,
        };

        {
            let mut drivers = self.drivers.lock().unwrap();
            drivers.insert(config.port, driver_process);
        }

        // Wait for driver to be ready
        self.wait_for_driver_ready(&endpoint, config.timeout)?;

        Ok(DriverInfo {
            config,
            status: DriverStatus::Running,
            pid: Some(pid),
            started_at,
            endpoint,
        })
    }

    /// Add driver-specific command line arguments
    fn add_driver_specific_args(&self, cmd: &mut Command, config: &DriverConfig) {
        match config.driver_type {
            DriverType::Chrome => {
                cmd.arg("--whitelisted-ips=");
                if config.verbose {
                    cmd.arg("--verbose");
                }
            }
            DriverType::Firefox => {
                cmd.arg("--host=127.0.0.1");
                if config.verbose {
                    cmd.args(["--log", "debug"]);
                }
            }
            DriverType::Generic(_) => {
                // Generic drivers may not support standard arguments
            }
        }
    }

    /// Create a driver not found error message
    fn create_driver_not_found_message(
        &self,
        driver_type: &DriverType,
        binary_name: &str,
    ) -> String {
        let install_message = self.get_install_message(driver_type);
        match install_message {
            Some(msg) => format!("{binary_name} not found in PATH. {msg}"),
            None => format!(
                "Driver '{binary_name}' not found in PATH. Please ensure it's installed and available."
            ),
        }
    }

    /// Get installation message for a driver type
    fn get_install_message(&self, driver_type: &DriverType) -> Option<&'static str> {
        match driver_type {
            DriverType::Chrome => {
                Some("Please install ChromeDriver: https://chromedriver.chromium.org/")
            }
            DriverType::Firefox => {
                Some("Please install GeckoDriver: https://github.com/mozilla/geckodriver/releases")
            }
            DriverType::Generic(_) => None,
        }
    }

    /// Get the binary name for a driver type
    fn get_driver_binary_name(&self, driver_type: &DriverType) -> String {
        match driver_type {
            DriverType::Chrome => "chromedriver".to_string(),
            DriverType::Firefox => "geckodriver".to_string(),
            DriverType::Generic(name) => name.clone(),
        }
    }

    /// Get supported driver types
    pub fn supported_drivers() -> Vec<DriverType> {
        vec![DriverType::Chrome, DriverType::Firefox]
    }

    /// Create a driver config for a specific type
    pub fn create_config(driver_type: DriverType, port: u16) -> DriverConfig {
        DriverConfig {
            driver_type,
            port,
            args: Vec::new(),
            timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
            verbose: false,
        }
    }
}

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

impl Drop for DriverManager {
    fn drop(&mut self) {
        // Clean up all running drivers when the manager is dropped
        // Use a simple approach that doesn't block the async runtime
        if let Ok(mut drivers) = self.drivers.lock() {
            for (port, mut driver_process) in drivers.drain() {
                let _ = driver_process.child.kill();
                log::info!("Killed driver process on port {port}");
            }
        }
    }
}

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

    #[test]
    fn test_driver_type_from_str() {
        assert_eq!(
            "chromedriver".parse::<DriverType>().unwrap(),
            DriverType::Chrome
        );
        assert_eq!("chrome".parse::<DriverType>().unwrap(), DriverType::Chrome);
        assert_eq!(
            "geckodriver".parse::<DriverType>().unwrap(),
            DriverType::Firefox
        );
        assert_eq!(
            "firefox".parse::<DriverType>().unwrap(),
            DriverType::Firefox
        );

        match "custom".parse::<DriverType>().unwrap() {
            DriverType::Generic(name) => assert_eq!(name, "custom"),
            _ => panic!("Expected Generic driver type"),
        }
    }

    #[test]
    fn test_driver_type_display() {
        assert_eq!(DriverType::Chrome.to_string(), "chromedriver");
        assert_eq!(DriverType::Firefox.to_string(), "geckodriver");
        assert_eq!(
            DriverType::Generic("custom".to_string()).to_string(),
            "custom"
        );
    }

    #[test]
    fn test_driver_config_default() {
        let config = DriverConfig::default();
        assert_eq!(config.driver_type, DriverType::Chrome);
        assert_eq!(config.port, CHROMEDRIVER_DEFAULT_PORT);
        assert_eq!(config.timeout, Duration::from_secs(DEFAULT_TIMEOUT_SECS));
        assert!(!config.verbose);
        assert!(config.args.is_empty());
    }

    #[test]
    fn test_driver_manager_new() {
        let manager = DriverManager::new();
        assert_eq!(manager.default_config.driver_type, DriverType::Chrome);
        assert_eq!(manager.default_config.port, CHROMEDRIVER_DEFAULT_PORT);
    }

    #[test]
    fn test_driver_manager_with_config() {
        let config = DriverConfig {
            driver_type: DriverType::Firefox,
            port: 19515, // Use a different port for testing
            args: vec!["--verbose".to_string()],
            timeout: Duration::from_secs(10),
            verbose: true,
        };

        let manager = DriverManager::with_config(config.clone());
        assert_eq!(manager.default_config.driver_type, config.driver_type);
        assert_eq!(manager.default_config.port, config.port);
        assert_eq!(manager.default_config.args, config.args);
        assert_eq!(manager.default_config.timeout, config.timeout);
        assert_eq!(manager.default_config.verbose, config.verbose);
    }

    #[test]
    fn test_supported_drivers() {
        let drivers = DriverManager::supported_drivers();
        assert!(drivers.contains(&DriverType::Chrome));
        assert!(drivers.contains(&DriverType::Firefox));
        assert_eq!(drivers.len(), 2);
    }

    #[test]
    fn test_create_config() {
        let config = DriverManager::create_config(DriverType::Firefox, 19515);
        assert_eq!(config.driver_type, DriverType::Firefox);
        assert_eq!(config.port, 19515);
        assert_eq!(config.timeout, Duration::from_secs(DEFAULT_TIMEOUT_SECS));
        assert!(!config.verbose);
    }

    #[test]
    fn test_is_port_in_use() {
        let manager = DriverManager::new();
        assert!(!manager.is_port_in_use(CHROMEDRIVER_DEFAULT_PORT));
        assert!(!manager.is_port_in_use(19515));
    }

    #[test]
    fn test_driver_binary_name() {
        let manager = DriverManager::new();
        assert_eq!(
            manager.get_driver_binary_name(&DriverType::Chrome),
            "chromedriver"
        );
        assert_eq!(
            manager.get_driver_binary_name(&DriverType::Firefox),
            "geckodriver"
        );
        assert_eq!(
            manager.get_driver_binary_name(&DriverType::Generic("custom".to_string())),
            "custom"
        );
    }

    #[test]
    fn test_list_drivers_empty() {
        let manager = DriverManager::new();
        let drivers = manager.list_drivers();
        assert!(drivers.is_empty());
    }

    #[test]
    fn test_get_driver_info_not_found() {
        let manager = DriverManager::new();
        let info = manager.get_driver_info(CHROMEDRIVER_DEFAULT_PORT);
        assert!(info.is_none());
    }

    #[test]
    fn test_stop_driver_not_found() {
        let manager = DriverManager::new();
        let result = manager.stop_driver(CHROMEDRIVER_DEFAULT_PORT);
        assert!(result.is_err());

        if let Err(TarziError::Driver(msg)) = result {
            assert!(msg.contains(&format!(
                "No driver running on port {CHROMEDRIVER_DEFAULT_PORT}"
            )));
        } else {
            panic!("Expected Driver error");
        }
    }

    #[test]
    fn test_driver_status_equality() {
        assert_eq!(DriverStatus::Stopped, DriverStatus::Stopped);
        assert_eq!(DriverStatus::Starting, DriverStatus::Starting);
        assert_eq!(DriverStatus::Running, DriverStatus::Running);
        assert_eq!(
            DriverStatus::Failed("test".to_string()),
            DriverStatus::Failed("test".to_string())
        );

        assert_ne!(DriverStatus::Stopped, DriverStatus::Running);
        assert_ne!(
            DriverStatus::Failed("test1".to_string()),
            DriverStatus::Failed("test2".to_string())
        );
    }

    // Note: Integration tests that actually start driver processes are in the tests/ directory
    // These unit tests focus on the logic and structure without requiring actual driver binaries
}

// Integration test helper functions
#[cfg(any(test, feature = "test-helpers"))]
pub mod test_helpers {
    use super::*;

    /// Check if a driver binary is available for testing
    pub fn is_driver_available(driver_type: &DriverType) -> bool {
        let manager = DriverManager::new();
        manager.check_driver_binary(driver_type).is_ok()
    }

    /// Create a test driver manager with specific configuration
    pub fn create_test_manager() -> DriverManager {
        let config = DriverConfig {
            driver_type: DriverType::Chrome,
            port: 19515, // Use a different port for testing
            args: vec!["--disable-gpu".to_string(), "--no-sandbox".to_string()],
            timeout: Duration::from_secs(10),
            verbose: true,
        };
        DriverManager::with_config(config)
    }

    /// Find an available port for testing
    pub fn find_available_port() -> u16 {
        use std::net::TcpListener;

        for port in 19515..19600 {
            if TcpListener::bind(("127.0.0.1", port)).is_ok() {
                return port;
            }
        }

        panic!("No available ports found for testing");
    }
}