Skip to main content

rocketmq_common/common/
chain.rs

1// Copyright 2023 The RocketMQ Rust Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Chain of responsibility pattern implementation.
16//!
17//! This module provides traits and types for implementing the chain of
18//! responsibility design pattern in RocketMQ.
19
20use std::cell::Cell;
21
22pub mod handler;
23
24pub use handler::Handler;
25
26/// Handler chain for managing a sequence of handlers.
27///
28/// This struct manages a collection of handlers and executes them in sequence.
29/// Each handler can process the request and decide whether to continue to the
30/// next handler in the chain.
31///
32/// # Type Parameters
33///
34/// * `T` - The type of the request/input
35/// * `R` - The type of the response/output
36///
37/// # Examples
38///
39/// ```rust,ignore
40/// use rocketmq_common::common::chain::{Handler, HandlerChain};
41///
42/// let chain = HandlerChain::<Request, Response>::create()
43///     .add_next(Box::new(ValidationHandler))
44///     .add_next(Box::new(AuthenticationHandler))
45///     .add_next(Box::new(ProcessingHandler));
46///
47/// let response = chain.handle(request);
48/// ```
49pub struct HandlerChain<T, R> {
50    /// List of handlers in the chain
51    handlers: Vec<Box<dyn Handler<T, R>>>,
52
53    /// Current position in the handler chain.
54    /// Uses Cell to achieve interior mutability, avoiding unsafe code.
55    current_index: Cell<usize>,
56}
57
58impl<T, R> HandlerChain<T, R> {
59    /// Create a new empty handler chain.
60    ///
61    /// # Returns
62    ///
63    /// A new `HandlerChain` instance with no handlers
64    ///
65    /// # Examples
66    ///
67    /// ```rust,ignore
68    /// let chain = HandlerChain::<Request, Response>::create();
69    /// ```
70    pub fn create() -> Self {
71        Self {
72            handlers: Vec::new(),
73            current_index: Cell::new(0),
74        }
75    }
76
77    /// Add a handler to the end of the chain.
78    ///
79    /// This method allows for builder-style chaining by returning `self`.
80    ///
81    /// # Arguments
82    ///
83    /// * `handler` - A boxed handler to add to the chain
84    ///
85    /// # Returns
86    ///
87    /// Self for method chaining
88    ///
89    /// # Examples
90    ///
91    /// ```rust,ignore
92    /// let chain = HandlerChain::create()
93    ///     .add_next(Box::new(FirstHandler))
94    ///     .add_next(Box::new(SecondHandler));
95    /// ```
96    pub fn add_next(mut self, handler: Box<dyn Handler<T, R>>) -> Self {
97        self.handlers.push(handler);
98        self
99    }
100
101    /// Process the request through the handler chain.
102    ///
103    /// This method executes handlers in sequence. Each handler can process
104    /// the request and optionally call this method again to continue to the
105    /// next handler in the chain.
106    ///
107    /// # Arguments
108    ///
109    /// * `t` - The request to process
110    ///
111    /// # Returns
112    ///
113    /// An `Option<R>` containing the response, or `None` if no handlers
114    /// are left or no response is produced
115    ///
116    /// # Implementation Note
117    ///
118    /// Uses Cell to store current_index, achieving interior mutability. This allows
119    /// modifying the index while holding an immutable borrow of self, avoiding
120    /// borrow conflicts and unsafe code.
121    ///
122    /// # Examples
123    ///
124    /// ```rust,ignore
125    /// let mut chain = HandlerChain::create()
126    ///     .add_next(Box::new(MyHandler));
127    ///
128    /// if let Some(response) = chain.handle(request) {
129    ///     println!("Got response: {:?}", response);
130    /// }
131    /// ```
132    pub fn handle(&self, t: T) -> Option<R> {
133        let index = self.current_index.get();
134        if index < self.handlers.len() {
135            // Update index (interior mutability)
136            self.current_index.set(index + 1);
137
138            // Now we can safely call the handler because current_index uses Cell
139            // No need to mutably borrow entire self
140            self.handlers[index].handle(t, self)
141        } else {
142            None
143        }
144    }
145
146    /// Reset the chain to start from the beginning.
147    ///
148    /// This allows reusing the same chain for multiple requests.
149    ///
150    /// # Examples
151    ///
152    /// ```rust,ignore
153    /// let mut chain = HandlerChain::create()
154    ///     .add_next(Box::new(MyHandler));
155    ///
156    /// chain.handle(request1);
157    /// chain.reset();
158    /// chain.handle(request2); // Start from first handler again
159    /// ```
160    pub fn reset(&mut self) {
161        self.current_index.set(0);
162    }
163
164    /// Get the number of handlers in the chain.
165    ///
166    /// # Returns
167    ///
168    /// The number of handlers
169    pub fn len(&self) -> usize {
170        self.handlers.len()
171    }
172
173    /// Check if the chain is empty.
174    ///
175    /// # Returns
176    ///
177    /// `true` if there are no handlers, `false` otherwise
178    pub fn is_empty(&self) -> bool {
179        self.handlers.is_empty()
180    }
181}
182
183impl<T, R> Default for HandlerChain<T, R> {
184    fn default() -> Self {
185        Self::create()
186    }
187}