Skip to main content

camel_processor/
claim_check.rs

1//! Claim Check EIP processor.
2//!
3//! Stashes the message body into a `ClaimCheckRepository` and replaces it with
4//! a lightweight key reference (text body containing the key). Later steps can
5//! retrieve (Get) or retrieve+remove (GetAndRemove) the body, or use LIFO
6//! stack operations (Push/Pop).
7//!
8//! # Process mode
9//!
10//! This is a **Process-mode** Tower `Service<Exchange>` — transforms the body
11//! in place, no child sub-pipeline. No `StepLifecycle` (holds only
12//! `Arc<dyn ClaimCheckRepository>`, no background work).
13
14use std::future::Future;
15use std::pin::Pin;
16use std::sync::Arc;
17use std::task::{Context, Poll};
18
19use tower::Service;
20
21use camel_api::body::Body;
22use camel_api::{
23    BoxValueFuture, CamelError, ClaimCheckRepository, Exchange, Headers, Message,
24    PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value,
25};
26
27/// Fallible claim-check key source.
28///
29/// The sync arm returns an error when the key cannot be resolved. The async
30/// arm evaluates to a [`Value`]: null/empty values are a validation error,
31/// strings pass through, other scalars are stringified, and non-scalar
32/// values (array/object) are rejected. Evaluation failures propagate
33/// BEFORE any repository mutation.
34// The closure shapes are part of the published contract (mirroring
35// camel-api's source enums); keep the signatures literal.
36#[allow(clippy::type_complexity)]
37#[derive(Clone)]
38pub enum ClaimKeySource {
39    /// Programmatic synchronous extractor.
40    Sync(Arc<dyn Fn(&Exchange) -> Result<String, CamelError> + Send + Sync>),
41    /// Language-backed asynchronous expression.
42    Async(Arc<dyn Fn(&Exchange) -> BoxValueFuture + Send + Sync>),
43}
44
45impl ClaimKeySource {
46    /// Resolve the claim-check key, propagating failures.
47    pub async fn key(&self, exchange: &Exchange) -> Result<String, CamelError> {
48        match self {
49            Self::Sync(f) => f(exchange),
50            Self::Async(f) => {
51                let value = f(exchange).await?;
52                match value {
53                    Value::Null => Err(claim_key_null_or_empty()),
54                    Value::String(s) if s.is_empty() => Err(claim_key_null_or_empty()),
55                    Value::String(s) => Ok(s),
56                    Value::Array(_) | Value::Object(_) => {
57                        Err(CamelError::ProcessorError(
58                            "claim_check key expression returned a non-scalar value (array/object); expected a string key".into(),
59                        ))
60                    }
61                    other => Ok(other.to_string()),
62                }
63            }
64        }
65    }
66}
67
68fn claim_key_null_or_empty() -> CamelError {
69    CamelError::ValidationError("claim_check key expression evaluated to null or empty".into())
70}
71
72/// Claim Check operation variant.
73#[derive(Clone, Debug, PartialEq, Eq)]
74pub enum ClaimCheckOp {
75    /// Stash the body in the repository; replace exchange body with key reference.
76    Set,
77    /// Retrieve the body from the repository by key; replace exchange body.
78    Get,
79    /// Retrieve and remove in one atomic step.
80    GetAndRemove,
81    /// Push current body onto a LIFO stack for this key; replace body with key reference.
82    Push,
83    /// Pop body from a LIFO stack for this key; replace exchange body.
84    Pop,
85}
86
87/// Claim Check EIP processor.
88///
89/// Transforms the exchange body to/from a `ClaimCheckRepository` using the
90/// configured operation and key expression. An optional `filter` controls
91/// which parts of the stashed Message are merged back during checkout
92/// operations (Get/GetAndRemove/Pop).
93#[derive(Clone)]
94pub struct ClaimCheckService {
95    repository: Arc<dyn ClaimCheckRepository>,
96    operation: ClaimCheckOp,
97    key_expression: ClaimKeySource,
98    filter: Option<ClaimCheckFilter>,
99}
100
101impl std::fmt::Debug for ClaimCheckService {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        f.debug_struct("ClaimCheckService")
104            .field("repository", &self.repository.name())
105            .field("operation", &self.operation)
106            .field("filter", &self.filter)
107            .finish()
108    }
109}
110
111impl ClaimCheckService {
112    /// Create a new `ClaimCheckService` without a filter.
113    pub fn new(
114        repository: Arc<dyn ClaimCheckRepository>,
115        operation: ClaimCheckOp,
116        key_expression: ClaimKeySource,
117    ) -> Self {
118        Self {
119            repository,
120            operation,
121            key_expression,
122            filter: None,
123        }
124    }
125
126    /// Attach a filter for selective merge-back during checkout operations.
127    pub fn with_filter(mut self, filter: ClaimCheckFilter) -> Self {
128        self.filter = Some(filter);
129        self
130    }
131}
132
133/// Merge cached headers from a stashed message into the current message
134/// according to filter rules. Called from the async `call` future with
135/// all data cloned in advance.
136///
137/// Also clears `PROPERTY_HTTP_CONTENT_TYPE_INHERITED` whenever the applied
138/// headers action lands or drops a `Content-Type` key, because the restored
139/// value no longer proves inherited provenance.
140fn merge_stashed(exchange: &mut Exchange, stashed: &Message, filter: &ClaimCheckFilter) {
141    let current = &mut exchange.input;
142
143    match filter.body {
144        FilterAction::Include => current.body = stashed.body.clone(),
145        FilterAction::Exclude => {}
146        FilterAction::Remove => current.body = Body::Empty,
147    }
148
149    let clears_marker = match &filter.headers_action {
150        HeadersAction::All(action) => match action {
151            FilterAction::Include => {
152                for (k, v) in &stashed.headers {
153                    current.headers.insert(k.clone(), v.clone());
154                }
155                stashed.headers.keys().any(|k| is_content_type_key(k))
156            }
157            FilterAction::Exclude => false,
158            FilterAction::Remove => {
159                current.headers.clear();
160                true
161            }
162        },
163        HeadersAction::ByPattern {
164            include,
165            exclude,
166            remove,
167        } => {
168            let clears_marker = action_touches_content_type(
169                include,
170                exclude,
171                remove,
172                &stashed.headers,
173                &current.headers,
174            );
175
176            if !include.is_empty() {
177                for (k, v) in &stashed.headers {
178                    if include.iter().any(|p| p.matches(k)) {
179                        current.headers.insert(k.clone(), v.clone());
180                    }
181                }
182            }
183            if !exclude.is_empty() {
184                for (k, v) in &stashed.headers {
185                    if !exclude.iter().any(|p| p.matches(k)) {
186                        current.headers.insert(k.clone(), v.clone());
187                    }
188                }
189            }
190            if !remove.is_empty() {
191                current
192                    .headers
193                    .retain(|k, _| !remove.iter().any(|p| p.matches(k)));
194            }
195
196            clears_marker
197        }
198    };
199
200    if clears_marker {
201        exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
202    }
203}
204
205fn is_content_type_key(key: &str) -> bool {
206    key.eq_ignore_ascii_case("content-type")
207}
208
209/// Predicate for [`HeadersAction::ByPattern`]: does applying the pattern set
210/// land or drop a `Content-Type` key?
211///
212/// Side-effect free; must be called before the header mutation so that
213/// `current_headers` reflects what the `remove` patterns act on.
214fn action_touches_content_type(
215    include: &[HeaderPattern],
216    exclude: &[HeaderPattern],
217    remove: &[HeaderPattern],
218    stashed_headers: &Headers,
219    current_headers: &Headers,
220) -> bool {
221    if !include.is_empty()
222        && stashed_headers
223            .keys()
224            .any(|k| is_content_type_key(k) && include.iter().any(|p| p.matches(k)))
225    {
226        return true;
227    }
228
229    if !exclude.is_empty()
230        && stashed_headers
231            .keys()
232            .any(|k| is_content_type_key(k) && !exclude.iter().any(|p| p.matches(k)))
233    {
234        return true;
235    }
236
237    if !remove.is_empty()
238        && current_headers
239            .keys()
240            .any(|k| is_content_type_key(k) && remove.iter().any(|p| p.matches(k)))
241    {
242        return true;
243    }
244
245    false
246}
247
248impl Service<Exchange> for ClaimCheckService {
249    type Response = Exchange;
250    type Error = CamelError;
251    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
252
253    fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
254        Poll::Ready(Ok(()))
255    }
256
257    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
258        let repository = self.repository.clone();
259        let operation = self.operation.clone();
260        let key_source = self.key_expression.clone();
261        let filter = self.filter.clone();
262
263        Box::pin(async move {
264            // Key resolution happens FIRST: an evaluation error propagates
265            // before any repository mutation.
266            let key = key_source.key(&exchange).await?;
267            match operation {
268                ClaimCheckOp::Set => {
269                    let stashed = exchange.input.clone();
270                    repository.set(&key, stashed).await?;
271                    exchange.input.body = Body::Text(key);
272                    Ok(exchange)
273                }
274                ClaimCheckOp::Get => {
275                    let stashed = repository.get(&key).await?;
276                    if let Some(ref f) = filter {
277                        merge_stashed(&mut exchange, &stashed, f);
278                    } else {
279                        exchange.input.body = stashed.body;
280                    }
281                    Ok(exchange)
282                }
283                ClaimCheckOp::GetAndRemove => {
284                    let stashed = repository.get_and_remove(&key).await?;
285                    if let Some(ref f) = filter {
286                        merge_stashed(&mut exchange, &stashed, f);
287                    } else {
288                        exchange.input.body = stashed.body;
289                    }
290                    Ok(exchange)
291                }
292                ClaimCheckOp::Push => {
293                    let stashed = exchange.input.clone();
294                    repository.push(&key, stashed).await?;
295                    exchange.input.body = Body::Text(key);
296                    Ok(exchange)
297                }
298                ClaimCheckOp::Pop => {
299                    let stashed = repository.pop(&key).await?;
300                    if let Some(ref f) = filter {
301                        merge_stashed(&mut exchange, &stashed, f);
302                    } else {
303                        exchange.input.body = stashed.body;
304                    }
305                    Ok(exchange)
306                }
307            }
308        })
309    }
310}
311
312fn has_regex_metachars(s: &str) -> bool {
313    s.contains(['^', '$', '(', ')', '[', ']', '{', '}', '|', '+', '.', '\\'])
314}
315
316#[derive(Debug, Clone)]
317pub enum HeaderPattern {
318    All,
319    Prefix(String),
320    Exact(String),
321    Regex(regex::Regex),
322}
323
324impl PartialEq for HeaderPattern {
325    fn eq(&self, other: &Self) -> bool {
326        match (self, other) {
327            (Self::All, Self::All) => true,
328            (Self::Prefix(a), Self::Prefix(b)) => a == b,
329            (Self::Exact(a), Self::Exact(b)) => a == b,
330            (Self::Regex(a), Self::Regex(b)) => a.as_str() == b.as_str(),
331            _ => false,
332        }
333    }
334}
335
336impl HeaderPattern {
337    fn compile(pattern: &str) -> Result<Self, FilterParseError> {
338        if pattern == "*" {
339            return Ok(Self::All);
340        }
341        if let Some(prefix) = pattern.strip_suffix('*') {
342            return Ok(Self::Prefix(prefix.to_string()));
343        }
344        if has_regex_metachars(pattern) {
345            match regex::Regex::new(pattern) {
346                Ok(re) => Ok(Self::Regex(re)),
347                Err(_) => Err(FilterParseError::InvalidPattern(pattern.to_string())),
348            }
349        } else {
350            Ok(Self::Exact(pattern.to_string()))
351        }
352    }
353
354    fn matches(&self, header_key: &str) -> bool {
355        match self {
356            Self::All => true,
357            Self::Prefix(prefix) => header_key.starts_with(prefix),
358            Self::Exact(exact) => header_key == exact,
359            Self::Regex(re) => re.is_match(header_key),
360        }
361    }
362}
363
364#[derive(Debug, Clone, PartialEq)]
365pub struct ClaimCheckFilter {
366    pub body: FilterAction,
367    pub headers_action: HeadersAction,
368}
369
370#[derive(Debug, Clone, Copy, PartialEq, Eq)]
371pub enum FilterAction {
372    Include,
373    Exclude,
374    Remove,
375}
376
377#[derive(Debug, Clone, PartialEq)]
378pub enum HeadersAction {
379    All(FilterAction),
380    ByPattern {
381        include: Vec<HeaderPattern>,
382        exclude: Vec<HeaderPattern>,
383        remove: Vec<HeaderPattern>,
384    },
385}
386
387#[derive(Debug)]
388pub enum FilterParseError {
389    InvalidToken(String),
390    InvalidPattern(String),
391    MixedIncludeExclude,
392}
393
394impl std::fmt::Display for FilterParseError {
395    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
396        match self {
397            Self::InvalidToken(tok) => write!(f, "invalid filter segment '{tok}'"),
398            Self::InvalidPattern(pat) => write!(f, "invalid header pattern '{pat}'"),
399            Self::MixedIncludeExclude => {
400                write!(f, "cannot mix include (+) and exclude (-) header patterns")
401            }
402        }
403    }
404}
405
406impl ClaimCheckFilter {
407    /// Parse a Camel 4.x filter string into structured rules.
408    /// `attachments` tokens are accepted as no-op but do not affect body/headers defaults.
409    pub fn parse(input: &str) -> Result<Self, FilterParseError> {
410        let mut body_action: Option<FilterAction> = None;
411        let mut headers_action: Option<HeadersAction> = None;
412        let mut has_positive_include = false;
413
414        for token in input.split(',') {
415            let token = token.trim();
416            if token.is_empty() {
417                continue;
418            }
419
420            let (prefix, rule) = if let Some(rest) = token.strip_prefix("--") {
421                (FilterAction::Remove, rest)
422            } else if let Some(rest) = token.strip_prefix('-') {
423                (FilterAction::Exclude, rest)
424            } else {
425                let rest = token.strip_prefix('+').unwrap_or(token);
426                (FilterAction::Include, rest)
427            };
428
429            match rule {
430                "body" => {
431                    if prefix == FilterAction::Include {
432                        has_positive_include = true;
433                    }
434                    body_action = Some(prefix);
435                }
436                "headers" | "header" => {
437                    if prefix == FilterAction::Include {
438                        has_positive_include = true;
439                    }
440                    headers_action = Some(HeadersAction::All(prefix));
441                }
442                "attachments" | "attachment" => {
443                    // Accepted as no-op; never affects has_positive_include or defaults
444                }
445                r if r.starts_with("header:") || r.starts_with("headers:") => {
446                    let (_, pattern_str) = r
447                        .split_once(':')
448                        .ok_or_else(|| FilterParseError::InvalidToken(r.to_string()))?;
449                    let pattern = HeaderPattern::compile(pattern_str)?;
450
451                    if prefix == FilterAction::Include {
452                        has_positive_include = true;
453                    }
454
455                    let (mut include, mut exclude, mut remove) = match headers_action.take() {
456                        Some(HeadersAction::ByPattern {
457                            include,
458                            exclude,
459                            remove,
460                        }) => (include, exclude, remove),
461                        _ => (vec![], vec![], vec![]),
462                    };
463                    match prefix {
464                        FilterAction::Include => {
465                            if !exclude.is_empty() {
466                                return Err(FilterParseError::MixedIncludeExclude);
467                            }
468                            include.push(pattern);
469                        }
470                        FilterAction::Exclude => {
471                            if !include.is_empty() {
472                                return Err(FilterParseError::MixedIncludeExclude);
473                            }
474                            exclude.push(pattern);
475                        }
476                        FilterAction::Remove => remove.push(pattern),
477                    }
478                    headers_action = Some(HeadersAction::ByPattern {
479                        include,
480                        exclude,
481                        remove,
482                    });
483                }
484                other => return Err(FilterParseError::InvalidToken(other.to_string())),
485            }
486        }
487
488        let default_if_omitted = if has_positive_include {
489            FilterAction::Exclude
490        } else {
491            FilterAction::Include
492        };
493
494        Ok(ClaimCheckFilter {
495            body: body_action.unwrap_or(default_if_omitted),
496            headers_action: headers_action.unwrap_or(HeadersAction::All(default_if_omitted)),
497        })
498    }
499}
500
501#[cfg(test)]
502#[path = "claim_check_tests.rs"]
503mod tests;