Skip to content

armgit / xerj

Public Imported from GitHub
0

AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.

fix(api,engine,wasm): an ingest pipeline xerj cannot run must refuse the write

xerj-org96777769f0ff
diff --git a/engine/crates/xerj-api/src/es_compat.rs b/engine/crates/xerj-api/src/es_compat.rs
index 95a9801a0..678c328c2 100644
--- a/engine/crates/xerj-api/src/es_compat.rs
+++ b/engine/crates/xerj-api/src/es_compat.rs
@@ -2299,10 +2299,13 @@ pub async fn index_doc_auto(
// Pipeline returned empty results — pass through original
serde_json::from_slice(&body).unwrap_or(Value::Null)
}
- Err(e) => {
- tracing::warn!(pipeline = %pipeline, error = %e, "pipeline execution failed, indexing without transform");
- serde_json::from_slice(&body).unwrap_or(Value::Null)
- }
+ // Issue #204, the purest form of the class on a user-DATA path:
+ // this used to warn and then index the ORIGINAL document. A
+ // pipeline whose job was to redact PII, drop a field or route the
+ // document simply did not run, and the caller got `201 Created`.
+ // `_bulk` already fails the item here; the single-document path now
+ // agrees with it.
+ Err(e) => return pipeline_execution_error(pipeline, &e).into_response(),
}
} else {
doc
@@ -2423,7 +2426,13 @@ pub async fn index_doc(
}
transformed
}
- _ => doc,
+ // Pipeline produced no output for this document — index the
+ // original body, which is what it asked for.
+ Ok(_) => doc,
+ // Issue #204: this arm was folded into `_ => doc`, so a pipeline
+ // that could not run left the document indexed UNTRANSFORMED under
+ // a success response. Refuse instead.
+ Err(e) => return pipeline_execution_error(pipeline, &e).into_response(),
}
} else {
doc
@@ -2544,7 +2553,13 @@ pub async fn create_doc(
}
transformed
}
- _ => doc,
+ // Pipeline produced no output for this document — index the
+ // original body, which is what it asked for.
+ Ok(_) => doc,
+ // Issue #204: this arm was folded into `_ => doc`, so a pipeline
+ // that could not run left the document indexed UNTRANSFORMED under
+ // a success response. Refuse instead.
+ Err(e) => return pipeline_execution_error(pipeline, &e).into_response(),
}
} else {
doc
@@ -13532,6 +13547,190 @@ mod ingest_pipeline_fail_closed_tests {
.expect("route response");
assert_eq!(response.status(), StatusCode::OK);
}
+
+ async fn index_doc(
+ state: AppState,
+ index: &str,
+ id: &str,
+ pipeline: &str,
+ doc: Value,
+ ) -> (StatusCode, Value) {
+ let response = crate::router::build_es_compat_router(state)
+ .oneshot(
+ Request::put(format!(
+ "/{index}/_doc/{id}?refresh=true&pipeline={pipeline}"
+ ))
+ .header("content-type", "application/json")
+ .body(Body::from(doc.to_string()))
+ .expect("request"),
+ )
+ .await
+ .expect("route response");
+ let status = response.status();
+ let bytes = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response bytes");
+ (
+ status,
+ serde_json::from_slice(&bytes).unwrap_or(Value::Null),
+ )
+ }
+
+ async fn get_source(state: AppState, index: &str, id: &str) -> Value {
+ let response = crate::router::build_es_compat_router(state)
+ .oneshot(
+ Request::get(format!("/{index}/_doc/{id}"))
+ .body(Body::empty())
+ .expect("request"),
+ )
+ .await
+ .expect("route response");
+ let bytes = to_bytes(response.into_body(), usize::MAX)
+ .await
+ .expect("response bytes");
+ serde_json::from_slice::<Value>(&bytes)
+ .expect("json")
+ .get("_source")
+ .cloned()
+ .unwrap_or(Value::Null)
+ }
+
+ /// A processor xerj does not implement is ACCEPTED (Elasticsearch accepts
+ /// it and `_simulate` still walks it) — but no document may then be
+ /// ingested through it. Pre-fix the write answered `201 Created` with the
+ /// document stored untransformed.
+ #[tokio::test]
+ async fn a_pipeline_with_an_unimplemented_processor_refuses_the_write() {
+ let state = test_state();
+
+ // `pipeline` (a pipeline calling another pipeline) is a real ES
+ // processor that xerj's compiled ingest path does not implement.
+ let (status, body) = put_pipeline(
+ state.clone(),
+ "outer",
+ json!({ "processors": [ { "pipeline": { "name": "inner" } } ] }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert_eq!(body["acknowledged"], json!(true));
+
+ // Stored and visible, exactly as ES does…
+ assert!(state.engine.pipelines.contains_key("outer"));
+ // …but explicitly marked as having no compiled form.
+ assert!(state.engine.unrunnable_pipelines.contains_key("outer"));
+ assert!(!state.engine.transform_pipelines.contains_key("outer"));
+
+ // …and a write through it is REFUSED rather than silently untransformed.
+ let (status, body) = index_doc(
+ state.clone(),
+ "logs",
+ "1",
+ "outer",
+ json!({ "msg": "hello" }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::BAD_REQUEST, "body: {body}");
+ let reason = body["error"]["reason"].as_str().unwrap_or_default();
+ assert!(
+ reason.contains("outer") && reason.contains("pipeline"),
+ "reason should name the pipeline: {reason}"
+ );
+
+ // Nothing was written.
+ assert!(get_source(state, "logs", "1").await.is_null());
+ }
+
+ /// The ES `rename` processor used to translate to a config shape the
+ /// `field_rename` plugin rejects (`from`/`to` instead of `mappings`), so
+ /// EVERY rename processor failed to compile — invisibly, under a 200.
+ #[tokio::test]
+ async fn the_es_rename_processor_actually_renames() {
+ let state = test_state();
+ let (status, body) = put_pipeline(
+ state.clone(),
+ "ren",
+ json!({
+ "processors": [
+ { "rename": { "field": "old_name", "target_field": "new_name" } }
+ ]
+ }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK, "body: {body}");
+ assert!(
+ state.engine.transform_pipelines.contains_key("ren"),
+ "rename must COMPILE, not merely be stored"
+ );
+
+ let (status, body) = index_doc(
+ state.clone(),
+ "renamed",
+ "1",
+ "ren",
+ json!({ "old_name": "v" }),
+ )
+ .await;
+ assert!(status.is_success(), "body: {body}");
+
+ let source = get_source(state, "renamed", "1").await;
+ assert_eq!(source["new_name"], json!("v"), "source: {source}");
+ assert!(source.get("old_name").is_none(), "source: {source}");
+ }
+
+ /// `DELETE` used to remove only the definition, leaving the compiled
+ /// pipeline live for anything that reached it by name.
+ #[tokio::test]
+ async fn deleting_a_pipeline_removes_the_compiled_form_too() {
+ let state = test_state();
+ let (status, _) = put_pipeline(
+ state.clone(),
+ "gone",
+ json!({ "processors": [ { "set": { "field": "a", "value": "b" } } ] }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(state.engine.transform_pipelines.contains_key("gone"));
+
+ let response = crate::router::build_es_compat_router(state.clone())
+ .oneshot(
+ Request::delete("/_ingest/pipeline/gone")
+ .body(Body::empty())
+ .expect("request"),
+ )
+ .await
+ .expect("route response");
+ assert_eq!(response.status(), StatusCode::OK);
+ assert!(!state.engine.pipelines.contains_key("gone"));
+ assert!(!state.engine.transform_pipelines.contains_key("gone"));
+ }
+
+ /// Re-defining a pipeline with something we cannot compile must not leave
+ /// the previous stages quietly running under the new definition's name.
+ #[tokio::test]
+ async fn redefining_with_an_unimplemented_processor_retires_the_old_stages() {
+ let state = test_state();
+ let (status, _) = put_pipeline(
+ state.clone(),
+ "evolving",
+ json!({ "processors": [ { "set": { "field": "a", "value": "b" } } ] }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(state.engine.transform_pipelines.contains_key("evolving"));
+
+ let (status, _) = put_pipeline(
+ state.clone(),
+ "evolving",
+ json!({ "processors": [ { "pipeline": { "name": "other" } } ] }),
+ )
+ .await;
+ assert_eq!(status, StatusCode::OK);
+ assert!(
+ !state.engine.transform_pipelines.contains_key("evolving"),
+ "the superseded compiled pipeline must not keep running"
+ );
+ assert!(state.engine.unrunnable_pipelines.contains_key("evolving"));
+ }
}
#[cfg(test)]
@@ -21506,6 +21705,22 @@ pub async fn put_settings(
// POST /_ingest/pipeline/{id}/_simulate
// ─────────────────────────────────────────────────────────────────────────────
+/// Refuse a write whose ingest pipeline did not run.
+///
+/// Issue #204. Every single-document write path used to swallow this and index
+/// the untransformed document under a `201 Created` — the redaction, the field
+/// drop, the routing the caller configured simply did not happen, and the only
+/// trace was a warn line. `_bulk` already failed the item; these paths now
+/// agree with it. The reason is passed through verbatim so an operator is told
+/// *why* (missing pipeline vs a processor this build cannot run) rather than
+/// having to guess.
+fn pipeline_execution_error(pipeline: &str, e: &xerj_wasm::WasmError) -> ApiError {
+ tracing::warn!(pipeline = %pipeline, error = %e, "refusing write: ingest pipeline did not run");
+ ApiError::new(xerj_common::XerjError::config(format!(
+ "document not indexed: ingest pipeline [{pipeline}] did not run: {e}"
+ )))
+}
+
pub async fn put_ingest_pipeline(
State(state): State<AppState>,
Path(id): Path<String>,
@@ -21563,11 +21778,25 @@ pub async fn put_ingest_pipeline(
}
"rename" => {
// ES: {"field": "old", "target_field": "new"}
- // xerj field_rename: {"from": "old", "to": "new"}
- json!({
- "from": proc_config.get("field").cloned().unwrap_or(Value::Null),
- "to": proc_config.get("target_field").cloned().unwrap_or(Value::Null)
- })
+ // xerj field_rename: {"mappings": {"old": "new"}}
+ //
+ // This used to emit `{"from": .., "to": ..}`, which the
+ // `field_rename` plugin rejects with "missing 'mappings'
+ // object" — so EVERY ES `rename` processor failed to
+ // compile. Under the old warn-and-store handler that was
+ // invisible: the pipeline was acknowledged, echoed back by
+ // GET, and renamed nothing at ingest. Issue #204 is what
+ // surfaced it; the translation is fixed here rather than
+ // left as a permanently-unrunnable processor.
+ match (
+ proc_config.get("field").and_then(Value::as_str),
+ proc_config.get("target_field").and_then(Value::as_str),
+ ) {
+ (Some(from), Some(to)) => json!({ "mappings": { from: to } }),
+ // Leave malformed input alone; the plugin's own
+ // validation produces the error message.
+ _ => proc_config.clone(),
+ }
}
_ => proc_config.clone(),
};
@@ -21580,19 +21809,49 @@ pub async fn put_ingest_pipeline(
} else {
body.clone()
};
- // `create_pipeline` publishes into BOTH the compiled map and the
- // GET-visible `pipelines` map, and only on success — so a rejected
- // definition leaves no phantom entry to echo back. (On success the stored
- // blob is the translated xerj config, exactly as before: `create_pipeline`
- // used to overwrite the raw body this handler had already inserted.)
- if let Err(e) = state.engine.create_pipeline(&id, xerj_config) {
- tracing::warn!(pipeline = %id, error = %e, "rejected ingest pipeline definition");
- let err = xerj_common::XerjError::invalid_mapping(format!(
- "pipeline [{id}] cannot be created: {e}"
- ));
- return ApiError::new(err).into_response();
+ // Three outcomes, and the difference between them is the whole point of
+ // issue #204:
+ //
+ // compiled → store the ES body verbatim (that is what ES
+ // echoes from GET, and what `_simulate` walks) and
+ // acknowledge.
+ // config we refuse → 400. The caller misconfigured a processor xerj
+ // does implement; storing it would mean answering
+ // "acknowledged" for redaction that never runs.
+ // stage we don't have → accept, exactly as ES does — but record WHY it
+ // has no compiled form, so every ingest path
+ // refuses loudly instead of indexing the document
+ // untransformed. This is the "degrade loudly"
+ // half of the issue: the capability gap is xerj's,
+ // not the caller's, and it surfaces at the point
+ // where a document would otherwise be silently
+ // mis-ingested.
+ match state.engine.create_pipeline(&id, xerj_config) {
+ Ok(()) => {
+ // `create_pipeline` stores the *translated* config; put the ES
+ // body back so GET and _simulate see what was actually submitted.
+ state.engine.pipelines.insert(id.clone(), body);
+ Json(json!({ "acknowledged": true })).into_response()
+ }
+ Err(xerj_wasm::WasmError::UnsupportedStage { stage }) => {
+ state.engine.register_unrunnable_pipeline(
+ &id,
+ body,
+ format!(
+ "processor [{stage}] is not implemented by this xerj build; \
+ no document can be ingested through pipeline [{id}]"
+ ),
+ );
+ Json(json!({ "acknowledged": true })).into_response()
+ }
+ Err(e) => {
+ tracing::warn!(pipeline = %id, error = %e, "rejected ingest pipeline definition");
+ let err = xerj_common::XerjError::invalid_mapping(format!(
+ "pipeline [{id}] cannot be created: {e}"
+ ));
+ ApiError::new(err).into_response()
+ }
}
- Json(json!({ "acknowledged": true })).into_response()
}
pub async fn get_ingest_pipeline(
@@ -21623,6 +21882,13 @@ pub async fn delete_ingest_pipeline(
Path(id): Path<String>,
) -> impl IntoResponse {
if state.engine.pipelines.remove(&id).is_some() {
+ // Issue #204: only the definition used to be removed. The COMPILED
+ // pipeline stayed in `transform_pipelines`, so a delete that answered
+ // `acknowledged: true` left the stages running for any caller that
+ // reached them by name (`POST /v1/ingest?pipeline=`) — deletion
+ // acknowledged, deletion not performed.
+ state.engine.transform_pipelines.remove(&id);
+ state.engine.unrunnable_pipelines.remove(&id);
Json(json!({ "acknowledged": true })).into_response()
} else {
let e = xerj_common::XerjError::index_not_found(format!("pipeline [{id}] is missing"));
@@ -25215,16 +25481,26 @@ pub async fn search_template(
}
}
}
- Value::Object(mut obj) => {
+ Value::Object(obj) => {
// JSON-encoded template object: recursively substitute in string values.
let rendered_str = render_template(
- &serde_json::to_string(&Value::Object(obj.clone())).unwrap_or_default(),
+ &serde_json::to_string(&Value::Object(obj)).unwrap_or_default(),
&params,
);
- serde_json::from_str(&rendered_str).unwrap_or(Value::Object({
- obj.insert("error".to_string(), Value::String("render failed".into()));
- obj
- }))
+ // Issue #204: this used to fall back to the UNRENDERED object
+ // with an `"error": "render failed"` key bolted on, and then
+ // ran a search with it — a different query from the one the
+ // template describes, under a 200. The string arm ten lines
+ // above already refuses; both arms now agree.
+ match serde_json::from_str(&rendered_str) {
+ Ok(v) => v,
+ Err(e) => {
+ let err = xerj_common::XerjError::invalid_query(format!(
+ "template rendered to invalid JSON: {e}"
+ ));
+ return ApiError::new(err).into_response();
+ }
+ }
}
other => other,
}
diff --git a/engine/crates/xerj-engine/src/bulk.rs b/engine/crates/xerj-engine/src/bulk.rs
index 9e9181d35..f4df56df8 100644
--- a/engine/crates/xerj-engine/src/bulk.rs
+++ b/engine/crates/xerj-engine/src/bulk.rs
@@ -1646,14 +1646,25 @@ pub async fn process_bulk_with_opts(
}
// Empty result set — index the original body unchanged.
Ok(_) => {}
- Err(_) => {
+ Err(e) => {
+ // A genuinely absent pipeline keeps ES's exact wording
+ // (the conformance suite asserts it). A pipeline that
+ // IS registered but carries a processor this build
+ // cannot run reports that instead — issue #204: telling
+ // an operator a pipeline "does not exist" when
+ // `GET /_ingest/pipeline` plainly returns it sends them
+ // hunting for the wrong problem.
+ let reason = match &e {
+ xerj_wasm::WasmError::PipelineNotRunnable { .. } => e.to_string(),
+ _ => format!("pipeline with id [{pid}] does not exist"),
+ };
items[item_idx] = Some(BulkItemResult {
action: action_type.to_string(),
index: target_index.clone(),
id: error_id.clone(),
status: 400,
result: None,
- error: Some(format!("pipeline with id [{pid}] does not exist")),
+ error: Some(reason),
get_source: None,
});
errors = true;
diff --git a/engine/crates/xerj-engine/src/engine.rs b/engine/crates/xerj-engine/src/engine.rs
index 136c30deb..ea5b82820 100644
--- a/engine/crates/xerj-engine/src/engine.rs
+++ b/engine/crates/xerj-engine/src/engine.rs
@@ -275,6 +275,14 @@ pub struct Engine {
pub scrolls: Arc<DashMap<String, ScrollContext>>,
/// pipeline_id → pipeline definition JSON
pub pipelines: Arc<DashMap<String, Value>>,
+ /// pipeline_id → why the stored definition has no compiled counterpart.
+ ///
+ /// Issue #204. A definition that carries a stage type this build does not
+ /// implement is still stored (Elasticsearch accepts it, and
+ /// `_ingest/pipeline/{id}/_simulate` still walks it), but nothing may be
+ /// ingested through it: `process_through_pipeline` refuses with the reason
+ /// recorded here instead of quietly indexing the untransformed document.
+ pub unrunnable_pipelines: Arc<DashMap<String, String>>,
/// index_name → open/closed state (true = closed)
pub closed_indices: Arc<DashMap<String, bool>>,
/// data stream name → DataStream
@@ -434,6 +442,7 @@ impl Engine {
templates: Arc::new(DashMap::new()),
scrolls: Arc::new(DashMap::new()),
pipelines: Arc::new(DashMap::new()),
+ unrunnable_pipelines: Arc::new(DashMap::new()),
closed_indices: Arc::new(DashMap::new()),
data_streams: Arc::new(DashMap::new()),
ilm_policies: Arc::new(DashMap::new()),
@@ -1677,10 +1686,34 @@ impl Engine {
let pipeline = xerj_wasm::pipeline::Pipeline::from_config(name, &cfg)?;
self.pipelines.insert(name.to_string(), config_json);
self.transform_pipelines.insert(name.to_string(), pipeline);
+ self.unrunnable_pipelines.remove(name);
info!(name, "transform pipeline created");
Ok(())
}
+ /// Store a pipeline definition that could not be compiled, together with
+ /// the reason, and make sure nothing stale is left behind.
+ ///
+ /// Issue #204. This exists for exactly one case: a definition xerj accepts
+ /// for wire compatibility (Elasticsearch does) but cannot execute, because
+ /// it names a processor this build does not implement. Storing it keeps
+ /// `GET`/`_simulate` truthful about what was submitted; recording the
+ /// reason is what stops [`Self::process_through_pipeline`] from silently
+ /// passing documents through untransformed. A previously-compiled pipeline
+ /// under the same id is REMOVED — re-defining a pipeline must not leave the
+ /// old stages quietly running under the new definition's name.
+ pub fn register_unrunnable_pipeline(&self, name: &str, definition: Value, reason: String) {
+ self.pipelines.insert(name.to_string(), definition);
+ self.transform_pipelines.remove(name);
+ self.unrunnable_pipelines
+ .insert(name.to_string(), reason.clone());
+ warn!(
+ name,
+ reason = reason.as_str(),
+ "ingest pipeline stored but NOT runnable — documents may not be ingested through it"
+ );
+ }
+
/// Run `docs` through a named pipeline, returning `(action, doc)` pairs.
///
/// Returns [`xerj_wasm::WasmError::PipelineNotFound`] when `pipeline_name`
@@ -1692,10 +1725,20 @@ impl Engine {
mut docs: Vec<Value>,
) -> std::result::Result<Vec<(xerj_wasm::pipeline::ProcessAction, Value)>, xerj_wasm::WasmError>
{
- let pipeline = self
- .transform_pipelines
- .get(pipeline_name)
- .ok_or_else(|| xerj_wasm::WasmError::PipelineNotFound(pipeline_name.to_string()))?;
+ let pipeline = self.transform_pipelines.get(pipeline_name).ok_or_else(|| {
+ // Issue #204: distinguish "no such pipeline" from "stored but this
+ // build cannot run it". Both must fail — what must not happen is a
+ // document being indexed untransformed — but reporting the second
+ // as the first sent operators hunting for a pipeline that is
+ // plainly there in `GET /_ingest/pipeline`.
+ match self.unrunnable_pipelines.get(pipeline_name) {
+ Some(reason) => xerj_wasm::WasmError::PipelineNotRunnable {
+ pipeline: pipeline_name.to_string(),
+ reason: reason.clone(),
+ },
+ None => xerj_wasm::WasmError::PipelineNotFound(pipeline_name.to_string()),
+ }
+ })?;
let actions = pipeline.process_batch(&mut docs);
Ok(actions.into_iter().zip(docs).collect())
diff --git a/engine/crates/xerj-wasm/src/lib.rs b/engine/crates/xerj-wasm/src/lib.rs
index d6bdc317f..9af56875d 100644
--- a/engine/crates/xerj-wasm/src/lib.rs
+++ b/engine/crates/xerj-wasm/src/lib.rs
@@ -52,6 +52,21 @@ pub enum WasmError {
#[error("invalid plugin config for '{plugin}': {reason}")]
InvalidConfig { plugin: String, reason: String },
+ /// The stage type is legitimate but this build does not implement it.
+ ///
+ /// Issue #204 keeps this separate from [`WasmError::InvalidConfig`]: a
+ /// caller who wrote a valid Elasticsearch processor xerj has not
+ /// implemented has not made a mistake, and must not be told they have.
+ /// What must never happen is the third option the code used to take —
+ /// accepting it and quietly running a shorter pipeline.
+ #[error("unsupported stage type '{stage}'")]
+ UnsupportedStage { stage: String },
+
+ /// The pipeline is registered but carries a stage this build cannot run,
+ /// so no document may pass through it.
+ #[error("pipeline '{pipeline}' is registered but cannot run: {reason}")]
+ PipelineNotRunnable { pipeline: String, reason: String },
+
#[error("plugin error in '{plugin}': {reason}")]
PluginError { plugin: String, reason: String },
diff --git a/engine/crates/xerj-wasm/src/pipeline.rs b/engine/crates/xerj-wasm/src/pipeline.rs
index 4395babf1..303b9d0b3 100644
--- a/engine/crates/xerj-wasm/src/pipeline.rs
+++ b/engine/crates/xerj-wasm/src/pipeline.rs
@@ -99,19 +99,27 @@ pub struct Pipeline {
impl Pipeline {
/// Build a [`Pipeline`] from a [`PipelineConfig`].
///
- /// Returns [`WasmError::InvalidConfig`] if an unknown stage type is
- /// encountered or a plugin-specific config is malformed.
+ /// Returns [`WasmError::InvalidConfig`] when a plugin-specific config is
+ /// malformed, and [`WasmError::UnsupportedStage`] when the stage type
+ /// itself is one xerj does not implement.
+ ///
+ /// Those two are deliberately distinct (issue #204). A malformed config is
+ /// a caller error and the definition must be refused. An unimplemented
+ /// stage type is a *xerj capability gap*: the caller wrote something
+ /// legitimate that we cannot run, and the honest answer is to say so at the
+ /// point of use rather than pretend either way.
pub fn from_config(name: impl Into<String>, config: &PipelineConfig) -> Result<Self> {
let name = name.into();
let mut stages: Vec<Arc<dyn TransformPlugin>> = Vec::new();
for stage_cfg in &config.stages {
let plugin =
- build_plugin(&stage_cfg.stage_type, &stage_cfg.config).map_err(|reason| {
- WasmError::InvalidConfig {
+ build_plugin(&stage_cfg.stage_type, &stage_cfg.config).map_err(|e| match e {
+ StageBuildError::Unsupported(stage) => WasmError::UnsupportedStage { stage },
+ StageBuildError::Config(reason) => WasmError::InvalidConfig {
plugin: stage_cfg.stage_type.clone(),
reason,
- }
+ },
})?;
stages.push(plugin);
}
@@ -181,11 +189,31 @@ impl std::fmt::Debug for Pipeline {
// ── Plugin factory ────────────────────────────────────────────────────────────
+/// Why [`build_plugin`] refused a stage.
+///
+/// Split in two on purpose (issue #204): `Config` is the caller's mistake and
+/// must be refused at definition time; `Unsupported` is xerj's gap and has to
+/// be reported as such so callers are not told their processor is invalid when
+/// it is merely unimplemented here.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub(crate) enum StageBuildError {
+ /// The stage type is not implemented by this build.
+ Unsupported(String),
+ /// The stage type exists but its config cannot be honoured.
+ Config(String),
+}
+
+impl From<String> for StageBuildError {
+ fn from(reason: String) -> Self {
+ Self::Config(reason)
+ }
+}
+
/// Instantiate a built-in plugin by name.
fn build_plugin(
stage_type: &str,
config: &Value,
-) -> std::result::Result<Arc<dyn TransformPlugin>, String> {
+) -> std::result::Result<Arc<dyn TransformPlugin>, StageBuildError> {
match stage_type {
"json_parse" => {
let field = str_field(config, "field")?;
@@ -262,12 +290,13 @@ fn build_plugin(
return Err(format!(
"unknown grok pattern '{s}' (known patterns: {})",
GROK_PATTERN_NAMES.join(", ")
- ));
+ )
+ .into());
}
s.clone()
}
Some(other) => {
- return Err(format!("'pattern' must be a string, got {other}"));
+ return Err(format!("'pattern' must be a string, got {other}").into());
}
};
Ok(Arc::new(GrokPlugin::new(field, pattern_name)))
@@ -285,7 +314,8 @@ fn build_plugin(
return Err(format!(
"unknown pii type '{t}' (known types: {})",
PII_TYPE_NAMES.join(", ")
- ));
+ )
+ .into());
}
}
requested
@@ -309,7 +339,8 @@ fn build_plugin(
return Err(format!(
"unknown convert target type '{target_type}' (known types: {})",
CONVERT_TARGET_TYPES.join(", ")
- ));
+ )
+ .into());
}
Ok(Arc::new(ConvertTypePlugin::new(field, target_type)))
}
@@ -356,7 +387,7 @@ fn build_plugin(
unknown => {
warn!(stage_type = unknown, "unknown pipeline stage type");
- Err(format!("unknown stage type '{unknown}'"))
+ Err(StageBuildError::Unsupported(unknown.to_string()))
}
}
}
@@ -516,6 +547,32 @@ mod fallback_regression_tests {
)
}
+ /// A stage type this build does not implement and a stage type whose
+ /// config we refuse are different answers, and callers act on the
+ /// difference: the first is xerj's gap (accept the definition, refuse the
+ /// writes), the second is the caller's mistake (refuse the definition).
+ /// Collapsing them was what let an unimplemented processor be silently
+ /// dropped in the first place.
+ #[test]
+ fn an_unimplemented_stage_type_is_distinguishable_from_a_bad_config() {
+ let err = build("pipeline", serde_json::json!({ "name": "other" }))
+ .expect_err("unimplemented stage type must not build");
+ assert!(
+ matches!(&err, WasmError::UnsupportedStage { stage } if stage == "pipeline"),
+ "expected UnsupportedStage, got: {err:?}"
+ );
+
+ let err = build(
+ "convert",
+ serde_json::json!({ "field": "f", "type": "int" }),
+ )
+ .expect_err("bad config must not build");
+ assert!(
+ matches!(err, WasmError::InvalidConfig { .. }),
+ "a known stage with a bad config is InvalidConfig, got: {err:?}"
+ );
+ }
+
#[test]
fn unknown_pii_type_is_rejected_not_silently_unredacted() {
// Pre-fix: `social_security` matched no `wants(..)` arm, the pattern