camel-api 0.21.0

Core traits and interfaces for rust-camel
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
use std::any::Any;
use std::collections::HashMap;
use std::sync::Arc;

use opentelemetry::Context;
use uuid::Uuid;

use crate::error::CamelError;
use crate::from_body::FromBody;
use crate::message::Message;
use crate::value::Value;

/// Extension key used by use_original_message: stashes the pre-route Message
/// so the error handler can restore body+headers before DLC dispatch.
pub const ORIGINAL_MESSAGE_EXTENSION: &str = "CamelOriginalMessage";

/// Pipeline-executor-recognized stop signal. Set by processors (ThrottleStrategy::Drop,
/// SamplingService) that cannot return PipelineOutcome::Stopped directly because they
/// are Tower Service<Exchange> (Process mode), not OutcomePipeline (Segment).
/// The executor checks this after each step completion. See ADR-0024 amendment.
pub const CAMEL_STOP: &str = "CamelStop";

/// Check whether the exchange carries the CamelStop signal.
///
/// Returns `true` if the `CamelStop` property is set to a boolean `true` value.
/// Used by the pipeline executor (`run_steps`) and segment adapters to detect
/// Process-mode processors that cannot return `PipelineOutcome::Stopped` directly.
pub fn is_camel_stop(exchange: &Exchange) -> bool {
    exchange
        .property(CAMEL_STOP)
        .and_then(|v| v.as_bool())
        .unwrap_or(false)
}

/// Property key for the exception message (error Display string).
pub const PROPERTY_EXCEPTION_MESSAGE: &str = "CamelExceptionMessage";
/// Property key for the exception kind (error variant name via classify()).
pub const PROPERTY_EXCEPTION_KIND: &str = "CamelExceptionKind";
/// Property key for the caught exception (Java Camel parity alias).
pub const PROPERTY_EXCEPTION_CAUGHT: &str = "CamelExceptionCaught";
/// Property key set when an exception has been handled (Java Camel parity).
pub const PROPERTY_EXCEPTION_HANDLED: &str = "CamelExceptionHandled";

/// The exchange pattern (fire-and-forget or request-reply).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExchangePattern {
    /// Fire-and-forget: message sent, no reply expected.
    #[default]
    InOnly,
    /// Request-reply: message sent, reply expected.
    InOut,
}

/// An Exchange represents a message being routed through the framework.
///
/// It contains the input message, an optional output message,
/// properties for passing data between processors, and error state.
#[derive(Debug)]
pub struct Exchange {
    /// The input (incoming) message.
    pub input: Message,
    /// The output (response) message, populated for InOut patterns.
    pub output: Option<Message>,
    /// Exchange-scoped properties for passing data between processors.
    pub properties: HashMap<String, Value>,
    /// Non-serializable extension values (e.g., channel senders).
    /// Stored as `Arc<dyn Any + Send + Sync>` so cloning is cheap (ref-count bump).
    pub extensions: HashMap<String, Arc<dyn Any + Send + Sync>>,
    /// Error state, if processing failed.
    pub error: Option<CamelError>,
    /// The exchange pattern.
    pub pattern: ExchangePattern,
    /// Unique correlation ID for distributed tracing.
    pub correlation_id: String,
    /// OpenTelemetry context for distributed tracing propagation.
    /// Carries the active span context between processing steps.
    /// Defaults to an empty context (noop span) if OTel is not active.
    pub otel_context: Context,
}

impl Exchange {
    /// Create a new exchange with the given input message.
    pub fn new(input: Message) -> Self {
        Self {
            input,
            output: None,
            properties: HashMap::new(),
            extensions: HashMap::new(),
            error: None,
            pattern: ExchangePattern::default(),
            correlation_id: Uuid::new_v4().to_string(),
            otel_context: Context::new(),
        }
    }

    /// Create a new exchange with the InOut pattern.
    pub fn new_in_out(input: Message) -> Self {
        Self {
            input,
            output: None,
            properties: HashMap::new(),
            extensions: HashMap::new(),
            error: None,
            pattern: ExchangePattern::InOut,
            correlation_id: Uuid::new_v4().to_string(),
            otel_context: Context::new(),
        }
    }

    /// Get the correlation ID for this exchange.
    pub fn correlation_id(&self) -> &str {
        &self.correlation_id
    }

    /// Get a property value.
    pub fn property(&self, key: &str) -> Option<&Value> {
        self.properties.get(key)
    }

    /// Set a property value.
    pub fn set_property(&mut self, key: impl Into<String>, value: impl Into<Value>) {
        self.properties.insert(key.into(), value.into());
    }

    /// Check if the exchange has an error.
    pub fn has_error(&self) -> bool {
        self.error.is_some()
    }

    /// Set an error on this exchange.
    ///
    /// Automatically populates exchange properties with error context so that
    /// all languages can access error information via their property mechanisms:
    /// - `CamelExceptionMessage` — the error's Display string
    /// - `CamelExceptionKind` — the error variant name (via `CamelError::classify()`)
    /// - `CamelExceptionCaught` — alias for Java Camel parity
    pub fn set_error(&mut self, error: CamelError) {
        let msg = error.to_string();
        let kind = error.classify().to_string();
        self.properties.insert(
            PROPERTY_EXCEPTION_MESSAGE.to_string(),
            Value::String(msg.clone()),
        );
        self.properties
            .insert(PROPERTY_EXCEPTION_KIND.to_string(), Value::String(kind));
        self.properties
            .insert(PROPERTY_EXCEPTION_CAUGHT.to_string(), Value::String(msg));
        self.error = Some(error);
    }

    /// Clear the error and remove all exception properties.
    ///
    /// Called after `handled:true` in on_exception steps to prevent stale
    /// error state from leaking into subsequent processing.
    pub fn clear_error(&mut self) {
        self.error = None;
        self.properties.remove(PROPERTY_EXCEPTION_MESSAGE);
        self.properties.remove(PROPERTY_EXCEPTION_KIND);
        self.properties.remove(PROPERTY_EXCEPTION_CAUGHT);
    }

    /// Mark the exception as handled and clear the error.
    ///
    /// Sets `CamelExceptionHandled = true` then calls `clear_error()`.
    /// This matches Java Camel's `Exchange.EXCEPTION_HANDLED` semantics.
    pub fn handle_error(&mut self) {
        self.properties
            .insert(PROPERTY_EXCEPTION_HANDLED.to_string(), Value::Bool(true));
        self.clear_error();
    }

    /// Store a non-serializable extension value (e.g. a channel sender).
    pub fn set_extension(&mut self, key: impl Into<String>, value: Arc<dyn Any + Send + Sync>) {
        self.extensions.insert(key.into(), value);
    }

    /// Retrieve a typed extension value. Returns `None` if the key is absent
    /// or the stored value is not of type `T`.
    pub fn get_extension<T: Any>(&self, key: &str) -> Option<&T> {
        self.extensions.get(key)?.downcast_ref::<T>()
    }

    /// Deserialize the body into type `T`.
    ///
    /// Uses built-in conversions for `String`, `Vec<u8>`, [`bytes::Bytes`], and
    /// `serde_json::Value`. For custom types, implement [`FromBody`] or use
    /// [`impl_from_body_via_serde!`].
    ///
    /// # Example
    /// ```rust,ignore
    /// let text: String = exchange.body_as::<String>()?;
    /// let raw: Vec<u8> = exchange.body_as::<Vec<u8>>()?;
    /// ```
    pub fn body_as<T: FromBody>(&self) -> Result<T, CamelError> {
        T::from_body(&self.input.body)
    }
}

impl Clone for Exchange {
    fn clone(&self) -> Self {
        Self {
            input: self.input.clone(),
            output: self.output.clone(),
            properties: self.properties.clone(),
            extensions: self.extensions.clone(), // Arc ref-count bump, cheap
            error: self.error.clone(),
            pattern: self.pattern,
            correlation_id: self.correlation_id.clone(),
            otel_context: self.otel_context.clone(),
        }
    }
}

impl Default for Exchange {
    fn default() -> Self {
        Self::new(Message::default())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::Body;
    use serde_json::json;

    #[test]
    fn test_exchange_new() {
        let msg = Message::new("test");
        let ex = Exchange::new(msg);
        assert_eq!(ex.input.body.as_text(), Some("test"));
        assert!(ex.output.is_none());
        assert!(!ex.has_error());
        assert_eq!(ex.pattern, ExchangePattern::InOnly);
    }

    #[test]
    fn test_exchange_in_out() {
        let ex = Exchange::new_in_out(Message::default());
        assert_eq!(ex.pattern, ExchangePattern::InOut);
    }

    #[test]
    fn test_exchange_properties() {
        let mut ex = Exchange::default();
        ex.set_property("key", Value::Bool(true));
        assert_eq!(ex.property("key"), Some(&Value::Bool(true)));
        assert_eq!(ex.property("missing"), None);
    }

    #[test]
    fn test_exchange_error() {
        let mut ex = Exchange::default();
        assert!(!ex.has_error());
        ex.set_error(CamelError::ProcessorError("test".into()));
        assert!(ex.has_error());
    }

    #[test]
    fn test_set_error_populates_properties() {
        let mut ex = Exchange::default();
        ex.set_error(CamelError::ProcessorError("boom".into()));

        assert!(ex.has_error());
        assert_eq!(
            ex.properties.get(PROPERTY_EXCEPTION_MESSAGE),
            Some(&Value::String("Processor error: boom".to_string()))
        );
        assert_eq!(
            ex.properties.get(PROPERTY_EXCEPTION_KIND),
            Some(&Value::String("processor".to_string()))
        );
        assert_eq!(
            ex.properties.get(PROPERTY_EXCEPTION_CAUGHT),
            Some(&Value::String("Processor error: boom".to_string()))
        );
    }

    #[test]
    fn test_clear_error_removes_properties() {
        let mut ex = Exchange::default();
        ex.set_error(CamelError::RouteError("fail".into()));
        assert!(ex.has_error());
        assert!(ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE));

        ex.clear_error();

        assert!(!ex.has_error());
        assert!(!ex.properties.contains_key(PROPERTY_EXCEPTION_MESSAGE));
        assert!(!ex.properties.contains_key(PROPERTY_EXCEPTION_KIND));
        assert!(!ex.properties.contains_key(PROPERTY_EXCEPTION_CAUGHT));
    }

    #[test]
    fn test_exchange_lifecycle() {
        let mut ex = Exchange::new(Message::new("input data"));
        assert_eq!(ex.input.body.as_text(), Some("input data"));

        // Set some properties
        ex.set_property("processed", Value::Bool(true));

        // Set output
        ex.output = Some(Message::new("output data"));
        assert!(ex.output.is_some());

        // Verify no error
        assert!(!ex.has_error());
    }

    #[test]
    fn test_exchange_otel_context_default() {
        let ex = Exchange::default();
        // Field must exist and be accessible — compilation is the test
        // Also verify it's a fresh context (noop span)
        use opentelemetry::trace::TraceContextExt;
        assert!(!ex.otel_context.span().span_context().is_valid());
    }

    #[test]
    fn test_exchange_otel_context_propagates_in_clone() {
        let ex = Exchange::default();
        let cloned = ex.clone();
        // Both should have the same (empty) context
        use opentelemetry::trace::TraceContextExt;
        assert!(!cloned.otel_context.span().span_context().is_valid());
    }

    #[test]
    fn test_set_and_get_extension() {
        use std::sync::Arc;
        let mut ex = Exchange::default();
        ex.set_extension("my.key", Arc::new(42u32));
        let val: Option<&u32> = ex.get_extension("my.key");
        assert_eq!(val, Some(&42u32));
    }

    #[test]
    fn test_get_extension_wrong_type_returns_none() {
        use std::sync::Arc;
        let mut ex = Exchange::default();
        ex.set_extension("my.key", Arc::new(42u32));
        let val: Option<&String> = ex.get_extension("my.key");
        assert!(val.is_none());
    }

    #[test]
    fn test_get_extension_missing_key_returns_none() {
        let ex = Exchange::default();
        let val: Option<&u32> = ex.get_extension("nope");
        assert!(val.is_none());
    }

    #[test]
    fn test_clone_shares_extension_arc() {
        use std::sync::Arc;
        let mut ex = Exchange::default();
        ex.set_extension("shared", Arc::new(99u64));
        let cloned = ex.clone();
        // Both see the same value
        assert_eq!(ex.get_extension::<u64>("shared"), Some(&99u64));
        assert_eq!(cloned.get_extension::<u64>("shared"), Some(&99u64));
    }

    #[test]
    fn test_body_as_string_from_text() {
        let ex = Exchange::new(Message::new(Body::Text("hello".to_string())));

        let result = ex.body_as::<String>();

        assert_eq!(result.unwrap(), "hello");
    }

    #[test]
    fn test_body_as_string_from_json_string() {
        let ex = Exchange::new(Message::new(Body::Json(json!("hello"))));

        let result = ex.body_as::<String>();

        assert_eq!(result.unwrap(), "hello");
    }

    #[test]
    fn test_body_as_json_value_from_json_number() {
        let ex = Exchange::new(Message::new(Body::Json(json!(42))));

        let result = ex.body_as::<serde_json::Value>();

        assert_eq!(result.unwrap(), json!(42));
    }

    #[test]
    fn test_body_as_vec_u8_from_bytes() {
        let ex = Exchange::new(Message::new(Body::from(vec![1u8, 2, 3, 4])));

        let result = ex.body_as::<Vec<u8>>();

        assert_eq!(result.unwrap(), vec![1u8, 2, 3, 4]);
    }

    #[test]
    fn test_body_as_string_from_empty_returns_err() {
        let ex = Exchange::new(Message::new(Body::Empty));

        let result = ex.body_as::<String>();

        assert!(result.is_err());
    }
}