From fe995ee7ce8b447d1597ec3e53cc1dad2122b495 Mon Sep 17 00:00:00 2001 From: Nikhil Sinha Date: Sun, 22 Nov 2026 10:16:21 +0530 Subject: [PATCH 1/2] feat: add OTLP protobuf ingestion support - support OTLP protobuf ingestion for logs, traces, metrics - accept header `Content-Type: application/x-protobuf` for protobuf ingestion - reduce payload size, network bandwidth, and decoding overhead compared with JSON --- Cargo.lock | 45 ++----- Cargo.toml | 2 +- src/handlers/http/ingest.rs | 122 ++++++++++++++++-- src/handlers/http/modal/utils/ingest_utils.rs | 118 +++++++++++++++-- src/handlers/mod.rs | 11 ++ 5 files changed, 243 insertions(+), 55 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 842800c98..aa45fc13a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -612,7 +612,7 @@ dependencies = [ "base64 0.23.1", "bytes", "futures", - "prost 0.14.1", + "prost", "prost-types", "tonic", "tonic-prost", @@ -2666,7 +2666,7 @@ dependencies = [ "datafusion-proto-common", "datafusion-proto-models", "object_store", - "prost 0.14.1", + "prost", ] [[package]] @@ -2677,7 +2677,7 @@ checksum = "6b92415a2442964f180d39cdcd8ff1edd99f9260c1499ba80a396499c2154d11" dependencies = [ "arrow", "datafusion-common", - "prost 0.14.1", + "prost", ] [[package]] @@ -2688,7 +2688,7 @@ checksum = "62e4c0bd6af4fcabdbe201ee86fbeef2ac423a44e1d8fda56d994c9e2d1d3ad2" dependencies = [ "datafusion-common", "datafusion-proto-common", - "prost 0.14.1", + "prost", ] [[package]] @@ -4480,7 +4480,7 @@ dependencies = [ "opentelemetry-http", "opentelemetry-proto", "opentelemetry_sdk", - "prost 0.14.1", + "prost", "reqwest 0.13.4", "serde_json", "thiserror 2.0.17", @@ -4499,7 +4499,7 @@ dependencies = [ "const-hex", "opentelemetry", "opentelemetry_sdk", - "prost 0.14.1", + "prost", "serde", "tonic", "tonic-prost", @@ -4683,7 +4683,7 @@ dependencies = [ "procfs 0.18.0", "prometheus", "prometheus-parse", - "prost 0.13.5", + "prost", "rand 0.8.6", "rayon", "rdkafka", @@ -5028,16 +5028,6 @@ dependencies = [ "unarray", ] -[[package]] -name = "prost" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5" -dependencies = [ - "bytes", - "prost-derive 0.13.5", -] - [[package]] name = "prost" version = "0.14.1" @@ -5045,20 +5035,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7231bd9b3d3d33c86b58adbac74b5ec0ad9f496b19d22801d773636feaa95f3d" dependencies = [ "bytes", - "prost-derive 0.14.1", -] - -[[package]] -name = "prost-derive" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d" -dependencies = [ - "anyhow", - "itertools 0.14.0", - "proc-macro2", - "quote", - "syn 2.0.117", + "prost-derive", ] [[package]] @@ -5080,7 +5057,7 @@ version = "0.14.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9b4db3d6da204ed77bb26ba83b6122a73aeb2e87e25fbf7ad2e84c4ccbf8f72" dependencies = [ - "prost 0.14.1", + "prost", ] [[package]] @@ -6541,7 +6518,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "66bd50ad6ce1252d87ef024b3d64fe4c3cf54a86fb9ef4c631fdd0ded7aeaa67" dependencies = [ "bytes", - "prost 0.14.1", + "prost", "tonic", ] @@ -6551,7 +6528,7 @@ version = "0.14.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a875a902255423d34c1f20838ab374126db8eb41625b7947a1d54113b0b7399" dependencies = [ - "prost 0.14.1", + "prost", "prost-types", "tonic", ] diff --git a/Cargo.toml b/Cargo.toml index c1f51c30e..fdd0b613b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -193,7 +193,7 @@ rustc-hash = "2.1.2" futures-core = "0.3.31" tempfile = "3.20.0" lazy_static = "1.4.0" -prost = "0.13.1" +prost = "0.14.1" dashmap = "6.2.1" parking_lot = "0.12.5" indexmap = { version = "2.14.0", features = ["serde"] } diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index 80ec36eb7..c89976514 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -20,14 +20,17 @@ use std::collections::{HashMap, HashSet}; use actix_web::http::StatusCode; use actix_web::web::{self, Json, Path}; -use actix_web::{HttpRequest, HttpResponse, http::header::ContentType}; +use actix_web::{ + HttpRequest, HttpResponse, + http::header::{ContentType, HeaderMap}, +}; use arrow_array::RecordBatch; use bytes::Bytes; use chrono::Utc; use once_cell::sync::Lazy; use rayon::{ThreadPool, ThreadPoolBuilder}; use tokio::sync::oneshot; -use tracing::error; +use tracing::{Span, error, instrument}; use crate::event::error::EventError; use crate::event::format::known_schema::{self, KNOWN_SCHEMA_LIST}; @@ -37,8 +40,9 @@ use crate::handlers::http::modal::utils::ingest_utils::{ ingest_helper, process_otel_content, validate_stream_for_ingestion, }; use crate::handlers::{ - DatasetTag, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, TELEMETRY_TYPE_KEY, - TelemetryType, + DATASET_TAGS_KEY, DatasetTag, EXTRACT_LOG_KEY, LOG_SOURCE_KEY, STREAM_NAME_HEADER_KEY, + TELEMETRY_TYPE_KEY, TelemetryType, parse_dataset_tags, + validate_agent_observability_constraints, }; use crate::metadata::SchemaVersion; use crate::metastore::MetastoreError; @@ -63,6 +67,24 @@ pub static INGESTION_THREADPOOL: Lazy = Lazy::new(|| { .expect("Unable to create Rayon thread pool") }); +pub fn dataset_tags_from_headers( + headers: &HeaderMap, + log_source: &LogSource, +) -> Result, PostError> { + let dataset_tags = headers + .get(DATASET_TAGS_KEY) + .and_then(|value| value.to_str().ok()) + .map(parse_dataset_tags) + .unwrap_or_default(); + + if dataset_tags.contains(&DatasetTag::AgentObservability) { + validate_agent_observability_constraints(std::slice::from_ref(log_source)) + .map_err(|message| PostError::Invalid(anyhow::anyhow!(message)))?; + } + + Ok(dataset_tags) +} + // Handler for POST /api/v1/ingest // ingests events by extracting stream name from header // creates if stream does not exist @@ -74,7 +96,10 @@ pub async fn ingest( return Err(PostError::Header(ParseHeaderError::MissingStreamName)); }; let tenant_id = get_tenant_id_from_request(&req); - let stream_name = stream_name.to_str().unwrap().to_owned(); + let stream_name = stream_name + .to_str() + .map_err(|_| PostError::Header(ParseHeaderError::InvalidValue))? + .to_owned(); if PARSEABLE .get_stream(&stream_name, &tenant_id) .is_ok_and(|stream| stream.get_stream_type() == StreamType::Internal) @@ -124,6 +149,7 @@ pub async fn ingest( }; let log_source_entry = LogSourceEntry::new(log_source.clone(), fields); + let dataset_tags = dataset_tags_from_headers(req.headers(), &log_source)?; PARSEABLE .create_stream_if_not_exists( @@ -133,7 +159,7 @@ pub async fn ingest( vec![log_source_entry.clone()], telemetry_type, &tenant_id, - vec![], + dataset_tags, vec![], ) .await @@ -235,7 +261,10 @@ pub async fn setup_otel_stream( return Err(PostError::Header(ParseHeaderError::MissingStreamName)); }; - let stream_name = stream_name.to_str().unwrap().to_owned(); + let stream_name = stream_name + .to_str() + .map_err(|_| PostError::Header(ParseHeaderError::InvalidValue))? + .to_owned(); let log_source_entry = LogSourceEntry::new( log_source.clone(), @@ -306,16 +335,23 @@ pub async fn setup_otel_stream( // Handler for POST /v1/logs to ingest OTEL logs // ingests events by extracting stream name from header // creates if stream does not exist +#[instrument( + name = "otel_logs_ingestion", + level = "info", + skip_all, + fields(stream_name = tracing::field::Empty, body_size = body.len()) +)] pub async fn handle_otel_logs_ingestion( req: HttpRequest, body: web::Bytes, ) -> Result { + let dataset_tags = dataset_tags_from_headers(req.headers(), &LogSource::OtelLogs)?; let (stream_name, log_source, ..) = setup_otel_stream( &req, LogSource::OtelLogs, &OTEL_LOG_KNOWN_FIELD_LIST, TelemetryType::Logs, - vec![], + dataset_tags, vec![], ) .await @@ -323,6 +359,7 @@ pub async fn handle_otel_logs_ingestion( error!("OTEL logs ingestion failed: {e}"); e })?; + Span::current().record("stream_name", stream_name.as_str()); process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Logs).await?; @@ -332,16 +369,23 @@ pub async fn handle_otel_logs_ingestion( // Handler for POST /v1/metrics to ingest OTEL metrics // ingests events by extracting stream name from header // creates if stream does not exist +#[instrument( + name = "otel_metrics_ingestion", + level = "info", + skip_all, + fields(stream_name = tracing::field::Empty, body_size = body.len()) +)] pub async fn handle_otel_metrics_ingestion( req: HttpRequest, body: web::Bytes, ) -> Result { + let dataset_tags = dataset_tags_from_headers(req.headers(), &LogSource::OtelMetrics)?; let (stream_name, log_source, ..) = setup_otel_stream( &req, LogSource::OtelMetrics, &OTEL_METRICS_KNOWN_FIELD_LIST, TelemetryType::Metrics, - vec![], + dataset_tags, vec![], ) .await @@ -349,6 +393,7 @@ pub async fn handle_otel_metrics_ingestion( error!("OTEL metrics ingestion failed: {e}"); e })?; + Span::current().record("stream_name", stream_name.as_str()); process_otel_content( &req, @@ -365,16 +410,23 @@ pub async fn handle_otel_metrics_ingestion( // Handler for POST /v1/traces to ingest OTEL traces // ingests events by extracting stream name from header // creates if stream does not exist +#[instrument( + name = "otel_traces_ingestion", + level = "info", + skip_all, + fields(stream_name = tracing::field::Empty, body_size = body.len()) +)] pub async fn handle_otel_traces_ingestion( req: HttpRequest, body: web::Bytes, ) -> Result { + let dataset_tags = dataset_tags_from_headers(req.headers(), &LogSource::OtelTraces)?; let (stream_name, log_source, ..) = setup_otel_stream( &req, LogSource::OtelTraces, &OTEL_TRACES_KNOWN_FIELD_LIST, TelemetryType::Traces, - vec![], + dataset_tags, vec![], ) .await @@ -382,6 +434,7 @@ pub async fn handle_otel_traces_ingestion( error!("OTEL traces ingestion failed: {e}"); e })?; + Span::current().record("stream_name", stream_name.as_str()); process_otel_content(&req, body, &stream_name, &log_source, TelemetryType::Traces).await?; @@ -623,6 +676,7 @@ impl actix_web::ResponseError for PostError { #[cfg(test)] mod tests { + use actix_web::http::header::{HeaderMap, HeaderName, HeaderValue}; use arrow::datatypes::Int64Type; use arrow_array::{ArrayRef, Float64Array, Int64Array, ListArray, StringArray}; use arrow_schema::{DataType, Field}; @@ -631,10 +685,56 @@ mod tests { use std::{collections::HashMap, sync::Arc}; use crate::{ - event::format::{EventFormat, json}, + event::format::{EventFormat, LogSource, json}, + handlers::{DATASET_TAGS_KEY, DatasetTag}, metadata::SchemaVersion, }; + #[test] + fn dataset_tags_from_headers_accepts_agent_observability_for_traces() { + let mut headers = HeaderMap::new(); + headers.insert( + HeaderName::from_static(DATASET_TAGS_KEY), + HeaderValue::from_static("agent-observability"), + ); + + let tags = super::dataset_tags_from_headers(&headers, &LogSource::OtelTraces).unwrap(); + assert_eq!(tags, vec![DatasetTag::AgentObservability]); + } + + #[test] + fn dataset_tags_from_headers_rejects_agent_observability_for_metrics() { + let mut headers = HeaderMap::new(); + headers.insert( + HeaderName::from_static(DATASET_TAGS_KEY), + HeaderValue::from_static("agent-observability"), + ); + + assert!(matches!( + super::dataset_tags_from_headers(&headers, &LogSource::OtelMetrics), + Err(super::PostError::Invalid(_)) + )); + } + + #[test] + fn dataset_tags_from_headers_accepts_unrestricted_tags() { + let mut headers = HeaderMap::new(); + headers.insert( + HeaderName::from_static(DATASET_TAGS_KEY), + HeaderValue::from_static("k8s-observability"), + ); + + let tags = super::dataset_tags_from_headers(&headers, &LogSource::OtelLogs).unwrap(); + assert_eq!(tags, vec![DatasetTag::K8sObservability]); + } + + #[test] + fn dataset_tags_from_headers_defaults_to_empty() { + let tags = + super::dataset_tags_from_headers(&HeaderMap::new(), &LogSource::OtelLogs).unwrap(); + assert!(tags.is_empty()); + } + #[test] fn event_stream_not_found_returns_not_found() { use actix_web::{ResponseError, http::StatusCode}; diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index 10ab755b5..d55b60c6e 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -19,14 +19,19 @@ use actix_web::http::header::USER_AGENT; use actix_web::{HttpRequest, web}; use chrono::Utc; +use opentelemetry_proto::tonic::collector::{ + logs::v1::ExportLogsServiceRequest, metrics::v1::ExportMetricsServiceRequest, + trace::v1::ExportTraceServiceRequest, +}; use opentelemetry_proto::tonic::{ logs::v1::LogsData, metrics::v1::MetricsData, trace::v1::TracesData, }; +use prost::Message as OtelProstMessage; use rayon::iter::{IntoParallelIterator, ParallelIterator}; use serde_json::Value; use std::collections::HashMap; use tokio::sync::oneshot; -use tracing::{error, instrument, warn}; +use tracing::{error, info_span, instrument, warn}; use crate::event::error::EventError; use crate::{ @@ -41,11 +46,14 @@ use crate::{ http::{ ingest::PostError, kinesis::{Message, flatten_kinesis_logs}, + max_event_payload_size, }, }, otel::{ - logs::flatten_otel_logs, metrics::flatten_otel_metrics, otel_utils::deserialize_otel_json, - traces::flatten_otel_traces, + logs::{flatten_otel_logs, flatten_otel_protobuf as flatten_otel_logs_protobuf}, + metrics::{flatten_otel_metrics, flatten_otel_metrics_protobuf}, + otel_utils::deserialize_otel_json, + traces::{flatten_otel_traces, flatten_otel_traces_protobuf}, }, parseable::{DEFAULT_TENANT, PARSEABLE}, storage::StreamType, @@ -158,12 +166,51 @@ fn handle_otel_ingestion( return Err(e); } } else if content_type == CONTENT_TYPE_PROTOBUF { - error!( - "Ingestion failed for stream {stream_name}: Protobuf ingestion is not supported in Parseable OSS" - ); - return Err(PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {stream_name}: Protobuf ingestion is not supported in Parseable OSS" - ))); + if body.len() > max_event_payload_size() { + let message = format!( + "Ingestion failed for stream {stream_name}: Protobuf message size {} exceeds maximum allowed size of {} bytes", + body.len(), + max_event_payload_size(), + ); + error!("{message}"); + return Err(PostError::Invalid(anyhow::anyhow!(message))); + } + + let records = { + let span = info_span!( + "flatten_otel_protobuf", + stream_name, + record_count = tracing::field::Empty, + ); + let _guard = span.enter(); + let records = decode_and_flatten_otel_protobuf( + body.as_ref(), + &log_source, + tenant_id.as_deref().unwrap_or(DEFAULT_TENANT), + ) + .map_err(|error| { + error!( + "Ingestion failed for stream {stream_name}: Failed to decode protobuf message: {error}" + ); + PostError::Invalid(anyhow::anyhow!( + "Ingestion failed for stream {stream_name}: Failed to decode protobuf message: {error}" + )) + })?; + span.record("record_count", records.len()); + records + }; + + if !records.is_empty() { + push_logs( + &stream_name, + Value::Array(records), + &log_source, + &p_custom_fields, + None, + telemetry_type, + &tenant_id, + )?; + } } else { error!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" @@ -185,6 +232,28 @@ fn handle_otel_ingestion( Ok(()) } +fn decode_and_flatten_otel_protobuf( + body: &[u8], + log_source: &LogSource, + tenant_id: &str, +) -> anyhow::Result> { + match log_source { + LogSource::OtelLogs => { + let message = ExportLogsServiceRequest::decode(body)?; + Ok(flatten_otel_logs_protobuf(&message, tenant_id)) + } + LogSource::OtelMetrics => { + let message = ExportMetricsServiceRequest::decode(body)?; + Ok(flatten_otel_metrics_protobuf(&message, tenant_id)) + } + LogSource::OtelTraces => { + let message = ExportTraceServiceRequest::decode(body)?; + Ok(flatten_otel_traces_protobuf(&message, tenant_id)) + } + _ => anyhow::bail!("protobuf OTLP ingestion requires an OTLP log source"), + } +} + #[instrument( name = "flatten_and_push_logs", level = "info", @@ -584,6 +653,37 @@ mod tests { use super::*; use actix_web::test::TestRequest; + #[test] + fn protobuf_logs_decode_uses_shared_otel_path() { + use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; + + let request = ExportLogsServiceRequest { + resource_logs: vec![ResourceLogs { + scope_logs: vec![ScopeLogs { + log_records: vec![LogRecord::default()], + ..Default::default() + }], + ..Default::default() + }], + }; + + let records = decode_and_flatten_otel_protobuf( + &request.encode_to_vec(), + &LogSource::OtelLogs, + "test-tenant", + ) + .unwrap(); + + assert_eq!(records.len(), 1); + } + + #[test] + fn protobuf_decode_rejects_non_otel_log_source() { + let error = + decode_and_flatten_otel_protobuf(&[], &LogSource::Json, "test-tenant").unwrap_err(); + assert!(error.to_string().contains("requires an OTLP log source")); + } + #[test] fn test_get_custom_fields_from_header_with_custom_fields() { let req = TestRequest::default() diff --git a/src/handlers/mod.rs b/src/handlers/mod.rs index 857d4b660..86d3220dc 100644 --- a/src/handlers/mod.rs +++ b/src/handlers/mod.rs @@ -22,6 +22,8 @@ use std::fmt::Display; use serde::{Deserialize, Serialize}; use tracing::warn; +use crate::event::format::LogSource; + pub mod airplane; pub mod http; pub mod livetail; @@ -129,6 +131,15 @@ impl Display for DatasetTag { } } +pub fn validate_agent_observability_constraints(log_sources: &[LogSource]) -> Result<(), String> { + if !log_sources.contains(&LogSource::OtelTraces) { + return Err( + "Dataset with tag 'agent-observability' must have log source 'otel-traces'".to_string(), + ); + } + Ok(()) +} + pub fn parse_dataset_tags(header_value: &str) -> Vec { header_value .split(',') From d5a88c8c58e3dbb8ce4118bc2df80a2e48a04343 Mon Sep 17 00:00:00 2001 From: Nikhil Sinha Date: Sun, 22 Nov 2026 11:23:16 +0530 Subject: [PATCH 2/2] refactor ingestion flow --- src/handlers/http/ingest.rs | 19 +- src/handlers/http/modal/utils/ingest_utils.rs | 372 +++++++++--------- 2 files changed, 186 insertions(+), 205 deletions(-) diff --git a/src/handlers/http/ingest.rs b/src/handlers/http/ingest.rs index c89976514..8fed81766 100644 --- a/src/handlers/http/ingest.rs +++ b/src/handlers/http/ingest.rs @@ -57,7 +57,7 @@ use crate::utils::header_parsing::ParseHeaderError; use crate::utils::json::{flatten::JsonFlattenError, strict::StrictValue}; use super::logstream::error::{CreateStreamError, StreamError}; -use super::modal::utils::ingest_utils::{flatten_and_push_logs, get_custom_fields_from_header}; +use super::modal::utils::ingest_utils::get_custom_fields_from_header; use super::users::dashboards::DashboardError; use super::users::filters::FiltersError; @@ -514,18 +514,15 @@ pub async fn post_event( return Err(e); } - if let Err(e) = flatten_and_push_logs( + ingest_helper( + stream_name, + tenant_id, + log_source, + TelemetryType::Logs, + p_custom_fields, json, - &stream_name, - &log_source, - &p_custom_fields, None, - TelemetryType::Logs, - &tenant_id, - ) { - error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } + )?; Ok(HttpResponse::Ok().finish()) } diff --git a/src/handlers/http/modal/utils/ingest_utils.rs b/src/handlers/http/modal/utils/ingest_utils.rs index d55b60c6e..23e155fd0 100644 --- a/src/handlers/http/modal/utils/ingest_utils.rs +++ b/src/handlers/http/modal/utils/ingest_utils.rs @@ -76,15 +76,30 @@ pub fn ingest_helper( json: Value, time_partition: Option, ) -> Result<(), PostError> { - if let Err(e) = flatten_and_push_logs( - json, - &stream_name, - &log_source, - &p_custom_fields, - time_partition, - telemetry_type, - &tenant_id, - ) { + let result = match &log_source { + LogSource::Kinesis => decode_flatten_and_push_kinesis( + json, + &stream_name, + &p_custom_fields, + time_partition, + telemetry_type, + &tenant_id, + ), + LogSource::OtelLogs | LogSource::OtelMetrics | LogSource::OtelTraces => { + Err(PostError::OtelNotSupported(stream_name.clone())) + } + _ => push_logs( + &stream_name, + json, + &log_source, + &p_custom_fields, + time_partition, + telemetry_type, + &tenant_id, + ), + }; + + if let Err(e) = result { error!("Ingestion failed for stream {stream_name}: {e}"); return Err(e); } @@ -92,6 +107,27 @@ pub fn ingest_helper( Ok(()) } +fn decode_flatten_and_push_kinesis( + json: Value, + stream_name: &str, + p_custom_fields: &HashMap, + time_partition: Option, + telemetry_type: TelemetryType, + tenant_id: &Option, +) -> Result<(), PostError> { + let message: Message = serde_json::from_value(json)?; + let records = convert_to_array(flatten_kinesis_logs(message)?)?; + push_logs( + stream_name, + records, + &LogSource::Kinesis, + p_custom_fields, + time_partition, + telemetry_type, + tenant_id, + ) +} + // Common content processing for OTEL ingestion pub async fn process_otel_content( req: &HttpRequest, @@ -141,31 +177,42 @@ fn handle_otel_ingestion( content_type: Option, tenant_id: Option, ) -> Result<(), PostError> { - match content_type { - Some(content_type) => { - if content_type == CONTENT_TYPE_JSON { - let json: serde_json::Value = match serde_json::from_slice(&body) { - Ok(v) => v, - Err(e) => { - error!( - "Ingestion failed for stream {stream_name}: malformed JSON in request body" - ); - return Err(PostError::SerdeError(e)); - } - }; - if let Err(e) = flatten_and_push_logs( + let Some(content_type) = content_type else { + let message = format!( + "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" + ); + error!("{message}"); + return Err(PostError::Invalid(anyhow::anyhow!(message))); + }; + let tenant = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); + let records = { + let span = info_span!( + "flatten_otel_payload", + stream_name, + content_type, + record_count = tracing::field::Empty, + ); + let _guard = span.enter(); + let records = match content_type.as_str() { + CONTENT_TYPE_JSON => { + let json = serde_json::from_slice(&body).map_err(|error| { + error!( + "Ingestion failed for stream {stream_name}: malformed JSON in request body" + ); + PostError::SerdeError(error) + })?; + decode_and_flatten_otel_json( json, - &stream_name, &log_source, - &p_custom_fields, - None, - telemetry_type, - &tenant_id, - ) { - error!("Ingestion failed for stream {stream_name}: {e}"); - return Err(e); - } - } else if content_type == CONTENT_TYPE_PROTOBUF { + tenant, + PARSEABLE.options.normalise_otel_payload, + ) + .map_err(|error| { + error!("Ingestion failed for stream {stream_name}: {error}"); + error + })? + } + CONTENT_TYPE_PROTOBUF => { if body.len() > max_event_payload_size() { let message = format!( "Ingestion failed for stream {stream_name}: Protobuf message size {} exceeds maximum allowed size of {} bytes", @@ -175,61 +222,66 @@ fn handle_otel_ingestion( error!("{message}"); return Err(PostError::Invalid(anyhow::anyhow!(message))); } - - let records = { - let span = info_span!( - "flatten_otel_protobuf", - stream_name, - record_count = tracing::field::Empty, - ); - let _guard = span.enter(); - let records = decode_and_flatten_otel_protobuf( - body.as_ref(), - &log_source, - tenant_id.as_deref().unwrap_or(DEFAULT_TENANT), - ) - .map_err(|error| { - error!( + decode_and_flatten_otel_protobuf(body.as_ref(), &log_source, tenant).map_err( + |error| { + let message = format!( "Ingestion failed for stream {stream_name}: Failed to decode protobuf message: {error}" ); - PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {stream_name}: Failed to decode protobuf message: {error}" - )) - })?; - span.record("record_count", records.len()); - records - }; - - if !records.is_empty() { - push_logs( - &stream_name, - Value::Array(records), - &log_source, - &p_custom_fields, - None, - telemetry_type, - &tenant_id, - )?; - } - } else { - error!( + error!("{message}"); + PostError::Invalid(anyhow::anyhow!(message)) + }, + )? + } + _ => { + let message = format!( "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" ); - return Err(PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {stream_name}: Unsupported Content-Type: {content_type}. Expected application/json or application/x-protobuf" - ))); + error!("{message}"); + return Err(PostError::Invalid(anyhow::anyhow!(message))); } + }; + span.record("record_count", records.len()); + records + }; + + if !records.is_empty() { + push_logs( + &stream_name, + Value::Array(records), + &log_source, + &p_custom_fields, + None, + telemetry_type, + &tenant_id, + )?; + } + + Ok(()) +} + +fn decode_and_flatten_otel_json( + json: Value, + log_source: &LogSource, + tenant_id: &str, + normalise: bool, +) -> Result, PostError> { + match log_source { + LogSource::OtelLogs => { + let message: LogsData = deserialize_otel_json(json, normalise)?; + Ok(flatten_otel_logs(&message, tenant_id)) } - None => { - error!( - "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" - ); - return Err(PostError::Invalid(anyhow::anyhow!( - "Ingestion failed for stream {stream_name}: Missing Content-Type header. Expected application/json or application/x-protobuf" - ))); + LogSource::OtelMetrics => { + let message: MetricsData = deserialize_otel_json(json, normalise)?; + Ok(flatten_otel_metrics(message, tenant_id)) } + LogSource::OtelTraces => { + let message: TracesData = deserialize_otel_json(json, normalise)?; + Ok(flatten_otel_traces(&message, tenant_id)) + } + _ => Err(PostError::Invalid(anyhow::anyhow!( + "JSON OTLP ingestion requires an OTLP log source" + ))), } - Ok(()) } fn decode_and_flatten_otel_protobuf( @@ -254,110 +306,6 @@ fn decode_and_flatten_otel_protobuf( } } -#[instrument( - name = "flatten_and_push_logs", - level = "info", - skip( - json, - log_source, - p_custom_fields, - time_partition, - telemetry_type, - tenant_id - ), - fields(stream_name) -)] -pub fn flatten_and_push_logs( - json: Value, - stream_name: &str, - log_source: &LogSource, - p_custom_fields: &HashMap, - time_partition: Option, - telemetry_type: TelemetryType, - tenant_id: &Option, -) -> Result<(), PostError> { - let tenant_str = tenant_id.as_deref().unwrap_or(DEFAULT_TENANT); - // Verify the dataset fields count - verify_dataset_fields_count(stream_name, tenant_id)?; - - match log_source { - LogSource::Kinesis => { - //custom flattening required for Amazon Kinesis - let message: Message = serde_json::from_value(json)?; - let flattened_kinesis_data = flatten_kinesis_logs(message)?; - let record = convert_to_array(flattened_kinesis_data)?; - push_logs( - stream_name, - record, - log_source, - p_custom_fields, - time_partition, - telemetry_type, - tenant_id, - )?; - } - LogSource::OtelLogs => { - let logs: LogsData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_logs(&logs, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - )?; - } - } - LogSource::OtelTraces => { - let traces: TracesData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_traces(&traces, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - )?; - } - } - LogSource::OtelMetrics => { - let metrics: MetricsData = - deserialize_otel_json(json, PARSEABLE.options.normalise_otel_payload)?; - let records = flatten_otel_metrics(metrics, tenant_str); - if !records.is_empty() { - push_logs( - stream_name, - Value::Array(records), - log_source, - p_custom_fields, - None, - telemetry_type, - tenant_id, - )?; - } - } - _ => push_logs( - stream_name, - json, - log_source, - p_custom_fields, - time_partition, - telemetry_type, - tenant_id, - )?, - } - - Ok(()) -} - #[instrument( name = "push_logs", level = "info", @@ -387,6 +335,13 @@ pub fn push_logs( let infer_timestamp = metadata.infer_timestamp; let p_timestamp = Utc::now(); + // Keep this in the common write path so pre-flattened inputs cannot bypass the limit. + verify_dataset_fields_count( + stream_name, + metadata.schema.len(), + PARSEABLE.options.dataset_fields_allowed_limit, + )?; + let data = convert_array_to_object( json, time_partition.as_ref(), @@ -566,14 +521,10 @@ pub fn get_otel_custom_fields_from_header( fn verify_dataset_fields_count( stream_name: &str, - tenant_id: &Option, + fields_count: usize, + allowed_limit: usize, ) -> Result<(), PostError> { - let fields_count = PARSEABLE - .get_stream(stream_name, tenant_id)? - .get_schema() - .fields() - .len(); - let dataset_fields_warn_threshold = 0.8 * PARSEABLE.options.dataset_fields_allowed_limit as f64; + let dataset_fields_warn_threshold = 0.8 * allowed_limit as f64; // Check if the fields count exceeds the warn threshold if fields_count > dataset_fields_warn_threshold as usize { tracing::trace!( @@ -581,16 +532,16 @@ fn verify_dataset_fields_count( stream_name, fields_count, dataset_fields_warn_threshold as usize, - PARSEABLE.options.dataset_fields_allowed_limit + allowed_limit ); } // Check if the fields count exceeds the limit // Return an error if the fields count exceeds the limit - if fields_count > PARSEABLE.options.dataset_fields_allowed_limit { + if fields_count > allowed_limit { let error = PostError::FieldsCountLimitExceeded( stream_name.to_string(), fields_count, - PARSEABLE.options.dataset_fields_allowed_limit, + allowed_limit, ); tracing::error!("{}", error); // Return an error if the fields count exceeds the limit @@ -654,7 +605,40 @@ mod tests { use actix_web::test::TestRequest; #[test] - fn protobuf_logs_decode_uses_shared_otel_path() { + fn dataset_field_limit_accepts_configured_limit() { + assert!(verify_dataset_fields_count("test-stream", 100, 100).is_ok()); + } + + #[test] + fn dataset_field_limit_rejects_count_above_configured_limit() { + let error = verify_dataset_fields_count("test-stream", 101, 100).unwrap_err(); + + assert!(matches!( + error, + PostError::FieldsCountLimitExceeded(stream, fields, allowed) + if stream == "test-stream" && fields == 101 && allowed == 100 + )); + } + + #[test] + fn json_logs_decode_to_flattened_records() { + let payload = serde_json::json!({ + "resourceLogs": [{ + "scopeLogs": [{ + "logRecords": [{}] + }] + }] + }); + + let records = + decode_and_flatten_otel_json(payload, &LogSource::OtelLogs, "test-tenant", false) + .unwrap(); + + assert_eq!(records.len(), 1); + } + + #[test] + fn protobuf_logs_decode_to_flattened_records() { use opentelemetry_proto::tonic::logs::v1::{LogRecord, ResourceLogs, ScopeLogs}; let request = ExportLogsServiceRequest {