micromegas/servers/mcp/
flight.rs1use super::provider::CallContext;
2use crate::client::flightsql_client::QueryEstimate;
3use crate::client::flightsql_client_factory::{
4 BearerFlightSQLClientFactory, FlightSQLClientFactory,
5};
6use anyhow::Result;
7use arrow::array::RecordBatch;
8use arrow_flight::error::FlightError;
9use async_trait::async_trait;
10use futures::StreamExt;
11use futures::stream::BoxStream;
12use micromegas_telemetry::time_range::TimeRange;
13use std::sync::Arc;
14
15#[async_trait]
17pub trait FlightUrlResolver: Send + Sync {
18 async fn resolve(&self) -> Result<String>;
19}
20
21pub struct FixedUrl(pub String);
22
23#[async_trait]
24impl FlightUrlResolver for FixedUrl {
25 async fn resolve(&self) -> Result<String> {
26 Ok(self.0.clone())
27 }
28}
29
30#[async_trait]
33pub trait FlightBackend: Send + Sync {
34 async fn prepare(
36 &self,
37 call: &CallContext,
38 sql: &str,
39 range: Option<TimeRange>,
40 ) -> Result<QueryEstimate>;
41
42 async fn execute(
45 &self,
46 call: &CallContext,
47 sql: &str,
48 range: Option<TimeRange>,
49 row_limit: usize,
50 ) -> Result<BoxStream<'static, Result<RecordBatch>>>;
51}
52
53pub struct GrpcFlightBackend {
55 resolver: Arc<dyn FlightUrlResolver>,
56}
57
58impl GrpcFlightBackend {
59 pub fn new(resolver: Arc<dyn FlightUrlResolver>) -> Self {
60 Self { resolver }
61 }
62
63 async fn make_client(
66 &self,
67 call: &CallContext,
68 ) -> Result<crate::client::flightsql_client::Client> {
69 let url = self.resolver.resolve().await?;
70 let mut factory = BearerFlightSQLClientFactory::new_with_client_type(
71 url,
72 call.authorization.clone(),
73 "mcp".to_string(),
74 )
75 .with_metadata("x-client-agent", sanitize_header(&call.client_agent))
76 .with_metadata("x-request-id", uuid::Uuid::new_v4().to_string());
77 if let Some(ip) = forwarded_for_value(&call.client_ip) {
78 factory = factory.with_metadata("x-forwarded-for", ip);
79 }
80 factory.make_client().await
81 }
82}
83
84fn forwarded_for_value(client_ip: &str) -> Option<String> {
88 client_ip
89 .trim()
90 .parse::<std::net::IpAddr>()
91 .ok()
92 .map(|ip| ip.to_string())
93}
94
95fn sanitize_header(value: &str) -> String {
97 let cleaned: String = value
98 .chars()
99 .map(|c| {
100 if c.is_ascii_graphic() || c == ' ' {
101 c
102 } else {
103 '?'
104 }
105 })
106 .collect();
107 if cleaned.is_empty() {
108 "unknown".to_string()
109 } else {
110 cleaned
111 }
112}
113
114#[async_trait]
115impl FlightBackend for GrpcFlightBackend {
116 async fn prepare(
117 &self,
118 call: &CallContext,
119 sql: &str,
120 range: Option<TimeRange>,
121 ) -> Result<QueryEstimate> {
122 let mut client = self.make_client(call).await?;
123 client.prepare_query(sql.to_string(), range).await
124 }
125
126 async fn execute(
127 &self,
128 call: &CallContext,
129 sql: &str,
130 range: Option<TimeRange>,
131 row_limit: usize,
132 ) -> Result<BoxStream<'static, Result<RecordBatch>>> {
133 let mut client = self.make_client(call).await?;
134 client
135 .inner_mut()
136 .set_header("limit", row_limit.to_string());
137 let stream = client.query_stream(sql.to_string(), range).await?;
138 Ok(stream.map(|r| r.map_err(anyhow::Error::from)).boxed())
139 }
140}
141
142pub fn describe_error(error: &anyhow::Error) -> String {
144 let status = error.downcast_ref::<tonic::Status>().or_else(|| {
145 match error.downcast_ref::<FlightError>() {
146 Some(FlightError::Tonic(status)) => Some(status),
147 _ => None,
148 }
149 });
150 match status {
151 Some(status) => format!("{:?}: {}", status.code(), status.message()),
152 None => format!("{error:#}"),
153 }
154}
155
156#[cfg(test)]
157mod forwarded_for_tests {
158 use super::forwarded_for_value;
159
160 #[test]
161 fn forwards_only_parseable_ips() {
162 assert_eq!(forwarded_for_value("10.1.2.3").as_deref(), Some("10.1.2.3"));
163 assert_eq!(forwarded_for_value("::1").as_deref(), Some("::1"));
164 assert_eq!(forwarded_for_value("unknown"), None);
165 }
166}