micromegas/servers/
ingestion.rs1use super::ingestion_auth::{
2 INSERT_PROCESS_PATH, RejectedRequestLogger, ingestion_auth_middleware,
3};
4use super::write_audience::resolve_write_audience;
5use axum::Extension;
6use axum::Router;
7use axum::body::Body;
8use axum::http::{Response, StatusCode};
9use axum::response::IntoResponse;
10use axum::routing::post;
11use micromegas_auth::types::{AuthContext, AuthProvider};
12use micromegas_ingestion::data_lake_connection::DataLakeConnection;
13use micromegas_ingestion::web_ingestion_service::{IngestionServiceError, WebIngestionService};
14use micromegas_ingestion::write_audience::WriteAudience;
15use micromegas_tracing::prelude::*;
16use std::future::Future;
17use std::net::SocketAddr;
18use std::sync::Arc;
19use std::time::Duration;
20use thiserror::Error;
21
22#[derive(Error, Debug)]
23pub enum IngestionError {
24 #[error("Bad request: {0}")]
25 BadRequest(String),
26
27 #[error("Internal server error: {0}")]
28 Internal(String),
29
30 #[error("Forbidden: {0}")]
32 Forbidden(String),
33}
34
35impl IntoResponse for IngestionError {
36 fn into_response(self) -> Response<Body> {
37 let (status, category, detail) = match self {
38 IngestionError::BadRequest(msg) => (StatusCode::BAD_REQUEST, "Bad request", msg),
39 IngestionError::Internal(msg) => (
40 StatusCode::INTERNAL_SERVER_ERROR,
41 "Internal server error",
42 msg,
43 ),
44 IngestionError::Forbidden(msg) => (StatusCode::FORBIDDEN, "Forbidden", msg),
45 };
46 error!("{status}: {detail}");
47 (status, category).into_response()
48 }
49}
50
51impl From<IngestionServiceError> for IngestionError {
52 fn from(err: IngestionServiceError) -> Self {
53 match err {
54 IngestionServiceError::ParseError(msg) => IngestionError::BadRequest(msg),
55 IngestionServiceError::DatabaseError(msg) => IngestionError::Internal(msg),
56 IngestionServiceError::StorageError(msg) => IngestionError::Internal(msg),
57 IngestionServiceError::AudienceConflict { .. }
58 | IngestionServiceError::StreamAudienceConflict { .. } => {
59 IngestionError::Forbidden(err.to_string())
60 }
61 }
62 }
63}
64
65pub async fn insert_process_request(
70 Extension(service): Extension<Arc<WebIngestionService>>,
71 ctx: Option<Extension<AuthContext>>,
72 body: bytes::Bytes,
73) -> Result<(), IngestionError> {
74 let audience = resolve_write_audience(ctx.as_ref(), service.default_audience());
75 service
76 .insert_process(body, &audience)
77 .await
78 .map_err(Into::into)
79}
80
81pub async fn insert_stream_request(
85 Extension(service): Extension<Arc<WebIngestionService>>,
86 ctx: Option<Extension<AuthContext>>,
87 body: bytes::Bytes,
88) -> Result<(), IngestionError> {
89 let audience = resolve_write_audience(ctx.as_ref(), service.default_audience());
90 service
91 .insert_stream(body, &audience)
92 .await
93 .map_err(Into::into)
94}
95
96pub async fn insert_block_request(
100 Extension(service): Extension<Arc<WebIngestionService>>,
101 ctx: Option<Extension<AuthContext>>,
102 body: bytes::Bytes,
103) -> Result<(), IngestionError> {
104 if body.is_empty() {
105 return Err(IngestionError::BadRequest("empty body".to_string()));
106 }
107 let audience = resolve_write_audience(ctx.as_ref(), service.default_audience());
108 service
109 .insert_block(body, &audience)
110 .await
111 .map_err(Into::into)
112}
113
114async fn ready_handler(Extension(service): Extension<Arc<WebIngestionService>>) -> StatusCode {
115 if service.check_ready().await {
116 StatusCode::OK
117 } else {
118 StatusCode::SERVICE_UNAVAILABLE
119 }
120}
121
122pub fn register_routes(router: Router) -> Router {
127 router
128 .route(INSERT_PROCESS_PATH, post(insert_process_request))
129 .route("/ingestion/insert_stream", post(insert_stream_request))
130 .route("/ingestion/insert_block", post(insert_block_request))
131}
132
133pub async fn serve_ingestion(
145 listen_addr: SocketAddr,
146 lake: DataLakeConnection,
147 auth_provider: Option<Arc<dyn AuthProvider>>,
148 shutdown: impl Future<Output = ()> + Send + 'static,
149 grace: Duration,
150) -> anyhow::Result<()> {
151 use axum::extract::DefaultBodyLimit;
152 use axum::middleware;
153 use axum::routing::get;
154 use tower_http::limit::RequestBodyLimitLayer;
155
156 use super::axum_utils::observability_middleware;
157 use super::shutdown::serve_axum_with_graceful_shutdown;
158
159 let default_audience =
168 WriteAudience::new(µmegas_auth::policy::default_audience_from_env("")?)?;
169 let service = Arc::new(WebIngestionService::new(lake, default_audience));
170
171 let health_router = Router::new()
172 .route("/health", get(|| async { axum::http::StatusCode::OK }))
173 .route("/ready", get(ready_handler))
174 .layer(Extension(service.clone()));
175
176 let firehose_auth = auth_provider.clone();
177 let cw_logs_firehose_auth = auth_provider.clone();
178
179 let mut protected_app = register_routes(Router::new())
180 .merge(super::otlp::otlp_router())
181 .merge(super::webhook::webhook_router())
182 .layer(DefaultBodyLimit::disable())
183 .layer(RequestBodyLimitLayer::new(100 * 1024 * 1024))
184 .layer(Extension(service.clone()));
185
186 let auth_enabled = auth_provider.is_some();
187 if let Some(provider) = auth_provider {
188 info!("Ingestion: authentication enabled");
189 let logger = Arc::new(RejectedRequestLogger::new());
190 protected_app = protected_app.layer(middleware::from_fn(move |req, next| {
191 ingestion_auth_middleware(provider.clone(), logger.clone(), req, next)
192 }));
193 } else {
194 warn!("Ingestion: authentication disabled — development mode only");
195 }
196
197 let firehose_app = super::firehose::firehose_router(service.clone(), firehose_auth);
201 let cw_logs_firehose_app =
202 super::firehose_cloudwatch_logs::firehose_router(service.clone(), cw_logs_firehose_auth);
203
204 let app = health_router
205 .merge(protected_app)
206 .merge(firehose_app)
207 .merge(cw_logs_firehose_app)
208 .layer(middleware::from_fn(observability_middleware));
209
210 let listener = tokio::net::TcpListener::bind(listen_addr)
211 .await
212 .map_err(|e| anyhow::anyhow!("ingestion: binding to {listen_addr}: {e}"))?;
213 info!("Ingestion serving on {listen_addr} authentication={auth_enabled}");
214
215 serve_axum_with_graceful_shutdown(
216 listener,
217 app.into_make_service_with_connect_info::<SocketAddr>(),
218 shutdown,
219 grace,
220 )
221 .await?;
222
223 Ok(())
224}