Skip to main content

rocketmq_client_rust/consumer/store/
controllable_offset.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::atomic::AtomicBool;
16use std::sync::atomic::AtomicI64;
17use std::sync::atomic::Ordering;
18use std::sync::Arc;
19
20pub struct ControllableOffset {
21    value: Arc<AtomicI64>,
22    allow_to_update: Arc<AtomicBool>,
23}
24
25impl ControllableOffset {
26    pub fn new(value: i64) -> Self {
27        Self {
28            value: Arc::new(AtomicI64::new(value)),
29            allow_to_update: Arc::new(AtomicBool::new(true)),
30        }
31    }
32
33    pub fn new_frozen(value: i64) -> Self {
34        Self {
35            value: Arc::new(AtomicI64::new(value)),
36            allow_to_update: Arc::new(AtomicBool::new(false)),
37        }
38    }
39
40    pub fn new_atomic(value: AtomicI64) -> Self {
41        Self {
42            value: Arc::new(value),
43            allow_to_update: Arc::new(AtomicBool::new(true)),
44        }
45    }
46
47    pub fn update(&self, target: i64, increase_only: bool) {
48        if self.allow_to_update.load(Ordering::SeqCst) {
49            self.value
50                .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |val| {
51                    if self.allow_to_update.load(Ordering::SeqCst) {
52                        if increase_only {
53                            Some(std::cmp::max(target, val))
54                        } else {
55                            Some(target)
56                        }
57                    } else {
58                        Some(val)
59                    }
60                })
61                .ok();
62        }
63    }
64
65    pub fn update_unconditionally(&self, target: i64) {
66        self.update(target, false);
67    }
68
69    pub fn update_and_freeze(&self, target: i64) {
70        self.value
71            .fetch_update(Ordering::SeqCst, Ordering::SeqCst, |val| {
72                self.allow_to_update.store(false, Ordering::SeqCst);
73                Some(target)
74            })
75            .ok();
76    }
77
78    pub fn get_offset(&self) -> i64 {
79        self.value.load(Ordering::SeqCst)
80    }
81}