Skip to main content

rocketmq_client_rust/consumer/
lite_pull_consumer.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::collections::HashMap;
16use std::collections::HashSet;
17use std::sync::Arc;
18
19use cheetah_string::CheetahString;
20use rocketmq_model::common::consumer::consume_from_where::ConsumeFromWhere;
21use rocketmq_model::common::message::message_ext::MessageExt;
22use rocketmq_model::common::message::message_queue::MessageQueue;
23use rocketmq_protocol::protocol::heartbeat::message_model::MessageModel;
24use rocketmq_protocol::protocol::heartbeat::subscription_data::SubscriptionData;
25
26use crate::consumer::allocate_message_queue_strategy::AllocateMessageQueueStrategy;
27use crate::consumer::message_queue_listener::ArcMessageQueueListener;
28use crate::consumer::message_queue_listener::MessageQueueListener;
29use crate::consumer::message_selector::MessageSelector;
30use crate::consumer::store::offset_store::OffsetStore;
31use crate::consumer::topic_message_queue_change_listener::TopicMessageQueueChangeListener;
32
33/// A consumer that pulls messages from brokers on demand, providing explicit control over
34/// fetch timing, offset management, and queue assignment.
35///
36/// Unlike the push consumer, the caller drives message retrieval through [`poll`] or
37/// [`poll_with_timeout`], and may manage offsets manually when auto-commit is disabled.
38/// Queue assignment can be controlled either by subscribing to topics (broker-side rebalance)
39/// or by calling [`assign`] directly (client-controlled assignment).
40///
41/// All methods are asynchronous and do not block the calling thread.
42///
43/// [`poll`]: MessagePoll::poll
44/// [`poll_with_timeout`]: MessagePoll::poll_with_timeout
45/// [`assign`]: AssignmentControl::assign
46#[allow(async_fn_in_trait)]
47pub trait SubscriptionControl: Send + Sync {
48    /// Subscribes to the specified topic using the default subscription expression.
49    ///
50    /// This function does not block the calling thread.
51    ///
52    /// # Arguments
53    ///
54    /// * `topic` - The name of the topic to subscribe to.
55    ///
56    /// # Errors
57    ///
58    /// Returns an error if the topic name is invalid or if the subscription cannot be
59    /// registered with the broker.
60    async fn subscribe(&self, topic: &str) -> crate::ClientResult<()>;
61
62    /// Subscribes to the specified topic with a tag-based or SQL-based filter expression.
63    ///
64    /// This function does not block the calling thread.
65    ///
66    /// # Arguments
67    ///
68    /// * `topic` - The name of the topic to subscribe to.
69    /// * `sub_expression` - A tag expression (e.g. `"TagA || TagB"`) or SQL-92 predicate. Pass
70    ///   `"*"` to receive all messages.
71    ///
72    /// # Errors
73    ///
74    /// Returns an error if the topic name is invalid, the expression cannot be parsed,
75    /// or the subscription cannot be registered with the broker.
76    async fn subscribe_with_expression(&self, topic: &str, sub_expression: &str) -> crate::ClientResult<()>;
77
78    /// Subscribes to the specified topic with a filter expression and a queue-change listener.
79    ///
80    /// The listener is invoked whenever the set of assigned [`MessageQueue`]s changes for
81    /// this topic due to rebalance.
82    ///
83    /// This function does not block the calling thread.
84    ///
85    /// # Arguments
86    ///
87    /// * `topic` - The name of the topic to subscribe to.
88    /// * `sub_expression` - A tag expression or SQL-92 predicate. Pass `"*"` for all messages.
89    /// * `listener` - A [`MessageQueueListener`] notified on queue assignment changes.
90    ///
91    /// # Errors
92    ///
93    /// Returns an error if the topic name is invalid, the expression cannot be parsed,
94    /// or the subscription cannot be registered with the broker.
95    async fn subscribe_with_listener<MQL>(
96        &self,
97        topic: &str,
98        sub_expression: &str,
99        listener: MQL,
100    ) -> crate::ClientResult<()>
101    where
102        MQL: MessageQueueListener + 'static;
103
104    /// Subscribes to the specified topic using a [`MessageSelector`] for server-side filtering.
105    ///
106    /// This function does not block the calling thread.
107    ///
108    /// # Arguments
109    ///
110    /// * `topic` - The name of the topic to subscribe to.
111    /// * `selector` - The filter selector. Pass `None` to receive all messages.
112    ///
113    /// # Errors
114    ///
115    /// Returns an error if the topic name is invalid, the selector expression is rejected
116    /// by the broker, or the subscription cannot be registered.
117    async fn subscribe_with_selector(&self, topic: &str, selector: Option<MessageSelector>) -> crate::ClientResult<()>;
118
119    /// Removes the subscription for the specified topic.
120    ///
121    /// Messages for this topic will no longer be fetched after the next rebalance cycle.
122    /// This function does not block the calling thread.
123    ///
124    /// # Arguments
125    ///
126    /// * `topic` - The name of the topic to unsubscribe from.
127    async fn unsubscribe(&self, topic: &str);
128
129    /// Populates `sub_expression_map` with the filter selector for each subscribed topic,
130    /// providing the subscription metadata required for heartbeat payloads.
131    ///
132    /// This function does not block the calling thread.
133    ///
134    /// # Arguments
135    ///
136    /// * `sub_expression_map` - Output map from topic name to its [`MessageSelector`]. Entries are
137    ///   inserted for every topic that has an active subscription with a selector.
138    ///
139    /// # Errors
140    ///
141    /// Returns an error if the subscription metadata cannot be retrieved.
142    async fn build_subscriptions_for_heartbeat(
143        &self,
144        sub_expression_map: &mut HashMap<String, MessageSelector>,
145    ) -> crate::ClientResult<()>;
146
147    /// Returns the subscriptions currently advertised in heartbeat payloads.
148    async fn subscriptions_for_heartbeat(&self) -> HashSet<SubscriptionData>;
149
150    /// Returns the configured message model.
151    async fn message_model(&self) -> MessageModel;
152
153    /// Sets the message model.
154    ///
155    /// This mirrors Java `DefaultLitePullConsumer.setMessageModel`.
156    async fn set_message_model(&self, message_model: MessageModel);
157
158    /// Returns where consumption starts when no offset exists.
159    async fn consume_from_where(&self) -> ConsumeFromWhere;
160
161    /// Sets where consumption starts when no offset exists.
162    ///
163    /// # Errors
164    ///
165    /// Returns an error for legacy `ConsumeFromWhere` values that Java LitePull rejects.
166    async fn set_consume_from_where(&self, consume_from_where: ConsumeFromWhere) -> crate::ClientResult<()>;
167
168    /// Returns the timestamp used by `ConsumeFromWhere::ConsumeFromTimestamp`.
169    async fn consume_timestamp(&self) -> Option<CheetahString>;
170
171    /// Sets the timestamp used by `ConsumeFromWhere::ConsumeFromTimestamp`.
172    async fn set_consume_timestamp(&self, consume_timestamp: Option<CheetahString>);
173
174    /// Returns the message queue allocation strategy used during rebalance.
175    async fn allocate_message_queue_strategy(&self) -> Arc<dyn AllocateMessageQueueStrategy + Send + Sync>;
176
177    /// Sets the message queue allocation strategy used during rebalance.
178    ///
179    /// This mirrors Java `DefaultLitePullConsumer.setAllocateMessageQueueStrategy`.
180    async fn set_allocate_message_queue_strategy(
181        &self,
182        allocate_message_queue_strategy: Arc<dyn AllocateMessageQueueStrategy + Send + Sync>,
183    );
184
185    /// Returns the listener notified when rebalance changes assigned message queues.
186    async fn message_queue_listener(&self) -> Option<ArcMessageQueueListener>;
187
188    /// Sets the listener notified when rebalance changes assigned message queues.
189    ///
190    /// Passing `None` clears the listener, matching Java's nullable
191    /// `DefaultLitePullConsumer.setMessageQueueListener`.
192    async fn set_message_queue_listener(&self, message_queue_listener: Option<ArcMessageQueueListener>);
193
194    /// Returns the topic metadata check interval in milliseconds.
195    async fn topic_metadata_check_interval_millis(&self) -> u64;
196
197    /// Sets the topic metadata check interval in milliseconds.
198    ///
199    /// Like Java, this applies directly to the stored configuration. If the
200    /// metadata task is already scheduled, the existing task keeps its start-time interval.
201    async fn set_topic_metadata_check_interval_millis(&self, interval_millis: u64);
202
203    /// Returns whether pulls always use the configured default broker ID.
204    async fn is_connect_broker_by_user(&self) -> bool;
205
206    /// Sets whether pulls always use the configured default broker ID.
207    ///
208    /// This mirrors Java `DefaultLitePullConsumer.setConnectBrokerByUser`.
209    async fn set_connect_broker_by_user(&self, connect_broker_by_user: bool);
210
211    /// Returns the broker ID used when user-controlled broker selection is enabled.
212    async fn default_broker_id(&self) -> u64;
213
214    /// Sets the broker ID used when user-controlled broker selection is enabled.
215    ///
216    /// This mirrors Java `DefaultLitePullConsumer.setDefaultBrokerId`.
217    async fn set_default_broker_id(&self, broker_id: u64);
218
219    /// Returns whether the subscription group runs in unit mode.
220    async fn is_unit_mode(&self) -> bool;
221
222    /// Sets whether the subscription group runs in unit mode.
223    ///
224    /// This mirrors Java `DefaultLitePullConsumer.setUnitMode`.
225    async fn set_unit_mode(&self, unit_mode: bool);
226
227    /// Registers a listener that is notified when the set of [`MessageQueue`]s for a topic changes.
228    ///
229    /// This function does not block the calling thread.
230    ///
231    /// # Arguments
232    ///
233    /// * `topic` - The topic to monitor for queue changes.
234    /// * `listener` - A [`TopicMessageQueueChangeListener`] invoked when the queue set changes.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if a listener is already registered for the given topic, or if the
239    /// registration fails due to an internal error.
240    async fn register_topic_message_queue_change_listener<TL>(
241        &self,
242        topic: &str,
243        listener: TL,
244    ) -> crate::ClientResult<()>
245    where
246        TL: TopicMessageQueueChangeListener + 'static;
247
248    /// Updates the name server address used for topic route discovery.
249    ///
250    /// This function does not block the calling thread.
251    ///
252    /// # Arguments
253    ///
254    /// * `name_server_address` - The new semicolon-separated name server address list.
255    async fn update_name_server_address(&self, name_server_address: &str);
256}
257
258#[allow(async_fn_in_trait)]
259pub trait AssignmentControl: Send + Sync {
260    /// Returns the set of [`MessageQueue`]s currently assigned to this consumer.
261    ///
262    /// This function does not block the calling thread.
263    ///
264    /// # Errors
265    ///
266    /// Returns an error if the consumer is not in the running state.
267    async fn assignment(&self) -> crate::ClientResult<HashSet<MessageQueue>>;
268
269    /// Manually assigns the given [`MessageQueue`]s to this consumer, bypassing broker rebalance.
270    ///
271    /// Any previously assigned queues not present in `message_queues` are removed.
272    /// This function does not block the calling thread.
273    ///
274    /// # Arguments
275    ///
276    /// * `message_queues` - The complete set of queues to assign to this consumer.
277    ///
278    /// # Errors
279    ///
280    /// Returns an error if `message_queues` is empty or the assignment cannot be applied.
281    async fn assign(&self, message_queues: Vec<MessageQueue>) -> crate::ClientResult<()>;
282
283    /// Sets the subscription filter expression applied when fetching from manually assigned queues.
284    ///
285    /// This function does not block the calling thread.
286    ///
287    /// # Arguments
288    ///
289    /// * `topic` - The topic for which the filter expression applies.
290    /// * `sub_expression` - A tag expression or SQL-92 predicate used to filter messages.
291    ///
292    /// # Errors
293    ///
294    /// Returns an error if the expression is blank, the consumer has already started, or
295    /// the subscription cannot be switched to manual assignment mode.
296    async fn set_sub_expression_for_assign(&self, topic: &str, sub_expression: &str) -> crate::ClientResult<()>;
297
298    /// Seeks the fetch position of the specified [`MessageQueue`] to the given offset.
299    ///
300    /// The next [`poll`] invocation will return messages starting from `offset`.
301    /// This function does not block the calling thread.
302    ///
303    /// # Arguments
304    ///
305    /// * `message_queue` - The queue whose fetch position is to be updated.
306    /// * `offset` - The target offset. Must be within the queue's valid range.
307    ///
308    /// # Errors
309    ///
310    /// Returns an error if the queue is not currently assigned to this consumer,
311    /// or if the specified offset is out of the valid range.
312    ///
313    /// [`poll`]: MessagePoll::poll
314    async fn seek(&self, message_queue: &MessageQueue, offset: i64) -> crate::ClientResult<()>;
315
316    /// Suspends message fetching for the specified [`MessageQueue`]s.
317    ///
318    /// Paused queues are excluded from subsequent [`poll`] results until [`resume`] is called.
319    /// This function does not block the calling thread.
320    ///
321    /// # Arguments
322    ///
323    /// * `message_queues` - The queues to pause.
324    ///
325    /// [`poll`]: MessagePoll::poll
326    /// [`resume`]: AssignmentControl::resume
327    async fn pause(&self, message_queues: Vec<MessageQueue>);
328
329    /// Resumes message fetching for the specified [`MessageQueue`]s.
330    ///
331    /// This function does not block the calling thread.
332    ///
333    /// # Arguments
334    ///
335    /// * `message_queues` - The queues to resume.
336    async fn resume(&self, message_queues: Vec<MessageQueue>);
337
338    /// Seeks the fetch position of the specified [`MessageQueue`] to its earliest available offset.
339    ///
340    /// This function does not block the calling thread.
341    ///
342    /// # Arguments
343    ///
344    /// * `message_queue` - The queue to seek to the beginning.
345    ///
346    /// # Errors
347    ///
348    /// Returns an error if the queue is not assigned to this consumer or if the earliest
349    /// offset cannot be retrieved from the broker.
350    async fn seek_to_begin(&self, message_queue: &MessageQueue) -> crate::ClientResult<()>;
351
352    /// Seeks the fetch position of the specified [`MessageQueue`] to its latest available offset.
353    ///
354    /// The next [`poll`] call will return only messages published after this point.
355    /// This function does not block the calling thread.
356    ///
357    /// # Arguments
358    ///
359    /// * `message_queue` - The queue to seek to the end.
360    ///
361    /// # Errors
362    ///
363    /// Returns an error if the queue is not assigned to this consumer or if the latest
364    /// offset cannot be retrieved from the broker.
365    ///
366    /// [`poll`]: MessagePoll::poll
367    async fn seek_to_end(&self, message_queue: &MessageQueue) -> crate::ClientResult<()>;
368
369    /// Checks whether a specific [`MessageQueue`] is currently paused.
370    ///
371    /// A paused queue will not be fetched from during [`poll`] operations until it is resumed.
372    ///
373    /// This function does not block the calling thread.
374    ///
375    /// # Arguments
376    ///
377    /// * `message_queue` - The queue to check.
378    ///
379    /// # Returns
380    ///
381    /// `true` if the queue is paused, `false` otherwise.
382    ///
383    /// [`poll`]: MessagePoll::poll
384    async fn is_paused(&self, message_queue: &MessageQueue) -> bool;
385}
386
387#[allow(async_fn_in_trait)]
388pub trait MessagePoll: Send + Sync {
389    /// Fetches the next batch of messages without allocating owned copies.
390    ///
391    /// Returns immutable `Arc<MessageExt>` handles without heap allocation or deep cloning.
392    /// The returned handles remain valid until
393    /// they are dropped. Messages that need to outlive the poll scope must be cloned explicitly.
394    ///
395    /// This method uses the default poll timeout configured for the consumer.
396    ///
397    /// # Performance
398    ///
399    /// Message contents are not copied. For workloads processing messages without long-term
400    /// storage, this eliminates allocation overhead compared to [`poll()`](Self::poll).
401    ///
402    /// # Examples
403    ///
404    /// ```rust,ignore
405    /// let messages = consumer.poll_zero_copy().await;
406    /// for msg in &messages {
407    ///     process_message(msg);
408    /// }
409    ///
410    /// // Clone only filtered messages
411    /// let messages = consumer.poll_zero_copy().await;
412    /// let important: Vec<MessageExt> = messages.into_iter()
413    ///     .filter(|msg| is_important(msg))
414    ///     .map(|msg| (*msg).clone())
415    ///     .collect();
416    /// ```
417    ///
418    /// Returns an empty vector if no messages are available within the default timeout period.
419    /// This function does not block the calling thread.
420    async fn poll_zero_copy(&self) -> Vec<std::sync::Arc<MessageExt>>;
421
422    /// Fetches the next batch of messages without allocating owned copies, with a specified
423    /// timeout.
424    ///
425    /// Behaves identically to [`poll_zero_copy()`](Self::poll_zero_copy), but waits up to `timeout` milliseconds
426    /// for messages to become available.
427    ///
428    /// # Arguments
429    ///
430    /// * `timeout` - Maximum time to wait for messages, in milliseconds.
431    ///
432    /// # Examples
433    ///
434    /// ```rust,ignore
435    /// let messages = consumer.poll_with_timeout_zero_copy(1000).await;
436    /// ```
437    ///
438    /// Returns an empty vector if no messages are available before the timeout expires.
439    /// This function does not block the calling thread.
440    async fn poll_with_timeout_zero_copy(&self, timeout: u64) -> Vec<std::sync::Arc<MessageExt>>;
441
442    /// Fetches the next batch of messages, returning owned copies.
443    ///
444    /// Each returned message is cloned from the internal message store. The caller
445    /// owns the returned messages and may store them beyond the poll scope.
446    ///
447    /// This method uses the default poll timeout configured for the consumer.
448    ///
449    /// # Performance
450    ///
451    /// All messages are deep-cloned, including message body and properties. For a 2KB message,
452    /// each poll returning 32 messages allocates approximately 90KB. At 100 polls per second,
453    /// this results in approximately 9MB/s of allocations.
454    ///
455    /// For workloads that do not require owned messages, [`poll_zero_copy()`](Self::poll_zero_copy) avoids
456    /// this allocation overhead.
457    ///
458    /// # Examples
459    ///
460    /// ```rust,ignore
461    /// let messages = consumer.poll().await;
462    /// my_store.save(messages);
463    /// ```
464    ///
465    /// Returns an empty vector if no messages are available within the timeout period.
466    /// This function does not block the calling thread.
467    async fn poll(&self) -> Vec<MessageExt>;
468
469    /// Fetches the next batch of messages with a specified timeout, returning owned copies.
470    ///
471    /// Behaves identically to [`poll()`](Self::poll), but waits up to `timeout` milliseconds for
472    /// messages to become available. All messages are deep-cloned.
473    ///
474    /// # Arguments
475    ///
476    /// * `timeout` - Maximum time to wait for messages, in milliseconds.
477    ///
478    /// Returns an empty vector if no messages are available before the timeout expires.
479    /// This function does not block the calling thread.
480    async fn poll_with_timeout(&self, timeout: u64) -> Vec<MessageExt>;
481
482    /// Returns the default timeout used by [`poll`] in milliseconds.
483    ///
484    /// This function does not block the calling thread.
485    ///
486    /// [`poll`]: MessagePoll::poll
487    async fn poll_timeout_millis(&self) -> u64;
488
489    /// Sets the default timeout used by [`poll`] in milliseconds.
490    ///
491    /// This follows the Java client setter and applies the value directly. Use
492    /// [`poll_with_timeout`] for a per-call timeout override.
493    ///
494    /// This function does not block the calling thread.
495    ///
496    /// [`poll`]: MessagePoll::poll
497    /// [`poll_with_timeout`]: MessagePoll::poll_with_timeout
498    async fn set_poll_timeout_millis(&self, timeout_millis: u64);
499
500    /// Returns the maximum time that the broker may suspend a long-poll pull request.
501    async fn broker_suspend_max_time_millis(&self) -> u64;
502
503    /// Sets the maximum time that the broker may suspend a long-poll pull request.
504    ///
505    /// This follows Java `DefaultLitePullConsumer.setBrokerSuspendMaxTimeMillis`
506    /// and applies the value directly.
507    async fn set_broker_suspend_max_time_millis(&self, timeout_millis: u64);
508
509    /// Returns the consumer-side timeout for suspended long-poll pull requests.
510    async fn consumer_timeout_millis_when_suspend(&self) -> u64;
511
512    /// Sets the consumer-side timeout for suspended long-poll pull requests.
513    ///
514    /// This follows Java `DefaultLitePullConsumer.setConsumerTimeoutMillisWhenSuspend`
515    /// and applies the value directly.
516    async fn set_consumer_timeout_millis_when_suspend(&self, timeout_millis: u64);
517
518    /// Returns the RPC timeout used by lite pull requests in milliseconds.
519    async fn consumer_pull_timeout_millis(&self) -> u64;
520
521    /// Sets the RPC timeout used by lite pull requests in milliseconds.
522    ///
523    /// This follows Java `DefaultLitePullConsumer.setConsumerPullTimeoutMillis`
524    /// and applies the value directly.
525    async fn set_consumer_pull_timeout_millis(&self, timeout_millis: u64);
526
527    /// Returns the maximum number of messages requested in a single pull.
528    async fn pull_batch_size(&self) -> i32;
529
530    /// Sets the maximum number of messages requested in a single pull.
531    ///
532    /// This follows the Java client setter and applies the value directly.
533    async fn set_pull_batch_size(&self, pull_batch_size: i32);
534
535    /// Returns the configured number of pull worker threads.
536    async fn pull_thread_nums(&self) -> usize;
537
538    /// Sets the configured number of pull worker threads.
539    ///
540    /// This mirrors Java `DefaultLitePullConsumer.setPullThreadNums`.
541    async fn set_pull_thread_nums(&self, pull_thread_nums: usize);
542
543    /// Returns the maximum total number of cached messages across all queues.
544    async fn pull_threshold_for_all(&self) -> i64;
545
546    /// Sets the maximum total number of cached messages across all queues.
547    ///
548    /// This follows the Java client setter and applies the value directly.
549    async fn set_pull_threshold_for_all(&self, pull_threshold_for_all: i64);
550
551    /// Returns the maximum cached message count for each queue.
552    async fn pull_threshold_for_queue(&self) -> i64;
553
554    /// Sets the maximum cached message count for each queue.
555    ///
556    /// This follows the Java client setter and applies the value directly.
557    async fn set_pull_threshold_for_queue(&self, pull_threshold_for_queue: i64);
558
559    /// Returns the maximum cached message size in MiB for each queue.
560    async fn pull_threshold_size_for_queue(&self) -> i32;
561
562    /// Sets the maximum cached message size in MiB for each queue.
563    ///
564    /// This follows the Java client setter and applies the value directly.
565    async fn set_pull_threshold_size_for_queue(&self, pull_threshold_size_for_queue: i32);
566
567    /// Returns the maximum allowed offset span in a cached process queue.
568    async fn consume_max_span(&self) -> i64;
569
570    /// Sets the maximum allowed offset span in a cached process queue.
571    ///
572    /// This follows the Java client setter and applies the value directly.
573    async fn set_consume_max_span(&self, consume_max_span: i64);
574}
575
576#[allow(async_fn_in_trait)]
577pub trait ConsumerOffsetControl: Send + Sync {
578    /// Returns the configured offset store, if one has been set or initialized.
579    async fn offset_store(&self) -> Option<Arc<OffsetStore>>;
580
581    /// Sets the offset store used by the consumer.
582    ///
583    /// This mirrors Java `DefaultLitePullConsumer.setOffsetStore`. The store
584    /// should be set before startup so load, rebalance, and commit paths share
585    /// the same backend.
586    async fn set_offset_store(&self, offset_store: Option<Arc<OffsetStore>>) -> crate::ClientResult<()>;
587
588    /// Returns whether automatic offset commit is enabled.
589    ///
590    /// This function does not block the calling thread.
591    async fn is_auto_commit(&self) -> bool;
592
593    /// Enables or disables automatic offset commit.
594    ///
595    /// When auto-commit is enabled, offsets are committed periodically without explicit calls
596    /// to [`commit`] or [`commit_sync`]. When disabled, the caller is responsible for committing
597    /// offsets.
598    ///
599    /// This function does not block the calling thread.
600    ///
601    /// # Arguments
602    ///
603    /// * `auto_commit` - `true` to enable automatic offset commit; `false` to disable it.
604    ///
605    /// [`commit`]: ConsumerOffsetControl::commit
606    /// [`commit_sync`]: ConsumerOffsetControl::commit_sync
607    async fn set_auto_commit(&self, auto_commit: bool);
608
609    /// Returns the interval between automatic offset commits in milliseconds.
610    ///
611    /// This function does not block the calling thread.
612    async fn auto_commit_interval_millis(&self) -> u64;
613
614    /// Sets the interval between automatic offset commits in milliseconds.
615    ///
616    /// Values below the Java client minimum of 1000ms are ignored, matching
617    /// `DefaultLitePullConsumer.setAutoCommitIntervalMillis`.
618    ///
619    /// This function does not block the calling thread.
620    ///
621    /// # Arguments
622    ///
623    /// * `interval_millis` - The new auto-commit interval in milliseconds.
624    async fn set_auto_commit_interval_millis(&self, interval_millis: u64);
625
626    /// Queries the broker for all [`MessageQueue`]s belonging to the specified topic.
627    ///
628    /// This function does not block the calling thread.
629    ///
630    /// # Arguments
631    ///
632    /// * `topic` - The name of the topic to query.
633    ///
634    /// # Errors
635    ///
636    /// Returns an error if the topic does not exist, if the name server is unreachable,
637    /// or if the consumer is not in the running state.
638    async fn fetch_message_queues(&self, topic: &str) -> crate::ClientResult<Vec<MessageQueue>>;
639
640    /// Queries the broker for the offset corresponding to the given timestamp in a queue.
641    ///
642    /// This function does not block the calling thread.
643    ///
644    /// # Arguments
645    ///
646    /// * `message_queue` - The queue to query.
647    /// * `timestamp` - The Unix timestamp in milliseconds. The broker returns the offset of the
648    ///   first message stored at or after this timestamp.
649    ///
650    /// # Errors
651    ///
652    /// Returns an error if the queue is not found on the broker or the query fails.
653    async fn offset_for_timestamp(&self, message_queue: &MessageQueue, timestamp: u64) -> crate::ClientResult<i64>;
654
655    /// Queries the broker for the earliest message store time of the specified queue.
656    ///
657    /// This function does not block the calling thread.
658    ///
659    /// # Arguments
660    ///
661    /// * `message_queue` - The queue to query.
662    ///
663    /// # Errors
664    ///
665    /// Returns an error if the queue is not found on the broker, the consumer is not running,
666    /// or this LitePull implementation does not support broker offset metadata queries.
667    async fn earliest_msg_store_time(&self, message_queue: &MessageQueue) -> crate::ClientResult<i64>;
668
669    /// Queries the broker for the current maximum offset of the specified queue.
670    ///
671    /// This function does not block the calling thread.
672    ///
673    /// # Arguments
674    ///
675    /// * `message_queue` - The queue to query.
676    ///
677    /// # Errors
678    ///
679    /// Returns an error if the queue is not found on the broker, the consumer is not running,
680    /// or this LitePull implementation does not support broker offset metadata queries.
681    async fn max_offset(&self, message_queue: &MessageQueue) -> crate::ClientResult<i64>;
682
683    /// Queries the broker for the current minimum offset of the specified queue.
684    ///
685    /// This function does not block the calling thread.
686    ///
687    /// # Arguments
688    ///
689    /// * `message_queue` - The queue to query.
690    ///
691    /// # Errors
692    ///
693    /// Returns an error if the queue is not found on the broker, the consumer is not running,
694    /// or this LitePull implementation does not support broker offset metadata queries.
695    async fn min_offset(&self, message_queue: &MessageQueue) -> crate::ClientResult<i64>;
696
697    /// Commits all consumed offsets to the consumer offset store.
698    ///
699    /// This function does not block the calling thread.
700    ///
701    /// # Deprecation
702    ///
703    /// This method is deprecated. The name implies broker-synchronous persistence, but Java
704    /// `DefaultLitePullConsumer.commitSync()` delegates to `commitAll()` and only updates the
705    /// consumer offset store. Use [`commit`] for the modern equivalent.
706    ///
707    /// [`commit`]: ConsumerOffsetControl::commit
708    async fn commit_sync(&self);
709
710    /// Commits the provided offsets and optionally persists them to the broker.
711    ///
712    /// This function does not block the calling thread.
713    ///
714    /// # Deprecation
715    ///
716    /// This method is deprecated. The name implies synchronous behavior, but the underlying
717    /// implementation relies on a background thread to commit offsets rather than committing
718    /// synchronously. Use [`commit_with_map`] instead.
719    ///
720    /// # Arguments
721    ///
722    /// * `offset_map` - A map from [`MessageQueue`] to the offset to commit.
723    /// * `persist` - When `true`, the committed offsets are persisted to the broker immediately.
724    ///
725    /// [`commit_with_map`]: ConsumerOffsetControl::commit_with_map
726    async fn commit_sync_with_map(&self, offset_map: HashMap<MessageQueue, i64>, persist: bool);
727
728    /// Commits all consumed offsets to the consumer offset store.
729    ///
730    /// This function does not block the calling thread. Broker or local-file persistence is
731    /// performed by the normal periodic persistence task, shutdown, or explicit
732    /// `commit_with_map` / `commit_with_set` calls with `persist = true`.
733    ///
734    /// [`commit_sync`]: ConsumerOffsetControl::commit_sync
735    async fn commit(&self);
736
737    /// Commits the provided offsets asynchronously, optionally persisting them to the broker.
738    ///
739    /// This function does not block the calling thread.
740    ///
741    /// # Arguments
742    ///
743    /// * `offset_map` - A map from [`MessageQueue`] to the offset to commit.
744    /// * `persist` - When `true`, the committed offsets are persisted to the broker.
745    async fn commit_with_map(&self, offset_map: HashMap<MessageQueue, i64>, persist: bool);
746
747    /// Commits the offsets for the specified subset of assigned queues.
748    ///
749    /// This function does not block the calling thread.
750    ///
751    /// # Arguments
752    ///
753    /// * `message_queues` - The queues whose current offsets are to be committed.
754    /// * `persist` - When `true`, the committed offsets are persisted to the broker.
755    async fn commit_with_set(&self, message_queues: HashSet<MessageQueue>, persist: bool);
756
757    /// Returns the last committed offset for the specified [`MessageQueue`].
758    ///
759    /// This function does not block the calling thread.
760    ///
761    /// # Arguments
762    ///
763    /// * `message_queue` - The queue to query.
764    ///
765    /// # Errors
766    ///
767    /// Returns an error if the queue is not assigned to this consumer or if the offset
768    /// cannot be retrieved from the offset store.
769    async fn committed(&self, message_queue: &MessageQueue) -> crate::ClientResult<i64>;
770
771    /// Commits all consumed offsets for all assigned queues to the local offset store.
772    ///
773    /// This method commits the current consumption offset for every assigned [`MessageQueue`].
774    /// It follows the Java client `commitAll()` behavior: offsets are updated in the consumer's
775    /// offset store, while broker or local-file persistence is handled by the normal periodic
776    /// persistence task, shutdown, or explicit `commit_with_map` / `commit_with_set` calls with
777    /// `persist = true`.
778    ///
779    /// This function does not block the calling thread.
780    ///
781    /// # Errors
782    ///
783    /// Returns an error if the consumer is not in the running state.
784    ///
785    /// [`commit`]: ConsumerOffsetControl::commit
786    async fn commit_all(&self) -> crate::ClientResult<()>;
787}
788
789#[allow(async_fn_in_trait)]
790pub trait ConsumerLifecycle: Send + Sync {
791    /// Starts the consumer and establishes connections to the broker and name server.
792    ///
793    /// This function does not block the calling thread.
794    ///
795    /// # Errors
796    ///
797    /// Returns an error if the consumer is already running, if required configuration is
798    /// invalid, or if the connection to the name server cannot be established.
799    async fn start(&self) -> crate::ClientResult<()>;
800
801    /// Shuts down the consumer and releases all associated resources.
802    ///
803    /// This function does not block the calling thread. After shutdown, the consumer
804    /// cannot be restarted.
805    async fn shutdown(&self);
806
807    /// Returns whether the consumer is currently in the running state.
808    ///
809    /// This function does not block the calling thread.
810    async fn is_running(&self) -> bool;
811}