celers-core 0.2.0

Core traits and types for CeleRS distributed task queue
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
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::fmt;
use std::time::{SystemTime, UNIX_EPOCH};

/// Task state enumeration with strict state machine transitions
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum TaskState {
    /// Task is queued but not yet picked up by a worker
    Pending,

    /// Task has been received by a worker
    Received,

    /// Task has been reserved by a worker but not yet executed
    Reserved,

    /// Task is currently being executed
    Running,

    /// Task is being retried (includes retry count)
    Retrying(u32),

    /// Task completed successfully with result
    Succeeded(Vec<u8>),

    /// Task failed with error message
    Failed(String),

    /// Task has been revoked
    Revoked,

    /// Task has been rejected
    Rejected,

    /// Custom user-defined state with optional metadata
    Custom {
        /// Custom state name
        name: String,
        /// Optional custom metadata as JSON bytes
        metadata: Option<Vec<u8>>,
    },
}

impl TaskState {
    /// Check if the task is in a terminal state
    #[inline]
    #[must_use]
    pub const fn is_terminal(&self) -> bool {
        matches!(
            self,
            TaskState::Succeeded(_)
                | TaskState::Failed(_)
                | TaskState::Revoked
                | TaskState::Rejected
        )
    }

    /// Create a custom state with a name
    #[must_use]
    pub fn custom(name: impl Into<String>) -> Self {
        Self::Custom {
            name: name.into(),
            metadata: None,
        }
    }

    /// Create a custom state with name and JSON metadata
    #[must_use]
    pub fn custom_with_metadata(name: impl Into<String>, metadata: Vec<u8>) -> Self {
        Self::Custom {
            name: name.into(),
            metadata: Some(metadata),
        }
    }

    /// Check if this is a custom state
    #[inline]
    #[must_use]
    pub const fn is_custom(&self) -> bool {
        matches!(self, TaskState::Custom { .. })
    }

    /// Get the custom state name if this is a custom state
    #[inline]
    #[must_use]
    pub fn custom_name(&self) -> Option<&str> {
        match self {
            TaskState::Custom { name, .. } => Some(name),
            _ => None,
        }
    }

    /// Get the custom state metadata if this is a custom state with metadata
    #[inline]
    #[must_use]
    pub fn custom_metadata(&self) -> Option<&[u8]> {
        match self {
            TaskState::Custom { metadata, .. } => metadata.as_deref(),
            _ => None,
        }
    }

    /// Check if the task is revoked
    #[inline]
    #[must_use]
    pub const fn is_revoked(&self) -> bool {
        matches!(self, TaskState::Revoked)
    }

    /// Check if the task is rejected
    #[inline]
    #[must_use]
    pub const fn is_rejected(&self) -> bool {
        matches!(self, TaskState::Rejected)
    }

    /// Check if the task is received
    #[inline]
    #[must_use]
    pub const fn is_received(&self) -> bool {
        matches!(self, TaskState::Received)
    }

    /// Check if the task can be retried
    #[inline]
    #[must_use]
    pub const fn can_retry(&self, max_retries: u32) -> bool {
        match self {
            TaskState::Failed(_) => true,
            TaskState::Retrying(count) => *count < max_retries,
            _ => false,
        }
    }

    /// Get the retry count
    #[inline]
    #[must_use]
    pub const fn retry_count(&self) -> u32 {
        match self {
            TaskState::Retrying(count) => *count,
            _ => 0,
        }
    }

    /// Check if the task is in an active (non-terminal) state
    #[inline]
    #[must_use]
    pub const fn is_active(&self) -> bool {
        !self.is_terminal()
    }

    /// Check if the task is pending
    #[inline]
    #[must_use]
    pub const fn is_pending(&self) -> bool {
        matches!(self, TaskState::Pending)
    }

    /// Check if the task is reserved
    #[inline]
    #[must_use]
    pub const fn is_reserved(&self) -> bool {
        matches!(self, TaskState::Reserved)
    }

    /// Check if the task is running
    #[inline]
    #[must_use]
    pub const fn is_running(&self) -> bool {
        matches!(self, TaskState::Running)
    }

    /// Check if the task is retrying
    #[inline]
    #[must_use]
    pub const fn is_retrying(&self) -> bool {
        matches!(self, TaskState::Retrying(_))
    }

    /// Check if the task succeeded
    #[inline]
    #[must_use]
    pub const fn is_succeeded(&self) -> bool {
        matches!(self, TaskState::Succeeded(_))
    }

    /// Check if the task failed
    #[inline]
    #[must_use]
    pub const fn is_failed(&self) -> bool {
        matches!(self, TaskState::Failed(_))
    }

    /// Get the success result if the task succeeded
    #[inline]
    #[must_use]
    pub fn success_result(&self) -> Option<&[u8]> {
        match self {
            TaskState::Succeeded(result) => Some(result),
            _ => None,
        }
    }

    /// Get the error message if the task failed
    #[inline]
    #[must_use]
    pub fn error_message(&self) -> Option<&str> {
        match self {
            TaskState::Failed(error) => Some(error),
            _ => None,
        }
    }
}

impl fmt::Display for TaskState {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TaskState::Pending => write!(f, "PENDING"),
            TaskState::Received => write!(f, "RECEIVED"),
            TaskState::Reserved => write!(f, "RESERVED"),
            TaskState::Running => write!(f, "RUNNING"),
            TaskState::Retrying(count) => write!(f, "RETRYING({count})"),
            TaskState::Succeeded(_) => write!(f, "SUCCEEDED"),
            TaskState::Failed(err) => write!(f, "FAILED: {err}"),
            TaskState::Revoked => write!(f, "REVOKED"),
            TaskState::Rejected => write!(f, "REJECTED"),
            TaskState::Custom { name, .. } => write!(f, "CUSTOM({name})"),
        }
    }
}

impl TaskState {
    /// Get a short string representation of the state name
    #[inline]
    #[must_use]
    pub fn name(&self) -> &str {
        match self {
            TaskState::Pending => "PENDING",
            TaskState::Received => "RECEIVED",
            TaskState::Reserved => "RESERVED",
            TaskState::Running => "RUNNING",
            TaskState::Retrying(_) => "RETRYING",
            TaskState::Succeeded(_) => "SUCCESS",
            TaskState::Failed(_) => "FAILURE",
            TaskState::Revoked => "REVOKED",
            TaskState::Rejected => "REJECTED",
            TaskState::Custom { name, .. } => name,
        }
    }
}

// ============================================================================
// State Transitions
// ============================================================================

/// A state transition record
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct StateTransition {
    /// Previous state
    pub from: TaskState,
    /// New state
    pub to: TaskState,
    /// Unix timestamp when the transition occurred
    pub timestamp: f64,
    /// Optional reason for the transition
    pub reason: Option<String>,
    /// Optional additional metadata
    pub metadata: Option<HashMap<String, serde_json::Value>>,
}

impl StateTransition {
    /// Create a new state transition
    #[must_use]
    pub fn new(from: TaskState, to: TaskState) -> Self {
        Self {
            from,
            to,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap_or_default()
                .as_secs_f64(),
            reason: None,
            metadata: None,
        }
    }

    /// Add a reason for the transition
    #[must_use]
    pub fn with_reason(mut self, reason: impl Into<String>) -> Self {
        self.reason = Some(reason.into());
        self
    }

    /// Add metadata to the transition
    #[must_use]
    pub fn with_metadata(mut self, metadata: HashMap<String, serde_json::Value>) -> Self {
        self.metadata = Some(metadata);
        self
    }

    /// Add a single metadata key-value pair
    #[must_use]
    pub fn with_meta(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.metadata
            .get_or_insert_with(HashMap::new)
            .insert(key.into(), value);
        self
    }
}

/// Tracks state transitions for a task
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct StateHistory {
    /// Current state
    pub current: Option<TaskState>,
    /// List of state transitions
    pub transitions: Vec<StateTransition>,
}

impl StateHistory {
    /// Create a new state history
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Create a new state history with initial state
    #[must_use]
    pub fn with_initial(state: TaskState) -> Self {
        Self {
            current: Some(state),
            transitions: Vec::new(),
        }
    }

    /// Transition to a new state
    pub fn transition(&mut self, to: TaskState) -> Option<StateTransition> {
        let from = self.current.take()?;
        let transition = StateTransition::new(from, to.clone());
        self.current = Some(to);
        self.transitions.push(transition.clone());
        Some(transition)
    }

    /// Transition to a new state with a reason
    pub fn transition_with_reason(
        &mut self,
        to: TaskState,
        reason: impl Into<String>,
    ) -> Option<StateTransition> {
        let from = self.current.take()?;
        let transition = StateTransition::new(from, to.clone()).with_reason(reason);
        self.current = Some(to);
        self.transitions.push(transition.clone());
        Some(transition)
    }

    /// Get the current state
    #[inline]
    #[must_use]
    pub fn current_state(&self) -> Option<&TaskState> {
        self.current.as_ref()
    }

    /// Get all transitions
    #[inline]
    #[must_use]
    pub fn get_transitions(&self) -> &[StateTransition] {
        &self.transitions
    }

    /// Get the last transition
    #[inline]
    #[must_use]
    pub fn last_transition(&self) -> Option<&StateTransition> {
        self.transitions.last()
    }

    /// Get the number of transitions
    #[inline]
    #[must_use]
    pub const fn transition_count(&self) -> usize {
        self.transitions.len()
    }

    /// Check if task has ever been in a specific state
    #[inline]
    #[must_use]
    pub fn has_been_in_state(&self, state_name: &str) -> bool {
        self.transitions.iter().any(|t| t.to.name() == state_name)
            || self
                .current
                .as_ref()
                .is_some_and(|s| s.name() == state_name)
    }

    /// Get the time spent in a specific state (returns None if never in that state)
    #[must_use]
    pub fn time_in_state(&self, state_name: &str) -> Option<f64> {
        let mut total_time = 0.0;
        let mut entry_time: Option<f64> = None;

        for transition in &self.transitions {
            if transition.from.name() == state_name {
                if let Some(entry) = entry_time {
                    total_time += transition.timestamp - entry;
                    entry_time = None;
                }
            }
            if transition.to.name() == state_name {
                entry_time = Some(transition.timestamp);
            }
        }

        // If still in the state, add time until now
        if let Some(entry) = entry_time {
            if self
                .current
                .as_ref()
                .is_some_and(|s| s.name() == state_name)
            {
                let now = SystemTime::now()
                    .duration_since(UNIX_EPOCH)
                    .unwrap_or_default()
                    .as_secs_f64();
                total_time += now - entry;
            }
        }

        if total_time > 0.0 || entry_time.is_some() {
            Some(total_time)
        } else {
            None
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_terminal_states() {
        assert!(TaskState::Succeeded(vec![]).is_terminal());
        assert!(TaskState::Failed("error".to_string()).is_terminal());
        assert!(!TaskState::Pending.is_terminal());
        assert!(!TaskState::Running.is_terminal());
    }

    #[test]
    fn test_retry_logic() {
        assert!(TaskState::Failed("error".to_string()).can_retry(3));
        assert!(TaskState::Retrying(2).can_retry(3));
        assert!(!TaskState::Retrying(3).can_retry(3));
        assert!(!TaskState::Succeeded(vec![]).can_retry(3));
    }

    // Property-based tests
    #[cfg(test)]
    mod proptests {
        use super::*;
        use proptest::prelude::*;

        // Strategy for generating TaskState
        fn task_state_strategy() -> impl Strategy<Value = TaskState> {
            prop_oneof![
                Just(TaskState::Pending),
                Just(TaskState::Received),
                Just(TaskState::Reserved),
                Just(TaskState::Running),
                (0u32..100).prop_map(TaskState::Retrying),
                prop::collection::vec(any::<u8>(), 0..100).prop_map(TaskState::Succeeded),
                any::<String>().prop_map(TaskState::Failed),
                Just(TaskState::Revoked),
                Just(TaskState::Rejected),
            ]
        }

        proptest! {
            #[test]
            fn test_terminal_states_are_consistent(state in task_state_strategy()) {
                // Property: If a state is terminal, it should not be active
                if state.is_terminal() {
                    prop_assert!(!state.is_active());
                } else {
                    prop_assert!(state.is_active());
                }
            }

            #[test]
            fn test_retry_count_is_non_negative(count in 0u32..1000) {
                let state = TaskState::Retrying(count);
                prop_assert_eq!(state.retry_count(), count);
                prop_assert!(state.is_retrying());
            }

            #[test]
            fn test_can_retry_respects_max_retries(current_retry in 0u32..100, max_retries in 0u32..100) {
                let state = TaskState::Retrying(current_retry);
                let can_retry = state.can_retry(max_retries);

                if current_retry < max_retries {
                    prop_assert!(can_retry, "Should be able to retry when current_retry < max_retries");
                } else {
                    prop_assert!(!can_retry, "Should not be able to retry when current_retry >= max_retries");
                }
            }

            #[test]
            fn test_failed_state_can_always_retry_once(max_retries in 1u32..100) {
                let state = TaskState::Failed("error".to_string());
                prop_assert!(state.can_retry(max_retries));
            }

            #[test]
            fn test_terminal_states_cannot_retry(max_retries in 1u32..100) {
                let terminal_states = vec![
                    TaskState::Succeeded(vec![1, 2, 3]),
                    TaskState::Revoked,
                    TaskState::Rejected,
                ];

                for state in terminal_states {
                    if !matches!(state, TaskState::Failed(_)) {
                        prop_assert!(!state.can_retry(max_retries) || state.is_failed());
                    }
                }
            }

            #[test]
            fn test_state_name_is_consistent(state in task_state_strategy()) {
                let name = state.name();
                prop_assert!(!name.is_empty(), "State name should never be empty");

                // Name should match the state type
                match &state {
                    TaskState::Pending => prop_assert_eq!(name, "PENDING"),
                    TaskState::Received => prop_assert_eq!(name, "RECEIVED"),
                    TaskState::Reserved => prop_assert_eq!(name, "RESERVED"),
                    TaskState::Running => prop_assert_eq!(name, "RUNNING"),
                    TaskState::Retrying(_) => prop_assert_eq!(name, "RETRYING"),
                    TaskState::Succeeded(_) => prop_assert_eq!(name, "SUCCESS"),
                    TaskState::Failed(_) => prop_assert_eq!(name, "FAILURE"),
                    TaskState::Revoked => prop_assert_eq!(name, "REVOKED"),
                    TaskState::Rejected => prop_assert_eq!(name, "REJECTED"),
                    TaskState::Custom { name: custom_name, .. } => prop_assert_eq!(name, custom_name),
                }
            }

            #[test]
            fn test_success_result_only_for_succeeded(result in prop::collection::vec(any::<u8>(), 0..100)) {
                let success_state = TaskState::Succeeded(result.clone());
                prop_assert_eq!(success_state.success_result(), Some(result.as_slice()));

                let other_states = vec![
                    TaskState::Pending,
                    TaskState::Running,
                    TaskState::Failed("error".to_string()),
                ];

                for state in other_states {
                    prop_assert_eq!(state.success_result(), None);
                }
            }

            #[test]
            fn test_error_message_only_for_failed(error_msg in any::<String>()) {
                let failed_state = TaskState::Failed(error_msg.clone());
                prop_assert_eq!(failed_state.error_message(), Some(error_msg.as_str()));

                let other_states = vec![
                    TaskState::Pending,
                    TaskState::Running,
                    TaskState::Succeeded(vec![]),
                ];

                for state in other_states {
                    prop_assert_eq!(state.error_message(), None);
                }
            }

            #[test]
            fn test_state_history_transitions_accumulate(
                num_transitions in 1usize..20,
            ) {
                let mut history = StateHistory::with_initial(TaskState::Pending);

                for i in 0..num_transitions {
                    let new_state = if i % 2 == 0 {
                        TaskState::Running
                    } else {
                        TaskState::Pending
                    };
                    history.transition(new_state);
                }

                prop_assert_eq!(history.transition_count(), num_transitions);
                prop_assert!(history.last_transition().is_some());
            }

            #[test]
            fn test_state_history_current_state_is_latest(state in task_state_strategy()) {
                let mut history = StateHistory::with_initial(TaskState::Pending);
                history.transition(state.clone());

                prop_assert_eq!(history.current_state(), Some(&state));
            }
        }
    }
}