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, Value};
8
9#[derive(Clone)]
11pub struct SetHeader<P> {
12 inner: P,
13 key: String,
14 value: Value,
15}
16
17impl<P> SetHeader<P> {
18 pub fn new(inner: P, key: impl Into<String>, value: impl Into<Value>) -> Self {
20 Self {
21 inner,
22 key: key.into(),
23 value: value.into(),
24 }
25 }
26}
27
28#[derive(Clone)]
30pub struct SetHeaderLayer {
31 key: String,
32 value: Value,
33}
34
35impl SetHeaderLayer {
36 pub fn new(key: impl Into<String>, value: impl Into<Value>) -> Self {
37 Self {
38 key: key.into(),
39 value: value.into(),
40 }
41 }
42}
43
44impl<S> tower::Layer<S> for SetHeaderLayer {
45 type Service = SetHeader<S>;
46
47 fn layer(&self, inner: S) -> Self::Service {
48 SetHeader::new(inner, self.key.clone(), self.value.clone())
49 }
50}
51
52impl<P> Service<Exchange> for SetHeader<P>
53where
54 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
55 P::Future: Send,
56{
57 type Response = Exchange;
58 type Error = CamelError;
59 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
60
61 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
62 self.inner.poll_ready(cx)
63 }
64
65 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
66 exchange
67 .input
68 .set_header(self.key.clone(), self.value.clone());
69 if self.key.eq_ignore_ascii_case("content-type") {
70 exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
71 }
72 let fut = self.inner.call(exchange);
73 Box::pin(fut)
74 }
75}
76
77#[derive(Clone)]
80pub struct SetHeaderIfAbsent<P> {
81 inner: P,
82 key: String,
83 value: Value,
84}
85
86impl<P> SetHeaderIfAbsent<P> {
87 pub fn new(inner: P, key: impl Into<String>, value: impl Into<Value>) -> Self {
90 Self {
91 inner,
92 key: key.into(),
93 value: value.into(),
94 }
95 }
96}
97
98impl<P> Service<Exchange> for SetHeaderIfAbsent<P>
99where
100 P: Service<Exchange, Response = Exchange, Error = CamelError> + Clone + Send + 'static,
101 P::Future: Send,
102{
103 type Response = Exchange;
104 type Error = CamelError;
105 type Future = Pin<Box<dyn Future<Output = Result<Exchange, CamelError>> + Send>>;
106
107 fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
108 self.inner.poll_ready(cx)
109 }
110
111 fn call(&mut self, mut exchange: Exchange) -> Self::Future {
112 if exchange.input.header_ic(&self.key).is_none() {
113 exchange
114 .input
115 .set_header(self.key.clone(), self.value.clone());
116 if self.key.eq_ignore_ascii_case("content-type") {
117 exchange.remove_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED);
118 }
119 }
120 let fut = self.inner.call(exchange);
121 Box::pin(fut)
122 }
123}
124
125#[cfg(test)]
126mod tests {
127 use super::*;
128 use camel_api::{IdentityProcessor, Message};
129 use tower::ServiceExt;
130
131 #[tokio::test]
132 async fn test_set_header_adds_header() {
133 let exchange = Exchange::new(Message::default());
134
135 let processor = SetHeader::new(IdentityProcessor, "source", Value::String("timer".into()));
136
137 let result = processor.oneshot(exchange).await.unwrap();
138 assert_eq!(
139 result.input.header("source"),
140 Some(&Value::String("timer".into()))
141 );
142 }
143
144 #[tokio::test]
145 async fn test_set_header_overwrites_existing() {
146 let mut exchange = Exchange::new(Message::default());
147 exchange
148 .input
149 .set_header("key", Value::String("old".into()));
150
151 let processor = SetHeader::new(IdentityProcessor, "key", Value::String("new".into()));
152
153 let result = processor.oneshot(exchange).await.unwrap();
154 assert_eq!(
155 result.input.header("key"),
156 Some(&Value::String("new".into()))
157 );
158 }
159
160 #[tokio::test]
161 async fn set_header_replaces_different_case() {
162 let mut exchange = Exchange::new(Message::default());
163 exchange
164 .input
165 .set_header("X-Flag", Value::String("old".into()));
166
167 let processor = SetHeader::new(IdentityProcessor, "x-flag", Value::String("new".into()));
168
169 let result = processor.oneshot(exchange).await.unwrap();
170 assert_eq!(
171 result.input.header("x-flag"),
172 Some(&Value::String("new".into()))
173 );
174 assert_eq!(result.input.header("X-Flag"), None);
175 assert_eq!(result.input.headers.len(), 1);
176 }
177
178 #[tokio::test]
179 async fn test_set_header_preserves_body() {
180 let exchange = Exchange::new(Message::new("body content"));
181
182 let processor = SetHeader::new(IdentityProcessor, "header", Value::Bool(true));
183
184 let result = processor.oneshot(exchange).await.unwrap();
185 assert_eq!(result.input.body.as_text(), Some("body content"));
186 assert_eq!(result.input.header("header"), Some(&Value::Bool(true)));
187 }
188
189 #[tokio::test]
190 async fn test_set_header_layer_composes() {
191 use tower::ServiceBuilder;
192
193 let svc = ServiceBuilder::new()
194 .layer(super::SetHeaderLayer::new(
195 "env",
196 Value::String("test".into()),
197 ))
198 .service(IdentityProcessor);
199
200 let exchange = Exchange::new(Message::default());
201 let result = svc.oneshot(exchange).await.unwrap();
202 assert_eq!(
203 result.input.header("env"),
204 Some(&Value::String("test".into()))
205 );
206 }
207
208 #[tokio::test]
211 async fn test_set_header_if_absent_adds_when_missing() {
212 let exchange = Exchange::new(Message::default());
213
214 let processor =
215 SetHeaderIfAbsent::new(IdentityProcessor, "source", Value::String("timer".into()));
216
217 let result = processor.oneshot(exchange).await.unwrap();
218 assert_eq!(
219 result.input.header("source"),
220 Some(&Value::String("timer".into()))
221 );
222 }
223
224 #[tokio::test]
225 async fn test_set_header_if_absent_preserves_existing() {
226 let mut exchange = Exchange::new(Message::default());
227 exchange
228 .input
229 .set_header("key", Value::String("old".into()));
230
231 let processor =
232 SetHeaderIfAbsent::new(IdentityProcessor, "key", Value::String("new".into()));
233
234 let result = processor.oneshot(exchange).await.unwrap();
235 assert_eq!(
236 result.input.header("key"),
237 Some(&Value::String("old".into()))
238 );
239 }
240
241 #[tokio::test]
242 async fn set_header_if_absent_respects_different_case() {
243 let mut exchange = Exchange::new(Message::default());
244 exchange
245 .input
246 .set_header("X-Flag", Value::String("old".into()));
247
248 let processor =
249 SetHeaderIfAbsent::new(IdentityProcessor, "x-flag", Value::String("new".into()));
250
251 let result = processor.oneshot(exchange).await.unwrap();
252 assert_eq!(
253 result.input.header_ic("x-flag"),
254 Some(&Value::String("old".into()))
255 );
256 assert_eq!(result.input.header("x-flag"), None);
257 assert_eq!(result.input.headers.len(), 1);
258 }
259
260 #[tokio::test]
261 async fn set_header_if_absent_sees_raw_map_different_case() {
262 let mut exchange = Exchange::new(Message::default());
263 exchange
264 .input
265 .headers
266 .insert("X-Flag".into(), Value::String("old".into()));
267
268 let processor =
269 SetHeaderIfAbsent::new(IdentityProcessor, "x-flag", Value::String("new".into()));
270
271 let result = processor.oneshot(exchange).await.unwrap();
272 assert_eq!(
273 result.input.header_ic("x-flag"),
274 Some(&Value::String("old".into()))
275 );
276 assert_eq!(result.input.header("x-flag"), None);
277 assert_eq!(result.input.headers.len(), 1);
278 }
279
280 #[tokio::test]
281 async fn test_set_header_if_absent_preserves_body() {
282 let exchange = Exchange::new(Message::new("body content"));
283
284 let processor = SetHeaderIfAbsent::new(IdentityProcessor, "header", Value::Bool(true));
285
286 let result = processor.oneshot(exchange).await.unwrap();
287 assert_eq!(result.input.body.as_text(), Some("body content"));
288 assert_eq!(result.input.header("header"), Some(&Value::Bool(true)));
289 }
290
291 #[tokio::test]
294 async fn set_header_clears_marker_on_content_type() {
295 let mut exchange = Exchange::new(Message::default());
296 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
297
298 let processor = SetHeader::new(IdentityProcessor, "Content-Type", "application/json");
299
300 let result = processor.oneshot(exchange).await.unwrap();
301 assert_eq!(
302 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
303 None,
304 "writing Content-Type must clear the inherited-content-type marker"
305 );
306 assert_eq!(
307 result.input.header("Content-Type"),
308 Some(&Value::String("application/json".into()))
309 );
310 }
311
312 #[tokio::test]
313 async fn set_header_keeps_marker_on_other_header() {
314 let mut exchange = Exchange::new(Message::default());
315 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
316
317 let processor = SetHeader::new(IdentityProcessor, "X-Flag", "on");
318
319 let result = processor.oneshot(exchange).await.unwrap();
320 assert_eq!(
321 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
322 Some(&Value::Bool(true)),
323 "writing an unrelated header must leave the marker untouched"
324 );
325 }
326
327 #[tokio::test]
328 async fn set_header_if_absent_clears_marker_only_when_written() {
329 let mut exchange = Exchange::new(Message::default());
331 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
332
333 let processor =
334 SetHeaderIfAbsent::new(IdentityProcessor, "Content-Type", "application/json");
335
336 let result = processor.oneshot(exchange).await.unwrap();
337 assert_eq!(
338 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
339 None,
340 "an if-absent write of Content-Type must clear the marker"
341 );
342 assert_eq!(
343 result.input.header("Content-Type"),
344 Some(&Value::String("application/json".into()))
345 );
346
347 let mut exchange = Exchange::new(Message::default());
349 exchange.set_property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED, Value::Bool(true));
350 exchange
351 .input
352 .set_header("Content-Type", Value::String("text/plain".into()));
353
354 let processor =
355 SetHeaderIfAbsent::new(IdentityProcessor, "Content-Type", "application/json");
356
357 let result = processor.oneshot(exchange).await.unwrap();
358 assert_eq!(
359 result.property(PROPERTY_HTTP_CONTENT_TYPE_INHERITED),
360 Some(&Value::Bool(true)),
361 "an if-absent no-op must not clear the marker"
362 );
363 assert_eq!(
364 result.input.header("Content-Type"),
365 Some(&Value::String("text/plain".into()))
366 );
367 }
368}