camel_processor/idempotent_consumer.rs
1//! Idempotent Consumer EIP — outcome-aware Segment implementation.
2//!
3//! Implements the Idempotent Consumer pattern at the `OutcomePipeline` layer
4//! (one layer above Tower), so that `PipelineOutcome::Stopped` from the child
5//! sub-pipeline propagates with the Exchange intact (ADR-0024, ADR-0025).
6//!
7//! # Why Segment-mode (NOT Process-mode)
8//!
9//! `compose_pipeline()` translates `PipelineOutcome::Stopped → Ok(ex)` for
10//! Tower `Service<Exchange>` consumers. If this EIP were a Tower Service,
11//! a duplicate-detected `Stopped` would become `Ok(ex)` and downstream steps
12//! would re-process the duplicate. By implementing `OutcomePipeline` directly,
13//! the segment returns `PipelineOutcome::Completed(ex)` for duplicates and
14//! skips the child sub-pipeline entirely.
15//!
16//! # Contract C1
17//!
18//! `IdempotentRepository::contains` returns `Result<bool, CamelError>` because
19//! backends (Redis, JDBC) can have transient read failures. The segment
20//! propagates `Err` as `PipelineOutcome::Failed` — it NEVER treats a failed
21//! read as "not a duplicate."
22
23use std::collections::HashSet;
24use std::future::Future;
25use std::pin::Pin;
26use std::sync::Arc;
27use std::sync::Mutex;
28
29use camel_api::{
30 BoxValueFuture, CamelError, Exchange, IdempotentRepository, OutcomePipeline, OutcomeSegment,
31 PipelineOutcome, Value,
32};
33use camel_component_api::RuntimeObservability;
34
35/// Exchange property set to `true` when the child sub-pipeline was skipped as
36/// a duplicate (contains-hit path or eager race path).
37///
38/// Implements the spec requirement "Duplicate skips and bookkeeping failures
39/// are observable" (`openspec/changes/idemon/specs/eip-idempotency/spec.md`).
40pub const CAMEL_IDEMPOTENT_DUPLICATE: &str = "camel.idempotent.duplicate";
41
42/// Fallible message-id source for the idempotent consumer.
43///
44/// An absent key — `None` from the sync arm, or null/empty from the async arm —
45/// is resolved by the segment's [`OnMissingKey`] policy: it is never silently
46/// forwarded. This deliberately drops Apache Camel parity, where a keyless
47/// exchange bypasses idempotency silently (ADR-0099). The async arm may fail
48/// with a [`camel_api::CamelError`]; the failure fails the step before the
49/// child runs. Non-scalar values (array/object) are rejected.
50// The closure shapes are part of the published contract (mirroring
51// camel-api's source enums); keep the signatures literal.
52#[allow(clippy::type_complexity)]
53#[derive(Clone)]
54pub enum MessageIdSource {
55 /// Programmatic synchronous extractor.
56 Sync(Arc<dyn Fn(&Exchange) -> Option<String> + Send + Sync>),
57 /// Language-backed asynchronous expression.
58 Async(Arc<dyn Fn(&Exchange) -> BoxValueFuture + Send + Sync>),
59}
60
61impl MessageIdSource {
62 /// Extract the optional message id, propagating async failures.
63 pub async fn message_id(
64 &self,
65 exchange: &Exchange,
66 ) -> Result<Option<String>, camel_api::CamelError> {
67 match self {
68 // An empty string is not a usable key: treat it exactly like an
69 // absent key so it can never collide as a real key.
70 Self::Sync(f) => Ok(f(exchange).filter(|s| !s.is_empty())),
71 Self::Async(f) => {
72 let value = f(exchange).await?;
73 Ok(match value {
74 Value::Null => None,
75 Value::String(s) if s.is_empty() => None,
76 Value::String(s) => Some(s),
77 Value::Array(_) | Value::Object(_) => {
78 return Err(camel_api::CamelError::ProcessorError(
79 "message id expression returned a non-scalar value (array/object); expected a string"
80 .into(),
81 ));
82 }
83 other => Some(other.to_string()),
84 })
85 }
86 }
87 }
88}
89
90/// Policy for an exchange whose idempotency key is absent or empty.
91///
92/// Implements the spec requirement "Idempotent consumer step reservation
93/// semantics" (`openspec/changes/idemon/specs/eip-idempotency/spec.md`): a
94/// missing key is never silently forwarded, and an empty string counts as a
95/// missing key on both the synchronous and asynchronous arms.
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
97pub enum OnMissingKey {
98 /// Fail the exchange with an error naming the step and the repository;
99 /// the child sub-pipeline does not run. This is the default.
100 #[default]
101 Fail,
102 /// Log a warning and forward the exchange to the child sub-pipeline
103 /// without repository interaction.
104 Process,
105}
106
107impl OnMissingKey {
108 /// Parses the canonical/DSL `idempotent_consumer.on_missing_key` knob:
109 /// absent or `"fail"` → [`Fail`](Self::Fail), `"process"` →
110 /// [`Process`](Self::Process). Any other value fails closed naming the
111 /// field and the accepted values.
112 pub fn parse(raw: Option<&str>) -> Result<Self, CamelError> {
113 match raw {
114 None | Some("fail") => Ok(Self::Fail),
115 Some("process") => Ok(Self::Process),
116 Some(other) => Err(CamelError::Config(format!(
117 "idempotent_consumer: invalid on_missing_key '{other}'; must be \"fail\" or \"process\""
118 ))),
119 }
120 }
121}
122
123/// Keys whose eager rollback could not be completed, shared by every clone of
124/// the segment that owns them.
125///
126/// `pending` holds keys whose reservation could not be removed after a failed
127/// child run; `in_flight` holds the pending key whose removal recovery is
128/// currently owned by exactly one clone, and spans the recovery from the
129/// ownership take until the key's reservation step resolves (ADR-0099,
130/// `openspec/changes/idemon/specs/eip-idempotency/spec.md`).
131///
132/// Every access is a single critical section: the lock is taken, mutated, and
133/// dropped — it is never held across an `.await` (the segment runs as a `Send`
134/// future).
135#[derive(Default)]
136struct PendingRollbacks {
137 pending: HashSet<String>,
138 in_flight: HashSet<String>,
139}
140
141/// Outcome-aware Idempotent Consumer segment.
142///
143/// Wraps a child sub-pipeline (`OutcomeSegment`) and a named
144/// `IdempotentRepository`. On each exchange:
145///
146/// 1. Extract message-id via `message_id(&exchange)`. `None` → resolve the
147/// exchange through `on_missing_key` ([`OnMissingKey::Fail`] fails the step,
148/// [`OnMissingKey::Process`] warns and forwards to the child).
149/// 2. Pending-rollback recovery, before any repository read: a key already
150/// in flight fails loudly; a pending key is taken atomically and its
151/// removal retried. On removal failure the key returns to pending and the
152/// step fails with the removal error.
153/// 3. Check `repo.contains(&key)`:
154/// - `Ok(true)` → duplicate, return `Completed(exchange)` (skip child).
155/// - `Ok(false)` → proceed.
156/// - `Err(e)` → `Failed(e)` (contract C1).
157/// 4. If `eager`: `repo.add(&key)` before child. `Ok(false)` = race duplicate
158/// → `Completed`. `Err` → `Failed`.
159/// 5. Run child pipeline.
160/// 6. Post-child:
161/// - `Completed` + non-eager → `repo.add(&key)` (best-effort).
162/// - `Stopped` → no add (pipeline terminating).
163/// - `Failed` + `eager` + `remove_on_failure` → `repo.remove(&key)`; a
164/// failed removal queues the key for pending-rollback recovery.
165///
166/// The in-flight marker is cleared as soon as the reservation step resolves
167/// (the pre-child `add` in eager mode, the post-child `add`/no-add in lazy
168/// mode), so a settled key never remains in flight.
169///
170/// # Eager mode + Stopped
171///
172/// In eager mode, the key is added BEFORE the child pipeline runs. If the child
173/// returns `Stopped`, the key remains registered — subsequent deliveries of the
174/// same message ID are treated as duplicates and return `Completed` immediately.
175/// This is intentional: a Stop indicates the route chose to terminate, and
176/// re-processing the same message would be incorrect.
177pub struct IdempotentConsumerSegment {
178 repository: Arc<dyn IdempotentRepository>,
179 message_id: MessageIdSource,
180 child_pipeline: OutcomeSegment,
181 eager: bool,
182 remove_on_failure: bool,
183 on_missing_key: OnMissingKey,
184 rt: Arc<dyn RuntimeObservability>,
185 rollback_state: Arc<Mutex<PendingRollbacks>>,
186}
187
188impl IdempotentConsumerSegment {
189 /// Build a new segment from a resolved repository, message-id extractor,
190 /// child sub-pipeline, and behaviour flags.
191 pub fn new(
192 repository: Arc<dyn IdempotentRepository>,
193 message_id: MessageIdSource,
194 child_pipeline: OutcomeSegment,
195 eager: bool,
196 remove_on_failure: bool,
197 on_missing_key: OnMissingKey,
198 rt: Arc<dyn RuntimeObservability>,
199 ) -> Self {
200 Self {
201 repository,
202 message_id,
203 child_pipeline,
204 eager,
205 remove_on_failure,
206 on_missing_key,
207 rt,
208 rollback_state: Arc::new(Mutex::new(PendingRollbacks::default())),
209 }
210 }
211
212 /// Drop the in-flight marker for `key`, if set.
213 ///
214 /// Called at every resolution point of the reservation step (fail paths
215 /// and success paths alike): a marker left behind would wedge every later
216 /// delivery of that key into the recovery-in-progress error.
217 fn clear_in_flight(&self, key: &str) {
218 self.lock_rollback_state().in_flight.remove(key);
219 }
220
221 /// Lock the shared rollback state, recovering it if a previous holder
222 /// panicked (a poisoned `HashSet` is still a consistent set).
223 fn lock_rollback_state(&self) -> std::sync::MutexGuard<'_, PendingRollbacks> {
224 self.rollback_state
225 .lock()
226 .unwrap_or_else(|e| e.into_inner())
227 }
228}
229
230impl Clone for IdempotentConsumerSegment {
231 fn clone(&self) -> Self {
232 Self {
233 repository: Arc::clone(&self.repository),
234 message_id: self.message_id.clone(),
235 child_pipeline: self.child_pipeline.clone(),
236 eager: self.eager,
237 remove_on_failure: self.remove_on_failure,
238 on_missing_key: self.on_missing_key,
239 rt: Arc::clone(&self.rt),
240 rollback_state: Arc::clone(&self.rollback_state),
241 }
242 }
243}
244
245impl OutcomePipeline for IdempotentConsumerSegment {
246 fn clone_box(&self) -> Box<dyn OutcomePipeline> {
247 Box::new(self.clone())
248 }
249
250 fn run<'a>(
251 &'a mut self,
252 exchange: Exchange,
253 ) -> Pin<Box<dyn Future<Output = PipelineOutcome> + Send + 'a>> {
254 Box::pin(async move {
255 // 1. Extract message-id. A missing key is resolved by the
256 // on_missing_key policy; a failed evaluation fails the step
257 // (contract C1).
258 let key = match self.message_id.message_id(&exchange).await {
259 Ok(Some(k)) => k,
260 Ok(None) => match self.on_missing_key {
261 OnMissingKey::Fail => {
262 return PipelineOutcome::Failed(CamelError::ProcessorError(format!(
263 "idempotent_consumer: no idempotency key on the exchange and on_missing_key is 'fail' (repository '{}')",
264 self.repository.name()
265 )));
266 }
267 OnMissingKey::Process => {
268 tracing::warn!(
269 repository = %self.repository.name(),
270 "idempotent_consumer: no idempotency key on the exchange; processing without idempotency (on_missing_key = 'process')"
271 );
272 return self.child_pipeline.run(exchange).await;
273 }
274 },
275 Err(e) => return PipelineOutcome::Failed(e),
276 };
277
278 // 2. Pending-rollback recovery (spec Requirement "Failed rollback
279 // fails the exchange and recovery is single-owner"): before any
280 // repository read, a key already under recovery fails loudly and
281 // a pending key is taken by exactly one clone. One critical
282 // section decides ownership; the guard is dropped before the
283 // removal `.await`.
284 let recovery_owner = {
285 let mut state = self.lock_rollback_state();
286 if state.in_flight.contains(&key) {
287 return PipelineOutcome::Failed(CamelError::ProcessorError(format!(
288 "idempotent_consumer: key is under pending-rollback recovery (repository '{}')",
289 self.repository.name()
290 )));
291 }
292 if state.pending.remove(&key) {
293 state.in_flight.insert(key.clone());
294 true
295 } else {
296 false
297 }
298 };
299
300 if recovery_owner {
301 match self.repository.remove(&key).await {
302 Ok(()) => {
303 // The in-flight marker stays held: this clone owns the
304 // recovery until its reservation step resolves (step 4
305 // below).
306 }
307 Err(remove_err) => {
308 {
309 let mut state = self.lock_rollback_state();
310 state.in_flight.remove(&key);
311 state.pending.insert(key.clone());
312 }
313 return PipelineOutcome::Failed(remove_err);
314 }
315 }
316 }
317
318 // 3. Check repository (contract C1: propagate Err, never treat as non-duplicate).
319 match self.repository.contains(&key).await {
320 Ok(true) => {
321 self.clear_in_flight(&key);
322 let mut exchange = exchange;
323 exchange.set_property(CAMEL_IDEMPOTENT_DUPLICATE, Value::Bool(true));
324 // allow-open-label rc-36ujy (repository: user-declared idempotent repository name)
325 self.rt.metrics().record_counter(
326 "camel.idempotent.duplicates",
327 1.0_f64,
328 &[("repository", self.repository.name())],
329 );
330 return PipelineOutcome::Completed(exchange);
331 }
332 Ok(false) => {}
333 Err(e) => {
334 self.clear_in_flight(&key);
335 return PipelineOutcome::Failed(e);
336 }
337 }
338
339 // 4. Eager mode: reserve the key before running the child.
340 if self.eager {
341 match self.repository.add(&key).await {
342 Ok(true) => {
343 // Reservation resolved: the marker's span ends here.
344 self.clear_in_flight(&key);
345 }
346 Ok(false) => {
347 // Race duplicate: a concurrent delivery reserved first.
348 self.clear_in_flight(&key);
349 let mut exchange = exchange;
350 exchange.set_property(CAMEL_IDEMPOTENT_DUPLICATE, Value::Bool(true));
351 // allow-open-label rc-36ujy (repository: user-declared idempotent repository name)
352 self.rt.metrics().record_counter(
353 "camel.idempotent.duplicates",
354 1.0_f64,
355 &[("repository", self.repository.name())],
356 );
357 return PipelineOutcome::Completed(exchange);
358 }
359 Err(e) => {
360 self.clear_in_flight(&key);
361 return PipelineOutcome::Failed(e);
362 }
363 }
364 }
365
366 // 5. Run child sub-pipeline.
367 let outcome = self.child_pipeline.run(exchange).await;
368
369 // 6. Post-child bookkeeping (best-effort; log transient errors).
370 match &outcome {
371 PipelineOutcome::Completed(_) if !self.eager => {
372 if let Err(e) = self.repository.add(&key).await {
373 // log-policy: system-broken
374 tracing::error!(
375 error = %e,
376 repository = %self.repository.name(),
377 key = %key,
378 "idempotent repository add failed post-success; next delivery may re-process"
379 );
380 // allow-open-label rc-36ujy (repository: user-declared idempotent repository name)
381 self.rt.metrics().record_counter(
382 "camel.idempotent.add_failures",
383 1.0_f64,
384 &[("repository", self.repository.name())],
385 );
386 }
387 }
388 PipelineOutcome::Failed(child_err) if self.eager && self.remove_on_failure => {
389 if let Err(remove_err) = self.repository.remove(&key).await {
390 {
391 let mut state = self.lock_rollback_state();
392 // defensive: in eager mode the marker was already cleared at add resolution
393 state.in_flight.remove(&key);
394 state.pending.insert(key.clone());
395 }
396 // log-policy: system-broken
397 tracing::error!(
398 child_error = %child_err,
399 rollback_error = %remove_err,
400 repository = %self.repository.name(),
401 key = %key,
402 "idempotent repository remove failed on failure rollback; key is queued for pending-rollback recovery"
403 );
404 }
405 }
406 _ => {}
407 }
408
409 // Lazy mode: the in-flight marker spans the post-child bookkeeping
410 // (add success, add failure with the success kept, or a non-success
411 // outcome where no add happens) and ends here.
412 if !self.eager {
413 self.clear_in_flight(&key);
414 }
415
416 outcome
417 })
418 }
419}
420
421#[cfg(test)]
422#[path = "idempotent_consumer_tests.rs"]
423mod tests;