camel_component_api/consumer.rs
1use std::sync::{Arc, OnceLock};
2
3use async_trait::async_trait;
4use tokio::sync::{mpsc, oneshot, watch};
5use tokio::task::JoinHandle;
6use tokio_util::sync::CancellationToken;
7
8use camel_api::security_policy::SecurityPolicy;
9use camel_api::{CamelError, Exchange, InFlightGauge};
10use camel_auth::CredentialSource;
11
12use crate::dispatch::InlineRouteDispatcher;
13
14/// Re-export of [`camel_api::InFlightClaim`] — the context-global
15/// accepted-not-completed RAII claim (drainclaim). The canonical
16/// definition and contract live in `camel_api::in_flight`; this alias
17/// keeps the historical `camel_component_api::consumer::InFlightClaim`
18/// path stable. claimfamily: the type moved to camel-api so
19/// [`camel_api::Exchange`] can carry it for stash-site residency.
20pub use camel_api::InFlightClaim;
21
22/// A message sent from a consumer to the route pipeline.
23///
24/// Fire-and-forget exchanges use `reply_tx = None`.
25/// Request-reply exchanges (e.g. `direct:`) provide a `reply_tx` so the
26/// pipeline result can be sent back to the consumer.
27pub struct ExchangeEnvelope {
28 pub exchange: Exchange,
29 pub reply_tx: Option<oneshot::Sender<Result<Exchange, CamelError>>>,
30 /// RAII claim on the context-global accepted-not-completed counter,
31 /// attached at acceptance boundaries (`ConsumerContext::send` /
32 /// `send_and_wait`, seda enqueue, inline dispatch). `None` on the raw
33 /// `sender()` fast path — a documented uncounted exception (drainclaim).
34 pub in_flight_claim: Option<InFlightClaim>,
35}
36
37/// Declares when the runtime may consider a Consumer "started".
38///
39/// `Immediate` (default) preserves the classic fire-and-forget semantics:
40/// `spawn_consumer_task` returns as soon as the consumer task is spawned,
41/// matching the behaviour of timer, file, direct and similar polling
42/// consumers whose `start()` IS the lifetime loop.
43///
44/// `Explicit` is for resource-binding consumers (HTTP, WebSocket, …) whose
45/// `start()` returns control only after the resource (e.g. `TcpListener`)
46/// is bound and ready. The consumer MUST call `ConsumerContext::mark_ready`
47/// after a successful bind so the runtime can await readiness and propagate
48/// pre-ready `start()` errors as proper startup failures.
49///
50/// Adding this as a default-returning trait method keeps every existing
51/// `Consumer` impl backward compatible.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
53#[non_exhaustive]
54pub enum ConsumerStartupMode {
55 /// Consumer's `start()` IS the lifetime loop. The runtime treats the
56 /// consumer as ready the moment `start()` is invoked. (Default)
57 #[default]
58 Immediate,
59 /// Consumer binds/registers a resource inside `start()` and signals
60 /// readiness explicitly via `ConsumerContext::mark_ready()`.
61 Explicit,
62}
63
64/// Internal state of a [`StartupSignal`].
65#[derive(Clone, Debug)]
66enum StartupState {
67 /// Consumer has not yet signalled readiness or failure.
68 Pending,
69 /// Consumer signalled readiness via `mark_ready()`.
70 Ready,
71 /// Consumer's `start()` returned an `Err` before signalling readiness.
72 Failed(String),
73}
74
75/// Shared handle used by a Consumer to signal readiness (or failure) to the
76/// runtime's [`StartupReceiver`].
77///
78/// Constructed in a pair via [`StartupSignal::pair`]. The signal is held by
79/// the consumer side (via [`ConsumerContext`]); the receiver is returned to
80/// the route controller.
81#[derive(Clone)]
82pub struct StartupSignal {
83 tx: watch::Sender<StartupState>,
84}
85
86impl StartupSignal {
87 /// Create a `(signal, receiver)` pair seeded in the `Pending` state.
88 pub fn pair() -> (Self, StartupReceiver) {
89 let (tx, rx) = watch::channel(StartupState::Pending);
90 (Self { tx }, StartupReceiver { rx })
91 }
92
93 /// Mark the consumer as ready. Idempotent — subsequent calls are no-ops
94 /// once the state has transitioned out of `Pending`.
95 ///
96 /// Returns `true` if this call transitioned `Pending → Ready`, `false`
97 /// if the state was already `Ready` or `Failed`. The runtime uses the
98 /// return value to detect Explicit consumers that returned `Ok` from
99 /// `start()` without calling `mark_ready` (a contract violation that
100 /// would hang the controller without the defensive fallback in
101 /// `spawn_consumer_task`).
102 pub fn mark_ready(&self) -> bool {
103 self.tx.send_if_modified(|s| {
104 if matches!(*s, StartupState::Pending) {
105 *s = StartupState::Ready;
106 true
107 } else {
108 false
109 }
110 })
111 }
112
113 /// Mark the consumer's startup as failed with `err`. Idempotent.
114 pub fn mark_failed(&self, err: String) {
115 self.tx.send_if_modified(|s| {
116 if matches!(*s, StartupState::Pending) {
117 *s = StartupState::Failed(err);
118 true
119 } else {
120 false
121 }
122 });
123 }
124}
125
126impl std::fmt::Debug for StartupSignal {
127 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
128 f.debug_struct("StartupSignal")
129 .field("state", &self.tx.borrow())
130 .finish()
131 }
132}
133
134/// Receiver half of the consumer startup handshake. Resolves once the
135/// consumer calls [`ConsumerContext::mark_ready`] (Ok) or its `start()`
136/// returns an `Err` first (Err).
137///
138/// For [`ConsumerStartupMode::Immediate`] consumers the receiver is
139/// pre-resolved at construction time (see [`StartupReceiver::immediate`]).
140pub struct StartupReceiver {
141 rx: watch::Receiver<StartupState>,
142}
143
144impl StartupReceiver {
145 /// Construct a receiver that is already resolved as `Ok`. Used for
146 /// [`ConsumerStartupMode::Immediate`] consumers so the controller can
147 /// uniformly `await` every receiver without changing behaviour.
148 pub fn immediate() -> Self {
149 let (tx, rx) = watch::channel(StartupState::Ready);
150 // Drop the sender — state is fixed at Ready. Receiver will never
151 // observe a closure error since it already holds Ready.
152 let _ = tx;
153 Self { rx }
154 }
155
156 /// Wait for the consumer to become ready or fail. Resolves:
157 /// - `Ok(())` if the consumer signalled readiness.
158 /// - `Err(CamelError::RouteError(_))` if the consumer's `start()`
159 /// returned an error before signalling readiness.
160 /// - `Err(CamelError::RouteError(_))` if the signal sender was dropped
161 /// without either transition (programming-contract violation).
162 pub async fn await_ready(mut self) -> Result<(), CamelError> {
163 loop {
164 match &*self.rx.borrow() {
165 StartupState::Pending => {}
166 StartupState::Ready => return Ok(()),
167 StartupState::Failed(msg) => {
168 return Err(CamelError::RouteError(msg.clone()));
169 }
170 }
171 if self.rx.changed().await.is_err() {
172 return Err(CamelError::RouteError(
173 "consumer startup signal dropped without resolving".to_string(),
174 ));
175 }
176 }
177 }
178}
179
180impl std::fmt::Debug for StartupReceiver {
181 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
182 f.debug_struct("StartupReceiver")
183 .field("state", &self.rx.borrow())
184 .finish()
185 }
186}
187
188/// Context provided to a Consumer, allowing it to send exchanges into the route.
189#[derive(Clone)]
190pub struct ConsumerContext {
191 sender: mpsc::Sender<ExchangeEnvelope>,
192 cancel_token: CancellationToken,
193 route_id: String,
194 startup: StartupSignal,
195 /// Inline dispatch capability slot, shared by all clones of this
196 /// context (`Arc<OnceLock<_>>`). Set once by the camel-core runtime
197 /// before the consumer starts; every clone observes the same value.
198 inline_dispatcher: Arc<OnceLock<Arc<dyn InlineRouteDispatcher>>>,
199 /// Context-global accepted-not-completed gauge, installed by the
200 /// camel-core runtime at consumer start (drainclaim). `None` keeps
201 /// the context's sends uncounted (tests, raw fast paths).
202 in_flight: Option<Arc<InFlightGauge>>,
203}
204
205impl ConsumerContext {
206 /// Create a new consumer context wrapping the given channel sender.
207 ///
208 /// The `route_id` identifies the route this consumer is bound to, enabling
209 /// ADR-0012 per-route metrics and health observations.
210 ///
211 /// The startup signal defaults to a fresh `Pending` pair; the consumer
212 /// can call [`Self::mark_ready`] once it has bound its resource. For
213 /// [`ConsumerStartupMode::Immediate`] consumers the runtime ignores
214 /// the signal (it constructs an already-resolved receiver instead).
215 pub fn new(
216 sender: mpsc::Sender<ExchangeEnvelope>,
217 cancel_token: CancellationToken,
218 route_id: String,
219 ) -> Self {
220 let (startup, _unused_receiver) = StartupSignal::pair();
221 // The receiver is dropped here: `spawn_consumer_task` constructs its
222 // own `(signal, receiver)` pair and replaces this one via
223 // `with_startup` so the controller holds the matching receiver.
224 let _ = _unused_receiver;
225 Self {
226 sender,
227 cancel_token,
228 route_id,
229 startup,
230 inline_dispatcher: Arc::new(OnceLock::new()),
231 in_flight: None,
232 }
233 }
234
235 /// Replace the startup signal carried by this context. Used by
236 /// `spawn_consumer_task` to install the signal whose matching receiver
237 /// is returned to the route controller.
238 pub fn with_startup(mut self, startup: StartupSignal) -> Self {
239 self.startup = startup;
240 self
241 }
242
243 /// Install the context-global accepted-not-completed gauge on this
244 /// context (drainclaim). The camel-core runtime calls this at consumer
245 /// start; afterwards every envelope sent via [`Self::send`] or
246 /// [`Self::send_and_wait`] carries an [`InFlightClaim`]. Contexts
247 /// without a gauge (tests, raw fast paths) send uncounted envelopes.
248 pub fn with_in_flight_counter(mut self, counter: Arc<InFlightGauge>) -> Self {
249 self.in_flight = Some(counter);
250 self
251 }
252
253 /// Returns the installed accepted-not-completed gauge, if any
254 /// (drainclaim). Components whose consumers dispatch through the raw
255 /// [`Self::sender`] fast path capture this once at consumer start and
256 /// mint an [`InFlightClaim`] at their acceptance-dequeue points, so raw
257 /// dispatches count exactly like [`Self::send`] (rc-nftni). Returns
258 /// `None` for contexts without a gauge (tests) — callers mint none.
259 pub fn in_flight_counter(&self) -> Option<Arc<InFlightGauge>> {
260 self.in_flight.clone()
261 }
262
263 /// Returns a clone of the internal [`StartupSignal`] so callers (e.g.
264 /// `spawn_consumer_task`) can drive failure propagation independently of
265 /// the consumer's own `mark_ready()` call.
266 pub fn startup_signal(&self) -> StartupSignal {
267 self.startup.clone()
268 }
269
270 /// Mark this consumer's startup as complete. Only meaningful for
271 /// [`ConsumerStartupMode::Explicit`] consumers — `Immediate` consumers
272 /// never need to call this because the runtime resolves their startup
273 /// receiver at construction time.
274 ///
275 /// Idempotent.
276 pub fn mark_ready(&self) {
277 let _ = self.startup.mark_ready();
278 }
279
280 /// Mark this consumer's startup as FAILED with `err`. Only meaningful for
281 /// [`ConsumerStartupMode::Explicit`] consumers whose readiness is gated on
282 /// an asynchronous event that may never arrive (e.g. Kafka partition
283 /// assignment). Calling this resolves the runtime's startup await with a
284 /// startup error instead of hanging.
285 ///
286 /// Idempotent — the first transition out of `Pending` wins, so a later
287 /// `mark_ready()` cannot override an earlier `mark_failed()` and vice
288 /// versa.
289 pub fn mark_failed(&self, err: String) {
290 self.startup.mark_failed(err);
291 }
292
293 /// Returns a future that resolves when shutdown is requested.
294 /// Use in `tokio::select!` inside consumer loops.
295 pub async fn cancelled(&self) {
296 self.cancel_token.cancelled().await
297 }
298
299 /// Returns true if shutdown has been requested.
300 pub fn is_cancelled(&self) -> bool {
301 self.cancel_token.is_cancelled()
302 }
303
304 /// Returns the route_id this consumer is bound to.
305 ///
306 /// Available for ADR-0012 metrics/health calls that require a route_id
307 /// (categories (b′), (e), (g)). Set at construction time by the route
308 /// controller when spawning the consumer task.
309 pub fn route_id(&self) -> &str {
310 &self.route_id
311 }
312
313 /// Returns a clone of the `CancellationToken`.
314 ///
315 /// Useful for consumers that spawn per-request tasks and need to propagate
316 /// shutdown to each task. See `HttpConsumer` for an example.
317 pub fn cancel_token(&self) -> CancellationToken {
318 self.cancel_token.clone()
319 }
320
321 /// Returns a clone of the channel sender for manual exchange submission.
322 ///
323 /// Useful for consumers that spawn per-request tasks (e.g., `HttpConsumer`)
324 /// where each task independently sends exchanges into the pipeline.
325 /// For simple consumers, prefer `send()` or `send_and_wait()` instead.
326 ///
327 /// Raw pushes through this sender bypass the claim minting of
328 /// [`Self::send`]; components using it MUST capture
329 /// [`Self::in_flight_counter`] once at start and attach a claim to every
330 /// envelope at their acceptance-dequeue point (rc-nftni), or their
331 /// in-flight work stays invisible to `total_in_flight()`.
332 pub fn sender(&self) -> mpsc::Sender<ExchangeEnvelope> {
333 self.sender.clone()
334 }
335
336 /// Publish the inline dispatch capability on this context.
337 ///
338 /// Set once by the camel-core runtime before the consumer starts, when
339 /// the route's effective concurrency model permits the inline fast path.
340 ///
341 /// Set-once, KEEP-FIRST contract: if a dispatcher was already published,
342 /// the first one stays in place, the second call is ignored with a
343 /// warning (it is not an error). All clones of this context share the
344 /// same slot, so a dispatcher set through any clone is visible through
345 /// all of them.
346 pub fn set_inline_dispatcher(&self, dispatcher: Arc<dyn InlineRouteDispatcher>) {
347 if self.inline_dispatcher.set(dispatcher).is_err() {
348 tracing::warn!("inline dispatcher already set; ignoring second set");
349 }
350 }
351
352 /// Returns the inline dispatch capability published by the camel-core
353 /// runtime, if any. See [`Self::set_inline_dispatcher`] for the
354 /// set-once-keep-first contract.
355 pub fn inline_dispatcher(&self) -> Option<Arc<dyn InlineRouteDispatcher>> {
356 self.inline_dispatcher.get().cloned()
357 }
358
359 /// Send an exchange into the route pipeline (fire-and-forget).
360 ///
361 /// Attaches an [`InFlightClaim`] when a counter is installed
362 /// ([`Self::with_in_flight_counter`]); a failed push drops the
363 /// envelope, which drops the claim and rolls the count back.
364 pub async fn send(&self, exchange: Exchange) -> Result<(), CamelError> {
365 self.sender
366 .send(ExchangeEnvelope {
367 exchange,
368 reply_tx: None,
369 in_flight_claim: self.in_flight.as_ref().map(InFlightClaim::attach),
370 })
371 .await
372 .map_err(|_| CamelError::ChannelClosed)
373 }
374
375 /// Send an exchange and wait for the pipeline result (request-reply).
376 ///
377 /// Returns `Ok(exchange)` on success or `Err(e)` if the pipeline failed
378 /// without an error handler absorbing the error.
379 pub async fn send_and_wait(&self, exchange: Exchange) -> Result<Exchange, CamelError> {
380 let (reply_tx, reply_rx) = oneshot::channel();
381 self.sender
382 .send(ExchangeEnvelope {
383 exchange,
384 reply_tx: Some(reply_tx),
385 in_flight_claim: self.in_flight.as_ref().map(InFlightClaim::attach),
386 })
387 .await
388 .map_err(|_| CamelError::ChannelClosed)?;
389 reply_rx.await.map_err(|_| CamelError::ChannelClosed)?
390 }
391}
392
393/// Security context passed to a consumer before `start()`.
394///
395/// Carries the route's security classification so consumers can register
396/// auth state before accepting connections. Declared routes carry the
397/// `SecurityPolicy` from the route controller; plan-only contexts (routes
398/// without a policy declaration) carry just the compiled
399/// [`RouteSecurityPlan`](camel_api::security_policy::RouteSecurityPlan) (`policy = None`). Authentication itself runs
400/// through the kernel fields (`plan` + `providers`).
401pub struct SecurityContext {
402 /// Route policy, when the route declared one. `None` for plan-only
403 /// contexts built via [`SecurityContext::from_plan`].
404 pub policy: Option<Arc<dyn SecurityPolicy>>,
405 pub credential_sources: Vec<CredentialSource>,
406 /// Compiled `RouteSecurityPlan` for the route, when one has been compiled.
407 ///
408 /// Phase-2 transports read the plan from here to drive per-route dispatch
409 /// enforcement. `None` until Task 1.8 compiles plans into the context.
410 pub plan: Option<camel_api::security_policy::RouteSecurityPlan>,
411 /// Provider registry carrying the route's named authenticators.
412 ///
413 /// Phase-2 transports read providers from here (grpc 2.1, mcp 2.6, ws 2.8,
414 /// http 2.9) instead of holding their own authenticator. `None` for routes
415 /// built before the registry injection path lands.
416 pub providers: Option<std::sync::Arc<camel_auth::ProviderRegistry>>,
417}
418
419impl SecurityContext {
420 pub fn new(policy: impl SecurityPolicy + 'static) -> Self {
421 Self {
422 policy: Some(Arc::new(policy)),
423 credential_sources: vec![CredentialSource::AuthorizationHeader],
424 plan: None,
425 providers: None,
426 }
427 }
428
429 pub fn from_arc(policy: Arc<dyn SecurityPolicy>) -> Self {
430 Self {
431 policy: Some(policy),
432 credential_sources: vec![CredentialSource::AuthorizationHeader],
433 plan: None,
434 providers: None,
435 }
436 }
437
438 /// Build a plan-only context: no policy, no providers, empty credential
439 /// sources. The controller delivers a route's compiled classification
440 /// (e.g. the `Public` default for an undeclared server route) through
441 /// this form.
442 pub fn from_plan(plan: camel_api::security_policy::RouteSecurityPlan) -> Self {
443 Self {
444 policy: None,
445 credential_sources: Vec::new(),
446 plan: Some(plan),
447 providers: None,
448 }
449 }
450
451 pub fn with_credential_sources(mut self, sources: Vec<CredentialSource>) -> Self {
452 self.credential_sources = sources;
453 self
454 }
455
456 /// Attach the compiled `RouteSecurityPlan` for this route.
457 pub fn with_plan(mut self, plan: camel_api::security_policy::RouteSecurityPlan) -> Self {
458 self.plan = Some(plan);
459 self
460 }
461
462 /// Attach the provider registry carrying this route's named authenticators.
463 pub fn with_providers(
464 mut self,
465 providers: std::sync::Arc<camel_auth::ProviderRegistry>,
466 ) -> Self {
467 self.providers = Some(providers);
468 self
469 }
470}
471
472impl Clone for SecurityContext {
473 fn clone(&self) -> Self {
474 Self {
475 policy: self.policy.clone(),
476 credential_sources: self.credential_sources.clone(),
477 plan: self.plan.clone(),
478 providers: self.providers.as_ref().map(Arc::clone),
479 }
480 }
481}
482
483impl std::fmt::Debug for SecurityContext {
484 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485 f.debug_struct("SecurityContext")
486 .field("policy", &self.policy.as_ref().map(|_| "<SecurityPolicy>"))
487 .field("credential_sources", &self.credential_sources)
488 .field("plan", &self.plan)
489 .field(
490 "providers",
491 &self.providers.as_ref().map(|_| "<ProviderRegistry>"),
492 )
493 .finish()
494 }
495}
496
497/// How a consumer's exchanges should be processed by the pipeline.
498#[derive(Debug, Clone, PartialEq, Eq)]
499#[non_exhaustive]
500pub enum ConcurrencyModel {
501 /// Exchanges are processed one at a time, in order. Default for polling
502 /// consumers (timer, file) and synchronous consumers (direct).
503 Sequential,
504 /// Exchanges are processed concurrently via `tokio::spawn`. Optional
505 /// semaphore limit (`max`). `None` means unbounded (channel buffer is
506 /// the only backpressure).
507 Concurrent { max: Option<usize> },
508}
509
510/// A Consumer receives data from an external system and submits Exchanges
511/// to the Route's Pipeline via the [`ConsumerContext`].
512///
513/// # Shutdown Contract
514///
515/// The Runtime guarantees the following lifecycle:
516///
517/// 1. `start()` is called once. The Runtime spawns a task that owns the Consumer.
518/// 2. On route stop, the Runtime cancels the [`ConsumerContext`] cancel token.
519/// 3. The spawned task calls `stop()` on ALL exit paths after `start()` succeeds
520/// (clean exit, crash, cancellation, natural completion).
521/// 4. `background_task_handle()` is a supervision hook for crash propagation (ADR-0007),
522/// NOT the shutdown API.
523///
524/// Component authors MUST ensure:
525///
526/// - `stop()` cancels all component-owned inner tasks and cleans up registrations/resources.
527/// - If inner tasks use a private `CancellationToken`, `stop()` MUST cancel it.
528/// - Best practice: inner tasks should use the [`ConsumerContext`] cancel token (or a child)
529/// so they respond to runtime shutdown without waiting for `stop()`.
530/// - If using a private token, `stop()` must cancel it to ensure prompt cleanup.
531/// - `background_task_handle()` returns the `JoinHandle` of the primary background task,
532/// if any. The Runtime monitors this handle for unexpected exits (crash propagation).
533#[async_trait]
534pub trait Consumer: Send + Sync {
535 /// Start consuming messages, sending them through the provided context.
536 async fn start(&mut self, context: ConsumerContext) -> Result<(), CamelError>;
537
538 /// Stop consuming messages and clean up all resources.
539 ///
540 /// Called by the Runtime on every exit path after `start()` succeeds.
541 /// See the [Shutdown Contract](#shutdown-contract) above.
542 async fn stop(&mut self) -> Result<(), CamelError>;
543
544 /// Temporarily suspend consuming messages without fully stopping.
545 ///
546 /// Default: no-op, returns `Ok(())`.
547 async fn suspend(&self) -> Result<(), CamelError> {
548 Ok(())
549 }
550
551 /// Resume consuming after a previous suspension.
552 ///
553 /// Default: no-op, returns `Ok(())`.
554 async fn resume(&self) -> Result<(), CamelError> {
555 Ok(())
556 }
557
558 /// Declares this consumer's natural concurrency model.
559 ///
560 /// The runtime uses this to decide whether to process exchanges
561 /// sequentially or spawn per-exchange. Consumers that accept inbound
562 /// connections (HTTP, WebSocket, Kafka) should override this to return
563 /// `ConcurrencyModel::Concurrent`.
564 ///
565 /// Default: `Sequential`.
566 fn concurrency_model(&self) -> ConcurrencyModel {
567 ConcurrencyModel::Sequential
568 }
569
570 /// Declares how the runtime should wait for this consumer's startup.
571 ///
572 /// - [`ConsumerStartupMode::Immediate`] (default): the consumer's
573 /// `start()` IS the lifetime loop. The runtime treats the route as
574 /// started as soon as `start()` is invoked, preserving the existing
575 /// fire-and-forget semantics for timer/file/direct/… consumers.
576 /// - [`ConsumerStartupMode::Explicit`]: the consumer binds/registers a
577 /// resource inside `start()` and MUST call
578 /// [`ConsumerContext::mark_ready`] after a successful bind. The
579 /// runtime awaits this signal (or an early `start()` error) before
580 /// treating the route as started, so HTTP/WebSocket listeners fail
581 /// fast when the bind fails instead of crashing the background task.
582 ///
583 /// Default: `Immediate`.
584 fn startup_mode(&self) -> ConsumerStartupMode {
585 ConsumerStartupMode::Immediate
586 }
587
588 /// Return a handle to the consumer's long-running background task so the
589 /// runtime can monitor it for unexpected exits after `start()` returns `Ok`.
590 ///
591 /// Default: `None` — consumer's work completes entirely within `start()`.
592 /// Override: return `Some(handle)` if `start()` spawns a detached task.
593 ///
594 /// **Contract:** the task must observe `ConsumerContext::cancelled()` so
595 /// runtime shutdown is distinguishable from crash exits.
596 ///
597 /// This method is called at most once; implementations should use `.take()`
598 /// to transfer ownership of the handle.
599 fn background_task_handle(&mut self) -> Option<JoinHandle<Result<(), CamelError>>> {
600 None
601 }
602
603 /// Set the security context for this consumer.
604 ///
605 /// Called by the route controller before `start()` so the consumer
606 /// can register auth state (e.g. WebSocket auth in `WsAppState`).
607 ///
608 /// Default: no-op, returns `Ok(())`.
609 fn set_security_context(&mut self, _ctx: SecurityContext) {}
610}
611
612#[cfg(test)]
613mod tests {
614 use super::*;
615
616 #[test]
617 fn consumer_context_exposes_route_id() {
618 let (tx, _rx) = mpsc::channel(1);
619 let ctx = ConsumerContext::new(tx, CancellationToken::new(), "test-route".to_string());
620 assert_eq!(ctx.route_id(), "test-route");
621 }
622
623 #[tokio::test]
624 async fn test_consumer_context_cancelled() {
625 let (tx, _rx) = mpsc::channel(16);
626 let token = CancellationToken::new();
627 let ctx = ConsumerContext::new(tx, token.clone(), "test-route".to_string());
628
629 assert!(!ctx.is_cancelled());
630 token.cancel();
631 ctx.cancelled().await;
632 assert!(ctx.is_cancelled());
633 }
634
635 #[test]
636 fn test_concurrency_model_default_is_sequential() {
637 use super::ConcurrencyModel;
638
639 struct DummyConsumer;
640
641 #[async_trait::async_trait]
642 impl super::Consumer for DummyConsumer {
643 async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
644 Ok(())
645 }
646 async fn stop(&mut self) -> Result<(), CamelError> {
647 Ok(())
648 }
649 }
650
651 let consumer = DummyConsumer;
652 assert_eq!(consumer.concurrency_model(), ConcurrencyModel::Sequential);
653 }
654
655 #[test]
656 fn test_concurrency_model_concurrent_override() {
657 use super::ConcurrencyModel;
658
659 struct ConcurrentConsumer;
660
661 #[async_trait::async_trait]
662 impl super::Consumer for ConcurrentConsumer {
663 async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
664 Ok(())
665 }
666 async fn stop(&mut self) -> Result<(), CamelError> {
667 Ok(())
668 }
669 fn concurrency_model(&self) -> ConcurrencyModel {
670 ConcurrencyModel::Concurrent { max: Some(16) }
671 }
672 }
673
674 let consumer = ConcurrentConsumer;
675 assert_eq!(
676 consumer.concurrency_model(),
677 ConcurrencyModel::Concurrent { max: Some(16) }
678 );
679 }
680
681 // --- ConsumerStartupMode tests ---
682
683 #[test]
684 fn test_default_startup_mode_is_immediate() {
685 struct DummyConsumer;
686
687 #[async_trait::async_trait]
688 impl super::Consumer for DummyConsumer {
689 async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
690 Ok(())
691 }
692 async fn stop(&mut self) -> Result<(), CamelError> {
693 Ok(())
694 }
695 }
696
697 let consumer = DummyConsumer;
698 assert_eq!(
699 consumer.startup_mode(),
700 super::ConsumerStartupMode::Immediate
701 );
702 }
703
704 #[test]
705 fn test_startup_mode_explicit_override() {
706 struct ExplicitConsumer;
707
708 #[async_trait::async_trait]
709 impl super::Consumer for ExplicitConsumer {
710 async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
711 Ok(())
712 }
713 async fn stop(&mut self) -> Result<(), CamelError> {
714 Ok(())
715 }
716 fn startup_mode(&self) -> super::ConsumerStartupMode {
717 super::ConsumerStartupMode::Explicit
718 }
719 }
720
721 let consumer = ExplicitConsumer;
722 assert_eq!(
723 consumer.startup_mode(),
724 super::ConsumerStartupMode::Explicit
725 );
726 }
727
728 #[tokio::test]
729 async fn test_startup_signal_mark_ready_resolves_receiver_ok() {
730 let (signal, receiver) = StartupSignal::pair();
731 // Not yet signalled — receiver should still be pending.
732 assert!(matches!(*receiver.rx.borrow(), StartupState::Pending));
733
734 // Mark ready — receiver must observe Ok.
735 signal.mark_ready();
736 let result = receiver.await_ready().await;
737 assert!(result.is_ok(), "expected Ok after mark_ready");
738 }
739
740 #[tokio::test]
741 async fn test_startup_signal_mark_failed_propagates_error() {
742 let (signal, receiver) = StartupSignal::pair();
743 signal.mark_failed("bind failed".to_string());
744 let err = receiver
745 .await_ready()
746 .await
747 .expect_err("expected Err after mark_failed");
748 match err {
749 CamelError::RouteError(msg) => assert!(msg.contains("bind failed")),
750 other => panic!("expected RouteError, got {other:?}"),
751 }
752 }
753
754 #[tokio::test]
755 async fn test_startup_signal_idempotent_first_wins() {
756 let (signal, receiver) = StartupSignal::pair();
757 signal.mark_ready();
758 // mark_failed after mark_ready must NOT override.
759 signal.mark_failed("late failure".to_string());
760 let result = receiver.await_ready().await;
761 assert!(result.is_ok(), "first transition (Ready) wins");
762 }
763
764 #[tokio::test]
765 async fn test_startup_receiver_immediate_is_pre_resolved_ok() {
766 let receiver = StartupReceiver::immediate();
767 let result = receiver.await_ready().await;
768 assert!(result.is_ok(), "immediate receiver must resolve Ok");
769 }
770
771 #[tokio::test]
772 async fn test_consumer_context_mark_ready_drives_signal() {
773 let (tx, _rx) = mpsc::channel(1);
774 let ctx = ConsumerContext::new(
775 tx,
776 CancellationToken::new(),
777 "startup-test-route".to_string(),
778 );
779 let (signal, receiver) = StartupSignal::pair();
780 let ctx = ctx.with_startup(signal);
781 ctx.mark_ready();
782 let result = receiver.await_ready().await;
783 assert!(result.is_ok(), "ctx.mark_ready must resolve the receiver");
784 }
785
786 #[tokio::test]
787 async fn test_consumer_context_mark_failed_drives_signal() {
788 let (tx, _rx) = mpsc::channel(1);
789 let ctx = ConsumerContext::new(
790 tx,
791 CancellationToken::new(),
792 "startup-fail-route".to_string(),
793 );
794 let (signal, receiver) = StartupSignal::pair();
795 let ctx = ctx.with_startup(signal);
796 ctx.mark_failed("assignment window elapsed".to_string());
797 let err = receiver
798 .await_ready()
799 .await
800 .expect_err("ctx.mark_failed must resolve the receiver as Err");
801 match err {
802 CamelError::RouteError(msg) => assert!(msg.contains("assignment window elapsed")),
803 other => panic!("expected RouteError, got {other:?}"),
804 }
805 }
806
807 #[tokio::test]
808 async fn test_startup_receiver_dropped_sender_returns_err() {
809 // Build a signal/receiver pair and drop the signal without ever
810 // transitioning — receiver must surface a contract-violation error.
811 let (_signal, receiver) = StartupSignal::pair();
812 drop(_signal);
813 let err = receiver
814 .await_ready()
815 .await
816 .expect_err("dropped signal must surface as Err");
817 match err {
818 CamelError::RouteError(msg) => assert!(msg.contains("dropped")),
819 other => panic!("expected RouteError, got {other:?}"),
820 }
821 }
822
823 #[tokio::test]
824 async fn test_consumer_default_suspend_resume() {
825 struct DummyConsumer;
826
827 #[async_trait::async_trait]
828 impl super::Consumer for DummyConsumer {
829 async fn start(&mut self, _ctx: super::ConsumerContext) -> Result<(), CamelError> {
830 Ok(())
831 }
832 async fn stop(&mut self) -> Result<(), CamelError> {
833 Ok(())
834 }
835 }
836
837 let consumer = DummyConsumer;
838 assert!(consumer.suspend().await.is_ok());
839 assert!(consumer.resume().await.is_ok());
840 }
841
842 // --- SecurityContext tests ---
843
844 struct StubPolicy;
845
846 #[async_trait::async_trait]
847 impl SecurityPolicy for StubPolicy {
848 async fn evaluate(
849 &self,
850 _exchange: &mut Exchange,
851 _auth: &camel_api::security_policy::AuthContext<'_>,
852 ) -> Result<camel_api::security_policy::AuthorizationDecision, CamelError> {
853 Ok(camel_api::security_policy::AuthorizationDecision::Granted {
854 principal: camel_api::security_policy::Principal {
855 subject: "stub".into(),
856 issuer: "stub".into(),
857 audience: vec![],
858 scopes: vec![],
859 roles: vec![],
860 claims: serde_json::json!({}),
861 },
862 })
863 }
864 }
865
866 struct StubAuthenticator;
867
868 #[async_trait::async_trait]
869 impl camel_auth::TokenAuthenticator for StubAuthenticator {
870 async fn authenticate_bearer(
871 &self,
872 _token: &str,
873 ) -> Result<camel_api::security_policy::Principal, CamelError> {
874 Ok(camel_api::security_policy::Principal {
875 subject: "stub".into(),
876 issuer: "stub".into(),
877 audience: vec![],
878 scopes: vec![],
879 roles: vec![],
880 claims: serde_json::json!({}),
881 })
882 }
883 }
884
885 #[test]
886 fn test_security_context_new() {
887 let ctx = SecurityContext::new(StubPolicy);
888 assert!(Arc::strong_count(ctx.policy.as_ref().expect("new sets policy")) == 1);
889 assert_eq!(
890 ctx.credential_sources,
891 vec![camel_auth::CredentialSource::AuthorizationHeader]
892 );
893 }
894
895 #[test]
896 fn test_security_context_from_arc() {
897 let policy: Arc<dyn SecurityPolicy> = Arc::new(StubPolicy);
898 let ctx = SecurityContext::from_arc(Arc::clone(&policy));
899 assert!(Arc::ptr_eq(
900 ctx.policy.as_ref().expect("from_arc sets policy"),
901 &policy
902 ));
903 assert_eq!(
904 ctx.credential_sources,
905 vec![camel_auth::CredentialSource::AuthorizationHeader]
906 );
907 }
908
909 #[test]
910 fn test_security_context_clone_independent() {
911 let ctx = SecurityContext::new(StubPolicy);
912 let cloned = ctx.clone();
913 assert!(Arc::ptr_eq(
914 ctx.policy.as_ref().expect("source policy"),
915 cloned.policy.as_ref().expect("cloned policy"),
916 ));
917 assert_eq!(ctx.credential_sources, cloned.credential_sources);
918 }
919
920 #[test]
921 fn test_security_context_debug_redacts_traits() {
922 let ctx = SecurityContext::new(StubPolicy);
923 let debug_str = format!("{ctx:?}");
924 assert!(debug_str.contains("<SecurityPolicy>"));
925 assert!(debug_str.contains("credential_sources"));
926 }
927
928 #[test]
929 fn test_security_context_with_credential_sources() {
930 let ctx = SecurityContext::new(StubPolicy).with_credential_sources(vec![
931 camel_auth::CredentialSource::Cookie {
932 name: "session".into(),
933 },
934 camel_auth::CredentialSource::AuthorizationHeader,
935 ]);
936 assert_eq!(ctx.credential_sources.len(), 2);
937 assert!(matches!(
938 &ctx.credential_sources[0],
939 camel_auth::CredentialSource::Cookie { .. }
940 ));
941 }
942
943 #[test]
944 fn security_context_holds_plan_and_providers() {
945 use camel_api::security_policy::{AccessMode, RouteSecurityPlan, TransportId};
946
947 let plan = RouteSecurityPlan {
948 access_mode: AccessMode::Public,
949 provider_ref: None,
950 transport: TransportId::Http,
951 credential_sources: vec![],
952 audience_binding: None,
953 };
954
955 let registry = camel_auth::ProviderRegistry::new();
956 registry.register(
957 "default",
958 camel_auth::ProviderEntry {
959 authenticator: Arc::new(StubAuthenticator),
960 audience_binding: None,
961 },
962 );
963
964 let ctx = SecurityContext::new(StubPolicy)
965 .with_plan(plan)
966 .with_providers(Arc::new(registry));
967
968 let ctx_plan = ctx.plan.as_ref().expect("plan must be attached");
969 assert!(matches!(ctx_plan.access_mode, AccessMode::Public));
970 assert_eq!(ctx_plan.transport, TransportId::Http);
971
972 let providers = ctx.providers.as_ref().expect("providers must be attached");
973 let resolved = providers.resolve("default").expect("provider must resolve");
974 assert!(resolved.audience_binding.is_none());
975 }
976
977 /// `finish-auth-flip` Task 1.3: the `SecurityContext.authenticator`
978 /// hand-off is deleted — transports authenticate through the kernel
979 /// fields (`plan` + `providers`). Registry/doc mentions of the word
980 /// `authenticator` (e.g. `ProviderEntry`) are allowed; the struct
981 /// field is not.
982 #[test]
983 fn security_context_authenticator_deleted_source_scan() {
984 let src = include_str!("consumer.rs");
985 // Assembled at runtime so this scan's own text cannot match.
986 let needle = format!("pub {}authenticator", "");
987 assert!(
988 !src.contains(&needle),
989 "SecurityContext.authenticator must stay deleted: field found in consumer.rs"
990 );
991 }
992}
993
994#[cfg(test)]
995#[path = "consumer_claim_tests.rs"]
996mod consumer_claim_tests;