pub struct HandlerChain<T, R> { /* private fields */ }Expand description
Handler chain for managing a sequence of handlers.
This struct manages a collection of handlers and executes them in sequence. Each handler can process the request and decide whether to continue to the next handler in the chain.
§Type Parameters
T- The type of the request/inputR- The type of the response/output
§Examples
use rocketmq_model::common::chain::{Handler, HandlerChain};
struct Increment;
struct Double;
impl Handler<i32, i32> for Increment {
fn handle(&self, request: i32, chain: &HandlerChain<i32, i32>) -> Option<i32> {
chain.handle(request + 1)
}
}
impl Handler<i32, i32> for Double {
fn handle(&self, request: i32, _chain: &HandlerChain<i32, i32>) -> Option<i32> {
Some(request * 2)
}
}
let chain = HandlerChain::create()
.add_next(Box::new(Increment))
.add_next(Box::new(Double));
assert_eq!(chain.handle(3), Some(8));
assert_eq!(chain.handle(3), None);The cursor advances before each handler is called. Handlers delegate explicitly
through Self::handle; returning a response without delegation stops that call.
Later calls continue at the current cursor. Independent requests require an
explicit Self::reset when reusing the chain.
Implementations§
Source§impl<T, R> HandlerChain<T, R>
impl<T, R> HandlerChain<T, R>
Sourcepub fn add_next(self, handler: Box<dyn Handler<T, R>>) -> Self
pub fn add_next(self, handler: Box<dyn Handler<T, R>>) -> Self
Add a handler to the end of the chain.
This method allows for builder-style chaining by returning self.
§Arguments
handler- A boxed handler to add to the chain
§Returns
Self for method chaining
See HandlerChain for a complete example with delegating and terminal handlers.
Sourcepub fn handle(&self, t: T) -> Option<R>
pub fn handle(&self, t: T) -> Option<R>
Process the request through the handler chain.
This method executes handlers in sequence. Each handler can process the request and optionally call this method again to continue to the next handler in the chain.
§Arguments
t- The request to process
§Returns
An Option<R> containing the response, or None if no handlers
are left or no response is produced
The cursor advances before invoking the selected handler. Returning a response
without calling chain.handle leaves later handlers for a subsequent call.
The cursor is not reset automatically, even if a handler returns None.
See HandlerChain for delegation and Self::reset for reuse.
Sourcepub fn reset(&mut self)
pub fn reset(&mut self)
Reset the chain to start from the beginning.
This allows reusing the same chain for multiple requests.
§Examples
use rocketmq_model::common::chain::{Handler, HandlerChain};
struct Echo;
impl Handler<i32, i32> for Echo {
fn handle(&self, request: i32, _chain: &HandlerChain<i32, i32>) -> Option<i32> {
Some(request)
}
}
let mut chain = HandlerChain::create().add_next(Box::new(Echo));
assert_eq!(chain.handle(7), Some(7));
assert_eq!(chain.handle(8), None);
chain.reset();
assert_eq!(chain.handle(8), Some(8));