camel-processor 0.57.0

Message processors 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
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};

use tower::Service;

use camel_api::{CamelError, Exchange, ValueSource};

/// A processor that sets a header from a fallible [`ValueSource`].
///
/// The source is evaluated first; a failed evaluation fails the step WITHOUT
/// setting the header and WITHOUT invoking the inner service.
#[derive(Clone)]
pub struct DynamicSetHeader<P> {
    inner: P,
    key: String,
    source: ValueSource,
}

impl<P> DynamicSetHeader<P> {
    pub fn new(inner: P, key: impl Into<String>, source: impl Into<ValueSource>) -> Self {
        Self {
            inner,
            key: key.into(),
            source: source.into(),
        }
    }
}

/// A Tower Layer that wraps an inner service with a [`DynamicSetHeader`].
#[derive(Clone)]
pub struct DynamicSetHeaderLayer {
    key: String,
    source: ValueSource,
}

impl DynamicSetHeaderLayer {
    pub fn new(key: impl Into<String>, source: impl Into<ValueSource>) -> Self {
        Self {
            key: key.into(),
            source: source.into(),
        }
    }
}

impl<S> tower::Layer<S> for DynamicSetHeaderLayer {
    type Service = DynamicSetHeader<S>;

    fn layer(&self, inner: S) -> Self::Service {
        DynamicSetHeader {
            inner,
            key: self.key.clone(),
            source: self.source.clone(),
        }
    }
}

impl<P> Service<Exchange> for DynamicSetHeader<P>
where
    P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
    P::Future: Send,
{
    type Response = Exchange;
    type Error = CamelError;
    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
        let source = self.source.clone();
        let key = self.key.clone();
        // Clone-and-replace: move the polled inner into the future so the
        // async body owns its service; a fresh clone stays behind.
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);
        Box::pin(async move {
            let value = source.evaluate(&exchange).await?;
            exchange.input.headers.insert(key, value);
            inner.call(exchange).await
        })
    }
}

/// A processor that sets a header from a fallible [`ValueSource`],
/// but ONLY if the header is not already present (if-absent semantics).
/// The presence check happens BEFORE expression evaluation — if the
/// header exists, the expression is never evaluated.
#[derive(Clone)]
pub struct DynamicSetHeaderIfAbsent<P> {
    inner: P,
    key: String,
    source: ValueSource,
}

impl<P> DynamicSetHeaderIfAbsent<P> {
    pub fn new(inner: P, key: impl Into<String>, source: impl Into<ValueSource>) -> Self {
        Self {
            inner,
            key: key.into(),
            source: source.into(),
        }
    }
}

impl<P> Service<Exchange> for DynamicSetHeaderIfAbsent<P>
where
    P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
    P::Future: Send,
{
    type Response = Exchange;
    type Error = CamelError;
    type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;

    fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
        self.inner.poll_ready(cx)
    }

    fn call(&mut self, mut exchange: Exchange) -> Self::Future {
        // Check BEFORE evaluating the expression: a present header skips
        // evaluation entirely (today's semantics).
        if exchange.input.headers.contains_key(&self.key) {
            let clone = self.inner.clone();
            let mut inner = std::mem::replace(&mut self.inner, clone);
            return Box::pin(inner.call(exchange));
        }

        let source = self.source.clone();
        let key = self.key.clone();
        // Clone-and-replace: the future owns the (already polled) inner.
        let clone = self.inner.clone();
        let mut inner = std::mem::replace(&mut self.inner, clone);
        Box::pin(async move {
            let value = source.evaluate(&exchange).await?;
            exchange.input.headers.insert(key, value);
            inner.call(exchange).await
        })
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;
    use std::sync::atomic::{AtomicUsize, Ordering};

    use camel_api::{BoxValueFuture, Exchange, IdentityProcessor, Message, Value, ValueSource};
    use tower::ServiceExt;

    use super::*;

    fn sync_source<F>(f: F) -> ValueSource
    where
        F: Fn(&Exchange) -> Value + Send + Sync + 'static,
    {
        ValueSource::Sync(Arc::new(f))
    }

    fn failing_source() -> ValueSource {
        ValueSource::Async(Arc::new(|_: &Exchange| {
            Box::pin(async { Err(CamelError::ProcessorError("expr boom".into())) })
                as BoxValueFuture
        }))
    }

    /// Inner service that records how many times it was invoked.
    #[derive(Clone)]
    struct CountingInner {
        called: Arc<AtomicUsize>,
    }

    impl Service<Exchange> for CountingInner {
        type Response = Exchange;
        type Error = CamelError;
        type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;

        fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
            Poll::Ready(Ok(()))
        }

        fn call(&mut self, exchange: Exchange) -> Self::Future {
            self.called.fetch_add(1, Ordering::SeqCst);
            Box::pin(async { Ok(exchange) })
        }
    }

    #[tokio::test]
    async fn dynamic_set_header_error_propagates() {
        let called = Arc::new(AtomicUsize::new(0));
        let svc = DynamicSetHeader::new(
            CountingInner {
                called: Arc::clone(&called),
            },
            "greeting",
            failing_source(),
        );

        let result = svc.oneshot(Exchange::new(Message::new("world"))).await;

        assert!(result.is_err(), "failed evaluation must fail the step");
        assert_eq!(
            called.load(Ordering::SeqCst),
            0,
            "inner must NOT run when evaluation fails"
        );
    }

    #[tokio::test]
    async fn dynamic_set_header_if_absent_error_propagates() {
        let called = Arc::new(AtomicUsize::new(0));
        let svc = DynamicSetHeaderIfAbsent::new(
            CountingInner {
                called: Arc::clone(&called),
            },
            "greeting",
            failing_source(),
        );

        // Header absent: the expression IS evaluated and its error propagates.
        let result = svc.oneshot(Exchange::new(Message::new("world"))).await;

        assert!(result.is_err(), "failed evaluation must fail the step");
        assert_eq!(
            called.load(Ordering::SeqCst),
            0,
            "inner must NOT run when evaluation fails"
        );
    }

    #[tokio::test]
    async fn dynamic_set_header_if_absent_present_header_skips_evaluation() {
        let evals = Arc::new(AtomicUsize::new(0));
        let evals_clone = evals.clone();
        let source = ValueSource::Async(Arc::new(move |_: &Exchange| {
            evals_clone.fetch_add(1, Ordering::SeqCst);
            Box::pin(async { Ok(Value::Bool(true)) }) as BoxValueFuture
        }));

        let mut msg = Message::new("computed");
        msg.set_header("key", Value::String("original".into()));

        let svc = DynamicSetHeaderIfAbsent::new(IdentityProcessor, "key", source);
        let result = svc.oneshot(Exchange::new(msg)).await.unwrap();

        assert_eq!(
            result.input.header("key"),
            Some(&Value::String("original".into()))
        );
        assert_eq!(
            evals.load(Ordering::SeqCst),
            0,
            "expression must NOT be evaluated when the header is already present"
        );
    }

    #[tokio::test]
    async fn test_dynamic_set_header_from_body() {
        let exchange = Exchange::new(Message::new("world"));

        let svc = DynamicSetHeader::new(
            IdentityProcessor,
            "greeting",
            sync_source(|ex: &Exchange| {
                Value::String(format!("hello {}", ex.input.body.as_text().unwrap_or("")))
            }),
        );

        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(
            result.input.header("greeting"),
            Some(&Value::String("hello world".into()))
        );
    }

    #[tokio::test]
    async fn test_dynamic_set_header_overwrites_existing() {
        let mut msg = Message::new("new");
        msg.set_header("key", Value::String("old".into()));
        let exchange = Exchange::new(msg);

        let svc = DynamicSetHeader::new(
            IdentityProcessor,
            "key",
            sync_source(|ex: &Exchange| {
                Value::String(ex.input.body.as_text().unwrap_or("").into())
            }),
        );

        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(
            result.input.header("key"),
            Some(&Value::String("new".into()))
        );
    }

    #[tokio::test]
    async fn test_dynamic_set_header_preserves_body() {
        let exchange = Exchange::new(Message::new("body content"));

        let svc = DynamicSetHeader::new(
            IdentityProcessor,
            "len",
            sync_source(|ex: &Exchange| {
                let len = ex.input.body.as_text().map(|t| t.len() as i64).unwrap_or(0);
                Value::Number(len.into())
            }),
        );

        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(result.input.body.as_text(), Some("body content"));
        assert_eq!(result.input.header("len"), Some(&Value::Number(12.into())));
    }

    #[tokio::test]
    async fn test_dynamic_set_header_layer_composes() {
        use tower::ServiceBuilder;

        let svc = ServiceBuilder::new()
            .layer(DynamicSetHeaderLayer::new(
                "computed",
                sync_source(|_ex: &Exchange| Value::Bool(true)),
            ))
            .service(IdentityProcessor);

        let exchange = Exchange::new(Message::default());
        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(result.input.header("computed"), Some(&Value::Bool(true)));
    }

    // ── DynamicSetHeaderIfAbsent ──

    #[tokio::test]
    async fn test_dynamic_set_header_if_absent_adds_when_missing() {
        let exchange = Exchange::new(Message::new("world"));

        let svc = DynamicSetHeaderIfAbsent::new(
            IdentityProcessor,
            "greeting",
            sync_source(|ex: &Exchange| {
                Value::String(format!("hello {}", ex.input.body.as_text().unwrap_or("")))
            }),
        );

        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(
            result.input.header("greeting"),
            Some(&Value::String("hello world".into()))
        );
    }

    #[tokio::test]
    async fn test_dynamic_set_header_if_absent_preserves_existing() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering};

        let mut msg = Message::new("computed");
        msg.set_header("key", Value::String("original".into()));
        let exchange = Exchange::new(msg);

        // Side-effect counter: expression increments this.
        // If the header is present, the expression must NEVER be called.
        let call_count = Arc::new(AtomicUsize::new(0));
        let cc = call_count.clone();

        let svc = DynamicSetHeaderIfAbsent::new(
            IdentityProcessor,
            "key",
            sync_source(move |ex: &Exchange| {
                cc.fetch_add(1, Ordering::SeqCst);
                Value::String(ex.input.body.as_text().unwrap_or("").into())
            }),
        );

        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(
            result.input.header("key"),
            Some(&Value::String("original".into()))
        );
        assert_eq!(
            call_count.load(Ordering::SeqCst),
            0,
            "expression must NOT be evaluated when header is present"
        );
    }

    #[tokio::test]
    async fn test_dynamic_set_header_if_absent_preserves_body() {
        let exchange = Exchange::new(Message::new("body content"));

        let svc = DynamicSetHeaderIfAbsent::new(
            IdentityProcessor,
            "len",
            sync_source(|ex: &Exchange| {
                let len = ex.input.body.as_text().map(|t| t.len() as i64).unwrap_or(0);
                Value::Number(len.into())
            }),
        );

        let result = svc.oneshot(exchange).await.unwrap();
        assert_eq!(result.input.body.as_text(), Some("body content"));
        assert_eq!(result.input.header("len"), Some(&Value::Number(12.into())));
    }
}