azums-core 0.1.1

Zero-dependency core traits, models, and QueueError for azums
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
use crate::{
    backend::{NotificationStream, StorageBackend, StreamBackend},
    model::{ConsumerGroupStatus, Event, Job, JobListItem, JobStatus, NewEvent, NewJob},
};
use async_trait::async_trait;
use chrono::{DateTime, Utc};
use std::{
    collections::HashMap,
    sync::{Arc, RwLock},
};
use tokio_stream::{wrappers::BroadcastStream, StreamExt};
use uuid::Uuid;

/// Attempt history record stored in [`MemoryBackend`].
#[derive(Debug, Clone)]
pub struct MemoryAttempt {
    pub id: Uuid,
    pub dataset_id: String,
    pub job_id: Uuid,
    pub attempt_no: i32,
    pub status: String,
    pub worker_id: String,
    pub started_at: DateTime<Utc>,
    pub finished_at: Option<DateTime<Utc>>,
    pub latency_ms: Option<i32>,
    pub error_code: Option<String>,
    pub error_message: Option<String>,
}

#[derive(Debug, Default)]
struct InnerState {
    jobs: HashMap<Uuid, Job>,
    archive: HashMap<Uuid, Job>,
    attempts: HashMap<Uuid, MemoryAttempt>,
    streams: HashMap<String, Vec<Event>>,
    stream_offsets: HashMap<(String, String), ConsumerGroupStatus>,
}

/// Thread-safe in-memory implementation of [`StorageBackend`].
///
/// Ideal for unit testing, ephemeral workloads, and local development without external database servers.
#[derive(Debug, Clone, Default)]
pub struct MemoryBackend {
    state: Arc<RwLock<InnerState>>,
    notifiers: Arc<RwLock<HashMap<String, tokio::sync::broadcast::Sender<()>>>>,
    stream_notifiers: Arc<RwLock<HashMap<String, tokio::sync::broadcast::Sender<()>>>>,
}

impl MemoryBackend {
    /// Creates a new, empty `MemoryBackend`.
    pub fn new() -> Self {
        Self::default()
    }

    /// Resets and clears all stored jobs and attempt history.
    pub fn clear(&self) {
        let mut state = self.state.write().unwrap();
        state.jobs.clear();
        state.archive.clear();
        state.attempts.clear();
        state.streams.clear();
        state.stream_offsets.clear();
    }

    fn notify_queue(&self, queue: &str) {
        let notifiers = self.notifiers.read().unwrap();
        if let Some(tx) = notifiers.get(queue) {
            let _ = tx.send(());
        }
    }

    fn notify_stream(&self, stream: &str) {
        let notifiers = self.stream_notifiers.read().unwrap();
        if let Some(tx) = notifiers.get(stream) {
            let _ = tx.send(());
        }
    }
}

#[async_trait]
impl StorageBackend for MemoryBackend {
    fn as_stream(&self) -> Option<&dyn StreamBackend> {
        Some(self)
    }
    async fn run_migrations(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn health_check(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn enqueue(&self, job: NewJob) -> anyhow::Result<Uuid> {
        let job_id = Uuid::new_v4();
        let now = Utc::now();
        let queue_name = job.queue.clone();

        let job_entity = Job {
            dataset_id: "default".to_string(),
            replay_of_job_id: None,
            id: job_id,
            queue: job.queue,
            job_type: job.job_type,
            payload: job.payload_json,
            run_at: job.run_at,
            status: JobStatus::Queued.as_str().to_string(),
            priority: job.priority,
            max_attempts: job.max_attempts,
            locked_at: None,
            locked_by: None,
            lock_expires_at: None,
            dlq_reason_code: None,
            dlq_at: None,
            created_at: now,
            updated_at: now,
        };

        {
            let mut state = self.state.write().unwrap();
            state.jobs.insert(job_id, job_entity);
        }

        self.notify_queue(&queue_name);
        Ok(job_id)
    }

    async fn subscribe(&self, queue: &str) -> anyhow::Result<NotificationStream> {
        let rx = {
            let mut notifiers = self.notifiers.write().unwrap();
            let tx = notifiers
                .entry(queue.to_string())
                .or_insert_with(|| tokio::sync::broadcast::channel(128).0);
            tx.subscribe()
        };

        let stream = BroadcastStream::new(rx).filter_map(|res| res.ok());
        Ok(Box::pin(stream))
    }

    async fn lease_jobs_batch(
        &self,
        queue: &str,
        worker_id: &str,
        lease_seconds: i64,
        batch_size: i64,
    ) -> anyhow::Result<Vec<Job>> {
        self.lease_jobs_batch_with_ordering(
            queue,
            worker_id,
            lease_seconds,
            batch_size,
            crate::model::QueueOrdering::Fifo,
        )
        .await
    }

    async fn lease_jobs_batch_with_ordering(
        &self,
        queue: &str,
        worker_id: &str,
        lease_seconds: i64,
        batch_size: i64,
        ordering: crate::model::QueueOrdering,
    ) -> anyhow::Result<Vec<Job>> {
        let mut state = self.state.write().unwrap();
        let now = Utc::now();

        let mut candidates: Vec<Job> = state
            .jobs
            .values()
            .filter(|j| j.queue == queue && j.status == "queued" && j.run_at <= now)
            .cloned()
            .collect();

        match ordering {
            crate::model::QueueOrdering::Fifo => {
                candidates.sort_by(|a, b| {
                    b.priority
                        .cmp(&a.priority)
                        .then_with(|| a.run_at.cmp(&b.run_at))
                        .then_with(|| a.created_at.cmp(&b.created_at))
                        .then_with(|| a.id.cmp(&b.id))
                });
            }
            crate::model::QueueOrdering::Fastest => {
                candidates.sort_by_key(|a| std::cmp::Reverse(a.priority));
            }
        }

        let candidates: Vec<Job> = candidates.into_iter().take(batch_size as usize).collect();
        if candidates.is_empty() {
            return Ok(Vec::new());
        }

        let lock_expires_at = now + chrono::Duration::seconds(lease_seconds);
        let mut leased = Vec::with_capacity(candidates.len());

        for mut candidate in candidates {
            if let Some(j) = state.jobs.get_mut(&candidate.id) {
                j.status = JobStatus::Running.as_str().to_string();
                j.locked_at = Some(now);
                j.locked_by = Some(worker_id.to_string());
                j.lock_expires_at = Some(lock_expires_at);
                j.updated_at = now;

                candidate.status = j.status.clone();
                candidate.locked_at = j.locked_at;
                candidate.locked_by = j.locked_by.clone();
                candidate.lock_expires_at = j.lock_expires_at;
                candidate.updated_at = j.updated_at;

                leased.push(candidate);
            }
        }

        Ok(leased)
    }

    async fn reap_expired_locks(&self) -> anyhow::Result<u64> {
        let mut state = self.state.write().unwrap();
        let now = Utc::now();
        let mut reaped = 0u64;

        for job in state.jobs.values_mut() {
            if job.status == "running" {
                if let Some(exp) = job.lock_expires_at {
                    if exp <= now {
                        job.status = JobStatus::Queued.as_str().to_string();
                        job.locked_at = None;
                        job.locked_by = None;
                        job.lock_expires_at = None;
                        job.updated_at = now;
                        reaped += 1;
                    }
                }
            }
        }

        Ok(reaped)
    }

    async fn start_attempts_batch(
        &self,
        _dataset_ids: &[String],
        job_ids: &[Uuid],
        worker_id: &str,
    ) -> anyhow::Result<Vec<(Uuid, Uuid, i32)>> {
        if job_ids.is_empty() {
            return Ok(Vec::new());
        }

        let mut state = self.state.write().unwrap();
        let now = Utc::now();
        let mut results = Vec::with_capacity(job_ids.len());

        for &job_id in job_ids {
            let max_attempt = state
                .attempts
                .values()
                .filter(|a| a.job_id == job_id)
                .map(|a| a.attempt_no)
                .max()
                .unwrap_or(0);

            let next_attempt_no = max_attempt + 1;
            let attempt_id = Uuid::new_v4();

            let attempt = MemoryAttempt {
                id: attempt_id,
                dataset_id: "default".to_string(),
                job_id,
                attempt_no: next_attempt_no,
                status: "running".to_string(),
                worker_id: worker_id.to_string(),
                started_at: now,
                finished_at: None,
                latency_ms: None,
                error_code: None,
                error_message: None,
            };

            state.attempts.insert(attempt_id, attempt);
            results.push((job_id, attempt_id, next_attempt_no));
        }

        Ok(results)
    }

    async fn mark_succeeded(
        &self,
        job_id: Uuid,
        attempt_id: Uuid,
        _worker_id: &str,
        latency_ms: i32,
    ) -> anyhow::Result<()> {
        let mut state = self.state.write().unwrap();
        let now = Utc::now();

        if let Some(att) = state.attempts.get_mut(&attempt_id) {
            att.status = "succeeded".to_string();
            att.finished_at = Some(now);
            att.latency_ms = Some(latency_ms);
        }

        if let Some(job) = state.jobs.get_mut(&job_id) {
            job.status = JobStatus::Succeeded.as_str().to_string();
            job.locked_at = None;
            job.locked_by = None;
            job.lock_expires_at = None;
            job.updated_at = now;
        }

        Ok(())
    }

    async fn mark_succeeded_batch(
        &self,
        _dataset_id: &str,
        updates: &[(Uuid, Uuid, i32)],
        worker_id: &str,
    ) -> anyhow::Result<()> {
        for &(job_id, attempt_id, latency_ms) in updates {
            self.mark_succeeded(job_id, attempt_id, worker_id, latency_ms)
                .await?;
        }
        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    async fn reschedule_for_retry(
        &self,
        job_id: Uuid,
        attempt_id: Uuid,
        _worker_id: &str,
        latency_ms: i32,
        next_run_at: DateTime<Utc>,
        error_code: &str,
        error_message: &str,
        _attempt_no: i32,
    ) -> anyhow::Result<()> {
        let mut state = self.state.write().unwrap();
        let now = Utc::now();

        if let Some(att) = state.attempts.get_mut(&attempt_id) {
            att.status = "failed".to_string();
            att.finished_at = Some(now);
            att.latency_ms = Some(latency_ms);
            att.error_code = Some(error_code.to_string());
            att.error_message = Some(error_message.to_string());
        }

        if let Some(job) = state.jobs.get_mut(&job_id) {
            job.status = JobStatus::Queued.as_str().to_string();
            job.run_at = next_run_at;
            job.locked_at = None;
            job.locked_by = None;
            job.lock_expires_at = None;
            job.updated_at = now;
        }

        Ok(())
    }

    #[allow(clippy::too_many_arguments)]
    async fn mark_dlq(
        &self,
        job_id: Uuid,
        attempt_id: Uuid,
        _worker_id: &str,
        latency_ms: i32,
        reason_code: &str,
        error_code: &str,
        error_message: &str,
        _attempt_no: i32,
    ) -> anyhow::Result<()> {
        let mut state = self.state.write().unwrap();
        let now = Utc::now();

        if let Some(att) = state.attempts.get_mut(&attempt_id) {
            att.status = "failed".to_string();
            att.finished_at = Some(now);
            att.latency_ms = Some(latency_ms);
            att.error_code = Some(error_code.to_string());
            att.error_message = Some(error_message.to_string());
        }

        if let Some(job) = state.jobs.get_mut(&job_id) {
            job.status = JobStatus::Dlq.as_str().to_string();
            job.dlq_reason_code = Some(reason_code.to_string());
            job.dlq_at = Some(now);
            job.locked_at = None;
            job.locked_by = None;
            job.lock_expires_at = None;
            job.updated_at = now;
        }

        Ok(())
    }

    async fn archive_succeeded_older_than(
        &self,
        cutoff: DateTime<Utc>,
        limit: i64,
    ) -> anyhow::Result<u64> {
        let mut state = self.state.write().unwrap();

        let to_archive: Vec<Uuid> = state
            .jobs
            .values()
            .filter(|j| j.status == "succeeded" && j.updated_at < cutoff)
            .take(limit as usize)
            .map(|j| j.id)
            .collect();

        let count = to_archive.len() as u64;
        for id in to_archive {
            if let Some(job) = state.jobs.remove(&id) {
                state.archive.insert(id, job);
            }
        }

        Ok(count)
    }

    async fn delete_history_for_succeeded_older_than(
        &self,
        cutoff: DateTime<Utc>,
        limit: i64,
    ) -> anyhow::Result<(u64, u64)> {
        let mut state = self.state.write().unwrap();

        let archived_ids: Vec<Uuid> = state
            .archive
            .values()
            .filter(|j| j.updated_at < cutoff)
            .map(|j| j.id)
            .collect();

        let to_remove: Vec<Uuid> = state
            .attempts
            .values()
            .filter(|a| a.started_at < cutoff && archived_ids.contains(&a.job_id))
            .take(limit as usize)
            .map(|a| a.id)
            .collect();

        let count = to_remove.len() as u64;
        for aid in to_remove {
            state.attempts.remove(&aid);
        }

        Ok((count, 0))
    }

    async fn perform_maintenance(&self) -> anyhow::Result<()> {
        Ok(())
    }

    async fn extend_lease(
        &self,
        job_id: Uuid,
        worker_id: &str,
        lease_seconds: i64,
    ) -> anyhow::Result<bool> {
        let mut state = self.state.write().unwrap();
        if let Some(job) = state.jobs.get_mut(&job_id) {
            if job.status == "running" && job.locked_by.as_deref() == Some(worker_id) {
                let now = Utc::now();
                job.lock_expires_at = Some(now + chrono::Duration::seconds(lease_seconds));
                job.updated_at = now;
                return Ok(true);
            }
        }
        Ok(false)
    }

    async fn get_job(&self, job_id: Uuid) -> anyhow::Result<Option<Job>> {
        let state = self.state.read().unwrap();
        let job = state
            .jobs
            .get(&job_id)
            .or_else(|| state.archive.get(&job_id))
            .cloned();
        Ok(job)
    }

    async fn list_jobs(
        &self,
        queue: Option<&str>,
        status: Option<&str>,
        limit: i64,
        _cursor_created_at: Option<DateTime<Utc>>,
        _cursor_id: Option<Uuid>,
    ) -> anyhow::Result<Vec<JobListItem>> {
        let state = self.state.read().unwrap();
        let limit = limit.clamp(1, 500) as usize;

        let mut items: Vec<JobListItem> = state
            .jobs
            .values()
            .filter(|j| {
                if let Some(q) = queue {
                    if j.queue != q {
                        return false;
                    }
                }
                if let Some(st) = status {
                    if j.status != st {
                        return false;
                    }
                }
                true
            })
            .map(|j| JobListItem {
                id: j.id,
                queue: j.queue.clone(),
                job_type: j.job_type.clone(),
                status: j.status.clone(),
                run_at: j.run_at,
                priority: j.priority,
                max_attempts: j.max_attempts,
                last_error_code: None,
                last_error_message: None,
                dlq_reason_code: j.dlq_reason_code.clone(),
                created_at: j.created_at,
                updated_at: j.updated_at,
            })
            .collect();

        items.sort_by(|a, b| {
            b.created_at
                .cmp(&a.created_at)
                .then_with(|| b.id.cmp(&a.id))
        });

        items.truncate(limit);
        Ok(items)
    }

    async fn replay_job(
        &self,
        job_id: Uuid,
        override_queue: Option<&str>,
        override_run_at: Option<DateTime<Utc>>,
    ) -> anyhow::Result<Uuid> {
        let mut state = self.state.write().unwrap();

        let src = state
            .jobs
            .get(&job_id)
            .or_else(|| state.archive.get(&job_id))
            .cloned()
            .ok_or_else(|| anyhow::anyhow!("Job {job_id} not found"))?;

        let new_id = Uuid::new_v4();
        let now = Utc::now();
        let target_queue = override_queue.unwrap_or(&src.queue).to_string();
        let target_run_at = override_run_at.unwrap_or(now);

        let target_queue_clone = target_queue.clone();
        let new_job = Job {
            dataset_id: "default".to_string(),
            replay_of_job_id: Some(job_id),
            id: new_id,
            queue: target_queue,
            job_type: src.job_type,
            payload: src.payload,
            run_at: target_run_at,
            status: JobStatus::Queued.as_str().to_string(),
            priority: src.priority,
            max_attempts: src.max_attempts,
            locked_at: None,
            locked_by: None,
            lock_expires_at: None,
            dlq_reason_code: None,
            dlq_at: None,
            created_at: now,
            updated_at: now,
        };

        state.jobs.insert(new_id, new_job);
        drop(state);
        self.notify_queue(&target_queue_clone);
        Ok(new_id)
    }
}

#[async_trait]
impl StreamBackend for MemoryBackend {
    async fn publish(&self, stream: &str, event: NewEvent) -> anyhow::Result<i64> {
        let mut state = self.state.write().unwrap();
        let log = state.streams.entry(stream.to_string()).or_default();
        let sequence_no = (log.len() + 1) as i64;
        let now = Utc::now();

        let event_entity = Event {
            sequence_no,
            stream_name: stream.to_string(),
            event_type: event.event_type,
            payload_json: event.payload_json,
            created_at: now,
        };

        log.push(event_entity);
        drop(state);

        self.notify_stream(stream);
        Ok(sequence_no)
    }

    async fn subscribe_stream(
        &self,
        stream: &str,
        _consumer_group: &str,
        _last_seq: Option<i64>,
    ) -> anyhow::Result<NotificationStream> {
        let rx = {
            let mut notifiers = self.stream_notifiers.write().unwrap();
            let tx = notifiers
                .entry(stream.to_string())
                .or_insert_with(|| tokio::sync::broadcast::channel(128).0);
            tx.subscribe()
        };

        let stream = BroadcastStream::new(rx).filter_map(|res| res.ok());
        Ok(Box::pin(stream))
    }

    async fn ack(&self, stream: &str, consumer_group: &str, seq: i64) -> anyhow::Result<()> {
        let mut state = self.state.write().unwrap();
        let key = (stream.to_string(), consumer_group.to_string());
        let now = Utc::now();

        let entry = state
            .stream_offsets
            .entry(key)
            .or_insert_with(|| ConsumerGroupStatus {
                consumer_group: consumer_group.to_string(),
                stream_name: stream.to_string(),
                last_acked_seq: 0,
                updated_at: now,
            });

        if seq > entry.last_acked_seq {
            entry.last_acked_seq = seq;
            entry.updated_at = now;
        }

        Ok(())
    }

    async fn read_events(
        &self,
        stream: &str,
        after_seq: i64,
        limit: i64,
    ) -> anyhow::Result<Vec<Event>> {
        let state = self.state.read().unwrap();
        let limit = limit.clamp(1, 1000) as usize;

        if let Some(log) = state.streams.get(stream) {
            let events: Vec<Event> = log
                .iter()
                .filter(|e| e.sequence_no > after_seq)
                .take(limit)
                .cloned()
                .collect();
            Ok(events)
        } else {
            Ok(Vec::new())
        }
    }

    async fn consumer_group_info(&self, stream: &str) -> anyhow::Result<Vec<ConsumerGroupStatus>> {
        let state = self.state.read().unwrap();
        let info: Vec<ConsumerGroupStatus> = state
            .stream_offsets
            .values()
            .filter(|cg| cg.stream_name == stream)
            .cloned()
            .collect();
        Ok(info)
    }
}