rocketmq-rust 0.8.0

Unofficial Rust implementation of Apache RocketMQ
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
// Copyright 2023 The RocketMQ Rust Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::str::FromStr;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;

use chrono::DateTime;
use chrono::Utc;
use cron::Schedule;

use crate::schedule::SchedulerError;

/// Trigger trait for determining when tasks should run
pub trait Trigger: Send + Sync {
    /// Get the next execution time after the given time
    fn next_execution_time(&self, after: SystemTime) -> Option<SystemTime>;

    /// Check if this trigger will fire again
    fn has_next(&self, after: SystemTime) -> bool;

    /// Get trigger description
    fn description(&self) -> String;

    /// Check if this trigger should fire now (new method for delay support)
    fn should_trigger_now(&self, now: SystemTime) -> bool {
        if let Some(next_time) = self.next_execution_time(now) {
            next_time <= now
        } else {
            false
        }
    }
}

/// Cron-based trigger
#[derive(Debug, Clone)]
pub struct CronTrigger {
    schedule: Schedule,
    expression: String,
}

impl CronTrigger {
    pub fn new(expression: impl Into<String>) -> Result<Self, SchedulerError> {
        let expression = expression.into();
        let schedule = Schedule::from_str(&expression)
            .map_err(|e| SchedulerError::TriggerError(format!("Invalid cron expression: {e}")))?;

        Ok(Self { schedule, expression })
    }

    /// Create a trigger that fires every minute
    pub fn every_minute() -> Result<Self, SchedulerError> {
        Self::new("0 * * * * *")
    }

    /// Create a trigger that fires every hour at minute 0
    pub fn hourly() -> Result<Self, SchedulerError> {
        Self::new("0 0 * * * *")
    }

    /// Create a trigger that fires daily at midnight
    pub fn daily() -> Result<Self, SchedulerError> {
        Self::new("0 0 0 * * *")
    }

    /// Create a trigger that fires weekly on Sunday at midnight
    pub fn weekly() -> Result<Self, SchedulerError> {
        Self::new("0 0 0 * * SUN")
    }

    /// Create a trigger that fires monthly on the 1st at midnight
    pub fn monthly() -> Result<Self, SchedulerError> {
        Self::new("0 0 0 1 * *")
    }
}

impl Trigger for CronTrigger {
    fn next_execution_time(&self, after: SystemTime) -> Option<SystemTime> {
        let after_datetime = system_time_to_datetime(after);
        self.schedule.after(&after_datetime).next().map(datetime_to_system_time)
    }

    fn has_next(&self, after: SystemTime) -> bool {
        self.next_execution_time(after).is_some()
    }

    fn description(&self) -> String {
        format!("Cron: {}", self.expression)
    }
}

/// Interval-based trigger
#[derive(Debug, Clone)]
pub struct IntervalTrigger {
    interval: Duration,
    start_time: Option<SystemTime>,
    end_time: Option<SystemTime>,
    repeat_count: Option<u32>,
    executed_count: u32,
}

impl IntervalTrigger {
    pub fn new(interval: Duration) -> Self {
        Self {
            interval,
            start_time: None,
            end_time: None,
            repeat_count: None,
            executed_count: 0,
        }
    }

    pub fn with_start_time(mut self, start_time: SystemTime) -> Self {
        self.start_time = Some(start_time);
        self
    }

    pub fn with_end_time(mut self, end_time: SystemTime) -> Self {
        self.end_time = Some(end_time);
        self
    }

    pub fn with_repeat_count(mut self, count: u32) -> Self {
        self.repeat_count = Some(count);
        self
    }

    pub fn every_seconds(seconds: u64) -> Self {
        Self::new(Duration::from_secs(seconds))
    }

    pub fn every_minutes(minutes: u64) -> Self {
        Self::new(Duration::from_secs(minutes * 60))
    }

    pub fn every_hours(hours: u64) -> Self {
        Self::new(Duration::from_secs(hours * 3600))
    }

    fn increment_executed_count(&mut self) {
        self.executed_count += 1;
    }
}

impl Trigger for IntervalTrigger {
    fn next_execution_time(&self, after: SystemTime) -> Option<SystemTime> {
        // Check repeat count limit
        if let Some(max_count) = self.repeat_count {
            if self.executed_count >= max_count {
                return None;
            }
        }

        let start = self.start_time.unwrap_or(after);

        // If we haven't started yet, return start time
        if after < start {
            return Some(start);
        }

        let next_time = if self.executed_count == 0 {
            start
        } else {
            after + self.interval
        };

        // Check end time limit
        if let Some(end) = self.end_time {
            if next_time > end {
                return None;
            }
        }

        Some(next_time)
    }

    fn has_next(&self, after: SystemTime) -> bool {
        self.next_execution_time(after).is_some()
    }

    fn description(&self) -> String {
        format!("Interval: {:?}", self.interval)
    }
}

/// One-time delay trigger
#[derive(Debug, Clone)]
pub struct DelayTrigger {
    delay: Duration,
    start_time: SystemTime,
    executed: bool,
}

impl DelayTrigger {
    pub fn new(delay: Duration) -> Self {
        Self {
            delay,
            start_time: SystemTime::now(),
            executed: false,
        }
    }

    pub fn after_seconds(seconds: u64) -> Self {
        Self::new(Duration::from_secs(seconds))
    }

    pub fn after_minutes(minutes: u64) -> Self {
        Self::new(Duration::from_secs(minutes * 60))
    }

    pub fn after_hours(hours: u64) -> Self {
        Self::new(Duration::from_secs(hours * 3600))
    }

    pub fn at_time(execution_time: SystemTime) -> Self {
        let now = SystemTime::now();
        let delay = execution_time.duration_since(now).unwrap_or(Duration::ZERO);
        Self {
            delay,
            start_time: now,
            executed: false,
        }
    }
    /// Mark as executed (used internally by scheduler)
    pub fn mark_executed(&mut self) {
        self.executed = true;
    }

    /// Check if already executed
    pub fn is_executed(&self) -> bool {
        self.executed
    }
}

impl Trigger for DelayTrigger {
    fn next_execution_time(&self, _after: SystemTime) -> Option<SystemTime> {
        if self.executed {
            None
        } else {
            Some(self.start_time + self.delay)
        }
    }

    fn has_next(&self, _after: SystemTime) -> bool {
        !self.executed
    }

    fn description(&self) -> String {
        format!("Delay: {:?}", self.delay)
    }

    fn should_trigger_now(&self, _now: SystemTime) -> bool {
        if self.executed {
            return false;
        }

        match self.start_time.elapsed() {
            Ok(elapsed) => elapsed >= self.delay,
            Err(_) => false,
        }
    }
}

/// Interval trigger with initial delay
#[derive(Debug, Clone)]
pub struct DelayedIntervalTrigger {
    interval: Duration,
    initial_delay: Duration,
    start_time: SystemTime,
    last_execution: Option<SystemTime>,
    end_time: Option<SystemTime>,
    repeat_count: Option<u32>,
    executed_count: u32,
}

impl DelayedIntervalTrigger {
    pub fn new(interval: Duration, initial_delay: Duration) -> Self {
        Self {
            interval,
            initial_delay,
            start_time: SystemTime::now(),
            last_execution: None,
            end_time: None,
            repeat_count: None,
            executed_count: 0,
        }
    }

    pub fn every_seconds_with_delay(interval_seconds: u64, delay_seconds: u64) -> Self {
        Self::new(
            Duration::from_secs(interval_seconds),
            Duration::from_secs(delay_seconds),
        )
    }

    pub fn every_minutes_with_delay(interval_minutes: u64, delay_minutes: u64) -> Self {
        Self::new(
            Duration::from_secs(interval_minutes * 60),
            Duration::from_secs(delay_minutes * 60),
        )
    }

    /// Set an end time for the trigger
    pub fn until(mut self, end_time: SystemTime) -> Self {
        self.end_time = Some(end_time);
        self
    }

    /// Set a maximum number of executions
    pub fn repeat(mut self, count: u32) -> Self {
        self.repeat_count = Some(count);
        self
    }

    /// Get the number of times this trigger has been executed
    pub fn execution_count(&self) -> u32 {
        self.executed_count
    }

    /// Mark that an execution has occurred
    pub fn mark_executed(&mut self, execution_time: SystemTime) {
        self.last_execution = Some(execution_time);
        self.executed_count += 1;
    }

    /// Check if this trigger should stop executing
    fn should_stop(&self, now: SystemTime) -> bool {
        // Check if we've reached the end time
        if let Some(end_time) = self.end_time {
            if now >= end_time {
                return true;
            }
        }

        // Check if we've reached the repeat count
        if let Some(repeat_count) = self.repeat_count {
            if self.executed_count >= repeat_count {
                return true;
            }
        }

        false
    }

    /// Calculate the first execution time
    fn first_execution_time(&self) -> SystemTime {
        self.start_time + self.initial_delay
    }
}

impl Trigger for DelayedIntervalTrigger {
    fn next_execution_time(&self, after: SystemTime) -> Option<SystemTime> {
        if self.should_stop(after) {
            return None;
        }

        match self.last_execution {
            None => {
                // First execution
                let first_time = self.first_execution_time();
                if first_time > after {
                    Some(first_time)
                } else {
                    // Calculate next proper interval if first time passed
                    let elapsed_since_first = after.duration_since(first_time).unwrap_or(Duration::ZERO);
                    let intervals_passed = (elapsed_since_first.as_millis() / self.interval.as_millis()) + 1;
                    Some(first_time + Duration::from_millis((intervals_passed * self.interval.as_millis()) as u64))
                }
            }
            Some(last) => {
                // Subsequent executions
                let next_time = last + self.interval;
                if next_time > after && !self.should_stop(next_time) {
                    Some(next_time)
                } else if next_time <= after {
                    // Calculate proper next interval if time passed
                    let elapsed = after.duration_since(last).unwrap_or(Duration::ZERO);
                    let intervals_passed = (elapsed.as_millis() / self.interval.as_millis()) + 1;
                    let calculated_next =
                        last + Duration::from_millis((intervals_passed * self.interval.as_millis()) as u64);

                    if !self.should_stop(calculated_next) {
                        Some(calculated_next)
                    } else {
                        None
                    }
                } else {
                    None
                }
            }
        }
    }

    fn has_next(&self, after: SystemTime) -> bool {
        !self.should_stop(after) && self.next_execution_time(after).is_some()
    }

    fn description(&self) -> String {
        let mut desc = format!(
            "DelayedInterval: interval={:?}, initial_delay={:?}, executed_count={}",
            self.interval, self.initial_delay, self.executed_count
        );

        if let Some(end_time) = self.end_time {
            desc.push_str(&format!(", end_time={end_time:?}"));
        }

        if let Some(repeat_count) = self.repeat_count {
            desc.push_str(&format!(", repeat_count={repeat_count}"));
        }

        desc
    }

    fn should_trigger_now(&self, now: SystemTime) -> bool {
        if self.should_stop(now) {
            return false;
        }

        match self.last_execution {
            None => {
                // Check if first execution time has arrived
                let first_time = self.first_execution_time();
                now >= first_time
            }
            Some(last) => {
                // Check if next execution time has arrived
                let next_time = last + self.interval;
                now >= next_time
            }
        }
    }
}

// Helper functions for time conversion
fn system_time_to_datetime(system_time: SystemTime) -> DateTime<Utc> {
    DateTime::from(system_time)
}

fn datetime_to_system_time(datetime: DateTime<Utc>) -> SystemTime {
    UNIX_EPOCH + Duration::from_secs(datetime.timestamp() as u64)
}