1#![deny(missing_docs)]
16
17mod 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::ReleaseCheckpointCreateRejection;
36pub use capability::ReleaseCheckpointCreationResult;
37pub use capability::ReleaseCheckpointRestoreRejection;
38pub use capability::ReleaseCheckpointRestoreVerificationResult;
39pub use capability::ReleaseCheckpointStore;
40pub use capability::ReplicationControl;
41pub use capability::StoreHealth;
42pub use capability::StoreLifecycle;
43pub use checkpoint::CheckpointArtifact;
44pub use checkpoint::CheckpointManifest;
45pub use checkpoint::CheckpointOffsets;
46pub use checkpoint::CheckpointRequest;
47pub use checkpoint::CheckpointRestoreVerification;
48pub use checkpoint::CheckpointStorageIdentity;
49pub use checkpoint::CheckpointStoreKind;
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::TimerAdmissionRoute;
84pub use timer::TimerEngineEpoch;
85pub use timer::TimerEngineId;
86pub use timer::TimerFileFormat;
87pub use timer::TimerGeneration;
88pub use timer::TimerId;
89pub use timer::TimerPayloadLocator;
90pub use timer::TimerPayloadStoreLocator;
91pub use timer::TimerRecallRegistration;
92pub use timer::TimerRecallRequest;
93pub use timer::TimerRecallStatus;
94pub use timer::TimerSourceCqOffset;
95pub use timer::TimerStoreMode;
96pub use timer::TimerTimelineCursor;
97pub use timer::EXTENDED_TIMELINE_FORMAT_VERSION;
98pub use timer::JAVA_COMPAT_TIMER_FORMAT_VERSION;
99pub use timer::NATIVE_TIMER_FORMAT_VERSION;
100pub use timer_snapshot::TimerSnapshotFile;
101pub use timer_snapshot::TimerSnapshotManifest;
102pub use timer_snapshot::TimerTimelineIndexKind;
103pub use timer_snapshot::TIMER_SNAPSHOT_SCHEMA_VERSION;
104pub use wal::WalPort;
105
106use std::fmt;
107use std::ops::Range;
108
109use bytes::Bytes;
110
111#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
115pub enum Durability {
116 #[default]
118 Memory,
119 Local,
121 Replicated,
123}
124
125#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
127pub enum AppendStatus {
128 #[default]
129 PutOk,
131 FlushDiskTimeout,
133 FlushReplicaTimeout,
135 ReplicaUnavailable,
137 ServiceUnavailable,
139 StorageUnavailable,
141 InvalidMessage,
143 PropertiesTooLarge,
145 PageCacheBusy,
147 Unknown,
149 InsufficientReplicas,
151 RemoteAppendFailed,
153 QueueLimitExceeded,
155 ScheduleFlowControl,
157 ScheduleMessageIllegal,
159 ScheduleDisabled,
161}
162
163impl AppendStatus {
164 pub const fn is_accepted(self) -> bool {
166 matches!(
167 self,
168 Self::PutOk | Self::FlushDiskTimeout | Self::FlushReplicaTimeout | Self::ReplicaUnavailable
169 )
170 }
171}
172
173#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct AppendReceipt {
176 status: AppendStatus,
177 appended_range: Option<Range<i64>>,
178 appended_watermark: i64,
179 durable_watermark: i64,
180 durability: Durability,
181}
182
183impl AppendReceipt {
184 pub fn try_new(
190 status: AppendStatus,
191 appended_range: Range<i64>,
192 appended_watermark: i64,
193 durable_watermark: i64,
194 durability: Durability,
195 ) -> Result<Self, StoreContractViolation> {
196 if appended_range.start == appended_range.end {
197 return Err(StoreContractViolation::AppendReceiptEmptyRange);
198 }
199 if appended_range.start > appended_range.end {
200 return Err(StoreContractViolation::AppendReceiptReversedRange);
201 }
202 if !status.is_accepted() {
203 return Err(StoreContractViolation::AppendReceiptRejectedStatusWithRange);
204 }
205 if appended_watermark < appended_range.end {
206 return Err(StoreContractViolation::AppendReceiptAppendedWatermarkBehindRange);
207 }
208 if durable_watermark > appended_watermark {
209 return Err(StoreContractViolation::AppendReceiptDurableWatermarkAheadOfAppended);
210 }
211 if durability == Durability::Replicated {
212 return Err(StoreContractViolation::AppendReceiptReplicatedDurabilityRequiresDecision);
213 }
214 match durability {
215 Durability::Memory if durable_watermark >= appended_range.end => {
216 return Err(StoreContractViolation::AppendReceiptMemoryDurabilityAlreadyCovered);
217 }
218 Durability::Local | Durability::Replicated if durable_watermark < appended_range.end => {
219 return Err(StoreContractViolation::AppendReceiptDurableWatermarkBehindRange);
220 }
221 Durability::Memory | Durability::Local | Durability::Replicated => {}
222 }
223 Ok(Self {
224 status,
225 appended_range: Some(appended_range),
226 appended_watermark,
227 durable_watermark,
228 durability,
229 })
230 }
231
232 pub fn try_new_with_replication(
239 status: AppendStatus,
240 appended_range: Range<i64>,
241 appended_watermark: i64,
242 durable_watermark: i64,
243 acknowledgement: ReplicationAcknowledgement,
244 ) -> Result<Self, StoreContractViolation> {
245 if acknowledgement.acknowledged_offset() < appended_range.end {
246 return Err(StoreContractViolation::AppendReceiptReplicationDecisionBehindRange);
247 }
248 let mut receipt = Self::try_new(
249 status,
250 appended_range,
251 appended_watermark,
252 durable_watermark,
253 Durability::Local,
254 )?;
255 receipt.durability = acknowledgement.durability();
256 Ok(receipt)
257 }
258
259 pub const fn try_rejected(
265 status: AppendStatus,
266 appended_watermark: i64,
267 durable_watermark: i64,
268 ) -> Result<Self, StoreContractViolation> {
269 if status.is_accepted() {
270 return Err(StoreContractViolation::AppendReceiptAcceptedStatusWithoutRange);
271 }
272 if durable_watermark > appended_watermark {
273 return Err(StoreContractViolation::AppendReceiptDurableWatermarkAheadOfAppended);
274 }
275 Ok(Self {
276 status,
277 appended_range: None,
278 appended_watermark,
279 durable_watermark,
280 durability: Durability::Memory,
281 })
282 }
283
284 pub const fn status(&self) -> AppendStatus {
286 self.status
287 }
288
289 pub fn appended_range(&self) -> Option<Range<i64>> {
291 self.appended_range.clone()
292 }
293
294 pub fn first_appended_offset(&self) -> Option<i64> {
296 self.appended_range.as_ref().map(|range| range.start)
297 }
298
299 pub fn last_appended_offset(&self) -> Option<i64> {
301 self.appended_range.as_ref().map(|range| range.end - 1)
302 }
303
304 pub const fn appended_watermark(&self) -> i64 {
306 self.appended_watermark
307 }
308
309 pub const fn durable_watermark(&self) -> i64 {
311 self.durable_watermark
312 }
313
314 pub const fn durability(&self) -> Durability {
316 self.durability
317 }
318
319 pub fn is_accepted(&self) -> bool {
321 self.status.is_accepted() && self.appended_range.is_some()
322 }
323
324 pub fn is_durable(&self) -> bool {
326 self.is_accepted()
327 && self.durability != Durability::Memory
328 && self
329 .appended_range
330 .as_ref()
331 .is_some_and(|range| self.durable_watermark >= range.end)
332 }
333}
334
335#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
337pub struct DerivedProgress {
338 source_watermark: i64,
339 derived_watermark: i64,
340}
341
342impl DerivedProgress {
343 pub const fn new(source_watermark: i64, derived_watermark: i64) -> Self {
345 Self {
346 source_watermark,
347 derived_watermark,
348 }
349 }
350
351 pub const fn source_watermark(self) -> i64 {
353 self.source_watermark
354 }
355
356 pub const fn derived_watermark(self) -> i64 {
358 self.derived_watermark
359 }
360
361 pub const fn acknowledges_primary_append(self) -> bool {
363 false
364 }
365
366 pub const fn satisfies_primary_durability(self) -> bool {
368 false
369 }
370}
371
372pub struct LeasedBytes<L> {
374 bytes: Bytes,
376 lease: L,
377}
378
379impl<L> LeasedBytes<L> {
380 pub const fn new(bytes: Bytes, lease: L) -> Self {
382 Self { bytes, lease }
383 }
384
385 pub const fn bytes(&self) -> &Bytes {
387 &self.bytes
388 }
389
390 pub fn into_bytes(self) -> Bytes {
392 self.bytes
393 }
394}
395
396impl<L: fmt::Debug> fmt::Debug for LeasedBytes<L> {
397 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
398 formatter
399 .debug_struct("LeasedBytes")
400 .field("bytes", &self.bytes)
401 .field("lease", &self.lease)
402 .finish()
403 }
404}
405
406#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
408pub enum ReadCacheState {
409 #[default]
410 Unknown,
412 Hot,
414 Cold,
416}
417
418#[derive(Debug)]
420pub struct SelectResult<L> {
421 start_offset: u64,
422 data: LeasedBytes<L>,
423 cache_state: ReadCacheState,
424}
425
426impl<L> SelectResult<L> {
427 pub const fn new(start_offset: u64, data: LeasedBytes<L>, cache_state: ReadCacheState) -> Self {
429 Self {
430 start_offset,
431 data,
432 cache_state,
433 }
434 }
435
436 pub const fn start_offset(&self) -> u64 {
438 self.start_offset
439 }
440
441 pub fn size(&self) -> usize {
443 self.data.bytes().len()
444 }
445
446 pub const fn data(&self) -> &LeasedBytes<L> {
448 &self.data
449 }
450
451 pub fn into_data(self) -> LeasedBytes<L> {
453 self.data
454 }
455
456 pub const fn cache_state(&self) -> ReadCacheState {
458 self.cache_state
459 }
460}
461
462#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
464pub enum GetStatus {
465 #[default]
466 Found,
468 NoMatchedMessage,
470 MessageWasRemoving,
472 OffsetFoundNull,
474 OffsetOverflowBadly,
476 OffsetOverflowOne,
478 OffsetTooSmall,
480 NoMatchedLogicQueue,
482 NoMessageInQueue,
484 OffsetReset,
486}
487
488#[derive(Debug)]
490pub struct GetResult<L> {
491 pub records: Vec<SelectResult<L>>,
493 pub queue_offsets: Vec<u64>,
495 pub status: Option<GetStatus>,
497 pub next_begin_offset: i64,
499 pub min_offset: i64,
501 pub max_offset: i64,
503 pub buffer_total_size: i32,
505 pub message_count: i32,
507 pub suggest_pulling_from_replica: bool,
509 pub commercial_message_count: i32,
511 pub commercial_size_per_message: i32,
513 pub cold_data_sum: i64,
515}
516
517impl<L> Default for GetResult<L> {
518 fn default() -> Self {
519 Self {
520 records: Vec::new(),
521 queue_offsets: Vec::new(),
522 status: None,
523 next_begin_offset: 0,
524 min_offset: 0,
525 max_offset: 0,
526 buffer_total_size: 0,
527 message_count: 0,
528 suggest_pulling_from_replica: false,
529 commercial_message_count: 0,
530 commercial_size_per_message: 4 * 1024,
531 cold_data_sum: 0,
532 }
533 }
534}
535
536#[derive(Clone, Debug, PartialEq, Eq)]
542pub struct DecodedReadResult<T> {
543 status: GetStatus,
544 next_begin_offset: i64,
545 min_offset: i64,
546 max_offset: i64,
547 records: Option<Vec<T>>,
548}
549
550impl<T> DecodedReadResult<T> {
551 pub fn new<R>(status: GetStatus, next_begin_offset: i64, min_offset: i64, max_offset: i64, records: R) -> Self
553 where
554 R: Into<Option<Vec<T>>>,
555 {
556 Self {
557 status,
558 next_begin_offset,
559 min_offset,
560 max_offset,
561 records: records.into(),
562 }
563 }
564
565 pub const fn status(&self) -> GetStatus {
567 self.status
568 }
569
570 pub const fn next_begin_offset(&self) -> i64 {
572 self.next_begin_offset
573 }
574
575 pub const fn min_offset(&self) -> i64 {
577 self.min_offset
578 }
579
580 pub const fn max_offset(&self) -> i64 {
582 self.max_offset
583 }
584
585 pub fn records(&self) -> Option<&[T]> {
587 self.records.as_deref()
588 }
589
590 pub fn into_records(self) -> Option<Vec<T>> {
592 self.records
593 }
594}
595
596#[derive(Debug)]
598pub struct QueryResult<L> {
599 pub records: Vec<SelectResult<L>>,
601 pub index_last_update_timestamp: i64,
603 pub index_last_update_physical_offset: i64,
605 pub buffer_total_size: i32,
607 pub index_query_safe: bool,
609 pub index_safe_physical_offset: i64,
611 pub index_confirm_physical_offset: i64,
613}
614
615impl<L> Default for QueryResult<L> {
616 fn default() -> Self {
617 Self {
618 records: Vec::new(),
619 index_last_update_timestamp: 0,
620 index_last_update_physical_offset: 0,
621 buffer_total_size: 0,
622 index_query_safe: true,
623 index_safe_physical_offset: 0,
624 index_confirm_physical_offset: 0,
625 }
626 }
627}
628
629#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
631pub struct FlushBacklog {
632 pub queue_depth: u64,
634 pub oldest_wait_millis: u64,
636}
637
638#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
645pub struct StoreHealthScope {
646 pub flush_backlog: bool,
648 pub replication: bool,
650 pub dispatch_lag: bool,
652 pub watermarks: bool,
654}
655
656impl StoreHealthScope {
657 pub const FULL: Self = Self {
659 flush_backlog: true,
660 replication: true,
661 dispatch_lag: true,
662 watermarks: true,
663 };
664
665 pub const CORE: Self = Self {
667 flush_backlog: false,
668 replication: false,
669 dispatch_lag: false,
670 watermarks: false,
671 };
672}
673
674#[derive(Clone, Debug, PartialEq, Eq)]
676pub struct StoreHealthSnapshot {
677 pub writable: bool,
679 pub last_error: Option<&'static rocketmq_error::ErrorDescriptor>,
681 pub page_cache_busy: bool,
683 pub transient_pool_deficient: bool,
685 pub flush_backlog: FlushBacklog,
687 pub dispatch_behind_bytes: i64,
689 pub shutdown: bool,
691 pub replication_pending_count: u64,
693 pub replication_oldest_wait_millis: u64,
695 pub appended_watermark: i64,
697 pub durable_watermark: i64,
699}
700
701impl Default for StoreHealthSnapshot {
702 fn default() -> Self {
703 Self {
704 writable: true,
705 last_error: None,
706 page_cache_busy: false,
707 transient_pool_deficient: false,
708 flush_backlog: FlushBacklog::default(),
709 dispatch_behind_bytes: 0,
710 shutdown: false,
711 replication_pending_count: 0,
712 replication_oldest_wait_millis: 0,
713 appended_watermark: 0,
714 durable_watermark: 0,
715 }
716 }
717}
718
719impl StoreHealthSnapshot {
720 pub const fn writable(&self) -> bool {
722 self.writable
723 }
724
725 pub const fn last_error(&self) -> Option<&'static rocketmq_error::ErrorDescriptor> {
727 self.last_error
728 }
729
730 pub const fn appended_watermark(&self) -> i64 {
732 self.appended_watermark
733 }
734
735 pub const fn durable_watermark(&self) -> i64 {
737 self.durable_watermark
738 }
739}