Skip to main content

rocketmq_store_api/
timer.rs

1// Copyright 2026 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//! Stable timer routing and storage identities shared across storage backends.
16
17use serde::Deserialize;
18use serde::Serialize;
19
20use crate::StoreContractViolation;
21
22/// Current route format written by the Java-compatible timer engine.
23pub const JAVA_COMPAT_TIMER_FORMAT_VERSION: u16 = 1;
24
25/// Current record format written by the extended timeline engine.
26pub const EXTENDED_TIMELINE_FORMAT_VERSION: u16 = 1;
27
28/// Broker-to-store request for generation-aware Extended Timer cancellation.
29#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
30pub struct TimerRecallRequest {
31    /// Original real topic encoded in the Recall handle.
32    pub topic: String,
33    /// Original unique message id encoded in the Recall handle.
34    pub unique_key: String,
35}
36
37/// Stable outcome of an Extended Timer cancellation attempt.
38#[derive(Clone, Copy, Debug, PartialEq, Eq)]
39pub enum TimerRecallStatus {
40    /// Pending/ready generation was atomically cancelled.
41    Cancelled,
42    /// It had already been cancelled.
43    AlreadyCancelled,
44    /// Delivery crossed the READY-to-DELIVERING linearization point.
45    TooLate,
46    /// Lookup does not exist on this owner.
47    NotFound,
48    /// Generation or state should be retried after materialization catches up.
49    Retry,
50    /// Corrupt/quarantined state requires repair.
51    Quarantined,
52    /// Backend does not own the Extended Timeline capability.
53    Unsupported,
54}
55
56/// Configured timer storage mode.
57#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Serialize)]
58#[serde(rename_all = "snake_case")]
59pub enum TimerStoreMode {
60    /// RocketMQ Java-compatible timer wheel and timer log.
61    #[default]
62    JavaCompat,
63    /// Native long-horizon timeline. This mode must fail closed until the capability is installed.
64    ExtendedTimeline,
65}
66
67impl TimerStoreMode {
68    /// Returns the stable configuration value.
69    pub const fn as_str(self) -> &'static str {
70        match self {
71            Self::JavaCompat => "java_compat",
72            Self::ExtendedTimeline => "extended_timeline",
73        }
74    }
75}
76
77/// Stable identifier of the engine that owns one accepted timer record.
78#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, Serialize)]
79pub enum TimerEngineId {
80    /// File timer wheel, encoded as `F` by RocketMQ Java.
81    #[serde(rename = "F")]
82    JavaCompat,
83    /// Extended timeline, encoded as `R` for the existing RocksDB protocol value.
84    #[serde(rename = "R")]
85    ExtendedTimeline,
86}
87
88impl TimerEngineId {
89    /// Returns the persistent wire value used in internal message properties.
90    pub const fn as_str(self) -> &'static str {
91        match self {
92            Self::JavaCompat => "F",
93            Self::ExtendedTimeline => "R",
94        }
95    }
96
97    /// Parses a persistent engine identifier and rejects unknown owners.
98    ///
99    /// # Errors
100    ///
101    /// Returns [`StoreContractViolation::TimerUnknownEngine`] when `value` is not a known engine id.
102    pub fn parse(value: &str) -> Result<Self, StoreContractViolation> {
103        match value {
104            "F" => Ok(Self::JavaCompat),
105            "R" => Ok(Self::ExtendedTimeline),
106            value => Err(StoreContractViolation::TimerUnknownEngine(value.to_owned())),
107        }
108    }
109}
110
111/// Stable logical timer identity.
112#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
113pub struct TimerId(u128);
114
115impl TimerId {
116    /// Creates a timer id from its persisted integer representation.
117    pub const fn new(value: u128) -> Self {
118        Self(value)
119    }
120
121    /// Returns the persisted integer representation.
122    pub const fn get(self) -> u128 {
123        self.0
124    }
125}
126
127/// Generation fencing stale recall and delivery records for one timer identity.
128#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
129pub struct TimerGeneration(u64);
130
131impl TimerGeneration {
132    /// Creates a generation.
133    pub const fn new(value: u64) -> Self {
134        Self(value)
135    }
136
137    /// Returns the persisted generation.
138    pub const fn get(self) -> u64 {
139        self.0
140    }
141}
142
143/// Epoch fencing work produced by an earlier engine owner.
144#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
145pub struct TimerEngineEpoch(u64);
146
147impl TimerEngineEpoch {
148    /// Creates an engine epoch.
149    pub const fn new(value: u64) -> Self {
150        Self(value)
151    }
152
153    /// Returns the persisted epoch.
154    pub const fn get(self) -> u64 {
155        self.0
156    }
157}
158
159/// Offset of a source record in the internal timer consume queue.
160#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
161pub struct TimerSourceCqOffset(i64);
162
163impl TimerSourceCqOffset {
164    /// Creates a source offset.
165    pub const fn new(value: i64) -> Self {
166        Self(value)
167    }
168
169    /// Returns the source offset.
170    pub const fn get(self) -> i64 {
171        self.0
172    }
173}
174
175/// Location of the canonical message payload in CommitLog.
176#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, Serialize)]
177pub struct TimerPayloadLocator {
178    commit_log_offset: i64,
179    size: u32,
180}
181
182impl TimerPayloadLocator {
183    /// Creates a payload locator.
184    ///
185    /// # Errors
186    ///
187    /// Returns [`StoreContractViolation::TimerInvalidPayloadLocator`] for a negative offset or zero size.
188    pub const fn try_new(commit_log_offset: i64, size: u32) -> Result<Self, StoreContractViolation> {
189        if commit_log_offset < 0 || size == 0 {
190            return Err(StoreContractViolation::TimerInvalidPayloadLocator);
191        }
192        Ok(Self {
193            commit_log_offset,
194            size,
195        })
196    }
197
198    /// Returns the physical CommitLog offset.
199    pub const fn commit_log_offset(self) -> i64 {
200        self.commit_log_offset
201    }
202
203    /// Returns the encoded payload size.
204    pub const fn size(self) -> u32 {
205        self.size
206    }
207}
208
209/// Stable location of one complete message in the long-horizon payload store.
210///
211/// Unlike [`TimerPayloadLocator`], this locator does not depend on the ordinary CommitLog
212/// retention window. Its partition is derived from the original UTC due day and delivery lane.
213#[derive(Clone, Copy, Debug, Deserialize, PartialEq, Eq, Hash, Serialize)]
214pub struct TimerPayloadStoreLocator {
215    due_day_utc: i32,
216    lane: u16,
217    segment_id: u64,
218    offset: u64,
219    length: u32,
220    checksum: u32,
221}
222
223impl TimerPayloadStoreLocator {
224    /// Creates a validated payload-store locator.
225    ///
226    /// # Errors
227    ///
228    /// Returns [`StoreContractViolation::TimerInvalidPayloadStoreLocator`] when `length` is zero.
229    pub const fn try_new(
230        due_day_utc: i32,
231        lane: u16,
232        segment_id: u64,
233        offset: u64,
234        length: u32,
235        checksum: u32,
236    ) -> Result<Self, StoreContractViolation> {
237        if length == 0 {
238            return Err(StoreContractViolation::TimerInvalidPayloadStoreLocator);
239        }
240        Ok(Self {
241            due_day_utc,
242            lane,
243            segment_id,
244            offset,
245            length,
246            checksum,
247        })
248    }
249
250    /// Returns the UTC day number since the Unix epoch.
251    pub const fn due_day_utc(self) -> i32 {
252        self.due_day_utc
253    }
254
255    /// Returns the stable delivery lane.
256    pub const fn lane(self) -> u16 {
257        self.lane
258    }
259
260    /// Returns the partition-local segment id.
261    pub const fn segment_id(self) -> u64 {
262        self.segment_id
263    }
264
265    /// Returns the byte offset within the segment.
266    pub const fn offset(self) -> u64 {
267        self.offset
268    }
269
270    /// Returns the encoded record length.
271    pub const fn length(self) -> u32 {
272        self.length
273    }
274
275    /// Returns the CRC32C of the complete encoded payload record.
276    pub const fn checksum(self) -> u32 {
277        self.checksum
278    }
279}
280
281/// Ordered position in a timer timeline.
282#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize)]
283pub struct TimerTimelineCursor {
284    due_time_ms: i64,
285    sequence: u64,
286}
287
288impl TimerTimelineCursor {
289    /// Creates a timeline cursor.
290    pub const fn new(due_time_ms: i64, sequence: u64) -> Self {
291        Self { due_time_ms, sequence }
292    }
293
294    /// Returns the inclusive due timestamp represented by this cursor.
295    pub const fn due_time_ms(self) -> i64 {
296        self.due_time_ms
297    }
298
299    /// Returns the deterministic tie-break sequence.
300    pub const fn sequence(self) -> u64 {
301        self.sequence
302    }
303}
304
305/// Immutable route persisted on first durable admission.
306#[derive(Clone, Debug, Deserialize, PartialEq, Eq, Serialize)]
307pub struct PersistedTimerRoute {
308    engine_id: TimerEngineId,
309    format_version: u16,
310    normalization_policy_fingerprint: u64,
311    generation: TimerGeneration,
312    delivery_token: String,
313}
314
315impl PersistedTimerRoute {
316    /// Creates and validates an immutable route.
317    ///
318    /// # Errors
319    ///
320    /// Returns [`StoreContractViolation::TimerInvalidRoute`] when the version or token is empty.
321    pub fn try_new(
322        engine_id: TimerEngineId,
323        format_version: u16,
324        normalization_policy_fingerprint: u64,
325        generation: TimerGeneration,
326        delivery_token: impl Into<String>,
327    ) -> Result<Self, StoreContractViolation> {
328        let delivery_token = delivery_token.into();
329        if format_version == 0 || delivery_token.is_empty() {
330            return Err(StoreContractViolation::TimerInvalidRoute);
331        }
332        Ok(Self {
333            engine_id,
334            format_version,
335            normalization_policy_fingerprint,
336            generation,
337            delivery_token,
338        })
339    }
340
341    /// Returns the owning engine.
342    pub const fn engine_id(&self) -> TimerEngineId {
343        self.engine_id
344    }
345
346    /// Returns the persistent record format version.
347    pub const fn format_version(&self) -> u16 {
348        self.format_version
349    }
350
351    /// Returns the normalization policy fingerprint captured at admission.
352    pub const fn normalization_policy_fingerprint(&self) -> u64 {
353        self.normalization_policy_fingerprint
354    }
355
356    /// Returns the logical schedule generation.
357    pub const fn generation(&self) -> TimerGeneration {
358        self.generation
359    }
360
361    /// Returns the stable delivery idempotency token.
362    pub fn delivery_token(&self) -> &str {
363        &self.delivery_token
364    }
365}