Skip to main content

hyprstream_flight/cli/
handlers.rs

1use crate::service::FlightSqlServer;
2use config::{Config, File};
3use hyprstream_metrics::storage::{duckdb::DuckDbBackend, StorageBackendType};
4use std::{collections::HashMap, error::Error as StdError, fmt, path::PathBuf};
5use tonic::transport::{Certificate, Identity, Server, ServerTlsConfig};
6use tracing::{debug, error, info};
7
8#[derive(Debug)]
9pub enum ConnectionError {
10    Timeout(String),
11    Other(Box<dyn StdError>),
12}
13
14impl fmt::Display for ConnectionError {
15    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16        match self {
17            ConnectionError::Timeout(msg) => write!(f, "Connection timeout: {msg}"),
18            ConnectionError::Other(e) => write!(f, "Connection error: {e}"),
19        }
20    }
21}
22
23impl StdError for ConnectionError {
24    fn source(&self) -> Option<&(dyn StdError + 'static)> {
25        match self {
26            ConnectionError::Timeout(_) => None,
27            ConnectionError::Other(e) => Some(e.as_ref()),
28        }
29    }
30}
31
32pub async fn handle_server(config: Config) -> Result<(), Box<dyn std::error::Error>> {
33    let addr = format!(
34        "{}:{}",
35        config.get_string("host")?.as_str(),
36        config.get_string("port")?.as_str()
37    )
38    .parse()?;
39
40    let backend = match config.get_string("storage.type")?.as_str() {
41        "duckdb" => {
42            let conn_str = config.get_string("storage.connection")?.clone();
43            let backend = DuckDbBackend::new(conn_str, HashMap::new(), None)?;
44            StorageBackendType::DuckDb(backend)
45        }
46        _ => return Err("Unsupported storage type (only duckdb supported currently)".into()),
47    };
48
49    let service = FlightSqlServer::new(backend).await?.into_service();
50    let mut server = Server::builder();
51
52    // Configure TLS if enabled
53    if config.get_bool("tls.enabled").unwrap_or(false) {
54        let cert = match config.get::<Vec<u8>>("tls.cert_data") {
55            Ok(data) => data,
56            Err(_) => {
57                let path = config
58                    .get_string("tls.cert_path")
59                    .map_err(|_| "TLS certificate not found")?;
60                std::fs::read(path).map_err(|_| "Failed to read TLS certificate")?
61            }
62        };
63        let key = match config.get::<Vec<u8>>("tls.key_data") {
64            Ok(data) => data,
65            Err(_) => {
66                let path = config
67                    .get_string("tls.key_path")
68                    .map_err(|_| "TLS key not found")?;
69                std::fs::read(path).map_err(|_| "Failed to read TLS key")?
70            }
71        };
72        let identity = Identity::from_pem(&cert, &key);
73
74        let mut tls_config = ServerTlsConfig::new().identity(identity);
75
76        if let Some(ca) = config.get::<Vec<u8>>("tls.ca_data").ok().or_else(|| {
77            config
78                .get_string("tls.ca_path")
79                .ok()
80                .filter(|p| !p.is_empty())
81                .and_then(|p| std::fs::read(p).ok())
82        }) {
83            tls_config = tls_config.client_ca_root(Certificate::from_pem(&ca));
84        }
85
86        server = server.tls_config(tls_config)?;
87    }
88
89    info!(address = %addr, "Starting Flight SQL server");
90    debug!(
91        tls_enabled = config.get_bool("tls.enabled").unwrap_or(false),
92        storage_type = config.get_string("storage.type").unwrap_or_default(),
93        "Server configuration"
94    );
95
96    server.add_service(service).serve(addr).await.map_err(|e| {
97        error!(error = %e, "Server failed to start");
98        e
99    })?;
100
101    Ok(())
102}
103
104pub fn handle_config(config_path: Option<PathBuf>) -> Result<(), Box<dyn std::error::Error>> {
105    let mut builder = Config::builder()
106        .set_default("host", "127.0.0.1")?
107        .set_default("port", "50051")?
108        .set_default("storage.type", "duckdb")?
109        .set_default("storage.connection", ":memory:")?;
110
111    // Load config file if provided
112    if let Some(path) = config_path {
113        builder = builder.add_source(File::from(path));
114    }
115
116    let settings = builder.build()?;
117    info!("Configuration loaded successfully");
118    debug!(settings = ?settings, "Current configuration settings");
119    Ok(())
120}