ipfrs_cli/commands/
gateway.rs

1//! HTTP Gateway command
2//!
3//! This module provides the HTTP gateway functionality with optional TLS support.
4
5use anyhow::{Context, Result};
6
7/// Run HTTP gateway server
8///
9/// # Arguments
10///
11/// * `listen` - Address and port to listen on
12/// * `data_dir` - Data directory containing the IPFRS repository
13/// * `tls_cert` - Optional path to TLS certificate file (PEM format)
14/// * `tls_key` - Optional path to TLS private key file (PEM format)
15///
16/// # Errors
17///
18/// Returns an error if:
19/// - Storage configuration is invalid
20/// - TLS certificate or key files cannot be read
21/// - Only one of cert/key is provided (both are required for TLS)
22/// - Gateway fails to start
23pub async fn run_gateway(
24    listen: String,
25    data_dir: String,
26    tls_cert: Option<String>,
27    tls_key: Option<String>,
28) -> Result<()> {
29    use ipfrs_interface::tls::TlsConfig;
30    use ipfrs_interface::{Gateway, GatewayConfig};
31    use ipfrs_storage::BlockStoreConfig;
32
33    let storage_config = BlockStoreConfig {
34        path: std::path::PathBuf::from(&data_dir).join("blocks"),
35        cache_size: 100 * 1024 * 1024, // 100MB
36    };
37
38    // Validate TLS configuration
39    let tls_config = match (tls_cert, tls_key) {
40        (Some(cert), Some(key)) => {
41            // Verify files exist
42            if !std::path::Path::new(&cert).exists() {
43                anyhow::bail!("TLS certificate file not found: {}", cert);
44            }
45            if !std::path::Path::new(&key).exists() {
46                anyhow::bail!("TLS private key file not found: {}", key);
47            }
48
49            Some(TlsConfig {
50                cert_path: cert.into(),
51                key_path: key.into(),
52            })
53        }
54        (None, None) => None,
55        (Some(_), None) => {
56            anyhow::bail!("TLS certificate provided but private key is missing (use --tls-key)");
57        }
58        (None, Some(_)) => {
59            anyhow::bail!("TLS private key provided but certificate is missing (use --tls-cert)");
60        }
61    };
62
63    let config = GatewayConfig {
64        listen_addr: listen.clone(),
65        storage_config,
66        tls_config: tls_config.clone(),
67        compression_config: Default::default(),
68    };
69
70    let protocol = if tls_config.is_some() {
71        "HTTPS"
72    } else {
73        "HTTP"
74    };
75    eprintln!("Starting {} gateway on {}", protocol, listen);
76    if tls_config.is_some() {
77        eprintln!("TLS enabled - using secure connections");
78    }
79
80    let gateway = Gateway::new(config).context("Failed to create gateway")?;
81    gateway
82        .start()
83        .await
84        .context("Failed to start gateway server")?;
85
86    Ok(())
87}