aurora-db 0.5.8

A lightweight, real-time embedded database with built-in PubSub, reactive queries, background workers, and intelligent caching.
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
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use uuid::Uuid;

/// Job status tracking the lifecycle of a background job
///
/// Jobs progress through states: Pending -> Running -> Completed/Failed -> DeadLetter
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub enum JobStatus {
    /// Job is queued and waiting to be processed
    Pending,
    /// Job is currently being executed by a worker
    Running,
    /// Job completed successfully
    Completed,
    /// Job failed but can be retried
    Failed { error: String, retries: u32 },
    /// Job permanently failed after max retries
    DeadLetter { error: String },
}

impl std::fmt::Display for JobStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JobStatus::Pending => write!(f, "Pending"),
            JobStatus::Running => write!(f, "Running"),
            JobStatus::Completed => write!(f, "Completed"),
            JobStatus::Failed { error, retries } => write!(f, "Failed({}, retries: {})", error, retries),
            JobStatus::DeadLetter { error } => write!(f, "DeadLetter({})", error),
        }
    }
}

/// Job priority for execution order
///
/// Higher priority jobs are executed first. Critical > High > Normal > Low.
///
/// # Examples
///
/// ```
/// use aurora_db::workers::{Job, JobPriority};
///
/// // Time-sensitive payment
/// let payment = Job::new("process_payment")
///     .with_priority(JobPriority::Critical);
///
/// // User-facing task
/// let notification = Job::new("send_notification")
///     .with_priority(JobPriority::High);
///
/// // Background cleanup
/// let cleanup = Job::new("cleanup_temp_files")
///     .with_priority(JobPriority::Low);
/// ```
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum JobPriority {
    /// Low priority (value: 1) - background tasks, cleanup
    Low = 1,
    /// Normal priority (value: 2) - default for most jobs
    Normal = 2,
    /// High priority (value: 3) - user-facing operations
    High = 3,
    /// Critical priority (value: 4) - payments, security
    Critical = 4,
}

impl std::fmt::Display for JobPriority {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            JobPriority::Low => write!(f, "Low"),
            JobPriority::Normal => write!(f, "Normal"),
            JobPriority::High => write!(f, "High"),
            JobPriority::Critical => write!(f, "Critical"),
        }
    }
}

/// A durable background job
///
/// Represents a unit of work that can be queued, scheduled, retried, and tracked.
/// Jobs are persisted to disk and survive restarts. Use the builder pattern to
/// configure job properties.
///
/// # Examples
///
/// ```
/// use aurora_db::workers::{Job, JobPriority};
/// use serde_json::json;
///
/// // Simple job
/// let job = Job::new("send_email")
///     .add_field("to", json!("user@example.com"))
///     .add_field("subject", json!("Welcome!"));
///
/// // Job with all options
/// let job = Job::new("process_video")
///     .add_field("video_id", json!("vid-123"))
///     .add_field("resolution", json!("1080p"))
///     .with_priority(JobPriority::High)
///     .with_max_retries(5)
///     .with_timeout(600) // 10 minutes
///     .scheduled_at(chrono::Utc::now() + chrono::Duration::hours(1));
/// ```
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Job {
    pub id: String,
    pub job_type: String,
    pub payload: HashMap<String, serde_json::Value>,
    pub priority: JobPriority,
    pub status: JobStatus,
    pub max_retries: u32,
    pub retry_count: u32,
    pub created_at: DateTime<Utc>,
    pub scheduled_at: Option<DateTime<Utc>>,
    pub started_at: Option<DateTime<Utc>>,
    pub completed_at: Option<DateTime<Utc>>,
    pub timeout_seconds: Option<u64>,
    /// Unix timestamp of last "I'm alive" signal from worker (for Reaper)
    #[serde(default)]
    pub last_heartbeat: u64,
    /// Seconds before worker is considered dead (default: 30)
    #[serde(default = "default_lease")]
    pub lease_duration: u64,
}

impl std::fmt::Display for Job {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", serde_json::to_string_pretty(self).unwrap_or_default())
    }
}

/// Default lease duration: 30 seconds
fn default_lease() -> u64 {
    30
}

impl Job {
    /// Create a new job
    ///
    /// Creates a job with default settings:
    /// - Priority: Normal
    /// - Max retries: 3
    /// - Timeout: 5 minutes
    /// - Status: Pending
    ///
    /// # Arguments
    /// * `job_type` - Type identifier for routing to the correct handler
    ///
    /// # Examples
    ///
   
    /// // Create different job types
    /// let email = Job::new("send_email");
    /// let image = Job::new("resize_image");
    /// let report = Job::new("generate_report");
    /// ```
    pub fn new(job_type: impl Into<String>) -> Self {
        Self {
            id: Uuid::new_v4().to_string(),
            job_type: job_type.into(),
            payload: HashMap::new(),
            priority: JobPriority::Normal,
            status: JobStatus::Pending,
            max_retries: 3,
            retry_count: 0,
            created_at: Utc::now(),
            scheduled_at: None,
            started_at: None,
            completed_at: None,
            timeout_seconds: Some(300), // 5 minutes default
            last_heartbeat: 0,
            lease_duration: default_lease(),
        }
    }

    /// Set job payload from a HashMap
    ///
    /// Replaces the entire payload with the provided HashMap.
    /// For adding individual fields, use `add_field()` instead.
    ///
    /// # Examples
    ///
   
    /// use std::collections::HashMap;
    /// use serde_json::json;
    ///
    /// let mut payload = HashMap::new();
    /// payload.insert("user_id".to_string(), json!("123"));
    /// payload.insert("amount".to_string(), json!(99.99));
    ///
    /// let job = Job::new("process_payment")
    ///     .with_payload(payload);
    /// ```
    pub fn with_payload(mut self, payload: HashMap<String, serde_json::Value>) -> Self {
        self.payload = payload;
        self
    }

    /// Add a single field to the job payload
    ///
    /// Use this for building the payload incrementally.
    /// Can be chained multiple times.
    ///
    /// # Examples
    ///
   
    /// use serde_json::json;
    ///
    /// let job = Job::new("send_email")
    ///     .add_field("to", json!("user@example.com"))
    ///     .add_field("subject", json!("Welcome!"))
    ///     .add_field("template", json!("welcome_email"))
    ///     .add_field("vars", json!({"name": "Alice"}));
    /// ```
    pub fn add_field(mut self, key: impl Into<String>, value: serde_json::Value) -> Self {
        self.payload.insert(key.into(), value);
        self
    }

    /// Set job priority
    ///
    /// Higher priority jobs are executed before lower priority ones.
    /// Default is `JobPriority::Normal`.
    ///
    /// # Examples
    ///
   
    /// // Critical - payments, security operations
    /// let payment = Job::new("charge_card")
    ///     .with_priority(JobPriority::Critical);
    ///
    /// // High - user-facing operations
    /// let notification = Job::new("push_notification")
    ///     .with_priority(JobPriority::High);
    ///
    /// // Low - background cleanup, analytics
    /// let cleanup = Job::new("clean_old_logs")
    ///     .with_priority(JobPriority::Low);
    /// ```
    pub fn with_priority(mut self, priority: JobPriority) -> Self {
        self.priority = priority;
        self
    }

    /// Set maximum retry attempts
    ///
    /// If a job fails, it will be retried up to this many times with
    /// exponential backoff. Default is 3 retries.
    ///
    /// # Examples
    ///
   
    /// // Network operation - retry more
    /// let api_call = Job::new("fetch_api_data")
    ///     .with_max_retries(5);
    ///
    /// // Critical operation - don't retry
    /// let one_time = Job::new("send_invoice")
    ///     .with_max_retries(0);
    ///
    /// // Flaky operation - retry extensively
    /// let external = Job::new("third_party_webhook")
    ///     .with_max_retries(10);
    /// ```
    pub fn with_max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// Schedule job for later execution
    ///
    /// Job will not be executed until the specified time.
    /// Useful for reminders, scheduled reports, delayed notifications.
    ///
    /// # Examples
    ///
   
    /// use chrono::{Utc, Duration};
    ///
    /// // Run in 1 hour
    /// let reminder = Job::new("send_reminder")
    ///     .add_field("message", json!("Meeting starts soon"))
    ///     .scheduled_at(Utc::now() + Duration::hours(1));
    ///
    /// // Run at specific time
    /// let report = Job::new("daily_report")
    ///     .scheduled_at(Utc::now().date_naive().and_hms_opt(9, 0, 0).unwrap());
    ///
    /// // Delayed retry pattern
    /// let retry = Job::new("retry_failed_upload")
    ///     .scheduled_at(Utc::now() + Duration::minutes(30));
    /// ```
    pub fn scheduled_at(mut self, at: DateTime<Utc>) -> Self {
        self.scheduled_at = Some(at);
        self
    }

    /// Set job execution timeout
    ///
    /// Job will be terminated if it runs longer than this.
    /// Default is 300 seconds (5 minutes).
    ///
    /// # Examples
    ///
   
    /// // Quick task
    /// let quick = Job::new("send_sms")
    ///     .with_timeout(30); // 30 seconds
    ///
    /// // Long-running task
    /// let video = Job::new("transcode_video")
    ///     .with_timeout(3600); // 1 hour
    ///
    /// // Very long task
    /// let batch = Job::new("process_millions_of_records")
    ///     .with_timeout(7200); // 2 hours
    /// ```
    pub fn with_timeout(mut self, seconds: u64) -> Self {
        self.timeout_seconds = Some(seconds);
        self
    }

    /// Check if job should be executed (based on schedule)
    pub fn should_run(&self) -> bool {
        match self.status {
            JobStatus::Pending => {
                if let Some(scheduled) = self.scheduled_at {
                    Utc::now() >= scheduled
                } else {
                    true
                }
            }
            _ => false,
        }
    }

    /// Mark job as running
    pub fn mark_running(&mut self) {
        self.status = JobStatus::Running;
        self.started_at = Some(Utc::now());
        self.touch(); // Update heartbeat when starting
    }

    /// Update heartbeat timestamp to "now"
    ///
    /// Workers should call this periodically while processing a job.
    /// The Reaper uses this to detect dead workers.
    pub fn touch(&mut self) {
        self.last_heartbeat = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
    }

    /// Check if job's heartbeat has expired (worker presumed dead)
    pub fn is_heartbeat_expired(&self) -> bool {
        if !matches!(self.status, JobStatus::Running) {
            return false;
        }
        let now = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_secs();
        now.saturating_sub(self.last_heartbeat) > self.lease_duration
    }

    /// Set custom lease duration
    pub fn with_lease_duration(mut self, seconds: u64) -> Self {
        self.lease_duration = seconds;
        self
    }

    /// Mark job as completed
    pub fn mark_completed(&mut self) {
        self.status = JobStatus::Completed;
        self.completed_at = Some(Utc::now());
    }

    /// Mark job as failed
    pub fn mark_failed(&mut self, error: String) {
        self.retry_count += 1;

        if self.retry_count >= self.max_retries {
            self.status = JobStatus::DeadLetter { error };
        } else {
            self.status = JobStatus::Failed {
                error,
                retries: self.retry_count,
            };
        }
    }

    /// Calculate next retry delay (exponential backoff)
    pub fn next_retry_delay(&self) -> chrono::Duration {
        let base_delay = 5; // 5 seconds
        let delay_seconds = base_delay * 2_i64.pow(self.retry_count);
        chrono::Duration::seconds(delay_seconds)
    }
}

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

    #[test]
    fn test_job_creation() {
        let job = Job::new("email")
            .add_field("to", serde_json::json!("user@example.com"))
            .add_field("subject", serde_json::json!("Hello"))
            .with_priority(JobPriority::High)
            .with_max_retries(5);

        assert_eq!(job.job_type, "email");
        assert_eq!(job.priority, JobPriority::High);
        assert_eq!(job.max_retries, 5);
        assert_eq!(job.status, JobStatus::Pending);
    }

    #[test]
    fn test_job_should_run() {
        let job = Job::new("test");
        assert!(job.should_run());

        let future_job = Job::new("test").scheduled_at(Utc::now() + chrono::Duration::hours(1));
        assert!(!future_job.should_run());

        let past_job = Job::new("test").scheduled_at(Utc::now() - chrono::Duration::hours(1));
        assert!(past_job.should_run());
    }

    #[test]
    fn test_job_retry_logic() {
        let mut job = Job::new("test").with_max_retries(3);

        job.mark_failed("Error 1".to_string());
        assert!(matches!(job.status, JobStatus::Failed { .. }));
        assert_eq!(job.retry_count, 1);

        job.mark_failed("Error 2".to_string());
        assert_eq!(job.retry_count, 2);

        job.mark_failed("Error 3".to_string());
        assert!(matches!(job.status, JobStatus::DeadLetter { .. }));
        assert_eq!(job.retry_count, 3);
    }

    #[test]
    fn test_exponential_backoff() {
        let mut job = Job::new("test");

        assert_eq!(job.next_retry_delay().num_seconds(), 5);

        job.retry_count = 1;
        assert_eq!(job.next_retry_delay().num_seconds(), 10);

        job.retry_count = 2;
        assert_eq!(job.next_retry_delay().num_seconds(), 20);

        job.retry_count = 3;
        assert_eq!(job.next_retry_delay().num_seconds(), 40);
    }
}