1use std::future::Future;
2use std::pin::Pin;
3use std::task::{Context, Poll};
4
5use tower::Service;
6
7use camel_api::{CamelError, Exchange, PROPERTY_HTTP_CONTENT_TYPE_INHERITED, ValueSource};
8
9#[derive(Clone)]
14pub struct DynamicSetHeader<P> {
15 inner: P,
16 key: String,
17 source: ValueSource,
18}
19
20impl<P> DynamicSetHeader<P> {
21 pub fn new(inner: P, key: impl Into<String>, source: impl Into<ValueSource>) -> Self {
22 Self {
23 inner,
24 key: key.into(),
25 source: source.into(),
26 }
27 }
28}
29
30#[derive(Clone)]
32pub struct DynamicSetHeaderLayer {
33 key: String,
34 source: ValueSource,
35}
36
37impl DynamicSetHeaderLayer {
38 pub fn new(key: impl Into<String>, source: impl Into<ValueSource>) -> Self {
39 Self {
40 key: key.into(),
41 source: source.into(),
42 }
43 }
44}
45
46impl<S> tower::Layer<S> for DynamicSetHeaderLayer {
47 type Service = DynamicSetHeader<S>;
48
49 fn layer(&self, inner: S) -> Self::Service {
50 DynamicSetHeader {
51 inner,
52 key: self.key.clone(),
53 source: self.source.clone(),
54 }
55 }
56}
57
58impl<P> Service<Exchange> for DynamicSetHeader<P>
59where
60 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
61 P::Future: Send,
62{
63 type Response = Exchange;
64 type Error = CamelError;
65 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
66
67 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
68 self.inner.poll_ready(cx)
69 }
70
71 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
72 let source = self.source.clone();
73 let key = self.key.clone();
74 let clone = self.inner.clone();
77 let mut inner = std::mem::replace(&mut self.inner, clone);
78 Box::pin(async move {
79 let value = source.evaluate(&exchange).await?;
80 let touches_content_type = key.eq_ignore_ascii_case("content-type");
81 exchange.input.set_header(key, value);
82 if touches_content_type {
83 exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
84 }
85 inner.call(exchange).await
86 })
87 }
88}
89
90#[derive(Clone)]
95pub struct DynamicSetHeaderIfAbsent<P> {
96 inner: P,
97 key: String,
98 source: ValueSource,
99}
100
101impl<P> DynamicSetHeaderIfAbsent<P> {
102 pub fn new(inner: P, key: impl Into<String>, source: impl Into<ValueSource>) -> Self {
103 Self {
104 inner,
105 key: key.into(),
106 source: source.into(),
107 }
108 }
109}
110
111impl<P> Service<Exchange> for DynamicSetHeaderIfAbsent<P>
112where
113 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
114 P::Future: Send,
115{
116 type Response = Exchange;
117 type Error = CamelError;
118 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
119
120 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
121 self.inner.poll_ready(cx)
122 }
123
124 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
125 if exchange.input.header_ic(&self.key).is_some() {
128 let clone = self.inner.clone();
129 let mut inner = std::mem::replace(&mut self.inner, clone);
130 return Box::pin(inner.call(exchange));
131 }
132
133 let source = self.source.clone();
134 let key = self.key.clone();
135 let clone = self.inner.clone();
137 let mut inner = std::mem::replace(&mut self.inner, clone);
138 Box::pin(async move {
139 let value = source.evaluate(&exchange).await?;
140 let touches_content_type = key.eq_ignore_ascii_case("content-type");
141 exchange.input.set_header(key, value);
142 if touches_content_type {
143 exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
144 }
145 inner.call(exchange).await
146 })
147 }
148}
149
150#[cfg(test)]
151mod tests {
152 use std::sync::Arc;
153 use std::sync::atomic::{AtomicUsize, Ordering};
154
155 use camel_api::{BoxValueFuture, Exchange, IdentityProcessor, Message, Value, ValueSource};
156 use tower::ServiceExt;
157
158 use super::*;
159
160 fn sync_source<F>(f: F) -> ValueSource
161 where
162 F: Fn(&Exchange) -> Value + Send + Sync + 'static,
163 {
164 ValueSource::Sync(Arc::new(f))
165 }
166
167 fn failing_source() -> ValueSource {
168 ValueSource::Async(Arc::new(|_: &Exchange| {
169 Box::pin(async { Err(CamelError::ProcessorError("expr boom".into())) })
170 as BoxValueFuture
171 }))
172 }
173
174 #[derive(Clone)]
176 struct CountingInner {
177 called: Arc<AtomicUsize>,
178 }
179
180 impl Service<Exchange> for CountingInner {
181 type Response = Exchange;
182 type Error = CamelError;
183 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
184
185 fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
186 Poll::Ready(Ok(()))
187 }
188
189 fn call(&mut self, exchange: Exchange) -> Self::Future {
190 self.called.fetch_add(1, Ordering::SeqCst);
191 Box::pin(async { Ok(exchange) })
192 }
193 }
194
195 #[tokio::test]
196 async fn dynamic_set_header_error_propagates() {
197 let called = Arc::new(AtomicUsize::new(0));
198 let svc = DynamicSetHeader::new(
199 CountingInner {
200 called: Arc::clone(&called),
201 },
202 "greeting",
203 failing_source(),
204 );
205
206 let result = svc.oneshot(Exchange::new(Message::new("world"))).await;
207
208 assert!(result.is_err(), "failed evaluation must fail the step");
209 assert_eq!(
210 called.load(Ordering::SeqCst),
211 0,
212 "inner must NOT run when evaluation fails"
213 );
214 }
215
216 #[tokio::test]
217 async fn dynamic_set_header_if_absent_error_propagates() {
218 let called = Arc::new(AtomicUsize::new(0));
219 let svc = DynamicSetHeaderIfAbsent::new(
220 CountingInner {
221 called: Arc::clone(&called),
222 },
223 "greeting",
224 failing_source(),
225 );
226
227 let result = svc.oneshot(Exchange::new(Message::new("world"))).await;
229
230 assert!(result.is_err(), "failed evaluation must fail the step");
231 assert_eq!(
232 called.load(Ordering::SeqCst),
233 0,
234 "inner must NOT run when evaluation fails"
235 );
236 }
237
238 #[tokio::test]
239 async fn dynamic_set_header_if_absent_present_header_skips_evaluation() {
240 let evals = Arc::new(AtomicUsize::new(0));
241 let evals_clone = evals.clone();
242 let source = ValueSource::Async(Arc::new(move |_: &Exchange| {
243 evals_clone.fetch_add(1, Ordering::SeqCst);
244 Box::pin(async { Ok(Value::Bool(true)) }) as BoxValueFuture
245 }));
246
247 let mut msg = Message::new("computed");
248 msg.set_header("key", Value::String("original".into()));
249
250 let svc = DynamicSetHeaderIfAbsent::new(IdentityProcessor, "key", source);
251 let result = svc.oneshot(Exchange::new(msg)).await.unwrap();
252
253 assert_eq!(
254 result.input.header("key"),
255 Some(&Value::String("original".into()))
256 );
257 assert_eq!(
258 evals.load(Ordering::SeqCst),
259 0,
260 "expression must NOT be evaluated when the header is already present"
261 );
262 }
263
264 #[tokio::test]
265 async fn test_dynamic_set_header_from_body() {
266 let exchange = Exchange::new(Message::new("world"));
267
268 let svc = DynamicSetHeader::new(
269 IdentityProcessor,
270 "greeting",
271 sync_source(|ex: &Exchange| {
272 Value::String(format!("hello {}", ex.input.body.as_text().unwrap_or("")))
273 }),
274 );
275
276 let result = svc.oneshot(exchange).await.unwrap();
277 assert_eq!(
278 result.input.header("greeting"),
279 Some(&Value::String("hello world".into()))
280 );
281 }
282
283 #[tokio::test]
284 async fn test_dynamic_set_header_overwrites_existing() {
285 let mut msg = Message::new("new");
286 msg.set_header("key", Value::String("old".into()));
287 let exchange = Exchange::new(msg);
288
289 let svc = DynamicSetHeader::new(
290 IdentityProcessor,
291 "key",
292 sync_source(|ex: &Exchange| {
293 Value::String(ex.input.body.as_text().unwrap_or("").into())
294 }),
295 );
296
297 let result = svc.oneshot(exchange).await.unwrap();
298 assert_eq!(
299 result.input.header("key"),
300 Some(&Value::String("new".into()))
301 );
302 }
303
304 #[tokio::test]
305 async fn dynamic_set_header_replaces_different_case() {
306 let mut msg = Message::default();
307 msg.set_header("X-Flag", Value::String("old".into()));
308
309 let svc = DynamicSetHeader::new(
310 IdentityProcessor,
311 "x-flag",
312 sync_source(|_ex: &Exchange| Value::String("raw".into())),
313 );
314
315 let result = svc.oneshot(Exchange::new(msg)).await.unwrap();
316 assert_eq!(
317 result.input.header("x-flag"),
318 Some(&Value::String("raw".into()))
319 );
320 assert_eq!(result.input.header("X-Flag"), None);
321 assert_eq!(result.input.headers.len(), 1);
322 }
323
324 #[tokio::test]
325 async fn test_dynamic_set_header_preserves_body() {
326 let exchange = Exchange::new(Message::new("body content"));
327
328 let svc = DynamicSetHeader::new(
329 IdentityProcessor,
330 "len",
331 sync_source(|ex: &Exchange| {
332 let len = ex.input.body.as_text().map(|t| t.len() as i64).unwrap_or(0);
333 Value::Number(len.into())
334 }),
335 );
336
337 let result = svc.oneshot(exchange).await.unwrap();
338 assert_eq!(result.input.body.as_text(), Some("body content"));
339 assert_eq!(result.input.header("len"), Some(&Value::Number(12.into())));
340 }
341
342 #[tokio::test]
343 async fn test_dynamic_set_header_layer_composes() {
344 use tower::ServiceBuilder;
345
346 let svc = ServiceBuilder::new()
347 .layer(DynamicSetHeaderLayer::new(
348 "computed",
349 sync_source(|_ex: &Exchange| Value::Bool(true)),
350 ))
351 .service(IdentityProcessor);
352
353 let exchange = Exchange::new(Message::default());
354 let result = svc.oneshot(exchange).await.unwrap();
355 assert_eq!(result.input.header("computed"), Some(&Value::Bool(true)));
356 }
357
358 #[tokio::test]
361 async fn test_dynamic_set_header_if_absent_adds_when_missing() {
362 let exchange = Exchange::new(Message::new("world"));
363
364 let svc = DynamicSetHeaderIfAbsent::new(
365 IdentityProcessor,
366 "greeting",
367 sync_source(|ex: &Exchange| {
368 Value::String(format!("hello {}", ex.input.body.as_text().unwrap_or("")))
369 }),
370 );
371
372 let result = svc.oneshot(exchange).await.unwrap();
373 assert_eq!(
374 result.input.header("greeting"),
375 Some(&Value::String("hello world".into()))
376 );
377 }
378
379 #[tokio::test]
380 async fn test_dynamic_set_header_if_absent_preserves_existing() {
381 use std::sync::Arc;
382 use std::sync::atomic::{AtomicUsize, Ordering};
383
384 let mut msg = Message::new("computed");
385 msg.set_header("key", Value::String("original".into()));
386 let exchange = Exchange::new(msg);
387
388 let call_count = Arc::new(AtomicUsize::new(0));
391 let cc = call_count.clone();
392
393 let svc = DynamicSetHeaderIfAbsent::new(
394 IdentityProcessor,
395 "key",
396 sync_source(move |ex: &Exchange| {
397 cc.fetch_add(1, Ordering::SeqCst);
398 Value::String(ex.input.body.as_text().unwrap_or("").into())
399 }),
400 );
401
402 let result = svc.oneshot(exchange).await.unwrap();
403 assert_eq!(
404 result.input.header("key"),
405 Some(&Value::String("original".into()))
406 );
407 assert_eq!(
408 call_count.load(Ordering::SeqCst),
409 0,
410 "expression must NOT be evaluated when header is present"
411 );
412 }
413
414 #[tokio::test]
415 async fn dynamic_set_header_if_absent_respects_different_case() {
416 let evals = Arc::new(AtomicUsize::new(0));
417 let evals_clone = Arc::clone(&evals);
418 let source = sync_source(move |_ex: &Exchange| {
419 evals_clone.fetch_add(1, Ordering::SeqCst);
420 Value::String("new".into())
421 });
422
423 let mut msg = Message::default();
424 msg.set_header("X-Flag", Value::String("old".into()));
425
426 let svc = DynamicSetHeaderIfAbsent::new(IdentityProcessor, "x-flag", source);
427 let result = svc.oneshot(Exchange::new(msg)).await.unwrap();
428
429 assert_eq!(
430 result.input.header("X-Flag"),
431 Some(&Value::String("old".into()))
432 );
433 assert_eq!(result.input.header("x-flag"), None);
434 assert_eq!(result.input.headers.len(), 1);
435 assert_eq!(
436 evals.load(Ordering::SeqCst),
437 0,
438 "expression must NOT be evaluated when a different-case header is present"
439 );
440 }
441
442 #[tokio::test]
443 async fn dynamic_set_header_if_absent_sees_raw_map_different_case() {
444 let evals = Arc::new(AtomicUsize::new(0));
445 let evals_clone = Arc::clone(&evals);
446 let source = sync_source(move |_ex: &Exchange| {
447 evals_clone.fetch_add(1, Ordering::SeqCst);
448 Value::String("new".into())
449 });
450
451 let mut msg = Message::default();
452 msg.headers
453 .insert("X-Flag".into(), Value::String("old".into()));
454
455 let svc = DynamicSetHeaderIfAbsent::new(IdentityProcessor, "x-flag", source);
456 let result = svc.oneshot(Exchange::new(msg)).await.unwrap();
457
458 assert_eq!(
459 result.input.header("X-Flag"),
460 Some(&Value::String("old".into()))
461 );
462 assert_eq!(result.input.header("x-flag"), None);
463 assert_eq!(result.input.headers.len(), 1);
464 assert_eq!(
465 evals.load(Ordering::SeqCst),
466 0,
467 "expression must NOT be evaluated when a raw-map case variant is present"
468 );
469 }
470
471 #[tokio::test]
472 async fn test_dynamic_set_header_if_absent_preserves_body() {
473 let exchange = Exchange::new(Message::new("body content"));
474
475 let svc = DynamicSetHeaderIfAbsent::new(
476 IdentityProcessor,
477 "len",
478 sync_source(|ex: &Exchange| {
479 let len = ex.input.body.as_text().map(|t| t.len() as i64).unwrap_or(0);
480 Value::Number(len.into())
481 }),
482 );
483
484 let result = svc.oneshot(exchange).await.unwrap();
485 assert_eq!(result.input.body.as_text(), Some("body content"));
486 assert_eq!(result.input.header("len"), Some(&Value::Number(12.into())));
487 }
488
489 #[tokio::test]
492 async fn dynamic_set_header_clears_marker_on_content_type() {
493 let mut exchange = Exchange::new(Message::default());
494 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
495
496 let svc = DynamicSetHeader::new(
497 IdentityProcessor,
498 "Content-Type",
499 sync_source(|_ex: &Exchange| Value::String("application/json".into())),
500 );
501
502 let result = svc.oneshot(exchange).await.unwrap();
503 assert_eq!(
504 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
505 None,
506 "a dynamic Content-Type write must clear the marker"
507 );
508 assert_eq!(
509 result.input.header("Content-Type"),
510 Some(&Value::String("application/json".into()))
511 );
512 }
513
514 #[tokio::test]
515 async fn dynamic_set_header_if_absent_clears_marker_only_when_written() {
516 let mut exchange = Exchange::new(Message::default());
518 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
519
520 let svc = DynamicSetHeaderIfAbsent::new(
521 IdentityProcessor,
522 "Content-Type",
523 sync_source(|_ex: &Exchange| Value::String("application/json".into())),
524 );
525
526 let result = svc.oneshot(exchange).await.unwrap();
527 assert_eq!(
528 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
529 None,
530 "an if-absent dynamic Content-Type write must clear the marker"
531 );
532 assert_eq!(
533 result.input.header("Content-Type"),
534 Some(&Value::String("application/json".into()))
535 );
536
537 let mut msg = Message::default();
539 msg.set_header("Content-Type", Value::String("text/plain".into()));
540 let mut exchange = Exchange::new(msg);
541 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
542
543 let svc = DynamicSetHeaderIfAbsent::new(
544 IdentityProcessor,
545 "Content-Type",
546 sync_source(|_ex: &Exchange| Value::String("application/json".into())),
547 );
548
549 let result = svc.oneshot(exchange).await.unwrap();
550 assert_eq!(
551 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
552 Some(&Value::Bool(true)),
553 "an if-absent dynamic no-op must not clear the marker"
554 );
555 assert_eq!(
556 result.input.header("Content-Type"),
557 Some(&Value::String("text/plain".into()))
558 );
559 }
560}