Skip to main content

micromegas/servers/
ingestion.rs

1use 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    /// A conflicting `insert_process` re-registration under a different audience. Maps to 403.
31    #[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
65/// Handles requests to insert process information.
66///
67/// Returns 403 for a conflicting re-registration under a different audience, 400 for malformed
68/// CBOR, 500 for database errors.
69pub 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
81/// Handles requests to insert stream information.
82///
83/// Returns 400 for malformed CBOR, 500 for database errors.
84pub 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
96/// Handles requests to insert block information.
97///
98/// Returns 400 for empty body or malformed CBOR, 500 for database/storage errors.
99pub 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
122/// Registers the ingestion routes with the given Axum `Router`.
123///
124/// This function adds routes for `/ingestion/insert_process`,
125/// `/ingestion/insert_stream`, and `/ingestion/insert_block`.
126pub 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
133/// Assemble and serve the HTTP ingestion endpoint.
134///
135/// Binds `listen_addr`, wires the ingestion routes + OTLP routes, applies
136/// the supplied `auth_provider` (or runs open when `None`), and shuts down
137/// gracefully when `shutdown` resolves.
138///
139/// Ingestion exposes no key-management HTTP surface of its own — keys for both
140/// `ingestion_api_keys` and `analytics_api_keys` are administered exclusively through
141/// `analytics-web-srv`'s own routes. Ingestion still *validates* incoming API keys via
142/// whichever `auth_provider` it was built with (including a `DbApiKeyAuthProvider`), it just
143/// does not expose a way to mint/list/revoke them.
144pub 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    // The deployment's default audience, resolved once at startup so a typo fails
160    // startup rather than surfacing per-request -- matching `LakehouseContext::new`'s handling
161    // of the same variable. Unprefixed (`""`): the ingestion edge must read exactly the
162    // unprefixed `MICROMEGAS_DEFAULT_AUDIENCE` name the lakehouse roles read, never a
163    // `{prefix}_DEFAULT_AUDIENCE` override, or the write side and the read side could be
164    // configured to disagree -- the exact failure this resolution exists to remove. The `?`
165    // here is redundant-by-design, not a reachable error path: `default_audience_from_env`
166    // already validates against the same charset predicate `WriteAudience::new` applies.
167    let default_audience =
168        WriteAudience::new(&micromegas_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    // The Firehose routes carry their own auth (Firehose can only send its credential via
198    // X-Amz-Firehose-Access-Key, not Authorization: Bearer), so they are merged outside
199    // protected_app and never hit the global Bearer auth_middleware.
200    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}