camel-component-api 0.14.0

Component API trait and registry 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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::sync::Arc;

use async_trait::async_trait;
use tokio::sync::{mpsc, oneshot};
use tokio::task::JoinHandle;
use tokio_util::sync::CancellationToken;

use camel_api::security_policy::SecurityPolicy;
use camel_api::{CamelError, Exchange};
use camel_auth::{CredentialSource, TokenAuthenticator};

/// A message sent from a consumer to the route pipeline.
///
/// Fire-and-forget exchanges use `reply_tx = None`.
/// Request-reply exchanges (e.g. `direct:`) provide a `reply_tx` so the
/// pipeline result can be sent back to the consumer.
pub struct ExchangeEnvelope {
    pub exchange: Exchange,
    pub reply_tx: Option<oneshot::Sender<Result<Exchange, CamelError>>>,
}

/// Context provided to a Consumer, allowing it to send exchanges into the route.
#[derive(Clone)]
pub struct ConsumerContext {
    sender: mpsc::Sender<ExchangeEnvelope>,
    cancel_token: CancellationToken,
}

impl ConsumerContext {
    /// Create a new consumer context wrapping the given channel sender.
    pub fn new(sender: mpsc::Sender<ExchangeEnvelope>, cancel_token: CancellationToken) -> Self {
        Self {
            sender,
            cancel_token,
        }
    }

    /// Returns a future that resolves when shutdown is requested.
    /// Use in `tokio::select!` inside consumer loops.
    pub async fn cancelled(&self) {
        self.cancel_token.cancelled().await
    }

    /// Returns true if shutdown has been requested.
    pub fn is_cancelled(&self) -> bool {
        self.cancel_token.is_cancelled()
    }

    /// Returns a clone of the `CancellationToken`.
    ///
    /// Useful for consumers that spawn per-request tasks and need to propagate
    /// shutdown to each task. See `HttpConsumer` for an example.
    pub fn cancel_token(&self) -> CancellationToken {
        self.cancel_token.clone()
    }

    /// Returns a clone of the channel sender for manual exchange submission.
    ///
    /// Useful for consumers that spawn per-request tasks (e.g., `HttpConsumer`)
    /// where each task independently sends exchanges into the pipeline.
    /// For simple consumers, prefer `send()` or `send_and_wait()` instead.
    pub fn sender(&self) -> mpsc::Sender<ExchangeEnvelope> {
        self.sender.clone()
    }

    /// Send an exchange into the route pipeline (fire-and-forget).
    pub async fn send(&self, exchange: Exchange) -> Result<(), CamelError> {
        self.sender
            .send(ExchangeEnvelope {
                exchange,
                reply_tx: None,
            })
            .await
            .map_err(|_| CamelError::ChannelClosed)
    }

    /// Send an exchange and wait for the pipeline result (request-reply).
    ///
    /// Returns `Ok(exchange)` on success or `Err(e)` if the pipeline failed
    /// without an error handler absorbing the error.
    pub async fn send_and_wait(&self, exchange: Exchange) -> Result<Exchange, CamelError> {
        let (reply_tx, reply_rx) = oneshot::channel();
        self.sender
            .send(ExchangeEnvelope {
                exchange,
                reply_tx: Some(reply_tx),
            })
            .await
            .map_err(|_| CamelError::ChannelClosed)?;
        reply_rx.await.map_err(|_| CamelError::ChannelClosed)?
    }
}

/// Security context passed to a consumer before `start()`.
///
/// Carries the `SecurityPolicy` and `TokenAuthenticator` from the route
/// controller so consumers (e.g. WebSocket) can register auth state
/// before accepting connections.
pub struct SecurityContext {
    pub policy: Arc<dyn SecurityPolicy>,
    pub authenticator: Arc<dyn TokenAuthenticator>,
    pub credential_sources: Vec<CredentialSource>,
}

impl SecurityContext {
    pub fn new(
        policy: impl SecurityPolicy + 'static,
        authenticator: Arc<dyn TokenAuthenticator>,
    ) -> Self {
        Self {
            policy: Arc::new(policy),
            authenticator,
            credential_sources: vec![CredentialSource::AuthorizationHeader],
        }
    }

    pub fn from_arc(
        policy: Arc<dyn SecurityPolicy>,
        authenticator: Arc<dyn TokenAuthenticator>,
    ) -> Self {
        Self {
            policy,
            authenticator,
            credential_sources: vec![CredentialSource::AuthorizationHeader],
        }
    }

    pub fn with_credential_sources(mut self, sources: Vec<CredentialSource>) -> Self {
        self.credential_sources = sources;
        self
    }
}

impl Clone for SecurityContext {
    fn clone(&self) -> Self {
        Self {
            policy: Arc::clone(&self.policy),
            authenticator: Arc::clone(&self.authenticator),
            credential_sources: self.credential_sources.clone(),
        }
    }
}

impl std::fmt::Debug for SecurityContext {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SecurityContext")
            .field("policy", &"<SecurityPolicy>")
            .field("authenticator", &"<TokenAuthenticator>")
            .field("credential_sources", &self.credential_sources)
            .finish()
    }
}

/// How a consumer's exchanges should be processed by the pipeline.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConcurrencyModel {
    /// Exchanges are processed one at a time, in order. Default for polling
    /// consumers (timer, file) and synchronous consumers (direct).
    Sequential,
    /// Exchanges are processed concurrently via `tokio::spawn`. Optional
    /// semaphore limit (`max`). `None` means unbounded (channel buffer is
    /// the only backpressure).
    Concurrent { max: Option<usize> },
}

/// A Consumer receives data from an external system and submits Exchanges
/// to the Route's Pipeline via the [`ConsumerContext`].
///
/// # Shutdown Contract
///
/// The Runtime guarantees the following lifecycle:
///
/// 1. `start()` is called once. The Runtime spawns a task that owns the Consumer.
/// 2. On route stop, the Runtime cancels the [`ConsumerContext`] cancel token.
/// 3. The spawned task calls `stop()` on ALL exit paths after `start()` succeeds
///    (clean exit, crash, cancellation, natural completion).
/// 4. `background_task_handle()` is a supervision hook for crash propagation (ADR-0007),
///    NOT the shutdown API.
///
/// Component authors MUST ensure:
///
/// - `stop()` cancels all component-owned inner tasks and cleans up registrations/resources.
/// - If inner tasks use a private `CancellationToken`, `stop()` MUST cancel it.
/// - Best practice: inner tasks should use the [`ConsumerContext`] cancel token (or a child)
///   so they respond to runtime shutdown without waiting for `stop()`.
/// - If using a private token, `stop()` must cancel it to ensure prompt cleanup.
/// - `background_task_handle()` returns the `JoinHandle` of the primary background task,
///   if any. The Runtime monitors this handle for unexpected exits (crash propagation).
#[async_trait]
pub trait Consumer: Send + Sync {
    /// Start consuming messages, sending them through the provided context.
    async fn start(&mut self, context: ConsumerContext) -> Result<(), CamelError>;

    /// Stop consuming messages and clean up all resources.
    ///
    /// Called by the Runtime on every exit path after `start()` succeeds.
    /// See the [Shutdown Contract](#shutdown-contract) above.
    async fn stop(&mut self) -> Result<(), CamelError>;

    /// Temporarily suspend consuming messages without fully stopping.
    ///
    /// Default: no-op, returns `Ok(())`.
    async fn suspend(&self) -> Result<(), CamelError> {
        Ok(())
    }

    /// Resume consuming after a previous suspension.
    ///
    /// Default: no-op, returns `Ok(())`.
    async fn resume(&self) -> Result<(), CamelError> {
        Ok(())
    }

    /// Declares this consumer's natural concurrency model.
    ///
    /// The runtime uses this to decide whether to process exchanges
    /// sequentially or spawn per-exchange. Consumers that accept inbound
    /// connections (HTTP, WebSocket, Kafka) should override this to return
    /// `ConcurrencyModel::Concurrent`.
    ///
    /// Default: `Sequential`.
    fn concurrency_model(&self) -> ConcurrencyModel {
        ConcurrencyModel::Sequential
    }

    /// Return a handle to the consumer's long-running background task so the
    /// runtime can monitor it for unexpected exits after `start()` returns `Ok`.
    ///
    /// Default: `None` — consumer's work completes entirely within `start()`.
    /// Override: return `Some(handle)` if `start()` spawns a detached task.
    ///
    /// **Contract:** the task must observe `ConsumerContext::cancelled()` so
    /// runtime shutdown is distinguishable from crash exits.
    ///
    /// This method is called at most once; implementations should use `.take()`
    /// to transfer ownership of the handle.
    fn background_task_handle(&mut self) -> Option<JoinHandle<Result<(), CamelError>>> {
        None
    }

    /// Set the security context for this consumer.
    ///
    /// Called by the route controller before `start()` so the consumer
    /// can register auth state (e.g. WebSocket auth in `WsAppState`).
    ///
    /// Default: no-op, returns `Ok(())`.
    fn set_security_context(&mut self, _ctx: SecurityContext) {}
}

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_consumer_context_cancelled() {
        let (tx, _rx) = mpsc::channel(16);
        let token = CancellationToken::new();
        let ctx = ConsumerContext::new(tx, token.clone());

        assert!(!ctx.is_cancelled());
        token.cancel();
        ctx.cancelled().await;
        assert!(ctx.is_cancelled());
    }

    #[test]
    fn test_concurrency_model_default_is_sequential() {
        use super::ConcurrencyModel;

        struct DummyConsumer;

        #[async_trait::async_trait]
        impl super::Consumer for DummyConsumer {
            async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
                Ok(())
            }
            async fn stop(&mut self) -> Result<(), CamelError> {
                Ok(())
            }
        }

        let consumer = DummyConsumer;
        assert_eq!(consumer.concurrency_model(), ConcurrencyModel::Sequential);
    }

    #[test]
    fn test_concurrency_model_concurrent_override() {
        use super::ConcurrencyModel;

        struct ConcurrentConsumer;

        #[async_trait::async_trait]
        impl super::Consumer for ConcurrentConsumer {
            async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
                Ok(())
            }
            async fn stop(&mut self) -> Result<(), CamelError> {
                Ok(())
            }
            fn concurrency_model(&self) -> ConcurrencyModel {
                ConcurrencyModel::Concurrent { max: Some(16) }
            }
        }

        let consumer = ConcurrentConsumer;
        assert_eq!(
            consumer.concurrency_model(),
            ConcurrencyModel::Concurrent { max: Some(16) }
        );
    }

    #[tokio::test]
    async fn test_consumer_default_suspend_resume() {
        struct DummyConsumer;

        #[async_trait::async_trait]
        impl super::Consumer for DummyConsumer {
            async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
                Ok(())
            }
            async fn stop(&mut self) -> Result<(), CamelError> {
                Ok(())
            }
        }

        let consumer = DummyConsumer;
        assert!(consumer.suspend().await.is_ok());
        assert!(consumer.resume().await.is_ok());
    }

    // --- SecurityContext tests ---

    struct StubPolicy;

    #[async_trait::async_trait]
    impl SecurityPolicy for StubPolicy {
        async fn evaluate(
            &self,
            _exchange: &mut Exchange,
        ) -> Result<camel_api::security_policy::AuthorizationDecision, CamelError> {
            Ok(camel_api::security_policy::AuthorizationDecision::Granted {
                principal: camel_api::security_policy::Principal {
                    subject: "stub".into(),
                    issuer: "stub".into(),
                    audience: vec![],
                    scopes: vec![],
                    roles: vec![],
                    claims: serde_json::json!({}),
                },
            })
        }
    }

    struct StubAuthenticator;

    #[async_trait::async_trait]
    impl camel_auth::TokenAuthenticator for StubAuthenticator {
        async fn authenticate_bearer(
            &self,
            _token: &str,
        ) -> Result<camel_api::security_policy::Principal, CamelError> {
            Ok(camel_api::security_policy::Principal {
                subject: "stub".into(),
                issuer: "stub".into(),
                audience: vec![],
                scopes: vec![],
                roles: vec![],
                claims: serde_json::json!({}),
            })
        }
    }

    #[test]
    fn test_security_context_new() {
        let ctx = SecurityContext::new(StubPolicy, Arc::new(StubAuthenticator));
        assert!(Arc::strong_count(&ctx.policy) == 1);
        assert!(Arc::strong_count(&ctx.authenticator) == 1);
        assert_eq!(
            ctx.credential_sources,
            vec![camel_auth::CredentialSource::AuthorizationHeader]
        );
    }

    #[test]
    fn test_security_context_from_arc() {
        let policy: Arc<dyn SecurityPolicy> = Arc::new(StubPolicy);
        let authenticator: Arc<dyn camel_auth::TokenAuthenticator> = Arc::new(StubAuthenticator);
        let ctx = SecurityContext::from_arc(Arc::clone(&policy), Arc::clone(&authenticator));
        assert!(Arc::ptr_eq(&ctx.policy, &policy));
        assert!(Arc::ptr_eq(&ctx.authenticator, &authenticator));
        assert_eq!(
            ctx.credential_sources,
            vec![camel_auth::CredentialSource::AuthorizationHeader]
        );
    }

    #[test]
    fn test_security_context_clone_independent() {
        let ctx = SecurityContext::new(StubPolicy, Arc::new(StubAuthenticator));
        let cloned = ctx.clone();
        assert!(Arc::ptr_eq(&ctx.policy, &cloned.policy));
        assert!(Arc::ptr_eq(&ctx.authenticator, &cloned.authenticator));
        assert_eq!(ctx.credential_sources, cloned.credential_sources);
    }

    #[test]
    fn test_security_context_debug_redacts_traits() {
        let ctx = SecurityContext::new(StubPolicy, Arc::new(StubAuthenticator));
        let debug_str = format!("{ctx:?}");
        assert!(debug_str.contains("<SecurityPolicy>"));
        assert!(debug_str.contains("<TokenAuthenticator>"));
        assert!(debug_str.contains("credential_sources"));
    }

    #[test]
    fn test_security_context_with_credential_sources() {
        let ctx = SecurityContext::new(StubPolicy, Arc::new(StubAuthenticator))
            .with_credential_sources(vec![
                camel_auth::CredentialSource::Cookie {
                    name: "session".into(),
                },
                camel_auth::CredentialSource::AuthorizationHeader,
            ]);
        assert_eq!(ctx.credential_sources.len(), 2);
        assert!(matches!(
            &ctx.credential_sources[0],
            camel_auth::CredentialSource::Cookie { .. }
        ));
    }
}