1pub mod cli;
19pub mod client;
20pub mod service;
21
22pub use client::FlightClient;
24pub use service::{DenyAllFlightAuthorizer, FlightAuthError, FlightAuthorizer, FlightSqlServer};
25
26use hyprstream_metrics::storage::{duckdb::DuckDbBackend, StorageBackendType};
27use hyprstream_metrics::RegistryClient;
28use std::collections::HashMap;
29use std::net::SocketAddr;
30use std::path::PathBuf;
31use std::sync::Arc;
32use tonic::transport::{Certificate, Identity, Server, ServerTlsConfig};
33use tracing::{debug, error, info};
34
35#[derive(Debug, Clone)]
37pub struct FlightConfig {
38 pub host: String,
40 pub port: u16,
42 pub tls_cert: Option<Vec<u8>>,
44 pub tls_key: Option<Vec<u8>>,
46 pub tls_ca: Option<Vec<u8>>,
48}
49
50impl Default for FlightConfig {
51 fn default() -> Self {
52 Self {
53 host: "127.0.0.1".to_owned(),
54 port: 50051,
55 tls_cert: None,
56 tls_key: None,
57 tls_ca: None,
58 }
59 }
60}
61
62impl FlightConfig {
63 pub fn with_host(mut self, host: impl Into<String>) -> Self {
64 self.host = host.into();
65 self
66 }
67
68 pub fn with_port(mut self, port: u16) -> Self {
69 self.port = port;
70 self
71 }
72
73 pub fn with_tls(mut self, cert: Vec<u8>, key: Vec<u8>) -> Self {
74 self.tls_cert = Some(cert);
75 self.tls_key = Some(key);
76 self
77 }
78
79 pub fn with_client_ca(mut self, ca: Vec<u8>) -> Self {
80 self.tls_ca = Some(ca);
81 self
82 }
83
84 pub fn addr(&self) -> Result<SocketAddr, std::net::AddrParseError> {
86 format!("{}:{}", self.host, self.port).parse()
87 }
88}
89
90pub async fn start_flight_server(
119 client: Option<Arc<dyn RegistryClient>>,
120 dataset_name: &str,
121 config: FlightConfig,
122) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
123 start_flight_server_with_authorizer(
124 client,
125 dataset_name,
126 config,
127 Arc::new(DenyAllFlightAuthorizer),
128 )
129 .await
130}
131
132pub async fn start_flight_server_with_authorizer(
134 client: Option<Arc<dyn RegistryClient>>,
135 dataset_name: &str,
136 config: FlightConfig,
137 authorizer: Arc<dyn FlightAuthorizer>,
138) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
139 let connection_string = if let Some(ref registry_client) = client {
141 let tracked = registry_client
143 .get_by_name(dataset_name)
144 .await
145 .map_err(|e| format!("Failed to look up dataset: {e}"))?
146 .ok_or_else(|| format!("Dataset '{dataset_name}' not found in registry"))?;
147
148 let dataset_path = PathBuf::from(&tracked.worktree_path);
149
150 info!(
151 dataset = %dataset_name,
152 path = %dataset_path.display(),
153 "Starting Flight SQL server for dataset"
154 );
155
156 let db_path = dataset_path.join("data.duckdb");
158 if db_path.exists() {
159 db_path.to_string_lossy().to_string()
160 } else {
161 ":memory:".to_owned()
162 }
163 } else {
164 info!("Starting Flight SQL server with in-memory database");
165 ":memory:".to_owned()
166 };
167
168 let backend = DuckDbBackend::new(connection_string, HashMap::new(), None)
170 .map_err(|e| format!("Failed to create DuckDB backend: {e}"))?;
171
172 let addr = config.addr()?;
173
174 let flight_service = FlightSqlServer::new(StorageBackendType::DuckDb(backend))
176 .await
177 .map_err(|e| format!("Failed to create Flight SQL server: {e}"))?
178 .with_authorizer(
179 authorizer,
180 if dataset_name.is_empty() {
181 "flight:*".to_owned()
182 } else {
183 format!("flight:dataset:{dataset_name}")
184 },
185 )
186 .into_service();
187
188 let mut server = Server::builder();
189
190 if let (Some(cert), Some(key)) = (&config.tls_cert, &config.tls_key) {
192 let identity = Identity::from_pem(cert, key);
193 let mut tls_config = ServerTlsConfig::new().identity(identity);
194
195 if let Some(ca) = &config.tls_ca {
196 tls_config = tls_config.client_ca_root(Certificate::from_pem(ca));
197 }
198
199 server = server.tls_config(tls_config)?;
200 debug!("TLS enabled for Flight SQL server");
201 }
202
203 info!(address = %addr, "Flight SQL server listening");
204
205 server
206 .add_service(flight_service)
207 .serve(addr)
208 .await
209 .map_err(|e| {
210 error!(error = %e, "Flight SQL server failed");
211 Box::new(e) as Box<dyn std::error::Error + Send + Sync>
212 })?;
213
214 Ok(())
215}
216
217#[cfg(test)]
218mod tests {
219 use std::path::PathBuf;
230
231 fn commands_server_src() -> String {
232 let mut p = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
233 p.push("src/cli/commands/server.rs");
234 std::fs::read_to_string(&p)
235 .unwrap_or_else(|e| panic!("could not read cli/commands/server.rs: {e}"))
236 }
237
238 #[test]
239 fn dead_mtls_and_tls_knobs_stay_deleted() {
240 let s = commands_server_src();
241 for needle in [
245 concat!("tls_client", "_ca"),
246 concat!("tls_min", "_version"),
247 concat!("tls_cipher", "_list"),
248 concat!("tls_prefer", "_server_ciphers"),
249 concat!("HYPRSTREAM_TLS_CLIENT", "_CA"),
250 concat!("HYPRSTREAM_TLS_MIN", "_VERSION"),
251 concat!("HYPRSTREAM_TLS_CIPHER", "_LIST"),
252 concat!("HYPRSTREAM_TLS_PREFER", "_SERVER_CIPHERS"),
253 ] {
254 assert!(
255 !s.contains(needle),
256 "hyprstream-flight CLI re-introduced dead TLS config `{needle}` (see #1152 W6): \
257 the Flight server never consumes it; advertising mTLS/knobs we lack is worse \
258 than absent config",
259 );
260 }
261 }
262}