diff --git a/Cargo.lock b/Cargo.lock
index 19b9aaabca4..f78fa9cfe79 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6029,11 +6029,11 @@ dependencies = [
[[package]]
name = "halfbrown"
-version = "0.3.0"
+version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aa2c385c6df70fd180bbb673d93039dbd2cd34e41d782600bdf6e1ca7bce39aa"
+checksum = "0c7ed2f2edad8a14c8186b847909a41fbb9c3eafa44f88bd891114ed5019da09"
dependencies = [
- "hashbrown 0.15.4",
+ "hashbrown 0.16.1",
"serde",
]
@@ -13346,13 +13346,11 @@ checksum = "d66dc143e6b11c1eddc06d5c423cfc97062865baf299914ab64caa38182078fe"
[[package]]
name = "simd-json"
-version = "0.15.1"
+version = "0.19.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c962f626b54771990066e5435ec8331d1462576cd2d1e62f24076ae014f92112"
+checksum = "e8f2e4d523646f7da6dde3983bd18ede0babc21c258ab708b3dd93ea0259719d"
dependencies = [
- "getrandom 0.3.4",
"halfbrown",
- "ref-cast",
"serde",
"serde_json",
"simdutf8",
@@ -13925,6 +13923,7 @@ dependencies = [
"hostname 0.4.1",
"log-store",
"mito2",
+ "pipeline",
"query",
"serde",
"servers",
@@ -13932,6 +13931,7 @@ dependencies = [
"store-api",
"table",
"tokio",
+ "toml 0.8.23",
"url",
]
@@ -15756,9 +15756,9 @@ checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"
[[package]]
name = "value-trait"
-version = "0.11.0"
+version = "0.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0508fce11ad19e0aab49ce20b6bec7f8f82902ded31df1c9fc61b90f0eb396b8"
+checksum = "545a3d7089f11f1741d12963c057adf9443fc24325110a6a6daf582e825fd51b"
dependencies = [
"float-cmp",
"halfbrown",
diff --git a/Cargo.toml b/Cargo.toml
index fd6a533ed11..bfec91a2d38 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -229,7 +229,7 @@ sea-query = "0.32"
serde = { version = "1.0", features = ["derive"] }
serde_json = { version = "1.0", features = ["float_roundtrip"] }
serde_with = "3"
-simd-json = "0.15"
+simd-json = "0.19"
similar-asserts = "1.6.0"
smallvec = { version = "1", features = ["serde"] }
snafu = "0.8"
diff --git a/config/config.md b/config/config.md
index 80f2f036bdf..3f221f7fe63 100644
--- a/config/config.md
+++ b/config/config.md
@@ -223,6 +223,8 @@
| `slow_query.sample_ratio` | Float | Unset | The sampling ratio of slow query log. The value should be in the range of (0, 1]. |
| `tracing` | -- | -- | The tracing options. Only effect when compiled with `tokio-console` feature. |
| `tracing.tokio_console_addr` | String | Unset | The tokio console address. |
+| `pipeline` | -- | -- | The pipeline options. |
+| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
Explicit request values override this setting. Malformed input may be discarded,
and invalid custom timestamps in identity ingestion fall back to server time.
Pipeline execution errors are controlled separately by `skip_error`.
Default is false. Requires a restart. |
| `memory` | -- | -- | The memory options. |
| `memory.enable_heap_profiling` | Bool | `true` | Whether to enable heap profiling activation during startup.
When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable
is set to "prof:true,prof_active:false". The official image adds this env variable.
Default is true. |
@@ -348,6 +350,8 @@
| `tracing.tokio_console_addr` | String | Unset | The tokio console address. |
| `memory` | -- | -- | The memory options. |
| `memory.enable_heap_profiling` | Bool | `true` | Whether to enable heap profiling activation during startup.
When enabled, heap profiling will be activated if the `MALLOC_CONF` environment variable
is set to "prof:true,prof_active:false". The official image adds this env variable.
Default is true. |
+| `pipeline` | -- | -- | The pipeline options. |
+| `pipeline.ignore_errors` | Bool | `false` | Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
Explicit request values override this setting. Malformed input may be discarded,
and invalid custom timestamps in identity ingestion fall back to server time.
Pipeline execution errors are controlled separately by `skip_error`.
Default is false. Requires a restart. |
| `event_recorder` | -- | -- | Configuration options for the event recorder. |
| `event_recorder.ttl` | String | `90d` | TTL for the events table that will be used to store the events. Default is `90d`. |
diff --git a/config/frontend.example.toml b/config/frontend.example.toml
index 766a21a9654..05e85c5b91f 100644
--- a/config/frontend.example.toml
+++ b/config/frontend.example.toml
@@ -362,6 +362,15 @@ ttl = "90d"
## Default is true.
enable_heap_profiling = true
+## The pipeline options.
+[pipeline]
+## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
+## Explicit request values override this setting. Malformed input may be discarded,
+## and invalid custom timestamps in identity ingestion fall back to server time.
+## Pipeline execution errors are controlled separately by `skip_error`.
+## Default is false. Requires a restart.
+ignore_errors = false
+
## Configuration options for the event recorder.
[event_recorder]
## TTL for the events table that will be used to store the events. Default is `90d`.
diff --git a/config/standalone.example.toml b/config/standalone.example.toml
index 587aa3c05eb..a23b8b46d67 100644
--- a/config/standalone.example.toml
+++ b/config/standalone.example.toml
@@ -869,6 +869,15 @@ default_ratio = 1.0
## @toml2docs:none-default
#+ tokio_console_addr = "127.0.0.1"
+## The pipeline options.
+[pipeline]
+## Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
+## Explicit request values override this setting. Malformed input may be discarded,
+## and invalid custom timestamps in identity ingestion fall back to server time.
+## Pipeline execution errors are controlled separately by `skip_error`.
+## Default is false. Requires a restart.
+ignore_errors = false
+
## The memory options.
[memory]
## Whether to enable heap profiling activation during startup.
diff --git a/src/frontend/src/frontend.rs b/src/frontend/src/frontend.rs
index 918185cb8f6..b2253812ac3 100644
--- a/src/frontend/src/frontend.rs
+++ b/src/frontend/src/frontend.rs
@@ -22,6 +22,7 @@ use common_options::datanode::DatanodeClientOptions;
use common_options::memory::MemoryOptions;
use common_telemetry::logging::{LoggingOptions, SlowQueryOptions, TracingOptions};
use meta_client::MetaClientOptions;
+use pipeline::PipelineOptions;
use query::options::QueryOptions;
use serde::{Deserialize, Serialize};
use servers::grpc::GrpcOptions;
@@ -75,6 +76,7 @@ pub struct FrontendOptions {
pub query: QueryOptions,
pub slow_query: SlowQueryOptions,
pub memory: MemoryOptions,
+ pub pipeline: PipelineOptions,
/// The event recorder options.
pub event_recorder: EventRecorderOptions,
/// Environment variable keys to read and report in heartbeat messages.
@@ -108,6 +110,7 @@ impl Default for FrontendOptions {
query: QueryOptions::default(),
slow_query: SlowQueryOptions::default(),
memory: MemoryOptions::default(),
+ pipeline: PipelineOptions::default(),
event_recorder: EventRecorderOptions::default(),
heartbeat_env_vars: vec![],
}
@@ -191,6 +194,17 @@ mod tests {
use crate::instance::builder::FrontendBuilder;
use crate::server::Services;
+ #[test]
+ fn test_pipeline_config() {
+ let defaults: FrontendOptions = toml::from_str("").unwrap();
+ assert!(!defaults.pipeline.ignore_errors);
+ let options: FrontendOptions = toml::from_str("[pipeline]\nignore_errors = true").unwrap();
+ assert!(options.pipeline.ignore_errors);
+ let serialized = toml::to_string(&options).unwrap();
+ let restored: FrontendOptions = toml::from_str(&serialized).unwrap();
+ assert_eq!(options.pipeline, restored.pipeline);
+ }
+
#[test]
fn test_toml() {
let opts = FrontendOptions::default();
diff --git a/src/frontend/src/instance/builder.rs b/src/frontend/src/instance/builder.rs
index 5126c625f5c..6faad305ef7 100644
--- a/src/frontend/src/instance/builder.rs
+++ b/src/frontend/src/instance/builder.rs
@@ -286,6 +286,7 @@ impl FrontendBuilder {
statement_executor.clone(),
self.catalog_manager.clone(),
query_engine.clone(),
+ self.options.pipeline.clone(),
));
plugins.insert::(statement_executor.clone());
diff --git a/src/frontend/src/instance/log_handler.rs b/src/frontend/src/instance/log_handler.rs
index ed3654559fd..72ff1b425ec 100644
--- a/src/frontend/src/instance/log_handler.rs
+++ b/src/frontend/src/instance/log_handler.rs
@@ -21,7 +21,7 @@ use client::Output;
use common_error::ext::BoxedError;
use datatypes::timestamp::TimestampNanosecond;
use pipeline::pipeline_operator::PipelineOperator;
-use pipeline::{Pipeline, PipelineInfo, PipelineVersion};
+use pipeline::{Pipeline, PipelineInfo, PipelineOptions, PipelineVersion};
use servers::error::{
AuthSnafu, Error as ServerError, ExecuteGrpcRequestSnafu, PipelineSnafu, Result as ServerResult,
};
@@ -100,6 +100,10 @@ impl PipelineHandler for Instance {
.await
}
+ fn pipeline_options(&self) -> &PipelineOptions {
+ self.pipeline_operator.options()
+ }
+
fn build_pipeline(&self, pipeline: &str) -> ServerResult {
PipelineOperator::build_pipeline(pipeline).context(PipelineSnafu)
}
diff --git a/src/pipeline/Cargo.toml b/src/pipeline/Cargo.toml
index d1a1f88ca8d..5907005cc03 100644
--- a/src/pipeline/Cargo.toml
+++ b/src/pipeline/Cargo.toml
@@ -53,6 +53,7 @@ paste.workspace = true
prometheus.workspace = true
query.workspace = true
regex.workspace = true
+serde.workspace = true
serde_json.workspace = true
session.workspace = true
snafu.workspace = true
@@ -67,7 +68,6 @@ yaml-rust = "0.4"
catalog = { workspace = true, features = ["testing"] }
criterion = { workspace = true, features = ["html_reports"] }
rayon = "1.0"
-serde = { version = "1.0", features = ["derive"] }
session = { workspace = true, features = ["testing"] }
[[bench]]
diff --git a/src/pipeline/src/lib.rs b/src/pipeline/src/lib.rs
index c657f61342c..330971d8cf8 100644
--- a/src/pipeline/src/lib.rs
+++ b/src/pipeline/src/lib.rs
@@ -19,6 +19,7 @@ pub mod error;
mod etl;
mod manager;
mod metrics;
+mod options;
mod tablesuffix;
pub use etl::ctx_req::{ContextOpt, ContextReq};
@@ -34,6 +35,7 @@ pub use manager::{
IdentityTimeIndex, PipelineContext, PipelineDefinition, PipelineInfo, PipelineRef,
PipelineTableRef, PipelineVersion, PipelineWay, SelectInfo, pipeline_operator, table, util,
};
+pub use options::PipelineOptions;
#[macro_export]
macro_rules! unwrap_or_continue_if_err {
diff --git a/src/pipeline/src/manager/pipeline_operator.rs b/src/pipeline/src/manager/pipeline_operator.rs
index 6c4256db69b..142980f9ee4 100644
--- a/src/pipeline/src/manager/pipeline_operator.rs
+++ b/src/pipeline/src/manager/pipeline_operator.rs
@@ -31,7 +31,6 @@ use snafu::{OptionExt, ResultExt};
use table::TableRef;
use table::requests::TTL_KEY;
-use crate::Pipeline;
use crate::error::{CatalogSnafu, CreateTableSnafu, PipelineTableNotFoundSnafu, Result};
use crate::manager::{PipelineInfo, PipelineTableRef, PipelineVersion};
use crate::metrics::{
@@ -39,6 +38,7 @@ use crate::metrics::{
METRIC_PIPELINE_RETRIEVE_HISTOGRAM,
};
use crate::table::{PIPELINE_TABLE_NAME, PipelineTable};
+use crate::{Pipeline, PipelineOptions};
/// PipelineOperator is responsible for managing pipelines.
/// It provides the ability to:
@@ -54,6 +54,7 @@ pub struct PipelineOperator {
catalog_manager: CatalogManagerRef,
query_engine: QueryEngineRef,
tables: RwLock>,
+ options: PipelineOptions,
}
impl PipelineOperator {
@@ -171,6 +172,7 @@ impl PipelineOperator {
statement_executor: StatementExecutorRef,
catalog_manager: CatalogManagerRef,
query_engine: QueryEngineRef,
+ options: PipelineOptions,
) -> Self {
Self {
inserter,
@@ -178,6 +180,7 @@ impl PipelineOperator {
catalog_manager,
tables: RwLock::new(HashMap::new()),
query_engine,
+ options,
}
}
@@ -274,6 +277,11 @@ impl PipelineOperator {
.await
}
+ /// Returns the server's pipeline options.
+ pub fn options(&self) -> &PipelineOptions {
+ &self.options
+ }
+
/// Compile a pipeline.
pub fn build_pipeline(pipeline: &str) -> Result {
PipelineTable::compile_pipeline(pipeline)
diff --git a/src/pipeline/src/options.rs b/src/pipeline/src/options.rs
new file mode 100644
index 00000000000..859559edf1a
--- /dev/null
+++ b/src/pipeline/src/options.rs
@@ -0,0 +1,26 @@
+// Copyright 2023 Greptime Team
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+use serde::{Deserialize, Serialize};
+
+#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(default)]
+pub struct PipelineOptions {
+ /// Default for the HTTP log ingestion and pipeline dry-run `ignore_errors` parameter.
+ /// Explicit request values override this setting. Malformed input may be discarded,
+ /// and invalid custom timestamps in identity ingestion fall back to server time.
+ /// Pipeline execution errors are controlled separately by `skip_error`.
+ /// Defaults to false. Changes require a restart.
+ pub ignore_errors: bool,
+}
diff --git a/src/servers/src/http/event.rs b/src/servers/src/http/event.rs
index f08c76bcdb9..60f9eaa848a 100644
--- a/src/servers/src/http/event.rs
+++ b/src/servers/src/http/event.rs
@@ -12,6 +12,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
+use std::borrow::Cow;
use std::collections::BTreeMap;
use std::fmt::Display;
use std::io::BufRead;
@@ -97,7 +98,8 @@ pub struct LogIngesterQueryParams {
pub pipeline_name: Option,
/// The version of the pipeline to be used for log ingestion.
pub version: Option,
- /// Whether to ignore errors during log ingestion.
+ /// Whether to ignore payload parsing and custom timestamp errors during log ingestion.
+ /// Defaults to the server's `pipeline.ignore_errors` setting when omitted.
pub ignore_errors: Option,
/// The source of the log data.
pub source: Option,
@@ -116,7 +118,7 @@ pub struct LogIngesterQueryParams {
/// Whether to skip errors during log ingestion.
/// If set to true, the ingestion will continue even if there are errors in the data.
/// If set to false, the ingestion will stop at the first error.
- /// This is different from `ignore_errors`, which is used to ignore errors during the pipeline execution.
+ /// This controls pipeline execution errors, separately from `ignore_errors`.
/// The priority of query params is lower than that headers of x-greptime-pipeline-params.
pub skip_error: Option,
}
@@ -584,9 +586,13 @@ fn add_step_info_for_pipeline_dryrun_error(step_msg: &str, e: Error) -> Response
/// Parse the data with given content type
/// If the content type is invalid, return error
/// content type is one of application/json, text/plain, application/x-ndjson
-fn parse_dryrun_data(data_type: String, data: String) -> Result> {
+fn parse_dryrun_data(
+ data_type: String,
+ data: String,
+ ignore_errors: bool,
+) -> Result> {
if let Ok(content_type) = ContentType::from_str(&data_type) {
- extract_pipeline_value_by_content_type(content_type, Bytes::from(data), false)
+ extract_pipeline_value_by_content_type(content_type, Bytes::from(data), ignore_errors)
} else {
InvalidParameterSnafu {
reason: format!(
@@ -612,11 +618,16 @@ pub async fn pipeline_dryrun(
query_ctx.set_channel(Channel::Log);
let query_ctx = Arc::new(query_ctx);
+ let ignore_errors = query_params
+ .ignore_errors
+ .unwrap_or(handler.pipeline_options().ignore_errors);
+
match check_pipeline_dryrun_params_valid(&payload) {
Some(params) => {
let data = parse_dryrun_data(
params.data_type.unwrap_or("application/json".to_string()),
params.data,
+ ignore_errors,
)?;
check_data_valid(data.len())?;
@@ -667,8 +678,6 @@ pub async fn pipeline_dryrun(
let version =
to_pipeline_version(query_params.version.as_deref()).context(PipelineSnafu)?;
- let ignore_errors = query_params.ignore_errors.unwrap_or(false);
-
let value =
extract_pipeline_value_by_content_type(content_type, payload, ignore_errors)?;
@@ -718,7 +727,9 @@ pub async fn log_ingester(
reason: "table is required",
})?;
- let ignore_errors = query_params.ignore_errors.unwrap_or(false);
+ let ignore_errors = query_params
+ .ignore_errors
+ .unwrap_or(handler.pipeline_options().ignore_errors);
let pipeline_name = query_params.pipeline_name.context(InvalidParameterSnafu {
reason: "pipeline_name is required",
@@ -833,36 +844,69 @@ impl<'a> TryFrom<&'a ContentType> for EventPayloadResolver<'a> {
impl EventPayloadResolver<'_> {
fn parse_payload(&self, payload: Bytes, ignore_errors: bool) -> Result> {
match self.inner {
- EventPayloadResolverInner::Json => transform_ndjson_array_factory(
- Deserializer::from_slice(&payload).into_iter(),
- ignore_errors,
- ),
+ EventPayloadResolverInner::Json => {
+ // Detect parse failures even when ignore_errors would discard them.
+ let mut saw_parse_error = false;
+ let result = transform_ndjson_array_factory(
+ Deserializer::from_slice(&payload)
+ .into_iter()
+ .inspect(|item| saw_parse_error |= item.is_err()),
+ ignore_errors,
+ );
+ if saw_parse_error && let Cow::Owned(text) = String::from_utf8_lossy(&payload) {
+ // Release partially parsed records before retrying the entire payload.
+ drop(result);
+ return transform_ndjson_array_factory(
+ Deserializer::from_str(&text).into_iter(),
+ ignore_errors,
+ );
+ }
+ result
+ }
EventPayloadResolverInner::Ndjson => {
let mut result = Vec::with_capacity(1000);
let mut buffer = Buffers::new(1000);
- for (index, line) in payload.lines().enumerate() {
- let mut line = match line {
- Ok(line) if !line.is_empty() => line,
- Ok(_) => continue, // Skip empty lines
- Err(_) if ignore_errors => continue,
- Err(e) => {
- warn!(e; "invalid string at index: {}", index);
- return InvalidParameterSnafu {
- reason: format!("invalid line at index: {}", index),
- }
- .fail();
- }
- };
+ let mut remaining = payload.as_ref();
+ let mut line_bytes = Vec::new();
+ // read_until keeps the optimized newline search without validating UTF-8.
+ for index in 0usize.. {
+ let original = remaining;
+ line_bytes.clear();
+ let read = remaining.read_until(b'\n', &mut line_bytes)?;
+ if read == 0 {
+ break;
+ }
- // simd_json, according to description, only de-escapes string at character level,
- // like any other json parser. So it should be safe here.
- if let Ok(v) = simd_json::serde::from_slice_with_buffers(
- unsafe { line.as_bytes_mut() },
- &mut buffer,
- ) {
+ let line = &original[..read];
+ let line = if let Some(line) = line.strip_suffix(b"\n") {
+ line.strip_suffix(b"\r").unwrap_or(line)
+ } else {
+ line
+ };
+ if line.is_empty() {
+ continue;
+ }
+
+ line_bytes.truncate(line.len());
+ let mut parsed =
+ simd_json::serde::from_slice_with_buffers(&mut line_bytes, &mut buffer);
+ // Retry from the original line because SIMD parsing can rewrite its input.
+ if parsed.is_err()
+ && let Cow::Owned(text) = String::from_utf8_lossy(line)
+ {
+ line_bytes = text.into_bytes();
+ parsed =
+ simd_json::serde::from_slice_with_buffers(&mut line_bytes, &mut buffer);
+ }
+
+ if let Ok(v) = parsed {
result.push(v);
} else if !ignore_errors {
- warn!("invalid JSON at index: {}, content: {:?}", index, line);
+ warn!(
+ "invalid JSON at index: {}, content: {:?}",
+ index,
+ String::from_utf8_lossy(line)
+ );
return InvalidParameterSnafu {
reason: format!("invalid JSON at index: {}", index),
}
@@ -1046,6 +1090,195 @@ mod tests {
assert_eq!(a, "[{\"a\":1},{\"b\":2}]");
}
+ #[test]
+ fn test_json_invalid_utf8_retry() {
+ let expected = vec![
+ json!({"message": "before"}).into(),
+ json!({"message": "bad\u{fffd}\u{fffd}\u{fffd}\u{7f}\u{7f}"}).into(),
+ json!({"message": "after"}).into(),
+ ];
+
+ for payload in [
+ b"[{\"message\":\"before\"},{\"message\":\"bad\xc1\x89\xc8\x7f\x7f\"},{\"message\":\"after\"}]".as_slice(),
+ b"{\"message\":\"before\"}\n{\"message\":\"bad\xc1\x89\xc8\x7f\x7f\"}\n{\"message\":\"after\"}".as_slice(),
+ ] {
+ for ignore_errors in [false, true] {
+ let actual = extract_pipeline_value_by_content_type(
+ ContentType::json(),
+ Bytes::from_static(payload),
+ ignore_errors,
+ )
+ .unwrap();
+ assert_eq!(actual, expected);
+ }
+ }
+ }
+
+ #[test]
+ fn test_json_invalid_utf8_retry_preserves_parse_errors() {
+ let cases = [
+ (
+ br#"{"message":"before"}{"message":"\uD800"}{"message":"after"}"#.as_slice(),
+ vec![json!({"message": "before"}).into()],
+ ),
+ (
+ b"{\"message\":\"before\"}{\"message\":\"bad\xff\"}{\"broken\":}".as_slice(),
+ vec![
+ json!({"message": "before"}).into(),
+ json!({"message": "bad\u{fffd}"}).into(),
+ ],
+ ),
+ ];
+
+ for (payload, expected) in cases {
+ for ignore_errors in [false, true] {
+ let result = extract_pipeline_value_by_content_type(
+ ContentType::json(),
+ Bytes::from_static(payload),
+ ignore_errors,
+ );
+ if ignore_errors {
+ assert_eq!(result.unwrap(), expected);
+ } else {
+ assert!(matches!(result, Err(Error::ParseJson { .. })));
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn test_json_invalid_utf8_retry_preserves_ignored_items() {
+ let payload = Bytes::from_static(b"0{\"message\":\"bad\xff\"}false{\"message\":\"after\"}");
+ let result =
+ extract_pipeline_value_by_content_type(ContentType::json(), payload.clone(), false);
+ assert!(matches!(result, Err(Error::InvalidParameter { .. })));
+
+ let actual =
+ extract_pipeline_value_by_content_type(ContentType::json(), payload.clone(), true)
+ .unwrap();
+ assert_eq!(
+ actual,
+ vec![
+ json!({"message": "bad\u{fffd}"}).into(),
+ json!({"message": "after"}).into(),
+ ],
+ );
+ }
+
+ #[test]
+ fn test_ndjson_invalid_utf8_retry() {
+ for invalid_bytes in [1, 8192] {
+ let mut payload = b"\n{\"message\":\"before\"}\r\n\r\n{\"escaped\":\"line\\nquote\\\"slash\\\\\",\"message\":\"bad".to_vec();
+ payload.extend(std::iter::repeat_n(0xff, invalid_bytes));
+ payload.extend_from_slice(b"\"}\r\n{\"message\":\"after\"}");
+ let payload = Bytes::from(payload);
+ let expected = vec![
+ json!({"message": "before"}).into(),
+ json!({
+ "escaped": "line\nquote\"slash\\",
+ "message": format!("bad{}", "\u{fffd}".repeat(invalid_bytes)),
+ })
+ .into(),
+ json!({"message": "after"}).into(),
+ ];
+
+ for ignore_errors in [false, true] {
+ let actual = extract_pipeline_value_by_content_type(
+ NDJSON_CONTENT_TYPE.clone(),
+ payload.clone(),
+ ignore_errors,
+ )
+ .unwrap();
+ assert_eq!(actual, expected);
+ }
+ }
+ }
+
+ #[test]
+ fn test_ndjson_invalid_utf8_retry_preserves_parse_errors() {
+ let too_deep = format!("{}0{}", "[".repeat(1025), "]".repeat(1025));
+ for bad_line in [
+ br#"{"escaped":"line\n","broken":}"#.as_slice(),
+ b"{\"escaped\":\"line\\n\",\"message\":\"bad\xff\",\"broken\":}".as_slice(),
+ br#"{"escaped":"line\n","message":"\uDC00"}"#.as_slice(),
+ br#"{"message":"\uD800"}"#.as_slice(),
+ br#"{"value":1e4294967296}"#.as_slice(),
+ b"{\"value\":123\0}".as_slice(),
+ b"{\"message\":\"bad\xe2\x82".as_slice(),
+ too_deep.as_bytes(),
+ ] {
+ let mut payload = b"{\"message\":\"before\"}\n".to_vec();
+ payload.extend_from_slice(bad_line);
+ payload.extend_from_slice(b"\n{\"message\":\"after\"}\n");
+ let payload = Bytes::from(payload);
+
+ for ignore_errors in [false, true] {
+ let result = extract_pipeline_value_by_content_type(
+ NDJSON_CONTENT_TYPE.clone(),
+ payload.clone(),
+ ignore_errors,
+ );
+ if ignore_errors {
+ assert_eq!(
+ result.unwrap(),
+ vec![
+ json!({"message": "before"}).into(),
+ json!({"message": "after"}).into(),
+ ],
+ );
+ } else {
+ assert!(matches!(
+ result,
+ Err(Error::InvalidParameter { reason, .. })
+ if reason.ends_with("at index: 1")
+ ));
+ }
+ }
+ }
+ }
+
+ #[test]
+ fn test_ndjson_large_exponents() {
+ let payload = Bytes::from_static(br#"{"zero":0e99999999999,"underflow":1e-4294967295}"#);
+ for ignore_errors in [false, true] {
+ let actual = extract_pipeline_value_by_content_type(
+ NDJSON_CONTENT_TYPE.clone(),
+ payload.clone(),
+ ignore_errors,
+ )
+ .unwrap();
+ assert_eq!(actual, vec![json!({"zero": 0.0, "underflow": 0.0}).into()]);
+ }
+ }
+
+ #[test]
+ fn test_ndjson_empty_and_whitespace_lines() {
+ for ignore_errors in [false, true] {
+ for payload in [b"".as_slice(), b"\n\r\n".as_slice()] {
+ let actual = extract_pipeline_value_by_content_type(
+ NDJSON_CONTENT_TYPE.clone(),
+ Bytes::from_static(payload),
+ ignore_errors,
+ )
+ .unwrap();
+ assert!(actual.is_empty());
+ }
+
+ for payload in [b"\r".as_slice(), b" \n".as_slice(), b"\r\r\n".as_slice()] {
+ let result = extract_pipeline_value_by_content_type(
+ NDJSON_CONTENT_TYPE.clone(),
+ Bytes::from_static(payload),
+ ignore_errors,
+ );
+ if ignore_errors {
+ assert!(result.unwrap().is_empty());
+ } else {
+ assert!(matches!(result, Err(Error::InvalidParameter { .. })));
+ }
+ }
+ }
+ }
+
#[test]
fn test_extract_by_content() {
let payload = r#"
diff --git a/src/servers/src/query_handler.rs b/src/servers/src/query_handler.rs
index d4b272de128..c58d6b3925e 100644
--- a/src/servers/src/query_handler.rs
+++ b/src/servers/src/query_handler.rs
@@ -40,7 +40,9 @@ use log_query::LogQuery;
use opentelemetry_proto::tonic::collector::logs::v1::ExportLogsServiceRequest;
use opentelemetry_proto::tonic::collector::trace::v1::ExportTraceServiceRequest;
use otel_arrow_rust::proto::opentelemetry::collector::metrics::v1::ExportMetricsServiceRequest;
-use pipeline::{GreptimePipelineParams, Pipeline, PipelineInfo, PipelineVersion, PipelineWay};
+use pipeline::{
+ GreptimePipelineParams, Pipeline, PipelineInfo, PipelineOptions, PipelineVersion, PipelineWay,
+};
use serde_json::Value;
use session::context::{QueryContext, QueryContextRef};
@@ -183,6 +185,9 @@ pub trait PipelineHandler {
query_ctx: &QueryContext,
) -> std::result::Result