rocketmq_model/common/chain/handler.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//! Handler trait for chain of responsibility pattern.
16//!
17//! This module provides the `Handler` trait which defines the interface for
18//! processing requests in a chain of responsibility pattern.
19
20use super::HandlerChain;
21
22/// Handler trait for chain of responsibility pattern.
23///
24/// Implementors of this trait can process requests of type `T` and return
25/// results of type `R`, with the ability to delegate to the next handler
26/// in the chain.
27///
28/// # Type Parameters
29///
30/// * `T` - The type of the request/input to be handled
31/// * `R` - The type of the response/output returned by the handler
32///
33/// # Examples
34///
35/// ```
36/// use rocketmq_model::common::chain::{Handler, HandlerChain};
37///
38/// struct NonNegative;
39/// impl Handler<i32, i32> for NonNegative {
40/// fn handle(&self, request: i32, chain: &HandlerChain<i32, i32>) -> Option<i32> {
41/// if request >= 0 {
42/// Some(request)
43/// } else {
44/// chain.handle(request)
45/// }
46/// }
47/// }
48///
49/// let mut chain = HandlerChain::create().add_next(Box::new(NonNegative));
50/// assert_eq!(chain.handle(3), Some(3));
51/// chain.reset();
52/// assert_eq!(chain.handle(-1), None);
53/// ```
54pub trait Handler<T, R> {
55 /// Handle a request and optionally delegate to the next handler in the chain.
56 ///
57 /// # Arguments
58 ///
59 /// * `t` - The request/input to be handled
60 /// * `chain` - The handler chain for delegating to subsequent handlers
61 ///
62 /// # Returns
63 ///
64 /// An `Option<R>` containing the response, or `None` if no response is produced
65 ///
66 /// The chain advances its cursor before invoking this method. Calling
67 /// [`HandlerChain::handle`] delegates to the next handler; returning directly
68 /// stops processing for this call. Later calls continue at the current cursor
69 /// until [`HandlerChain::reset`] is called explicitly.
70 ///
71 /// See [`HandlerChain`] for a complete delegation example.
72 fn handle(&self, t: T, chain: &HandlerChain<T, R>) -> Option<R>;
73}