Skip to main content

rocketmq_client_rust/hook/
consume_message_hook.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
15use std::sync::Arc;
16
17use crate::hook::consume_message_context::ConsumeMessageContext;
18
19/// Type alias for a thread-safe hook reference.
20pub type ConsumeMessageHookArc = Arc<dyn ConsumeMessageHook>;
21
22/// Hook for message consumption lifecycle events.
23///
24/// Implementations are invoked synchronously before and after each batch of messages
25/// is consumed by a push consumer. Multiple hooks may be registered and are executed
26/// in registration order.
27///
28/// # Examples
29///
30/// ```ignore
31/// use rocketmq_client::ConsumeMessageContext;
32/// use rocketmq_client::ConsumeMessageHook;
33///
34/// struct LoggingHook;
35///
36/// impl ConsumeMessageHook for LoggingHook {
37///     fn hook_name(&self) -> &'static str {
38///         "LoggingHook"
39///     }
40///
41///     fn consume_message_before(&self, context: &ConsumeMessageContext) {
42///         println!("Before consuming {} messages from {}",
43///                  context.msg_list.len(), context.consumer_group);
44///     }
45///
46///     fn consume_message_after(&self, context: &ConsumeMessageContext) {
47///         println!("After consuming, success: {}", context.success);
48///     }
49/// }
50/// ```
51pub trait ConsumeMessageHook: Send + Sync {
52    /// Returns the unique name of this hook.
53    fn hook_name(&self) -> &'static str;
54
55    /// Invoked before message consumption begins.
56    fn consume_message_before(&self, context: &mut ConsumeMessageContext);
57
58    /// Invoked after message consumption completes.
59    ///
60    /// The context reflects the final consumption status, including whether
61    /// the messages were consumed successfully.
62    fn consume_message_after(&self, context: &mut ConsumeMessageContext);
63}