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::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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
111pub enum Durability {
112 #[default]
114 Memory,
115 Local,
117 Replicated,
119}
120
121#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
123pub enum AppendStatus {
124 #[default]
125 PutOk,
127 FlushDiskTimeout,
129 FlushReplicaTimeout,
131 ReplicaUnavailable,
133 ServiceUnavailable,
135 StorageUnavailable,
137 InvalidMessage,
139 PropertiesTooLarge,
141 PageCacheBusy,
143 Unknown,
145 InsufficientReplicas,
147 RemoteAppendFailed,
149 QueueLimitExceeded,
151 ScheduleFlowControl,
153 ScheduleMessageIllegal,
155 ScheduleDisabled,
157}
158
159impl AppendStatus {
160 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#[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 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 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 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 pub const fn status(&self) -> AppendStatus {
282 self.status
283 }
284
285 pub fn appended_range(&self) -> Option<Range<i64>> {
287 self.appended_range.clone()
288 }
289
290 pub fn first_appended_offset(&self) -> Option<i64> {
292 self.appended_range.as_ref().map(|range| range.start)
293 }
294
295 pub fn last_appended_offset(&self) -> Option<i64> {
297 self.appended_range.as_ref().map(|range| range.end - 1)
298 }
299
300 pub const fn appended_watermark(&self) -> i64 {
302 self.appended_watermark
303 }
304
305 pub const fn durable_watermark(&self) -> i64 {
307 self.durable_watermark
308 }
309
310 pub const fn durability(&self) -> Durability {
312 self.durability
313 }
314
315 pub fn is_accepted(&self) -> bool {
317 self.status.is_accepted() && self.appended_range.is_some()
318 }
319
320 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
333pub struct DerivedProgress {
334 source_watermark: i64,
335 derived_watermark: i64,
336}
337
338impl DerivedProgress {
339 pub const fn new(source_watermark: i64, derived_watermark: i64) -> Self {
341 Self {
342 source_watermark,
343 derived_watermark,
344 }
345 }
346
347 pub const fn source_watermark(self) -> i64 {
349 self.source_watermark
350 }
351
352 pub const fn derived_watermark(self) -> i64 {
354 self.derived_watermark
355 }
356
357 pub const fn acknowledges_primary_append(self) -> bool {
359 false
360 }
361
362 pub const fn satisfies_primary_durability(self) -> bool {
364 false
365 }
366}
367
368pub struct LeasedBytes<L> {
370 bytes: Bytes,
372 lease: L,
373}
374
375impl<L> LeasedBytes<L> {
376 pub const fn new(bytes: Bytes, lease: L) -> Self {
378 Self { bytes, lease }
379 }
380
381 pub const fn bytes(&self) -> &Bytes {
383 &self.bytes
384 }
385
386 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
404pub enum ReadCacheState {
405 #[default]
406 Unknown,
408 Hot,
410 Cold,
412}
413
414#[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 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 pub const fn start_offset(&self) -> u64 {
434 self.start_offset
435 }
436
437 pub fn size(&self) -> usize {
439 self.data.bytes().len()
440 }
441
442 pub const fn data(&self) -> &LeasedBytes<L> {
444 &self.data
445 }
446
447 pub fn into_data(self) -> LeasedBytes<L> {
449 self.data
450 }
451
452 pub const fn cache_state(&self) -> ReadCacheState {
454 self.cache_state
455 }
456}
457
458#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
460pub enum GetStatus {
461 #[default]
462 Found,
464 NoMatchedMessage,
466 MessageWasRemoving,
468 OffsetFoundNull,
470 OffsetOverflowBadly,
472 OffsetOverflowOne,
474 OffsetTooSmall,
476 NoMatchedLogicQueue,
478 NoMessageInQueue,
480 OffsetReset,
482}
483
484#[derive(Debug)]
486pub struct GetResult<L> {
487 pub records: Vec<SelectResult<L>>,
489 pub queue_offsets: Vec<u64>,
491 pub status: Option<GetStatus>,
493 pub next_begin_offset: i64,
495 pub min_offset: i64,
497 pub max_offset: i64,
499 pub buffer_total_size: i32,
501 pub message_count: i32,
503 pub suggest_pulling_from_replica: bool,
505 pub commercial_message_count: i32,
507 pub commercial_size_per_message: i32,
509 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#[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 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 pub const fn status(&self) -> GetStatus {
563 self.status
564 }
565
566 pub const fn next_begin_offset(&self) -> i64 {
568 self.next_begin_offset
569 }
570
571 pub const fn min_offset(&self) -> i64 {
573 self.min_offset
574 }
575
576 pub const fn max_offset(&self) -> i64 {
578 self.max_offset
579 }
580
581 pub fn records(&self) -> Option<&[T]> {
583 self.records.as_deref()
584 }
585
586 pub fn into_records(self) -> Option<Vec<T>> {
588 self.records
589 }
590}
591
592#[derive(Debug)]
594pub struct QueryResult<L> {
595 pub records: Vec<SelectResult<L>>,
597 pub index_last_update_timestamp: i64,
599 pub index_last_update_physical_offset: i64,
601 pub buffer_total_size: i32,
603 pub index_query_safe: bool,
605 pub index_safe_physical_offset: i64,
607 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
627pub struct FlushBacklog {
628 pub queue_depth: u64,
630 pub oldest_wait_millis: u64,
632}
633
634#[derive(Clone, Debug, PartialEq, Eq)]
636pub struct StoreHealthSnapshot {
637 pub writable: bool,
639 pub last_error: Option<&'static rocketmq_error::ErrorDescriptor>,
641 pub page_cache_busy: bool,
643 pub transient_pool_deficient: bool,
645 pub flush_backlog: FlushBacklog,
647 pub dispatch_behind_bytes: i64,
649 pub shutdown: bool,
651 pub replication_pending_count: u64,
653 pub replication_oldest_wait_millis: u64,
655 pub appended_watermark: i64,
657 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 pub const fn writable(&self) -> bool {
682 self.writable
683 }
684
685 pub const fn last_error(&self) -> Option<&'static rocketmq_error::ErrorDescriptor> {
687 self.last_error
688 }
689
690 pub const fn appended_watermark(&self) -> i64 {
692 self.appended_watermark
693 }
694
695 pub const fn durable_watermark(&self) -> i64 {
697 self.durable_watermark
698 }
699}