Skip to main content

rocketmq_store_api/
ha_contract.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//! Backend-neutral high-availability value types and acknowledgement decisions.
16
17use std::collections::BTreeSet;
18use std::num::NonZeroUsize;
19
20use crate::Durability;
21use crate::StoreContractViolation;
22
23/// A positive Controller-issued master epoch.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
25pub struct MasterEpoch(i32);
26
27impl MasterEpoch {
28    /// Returns the wire-compatible epoch value.
29    pub const fn get(self) -> i32 {
30        self.0
31    }
32}
33
34impl TryFrom<i32> for MasterEpoch {
35    type Error = StoreContractViolation;
36
37    fn try_from(value: i32) -> Result<Self, Self::Error> {
38        if value <= 0 {
39            return Err(StoreContractViolation::HaInvalidMasterEpoch(value));
40        }
41        Ok(Self(value))
42    }
43}
44
45/// A positive Controller-issued sync-state-set epoch.
46#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
47pub struct SyncStateSetEpoch(i32);
48
49impl SyncStateSetEpoch {
50    /// Returns the wire-compatible epoch value.
51    pub const fn get(self) -> i32 {
52        self.0
53    }
54}
55
56impl TryFrom<i32> for SyncStateSetEpoch {
57    type Error = StoreContractViolation;
58
59    fn try_from(value: i32) -> Result<Self, Self::Error> {
60        if value <= 0 {
61            return Err(StoreContractViolation::HaInvalidSyncStateSetEpoch(value));
62        }
63        Ok(Self(value))
64    }
65}
66
67/// A replication acknowledgement count greater than the local leader alone.
68#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
69pub struct ReplicaCount(NonZeroUsize);
70
71impl ReplicaCount {
72    /// Creates a replica count that necessarily requires at least one remote acknowledgement.
73    ///
74    /// # Errors
75    ///
76    /// Returns [`StoreContractViolation::HaInvalidReplicaCount`] when `value` is less than two.
77    pub fn try_new(value: usize) -> Result<Self, StoreContractViolation> {
78        if value < 2 {
79            return Err(StoreContractViolation::HaInvalidReplicaCount(value));
80        }
81        Ok(Self(NonZeroUsize::new(value).expect("value is proven non-zero")))
82    }
83
84    /// Returns the number of acknowledgements, including the local leader.
85    pub const fn get(self) -> usize {
86        self.0.get()
87    }
88}
89
90/// The explicit durability condition requested by a synchronous append.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
92pub enum AckPolicy {
93    /// Require only the local durable watermark.
94    LocalDurable,
95    /// Require the local leader and the configured number of unique in-sync members.
96    ReplicaCount(ReplicaCount),
97    /// Require the local leader and every member of the current sync-state set.
98    AllInSyncSet,
99}
100
101impl AckPolicy {
102    /// Converts a legacy ACK count or sentinel at a wire/configuration boundary.
103    ///
104    /// # Errors
105    ///
106    /// Returns [`StoreContractViolation::HaInvalidAckPolicy`] for zero, negative values other than
107    /// `all_in_sync_state_set`, or values that cannot be represented as `usize`.
108    pub fn try_from_legacy(value: i32, all_in_sync_state_set: i32) -> Result<Self, StoreContractViolation> {
109        if value == all_in_sync_state_set {
110            return Ok(Self::AllInSyncSet);
111        }
112        if value == 1 {
113            return Ok(Self::LocalDurable);
114        }
115        if value <= 0 {
116            return Err(StoreContractViolation::HaInvalidAckPolicy(value));
117        }
118        let count = usize::try_from(value).map_err(|_| StoreContractViolation::HaInvalidAckPolicy(value))?;
119        Ok(Self::ReplicaCount(ReplicaCount::try_new(count)?))
120    }
121}
122
123/// The Controller authority required to accept a write or role transition.
124#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
125pub struct WriteAuthority {
126    broker_id: i64,
127    master_epoch: MasterEpoch,
128}
129
130/// A generation-scoped Controller write lease token.
131///
132/// The token deliberately excludes an expiry timestamp. A Broker converts the
133/// Controller-provided duration into a process-local monotonic deadline before
134/// installing it in Store.
135#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
136pub struct WriteLeaseToken {
137    authority: WriteAuthority,
138    generation: u64,
139}
140
141impl WriteLeaseToken {
142    /// Creates a token for a non-zero Controller lease generation.
143    ///
144    /// # Errors
145    ///
146    /// Returns [`StoreContractViolation::HaInvalidLeaseGeneration`] when `generation` is zero.
147    pub fn try_new(authority: WriteAuthority, generation: u64) -> Result<Self, StoreContractViolation> {
148        if generation == 0 {
149            return Err(StoreContractViolation::HaInvalidLeaseGeneration(generation));
150        }
151        Ok(Self { authority, generation })
152    }
153
154    /// Returns the Controller authority carried by this lease.
155    pub const fn authority(self) -> WriteAuthority {
156        self.authority
157    }
158
159    /// Returns the monotonically increasing lease generation.
160    pub const fn generation(self) -> u64 {
161        self.generation
162    }
163}
164
165impl WriteAuthority {
166    /// Creates an authority for a non-negative broker identifier and positive epoch.
167    ///
168    /// # Errors
169    ///
170    /// Returns [`StoreContractViolation::HaInvalidBrokerId`] when `broker_id` is negative.
171    pub fn try_new(broker_id: i64, master_epoch: MasterEpoch) -> Result<Self, StoreContractViolation> {
172        if broker_id < 0 {
173            return Err(StoreContractViolation::HaInvalidBrokerId(broker_id));
174        }
175        Ok(Self {
176            broker_id,
177            master_epoch,
178        })
179    }
180
181    /// Creates an authority from a wire broker identifier.
182    ///
183    /// # Errors
184    ///
185    /// Returns [`StoreContractViolation::HaBrokerIdOutOfRange`] when the identifier cannot be represented
186    /// by the canonical signed broker-id type.
187    pub fn try_from_u64(broker_id: u64, master_epoch: MasterEpoch) -> Result<Self, StoreContractViolation> {
188        let broker_id =
189            i64::try_from(broker_id).map_err(|_| StoreContractViolation::HaBrokerIdOutOfRange(broker_id))?;
190        Self::try_new(broker_id, master_epoch)
191    }
192
193    /// Returns the authorized broker identifier.
194    pub const fn broker_id(self) -> i64 {
195        self.broker_id
196    }
197
198    /// Returns the authorized master epoch.
199    pub const fn master_epoch(self) -> MasterEpoch {
200        self.master_epoch
201    }
202}
203
204/// One remote replica's durable acknowledgement.
205#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
206pub struct ReplicaAck {
207    broker_id: i64,
208    durable_offset: i64,
209}
210
211impl ReplicaAck {
212    /// Creates a validated remote acknowledgement.
213    ///
214    /// # Errors
215    ///
216    /// Returns a typed error for a negative broker identifier or durable offset.
217    pub fn try_new(broker_id: i64, durable_offset: i64) -> Result<Self, StoreContractViolation> {
218        if broker_id < 0 {
219            return Err(StoreContractViolation::HaInvalidBrokerId(broker_id));
220        }
221        if durable_offset < 0 {
222            return Err(StoreContractViolation::HaInvalidOffset(durable_offset));
223        }
224        Ok(Self {
225            broker_id,
226            durable_offset,
227        })
228    }
229
230    /// Returns the acknowledging broker identifier.
231    pub const fn broker_id(self) -> i64 {
232        self.broker_id
233    }
234
235    /// Returns the exclusive durable offset reported by the replica.
236    pub const fn durable_offset(self) -> i64 {
237        self.durable_offset
238    }
239}
240
241/// A non-empty set of non-negative broker identifiers.
242#[derive(Clone, Debug, PartialEq, Eq)]
243pub struct SyncStateSet(BTreeSet<i64>);
244
245impl SyncStateSet {
246    /// Creates a validated, de-duplicated sync-state set.
247    ///
248    /// # Errors
249    ///
250    /// Returns a typed error when the set is empty or contains a negative broker identifier.
251    pub fn try_new(members: impl IntoIterator<Item = i64>) -> Result<Self, StoreContractViolation> {
252        let members = members.into_iter().collect::<BTreeSet<_>>();
253        if members.is_empty() {
254            return Err(StoreContractViolation::HaEmptySyncStateSet);
255        }
256        if let Some(broker_id) = members.iter().copied().find(|broker_id| *broker_id < 0) {
257            return Err(StoreContractViolation::HaInvalidBrokerId(broker_id));
258        }
259        Ok(Self(members))
260    }
261
262    /// Returns whether the set contains a broker identifier.
263    pub fn contains(&self, broker_id: i64) -> bool {
264        self.0.contains(&broker_id)
265    }
266
267    /// Returns the number of unique members.
268    fn len(&self) -> usize {
269        self.0.len()
270    }
271
272    fn iter(&self) -> impl Iterator<Item = i64> + '_ {
273        self.0.iter().copied()
274    }
275}
276
277/// A complete, validated observation used for one acknowledgement decision.
278#[derive(Clone, Debug, PartialEq, Eq)]
279pub struct ReplicationObservation {
280    current_authority: WriteAuthority,
281    requested_authority: WriteAuthority,
282    policy: AckPolicy,
283    required_offset: i64,
284    local_durable_watermark: i64,
285    replica_acks: Vec<ReplicaAck>,
286    sync_state_set: SyncStateSet,
287}
288
289impl ReplicationObservation {
290    /// Creates a complete replication observation.
291    ///
292    /// # Errors
293    ///
294    /// Returns a typed error for negative offsets or when the current leader is absent from the
295    /// supplied sync-state set.
296    pub fn try_new(
297        current_authority: WriteAuthority,
298        requested_authority: WriteAuthority,
299        policy: AckPolicy,
300        required_offset: i64,
301        local_durable_watermark: i64,
302        replica_acks: Vec<ReplicaAck>,
303        sync_state_set: SyncStateSet,
304    ) -> Result<Self, StoreContractViolation> {
305        if required_offset < 0 {
306            return Err(StoreContractViolation::HaInvalidOffset(required_offset));
307        }
308        if local_durable_watermark < 0 {
309            return Err(StoreContractViolation::HaInvalidOffset(local_durable_watermark));
310        }
311        if !sync_state_set.contains(current_authority.broker_id()) {
312            return Err(StoreContractViolation::HaLeaderMissingFromSyncStateSet(
313                current_authority.broker_id(),
314            ));
315        }
316        Ok(Self {
317            current_authority,
318            requested_authority,
319            policy,
320            required_offset,
321            local_durable_watermark,
322            replica_acks,
323            sync_state_set,
324        })
325    }
326}
327
328/// A proof produced only after the canonical acknowledgement decision succeeds.
329#[derive(Clone, Copy, Debug, PartialEq, Eq)]
330pub struct ReplicationAcknowledgement {
331    durability: Durability,
332    acknowledged_offset: i64,
333}
334
335impl ReplicationAcknowledgement {
336    /// Returns the durability proven by the decision.
337    pub const fn durability(self) -> Durability {
338        self.durability
339    }
340
341    /// Returns the exclusive offset covered by the decision.
342    pub const fn acknowledged_offset(self) -> i64 {
343        self.acknowledged_offset
344    }
345}
346
347/// Why a write authority or replica policy was rejected.
348#[derive(Clone, Copy, Debug, PartialEq, Eq)]
349pub enum HaRejectReason {
350    /// The request belongs to an older Controller epoch.
351    StaleAuthority,
352    /// The request does not exactly match the currently installed authority.
353    AuthorityMismatch,
354}
355
356/// Canonical outcome of evaluating authority, local durability, and replica acknowledgements.
357#[derive(Clone, Copy, Debug, PartialEq, Eq)]
358pub enum ReplicationDecision {
359    /// The requested durability was proven.
360    Acknowledge(ReplicationAcknowledgement),
361    /// The authority and membership are valid, but progress has not reached this offset.
362    Wait {
363        /// Exclusive offset required from local storage and applicable replicas.
364        required_offset: i64,
365    },
366    /// The request must fail closed rather than wait or downgrade durability.
367    Reject(HaRejectReason),
368}
369
370/// Evaluates one append without I/O, mutation, retry, or implicit durability downgrade.
371pub fn decide_replication(observation: &ReplicationObservation) -> ReplicationDecision {
372    let current = observation.current_authority;
373    let requested = observation.requested_authority;
374    if requested.master_epoch() < current.master_epoch() {
375        return ReplicationDecision::Reject(HaRejectReason::StaleAuthority);
376    }
377    if requested != current {
378        return ReplicationDecision::Reject(HaRejectReason::AuthorityMismatch);
379    }
380    if observation.local_durable_watermark < observation.required_offset {
381        return ReplicationDecision::Wait {
382            required_offset: observation.required_offset,
383        };
384    }
385
386    let acknowledge = |durability| {
387        ReplicationDecision::Acknowledge(ReplicationAcknowledgement {
388            durability,
389            acknowledged_offset: observation.required_offset,
390        })
391    };
392    match observation.policy {
393        AckPolicy::LocalDurable => acknowledge(Durability::Local),
394        AckPolicy::ReplicaCount(required) => {
395            let mut acknowledged = BTreeSet::from([current.broker_id()]);
396            for replica in &observation.replica_acks {
397                if replica.broker_id() != current.broker_id()
398                    && observation.sync_state_set.contains(replica.broker_id())
399                    && replica.durable_offset() >= observation.required_offset
400                {
401                    acknowledged.insert(replica.broker_id());
402                }
403            }
404            if acknowledged.len() >= required.get() {
405                acknowledge(Durability::Replicated)
406            } else {
407                ReplicationDecision::Wait {
408                    required_offset: observation.required_offset,
409                }
410            }
411        }
412        AckPolicy::AllInSyncSet => {
413            if observation.sync_state_set.len() == 1 {
414                return acknowledge(Durability::Local);
415            }
416            let acknowledged = observation
417                .replica_acks
418                .iter()
419                .filter(|replica| {
420                    replica.broker_id() != current.broker_id()
421                        && observation.sync_state_set.contains(replica.broker_id())
422                        && replica.durable_offset() >= observation.required_offset
423                })
424                .map(|replica| replica.broker_id())
425                .collect::<BTreeSet<_>>();
426            if observation
427                .sync_state_set
428                .iter()
429                .filter(|broker_id| *broker_id != current.broker_id())
430                .all(|broker_id| acknowledged.contains(&broker_id))
431            {
432                acknowledge(Durability::Replicated)
433            } else {
434                ReplicationDecision::Wait {
435                    required_offset: observation.required_offset,
436                }
437            }
438        }
439    }
440}