Skip to main content

rocketmq_store_api/
lib.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#![deny(missing_docs)]
16
17//! Storage capabilities and their contract-violation model.
18
19mod capability;
20pub mod checkpoint;
21mod checkpoint_artifact;
22mod contract;
23mod error;
24mod ha_contract;
25mod progress;
26mod timer;
27mod timer_snapshot;
28mod wal;
29
30pub use capability::AdminStore;
31pub use capability::DerivedRecordSink;
32pub use capability::MessageAppender;
33pub use capability::MessageReader;
34pub use capability::OffsetIndex;
35pub use capability::ReleaseCheckpointCreateOutcome;
36pub use capability::ReleaseCheckpointCreateRejection;
37pub use capability::ReleaseCheckpointRestoreOutcome;
38pub use capability::ReleaseCheckpointRestoreRejection;
39pub use capability::ReleaseCheckpointStore;
40pub use capability::ReplicationControl;
41pub use capability::StoreHealth;
42pub use capability::StoreLifecycle;
43pub use checkpoint::CheckpointArtifact;
44pub use checkpoint::CheckpointBackend;
45pub use checkpoint::CheckpointManifest;
46pub use checkpoint::CheckpointOffsets;
47pub use checkpoint::CheckpointRequest;
48pub use checkpoint::CheckpointRestoreVerification;
49pub use checkpoint::CheckpointStorageIdentity;
50pub use checkpoint::CHECKPOINT_SCHEMA_VERSION;
51pub use checkpoint_artifact::file_uri_to_path;
52pub use checkpoint_artifact::hash_checkpoint_directory;
53pub use checkpoint_artifact::path_to_file_uri;
54pub use checkpoint_artifact::CheckpointDirectoryDigest;
55pub use checkpoint_artifact::RELEASE_CHECKPOINT_MANIFEST_FILE;
56pub use contract::StoreContractViolation;
57pub use error::StoreComponent;
58pub use error::StoreError;
59pub use error::StoreOperation;
60pub use ha_contract::decide_replication;
61pub use ha_contract::AckPolicy;
62pub use ha_contract::HaRejectReason;
63pub use ha_contract::MasterEpoch;
64pub use ha_contract::ReplicaAck;
65pub use ha_contract::ReplicaCount;
66pub use ha_contract::ReplicationAcknowledgement;
67pub use ha_contract::ReplicationDecision;
68pub use ha_contract::ReplicationObservation;
69pub use ha_contract::SyncStateSet;
70pub use ha_contract::SyncStateSetEpoch;
71pub use ha_contract::WriteAuthority;
72pub use ha_contract::WriteLeaseToken;
73pub use progress::CursorAdvance;
74pub use progress::CursorAdvanceDisposition;
75pub use progress::DerivedCheckpoint;
76pub use progress::DerivedCursor;
77pub use progress::DerivedEngine;
78pub use progress::DerivedRecordId;
79pub use progress::LegacyDerivedCursorV0;
80pub use progress::DERIVED_CHECKPOINT_ENCODED_LEN;
81pub use progress::DERIVED_CHECKPOINT_FORMAT_VERSION;
82pub use timer::PersistedTimerRoute;
83pub use timer::TimerEngineEpoch;
84pub use timer::TimerEngineId;
85pub use timer::TimerGeneration;
86pub use timer::TimerId;
87pub use timer::TimerPayloadLocator;
88pub use timer::TimerPayloadStoreLocator;
89pub use timer::TimerRecallRequest;
90pub use timer::TimerRecallStatus;
91pub use timer::TimerSourceCqOffset;
92pub use timer::TimerStoreMode;
93pub use timer::TimerTimelineCursor;
94pub use timer::EXTENDED_TIMELINE_FORMAT_VERSION;
95pub use timer::JAVA_COMPAT_TIMER_FORMAT_VERSION;
96pub use timer_snapshot::TimerSnapshotFile;
97pub use timer_snapshot::TimerSnapshotManifest;
98pub use timer_snapshot::TimerTimelineIndexKind;
99pub use timer_snapshot::TIMER_SNAPSHOT_SCHEMA_VERSION;
100pub use wal::WalPort;
101
102use std::fmt;
103use std::ops::Range;
104
105use bytes::Bytes;
106
107/// Durability reached by a primary-log append.
108///
109/// Derived-record progress never upgrades this value.
110#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
111pub enum Durability {
112    /// The primary log accepted the bytes, without a durable-write guarantee.
113    #[default]
114    Memory,
115    /// The durable watermark covers the complete appended range locally.
116    Local,
117    /// The configured replica acknowledgement condition was also satisfied.
118    Replicated,
119}
120
121/// Backend-neutral outcome of a legacy-compatible append attempt.
122#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
123pub enum AppendStatus {
124    #[default]
125    /// Represents the put ok case.
126    PutOk,
127    /// Represents the flush disk timeout case.
128    FlushDiskTimeout,
129    /// Represents the flush replica timeout case.
130    FlushReplicaTimeout,
131    /// Represents the replica unavailable case.
132    ReplicaUnavailable,
133    /// Represents the service unavailable case.
134    ServiceUnavailable,
135    /// Represents the storage unavailable case.
136    StorageUnavailable,
137    /// Represents the invalid message case.
138    InvalidMessage,
139    /// Represents the properties too large case.
140    PropertiesTooLarge,
141    /// Represents the page cache busy case.
142    PageCacheBusy,
143    /// Represents the unknown case.
144    Unknown,
145    /// Represents the insufficient replicas case.
146    InsufficientReplicas,
147    /// Represents the remote append failed case.
148    RemoteAppendFailed,
149    /// Represents the queue limit exceeded case.
150    QueueLimitExceeded,
151    /// Represents the schedule flow control case.
152    ScheduleFlowControl,
153    /// Represents the schedule message illegal case.
154    ScheduleMessageIllegal,
155    /// Represents the schedule disabled case.
156    ScheduleDisabled,
157}
158
159impl AppendStatus {
160    /// Returns whether the primary log accepted the append.
161    pub const fn is_accepted(self) -> bool {
162        matches!(
163            self,
164            Self::PutOk | Self::FlushDiskTimeout | Self::FlushReplicaTimeout | Self::ReplicaUnavailable
165        )
166    }
167}
168
169/// Canonical receipt for one primary-log append attempt.
170#[derive(Clone, Debug, PartialEq, Eq)]
171pub struct AppendReceipt {
172    status: AppendStatus,
173    appended_range: Option<Range<i64>>,
174    appended_watermark: i64,
175    durable_watermark: i64,
176    durability: Durability,
177}
178
179impl AppendReceipt {
180    /// Creates a receipt after validating range, status, watermark, and durability invariants.
181    ///
182    /// # Errors
183    ///
184    /// Returns [`StoreContractViolation`] when any receipt field contradicts another field.
185    pub fn try_new(
186        status: AppendStatus,
187        appended_range: Range<i64>,
188        appended_watermark: i64,
189        durable_watermark: i64,
190        durability: Durability,
191    ) -> Result<Self, StoreContractViolation> {
192        if appended_range.start == appended_range.end {
193            return Err(StoreContractViolation::AppendReceiptEmptyRange);
194        }
195        if appended_range.start > appended_range.end {
196            return Err(StoreContractViolation::AppendReceiptReversedRange);
197        }
198        if !status.is_accepted() {
199            return Err(StoreContractViolation::AppendReceiptRejectedStatusWithRange);
200        }
201        if appended_watermark < appended_range.end {
202            return Err(StoreContractViolation::AppendReceiptAppendedWatermarkBehindRange);
203        }
204        if durable_watermark > appended_watermark {
205            return Err(StoreContractViolation::AppendReceiptDurableWatermarkAheadOfAppended);
206        }
207        if durability == Durability::Replicated {
208            return Err(StoreContractViolation::AppendReceiptReplicatedDurabilityRequiresDecision);
209        }
210        match durability {
211            Durability::Memory if durable_watermark >= appended_range.end => {
212                return Err(StoreContractViolation::AppendReceiptMemoryDurabilityAlreadyCovered);
213            }
214            Durability::Local | Durability::Replicated if durable_watermark < appended_range.end => {
215                return Err(StoreContractViolation::AppendReceiptDurableWatermarkBehindRange);
216            }
217            Durability::Memory | Durability::Local | Durability::Replicated => {}
218        }
219        Ok(Self {
220            status,
221            appended_range: Some(appended_range),
222            appended_watermark,
223            durable_watermark,
224            durability,
225        })
226    }
227
228    /// Creates a receipt from a proof produced by [`decide_replication`].
229    ///
230    /// # Errors
231    ///
232    /// Returns [`StoreContractViolation`] when receipt fields contradict each other or the supplied
233    /// acknowledgement does not cover the complete appended range.
234    pub fn try_new_with_replication(
235        status: AppendStatus,
236        appended_range: Range<i64>,
237        appended_watermark: i64,
238        durable_watermark: i64,
239        acknowledgement: ReplicationAcknowledgement,
240    ) -> Result<Self, StoreContractViolation> {
241        if acknowledgement.acknowledged_offset() < appended_range.end {
242            return Err(StoreContractViolation::AppendReceiptReplicationDecisionBehindRange);
243        }
244        let mut receipt = Self::try_new(
245            status,
246            appended_range,
247            appended_watermark,
248            durable_watermark,
249            Durability::Local,
250        )?;
251        receipt.durability = acknowledgement.durability();
252        Ok(receipt)
253    }
254
255    /// Creates a rejected receipt after validating status and watermark invariants.
256    ///
257    /// # Errors
258    ///
259    /// Returns [`StoreContractViolation`] for an accepted status or reversed progress watermarks.
260    pub const fn try_rejected(
261        status: AppendStatus,
262        appended_watermark: i64,
263        durable_watermark: i64,
264    ) -> Result<Self, StoreContractViolation> {
265        if status.is_accepted() {
266            return Err(StoreContractViolation::AppendReceiptAcceptedStatusWithoutRange);
267        }
268        if durable_watermark > appended_watermark {
269            return Err(StoreContractViolation::AppendReceiptDurableWatermarkAheadOfAppended);
270        }
271        Ok(Self {
272            status,
273            appended_range: None,
274            appended_watermark,
275            durable_watermark,
276            durability: Durability::Memory,
277        })
278    }
279
280    /// Returns the neutral append outcome.
281    pub const fn status(&self) -> AppendStatus {
282        self.status
283    }
284
285    /// Returns the half-open physical range written by this operation.
286    pub fn appended_range(&self) -> Option<Range<i64>> {
287        self.appended_range.clone()
288    }
289
290    /// Returns the first physical byte appended by this operation.
291    pub fn first_appended_offset(&self) -> Option<i64> {
292        self.appended_range.as_ref().map(|range| range.start)
293    }
294
295    /// Returns the last physical byte appended by this operation.
296    pub fn last_appended_offset(&self) -> Option<i64> {
297        self.appended_range.as_ref().map(|range| range.end - 1)
298    }
299
300    /// Returns the exclusive primary-log append watermark observed after the operation.
301    pub const fn appended_watermark(&self) -> i64 {
302        self.appended_watermark
303    }
304
305    /// Returns the exclusive durable watermark observed after the operation.
306    pub const fn durable_watermark(&self) -> i64 {
307        self.durable_watermark
308    }
309
310    /// Returns the explicitly reached durability level.
311    pub const fn durability(&self) -> Durability {
312        self.durability
313    }
314
315    /// Returns whether the primary log accepted a non-empty appended range.
316    pub fn is_accepted(&self) -> bool {
317        self.status.is_accepted() && self.appended_range.is_some()
318    }
319
320    /// Returns whether the complete appended range reached the reported durable watermark.
321    pub fn is_durable(&self) -> bool {
322        self.is_accepted()
323            && self.durability != Durability::Memory
324            && self
325                .appended_range
326                .as_ref()
327                .is_some_and(|range| self.durable_watermark >= range.end)
328    }
329}
330
331/// Progress of derived records, independent from primary-log acknowledgement.
332#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
333pub struct DerivedProgress {
334    source_watermark: i64,
335    derived_watermark: i64,
336}
337
338impl DerivedProgress {
339    /// Creates an independent derived-progress observation.
340    pub const fn new(source_watermark: i64, derived_watermark: i64) -> Self {
341        Self {
342            source_watermark,
343            derived_watermark,
344        }
345    }
346
347    /// Returns the exclusive primary-log source watermark observed by derivation.
348    pub const fn source_watermark(self) -> i64 {
349        self.source_watermark
350    }
351
352    /// Returns the exclusive watermark completed by the derived store.
353    pub const fn derived_watermark(self) -> i64 {
354        self.derived_watermark
355    }
356
357    /// Derived progress is never a primary append acknowledgement.
358    pub const fn acknowledges_primary_append(self) -> bool {
359        false
360    }
361
362    /// Derived progress is never a primary durability condition.
363    pub const fn satisfies_primary_durability(self) -> bool {
364        false
365    }
366}
367
368/// Bytes whose backend lease remains held for the lifetime of this value.
369pub struct LeasedBytes<L> {
370    // Bytes drop before the lease, so a backend view is gone before its guard is released.
371    bytes: Bytes,
372    lease: L,
373}
374
375impl<L> LeasedBytes<L> {
376    /// Couples bytes with the guard that keeps their source alive.
377    pub const fn new(bytes: Bytes, lease: L) -> Self {
378        Self { bytes, lease }
379    }
380
381    /// Returns the readable bytes while retaining the lease.
382    pub const fn bytes(&self) -> &Bytes {
383        &self.bytes
384    }
385
386    /// Consumes the lease and returns independently owned bytes.
387    pub fn into_bytes(self) -> Bytes {
388        self.bytes
389    }
390}
391
392impl<L: fmt::Debug> fmt::Debug for LeasedBytes<L> {
393    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
394        formatter
395            .debug_struct("LeasedBytes")
396            .field("bytes", &self.bytes)
397            .field("lease", &self.lease)
398            .finish()
399    }
400}
401
402/// Neutral cache-residency observation for a selected byte range.
403#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
404pub enum ReadCacheState {
405    #[default]
406    /// Represents the unknown case.
407    Unknown,
408    /// Represents the hot case.
409    Hot,
410    /// Represents the cold case.
411    Cold,
412}
413
414/// One selected physical byte range coupled to its backend lease.
415#[derive(Debug)]
416pub struct SelectResult<L> {
417    start_offset: u64,
418    data: LeasedBytes<L>,
419    cache_state: ReadCacheState,
420}
421
422impl<L> SelectResult<L> {
423    /// Creates a selected range from neutral bytes and location metadata.
424    pub const fn new(start_offset: u64, data: LeasedBytes<L>, cache_state: ReadCacheState) -> Self {
425        Self {
426            start_offset,
427            data,
428            cache_state,
429        }
430    }
431
432    /// Returns the physical start offset.
433    pub const fn start_offset(&self) -> u64 {
434        self.start_offset
435    }
436
437    /// Returns the selected byte length.
438    pub fn size(&self) -> usize {
439        self.data.bytes().len()
440    }
441
442    /// Returns the leased data.
443    pub const fn data(&self) -> &LeasedBytes<L> {
444        &self.data
445    }
446
447    /// Consumes the selected result and returns its leased data.
448    pub fn into_data(self) -> LeasedBytes<L> {
449        self.data
450    }
451
452    /// Returns the neutral cache observation.
453    pub const fn cache_state(&self) -> ReadCacheState {
454        self.cache_state
455    }
456}
457
458/// Canonical result status for a bounded logical get.
459#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
460pub enum GetStatus {
461    #[default]
462    /// Represents the found case.
463    Found,
464    /// Represents the no matched message case.
465    NoMatchedMessage,
466    /// Represents the message was removing case.
467    MessageWasRemoving,
468    /// Represents the offset found null case.
469    OffsetFoundNull,
470    /// Represents the offset overflow badly case.
471    OffsetOverflowBadly,
472    /// Represents the offset overflow one case.
473    OffsetOverflowOne,
474    /// Represents the offset too small case.
475    OffsetTooSmall,
476    /// Represents the no matched logic queue case.
477    NoMatchedLogicQueue,
478    /// Represents the no message in queue case.
479    NoMessageInQueue,
480    /// Represents the offset reset case.
481    OffsetReset,
482}
483
484/// Canonical neutral projection of a legacy logical get result.
485#[derive(Debug)]
486pub struct GetResult<L> {
487    /// The records value.
488    pub records: Vec<SelectResult<L>>,
489    /// The queue offsets value.
490    pub queue_offsets: Vec<u64>,
491    /// The status value.
492    pub status: Option<GetStatus>,
493    /// The next begin offset value.
494    pub next_begin_offset: i64,
495    /// The min offset value.
496    pub min_offset: i64,
497    /// The max offset value.
498    pub max_offset: i64,
499    /// The buffer total size value.
500    pub buffer_total_size: i32,
501    /// The number of message entries.
502    pub message_count: i32,
503    /// Whether suggest pulling from replica.
504    pub suggest_pulling_from_replica: bool,
505    /// The number of commercial message entries.
506    pub commercial_message_count: i32,
507    /// The commercial size per message value.
508    pub commercial_size_per_message: i32,
509    /// The cold data sum value.
510    pub cold_data_sum: i64,
511}
512
513impl<L> Default for GetResult<L> {
514    fn default() -> Self {
515        Self {
516            records: Vec::new(),
517            queue_offsets: Vec::new(),
518            status: None,
519            next_begin_offset: 0,
520            min_offset: 0,
521            max_offset: 0,
522            buffer_total_size: 0,
523            message_count: 0,
524            suggest_pulling_from_replica: false,
525            commercial_message_count: 0,
526            commercial_size_per_message: 4 * 1024,
527            cold_data_sum: 0,
528        }
529    }
530}
531
532/// Owned logical-read outcome after backend leases have been decoded by an adapter.
533///
534/// This projection keeps storage navigation semantics in the storage boundary while allowing the
535/// caller to own decoded records. `None` records remain distinct from a successful read containing
536/// an empty record collection.
537#[derive(Clone, Debug, PartialEq, Eq)]
538pub struct ReadOutcome<T> {
539    status: GetStatus,
540    next_begin_offset: i64,
541    min_offset: i64,
542    max_offset: i64,
543    records: Option<Vec<T>>,
544}
545
546impl<T> ReadOutcome<T> {
547    /// Creates an owned read outcome from canonical store navigation fields.
548    pub fn new<R>(status: GetStatus, next_begin_offset: i64, min_offset: i64, max_offset: i64, records: R) -> Self
549    where
550        R: Into<Option<Vec<T>>>,
551    {
552        Self {
553            status,
554            next_begin_offset,
555            min_offset,
556            max_offset,
557            records: records.into(),
558        }
559    }
560
561    /// Returns the exact backend-neutral logical-read status.
562    pub const fn status(&self) -> GetStatus {
563        self.status
564    }
565
566    /// Returns the next logical offset suggested by the store.
567    pub const fn next_begin_offset(&self) -> i64 {
568        self.next_begin_offset
569    }
570
571    /// Returns the minimum readable logical offset.
572    pub const fn min_offset(&self) -> i64 {
573        self.min_offset
574    }
575
576    /// Returns the maximum logical offset observed by the store.
577    pub const fn max_offset(&self) -> i64 {
578        self.max_offset
579    }
580
581    /// Returns decoded records without transferring ownership.
582    pub fn records(&self) -> Option<&[T]> {
583        self.records.as_deref()
584    }
585
586    /// Consumes the outcome and returns its decoded records.
587    pub fn into_records(self) -> Option<Vec<T>> {
588        self.records
589    }
590}
591
592/// Canonical neutral projection of a legacy key query result.
593#[derive(Debug)]
594pub struct QueryResult<L> {
595    /// The records value.
596    pub records: Vec<SelectResult<L>>,
597    /// The index last update timestamp value.
598    pub index_last_update_timestamp: i64,
599    /// The index last update physical offset value.
600    pub index_last_update_physical_offset: i64,
601    /// The buffer total size value.
602    pub buffer_total_size: i32,
603    /// Whether index query safe.
604    pub index_query_safe: bool,
605    /// The index safe physical offset value.
606    pub index_safe_physical_offset: i64,
607    /// The index confirm physical offset value.
608    pub index_confirm_physical_offset: i64,
609}
610
611impl<L> Default for QueryResult<L> {
612    fn default() -> Self {
613        Self {
614            records: Vec::new(),
615            index_last_update_timestamp: 0,
616            index_last_update_physical_offset: 0,
617            buffer_total_size: 0,
618            index_query_safe: true,
619            index_safe_physical_offset: 0,
620            index_confirm_physical_offset: 0,
621        }
622    }
623}
624
625/// Compact durable-write pressure projection.
626#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
627pub struct FlushBacklog {
628    /// The queue depth value.
629    pub queue_depth: u64,
630    /// The oldest wait duration in milliseconds.
631    pub oldest_wait_millis: u64,
632}
633
634/// Canonical backend-neutral health projection.
635#[derive(Clone, Debug, PartialEq, Eq)]
636pub struct StoreHealthSnapshot {
637    /// Whether writable.
638    pub writable: bool,
639    /// Catalog identity of the latest health failure.
640    pub last_error: Option<&'static rocketmq_error::ErrorDescriptor>,
641    /// Whether page cache busy.
642    pub page_cache_busy: bool,
643    /// Whether transient pool deficient.
644    pub transient_pool_deficient: bool,
645    /// The flush backlog value.
646    pub flush_backlog: FlushBacklog,
647    /// The dispatch behind size in bytes.
648    pub dispatch_behind_bytes: i64,
649    /// Whether shutdown.
650    pub shutdown: bool,
651    /// The number of replication pending entries.
652    pub replication_pending_count: u64,
653    /// The replication oldest wait duration in milliseconds.
654    pub replication_oldest_wait_millis: u64,
655    /// The appended watermark value.
656    pub appended_watermark: i64,
657    /// The durable watermark value.
658    pub durable_watermark: i64,
659}
660
661impl Default for StoreHealthSnapshot {
662    fn default() -> Self {
663        Self {
664            writable: true,
665            last_error: None,
666            page_cache_busy: false,
667            transient_pool_deficient: false,
668            flush_backlog: FlushBacklog::default(),
669            dispatch_behind_bytes: 0,
670            shutdown: false,
671            replication_pending_count: 0,
672            replication_oldest_wait_millis: 0,
673            appended_watermark: 0,
674            durable_watermark: 0,
675        }
676    }
677}
678
679impl StoreHealthSnapshot {
680    /// Returns whether the store currently accepts primary writes.
681    pub const fn writable(&self) -> bool {
682        self.writable
683    }
684
685    /// Returns the catalog identity of the latest health failure.
686    pub const fn last_error(&self) -> Option<&'static rocketmq_error::ErrorDescriptor> {
687        self.last_error
688    }
689
690    /// Returns the exclusive primary-log append watermark.
691    pub const fn appended_watermark(&self) -> i64 {
692        self.appended_watermark
693    }
694
695    /// Returns the exclusive durable watermark.
696    pub const fn durable_watermark(&self) -> i64 {
697        self.durable_watermark
698    }
699}