pgqrs 0.15.2

A high-performance PostgreSQL-backed job queue for Rust applications
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
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
//! Worker, producer, and consumer interfaces.

use crate::error::{Error, Result};
use crate::rate_limit::RateLimitStatus;
use crate::stats::WorkerStats;
use crate::store::{AnyStore, Store};
pub use crate::types::{
    QueueMessage, QueueRecord, RunRecord, StepRecord, WorkerRecord, WorkerStatus, WorkflowRecord,
};
use crate::validation::{PayloadValidator, ValidationConfig};
use async_trait::async_trait;
use chrono::{DateTime, Duration, Utc};
use serde_json::Value;

/// Common worker operations and lifecycle hooks.
#[async_trait]
pub trait Worker: Send + Sync {
    /// Get the worker record for this instance.
    fn worker_record(&self) -> &WorkerRecord;

    /// Get the worker id for this instance.
    fn worker_id(&self) -> i64 {
        self.worker_record().id
    }

    async fn status(&self) -> crate::error::Result<WorkerStatus>;
    async fn suspend(&self) -> crate::error::Result<()>;
    async fn resume(&self) -> crate::error::Result<()>;
    async fn shutdown(&self) -> crate::error::Result<()>;
    async fn heartbeat(&self) -> crate::error::Result<()>;
    async fn is_healthy(&self, max_age: Duration) -> crate::error::Result<bool>;
}

/// Administrative worker for queues, workers, and stats.
#[derive(Clone, Debug)]
pub struct Admin {
    pub(crate) store: AnyStore,
    pub(crate) worker_record: WorkerRecord,
}

/// Generic worker handle backed by a store and worker record.
#[derive(Clone, Debug)]
pub struct WorkerHandle {
    pub(crate) store: AnyStore,
    pub(crate) worker_record: WorkerRecord,
}

impl Admin {
    pub(crate) async fn new(store: AnyStore, name: &str) -> Result<Self> {
        let worker_record = store.workers().register(None, name).await?;
        Ok(Self {
            store,
            worker_record,
        })
    }

    pub(crate) async fn new_ephemeral(store: AnyStore) -> Result<Self> {
        let worker_record = store.workers().register_ephemeral(None).await?;
        Ok(Self {
            store,
            worker_record,
        })
    }

    pub async fn verify(&self) -> Result<()> {
        self.store.db_state().verify().await
    }

    pub async fn delete_queue(&self, queue_info: &QueueRecord) -> Result<()> {
        let total_workers = self.store.workers().count_by_fk(queue_info.id).await?;
        if total_workers > 0 {
            return Err(Error::ValidationFailed {
                reason: format!(
                    "Cannot delete queue '{}': {} worker(s) are still assigned to this queue. Delete workers first.",
                    queue_info.queue_name, total_workers
                ),
            });
        }

        let total_references = self.store.messages().count_by_fk(queue_info.id).await?;
        if total_references > 0 {
            return Err(Error::ValidationFailed {
                reason: format!(
                    "Cannot delete queue '{}': {} references exist in messages table. Purge data first.",
                    queue_info.queue_name, total_references
                ),
            });
        }

        self.store.queues().delete(queue_info.id).await?;
        Ok(())
    }

    pub async fn purge_queue(&self, name: &str) -> Result<()> {
        let queue = self.store.queues().get_by_name(name).await?;
        self.store.db_state().purge_queue(queue.id).await
    }

    pub async fn dlq(&self) -> Result<Vec<i64>> {
        self.store
            .messages()
            .move_to_dlq(self.store.config().max_read_ct)
            .await
    }

    pub async fn queue_metrics(&self, name: &str) -> Result<crate::QueueMetrics> {
        let queue = self.store.queues().get_by_name(name).await?;
        self.store.db_state().queue_metrics(queue.id).await
    }

    pub async fn all_queues_metrics(&self) -> Result<Vec<crate::QueueMetrics>> {
        self.store.db_state().all_queues_metrics().await
    }

    pub async fn system_stats(&self) -> Result<crate::SystemStats> {
        self.store.db_state().system_stats().await
    }

    pub async fn worker_health_stats(
        &self,
        heartbeat_timeout: chrono::Duration,
        group_by_queue: bool,
    ) -> Result<Vec<crate::WorkerHealthStats>> {
        self.store
            .db_state()
            .worker_health_stats(heartbeat_timeout, group_by_queue)
            .await
    }

    pub async fn worker_stats(&self, queue_name: &str) -> Result<WorkerStats> {
        let queue_id = self.store.queues().get_by_name(queue_name).await?.id;
        let workers = self.store.workers().filter_by_fk(queue_id).await?;

        let total_workers = workers.len() as u32;
        let ready_workers = workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Ready)
            .count() as u32;
        let polling_workers = workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Polling)
            .count() as u32;
        let interrupted_workers = workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Interrupted)
            .count() as u32;
        let suspended_workers = workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Suspended)
            .count() as u32;
        let stopped_workers = workers
            .iter()
            .filter(|w| w.status == WorkerStatus::Stopped)
            .count() as u32;

        let mut total_messages = 0u64;
        for worker in &workers {
            total_messages += self
                .store
                .messages()
                .count_by_consumer_worker(worker.id)
                .await? as u64;
        }

        let average_messages_per_worker = if total_workers > 0 {
            total_messages as f64 / total_workers as f64
        } else {
            0.0
        };

        let now = Utc::now();
        let oldest_worker_age = workers
            .iter()
            .map(|w| now.signed_duration_since(w.started_at))
            .max()
            .unwrap_or(chrono::Duration::zero());
        let newest_heartbeat_age = workers
            .iter()
            .map(|w| now.signed_duration_since(w.heartbeat_at))
            .min()
            .unwrap_or(chrono::Duration::zero());

        Ok(WorkerStats {
            total_workers,
            ready_workers,
            polling_workers,
            interrupted_workers,
            suspended_workers,
            stopped_workers,
            average_messages_per_worker,
            oldest_worker_age,
            newest_heartbeat_age,
        })
    }

    pub async fn delete_worker(&self, worker_id: i64) -> Result<u64> {
        let reference_count = self
            .store
            .messages()
            .count_worker_references(worker_id)
            .await?;
        if reference_count > 0 {
            return Err(Error::ValidationFailed {
                reason: format!(
                    "Worker has {} references (associated messages/archives)",
                    reference_count
                ),
            });
        }

        self.store.workers().delete(worker_id).await
    }

    pub async fn get_worker_messages(&self, worker_id: i64) -> Result<Vec<QueueMessage>> {
        let worker = self.store.workers().get(worker_id).await?;
        if worker.queue_id.is_none() {
            return Err(Error::ValidationFailed {
                reason: "Cannot get messages for admin worker".to_string(),
            });
        }

        self.store
            .messages()
            .list_by_consumer_worker(worker_id)
            .await
    }

    pub async fn reclaim_messages(
        &self,
        queue_id: i64,
        older_than: Option<chrono::Duration>,
    ) -> Result<u64> {
        let timeout = older_than.unwrap_or_else(|| {
            chrono::Duration::seconds(self.store.config().heartbeat_interval as i64)
        });
        let zombies = self
            .store
            .workers()
            .list_zombies_for_queue(queue_id, timeout)
            .await?;

        let mut total_released = 0;
        for zombie in zombies {
            total_released += self
                .store
                .messages()
                .release_by_consumer_worker(zombie.id)
                .await?;
            self.store.workers().mark_stopped(zombie.id).await?;
        }

        Ok(total_released)
    }

    pub async fn purge_old_workers(&self, older_than: chrono::Duration) -> Result<u64> {
        self.store.db_state().purge_old_workers(older_than).await
    }

    pub async fn release_worker_messages(&self, worker_id: i64) -> Result<u64> {
        self.store
            .messages()
            .release_by_consumer_worker(worker_id)
            .await
    }
}

impl WorkerHandle {
    pub(crate) fn new(store: AnyStore, worker_record: WorkerRecord) -> Self {
        Self {
            store,
            worker_record,
        }
    }
}

#[async_trait]
impl crate::store::Worker for Admin {
    fn worker_record(&self) -> &WorkerRecord {
        &self.worker_record
    }

    async fn status(&self) -> Result<WorkerStatus> {
        self.store.workers().get_status(self.worker_record.id).await
    }

    async fn suspend(&self) -> Result<()> {
        self.store.workers().suspend(self.worker_record.id).await
    }

    async fn resume(&self) -> Result<()> {
        self.store.workers().resume(self.worker_record.id).await
    }

    async fn shutdown(&self) -> Result<()> {
        self.store.workers().shutdown(self.worker_record.id).await
    }

    async fn heartbeat(&self) -> Result<()> {
        self.store.workers().heartbeat(self.worker_record.id).await
    }

    async fn is_healthy(&self, max_age: chrono::Duration) -> Result<bool> {
        self.store
            .workers()
            .is_healthy(self.worker_record.id, max_age)
            .await
    }
}

#[async_trait]
impl crate::store::Worker for WorkerHandle {
    fn worker_record(&self) -> &WorkerRecord {
        &self.worker_record
    }

    async fn status(&self) -> Result<WorkerStatus> {
        self.store.workers().get_status(self.worker_record.id).await
    }

    async fn suspend(&self) -> Result<()> {
        self.store.workers().suspend(self.worker_record.id).await
    }

    async fn resume(&self) -> Result<()> {
        self.store.workers().resume(self.worker_record.id).await
    }

    async fn shutdown(&self) -> Result<()> {
        self.store.workers().shutdown(self.worker_record.id).await
    }

    async fn heartbeat(&self) -> Result<()> {
        self.store.workers().heartbeat(self.worker_record.id).await
    }

    async fn is_healthy(&self, max_age: chrono::Duration) -> Result<bool> {
        self.store
            .workers()
            .is_healthy(self.worker_record.id, max_age)
            .await
    }
}

/// Producer for enqueueing messages to a queue.
#[derive(Clone, Debug)]
pub struct Producer {
    store: AnyStore,
    queue_info: QueueRecord,
    worker_record: WorkerRecord,
    validator: PayloadValidator,
    current_time: Option<DateTime<Utc>>,
}

impl Producer {
    /// Create a producer bound to a queue and worker record.
    pub fn new(
        store: AnyStore,
        queue_info: QueueRecord,
        worker_record: WorkerRecord,
        validation_config: ValidationConfig,
    ) -> Self {
        Self {
            store,
            queue_info,
            worker_record,
            validator: PayloadValidator::new(validation_config),
            current_time: None,
        }
    }

    /// Set the current time used for enqueue timestamps.
    pub fn with_time(mut self, time: DateTime<Utc>) -> Self {
        self.current_time = Some(time);
        self
    }

    /// Return the current time used for enqueue timestamps.
    pub fn current_time(&self) -> DateTime<Utc> {
        self.current_time.unwrap_or_else(Utc::now)
    }

    /// Return the worker id for this producer.
    pub fn worker_id(&self) -> i64 {
        self.worker_record.id
    }

    /// Return the worker record for this producer.
    pub fn worker_record(&self) -> &WorkerRecord {
        &self.worker_record
    }

    /// Fetch the current worker status.
    pub async fn status(&self) -> crate::error::Result<WorkerStatus> {
        self.store.workers().get_status(self.worker_record.id).await
    }

    /// Suspend this worker.
    pub async fn suspend(&self) -> crate::error::Result<()> {
        self.store.workers().suspend(self.worker_record.id).await?;
        Ok(())
    }

    /// Resume this worker.
    pub async fn resume(&self) -> crate::error::Result<()> {
        self.store.workers().resume(self.worker_record.id).await?;
        Ok(())
    }

    /// Shut down this worker.
    pub async fn shutdown(&self) -> crate::error::Result<()> {
        self.store.workers().shutdown(self.worker_record.id).await?;
        Ok(())
    }

    /// Record a heartbeat for this worker.
    pub async fn heartbeat(&self) -> crate::error::Result<()> {
        self.store
            .workers()
            .heartbeat(self.worker_record.id)
            .await?;
        Ok(())
    }

    /// Check if the worker heartbeat is within the given age.
    pub async fn is_healthy(&self, max_age: Duration) -> crate::error::Result<bool> {
        self.store
            .workers()
            .is_healthy(self.worker_record.id, max_age)
            .await
    }

    /// Fetch a message by id.
    pub async fn get_message_by_id(&self, msg_id: i64) -> crate::error::Result<QueueMessage> {
        self.store.messages().get(msg_id).await
    }

    /// Enqueue a message immediately.
    pub async fn enqueue(&self, payload: &Value) -> crate::error::Result<QueueMessage> {
        self.enqueue_delayed(payload, 0).await
    }

    /// Enqueue a message with a delay in seconds.
    pub async fn enqueue_delayed(
        &self,
        payload: &Value,
        delay_seconds: u32,
    ) -> crate::error::Result<QueueMessage> {
        self.validator.validate(payload)?;

        let now = self.current_time();
        let vt = now + chrono::Duration::seconds(i64::from(delay_seconds));

        let new_message = crate::types::NewQueueMessage {
            queue_id: self.queue_info.id,
            payload: payload.clone(),
            read_ct: 0,
            enqueued_at: now,
            vt,
            producer_worker_id: Some(self.worker_record.id),
            consumer_worker_id: None,
        };

        let msg = self.store.messages().insert(new_message).await?;
        Ok(msg)
    }

    /// Enqueue multiple messages immediately.
    pub async fn batch_enqueue(
        &self,
        payloads: &[Value],
    ) -> crate::error::Result<Vec<QueueMessage>> {
        self.batch_enqueue_delayed(payloads, 0).await
    }

    /// Enqueue multiple messages with a delay in seconds.
    pub async fn batch_enqueue_delayed(
        &self,
        payloads: &[Value],
        delay_seconds: u32,
    ) -> crate::error::Result<Vec<QueueMessage>> {
        self.batch_enqueue_at(payloads, self.current_time(), delay_seconds)
            .await
    }

    /// Enqueue a message using an explicit time reference.
    pub async fn enqueue_at(
        &self,
        payload: &Value,
        now: chrono::DateTime<chrono::Utc>,
        delay_seconds: u32,
    ) -> crate::error::Result<QueueMessage> {
        self.validator.validate(payload)?;

        let vt = now + chrono::Duration::seconds(i64::from(delay_seconds));

        let new_message = crate::types::NewQueueMessage {
            queue_id: self.queue_info.id,
            payload: payload.clone(),
            read_ct: 0,
            enqueued_at: now,
            vt,
            producer_worker_id: Some(self.worker_record.id),
            consumer_worker_id: None,
        };

        let msg = self.store.messages().insert(new_message).await?;
        Ok(msg)
    }

    /// Enqueue multiple messages using an explicit time reference.
    pub async fn batch_enqueue_at(
        &self,
        payloads: &[Value],
        now: chrono::DateTime<chrono::Utc>,
        delay_seconds: u32,
    ) -> crate::error::Result<Vec<QueueMessage>> {
        self.validator.validate_batch(payloads)?;

        let vt = now + chrono::Duration::seconds(i64::from(delay_seconds));

        let ids = self
            .store
            .messages()
            .batch_insert(
                self.queue_info.id,
                payloads,
                crate::types::BatchInsertParams {
                    read_ct: 0,
                    enqueued_at: now,
                    vt,
                    producer_worker_id: Some(self.worker_record.id),
                    consumer_worker_id: None,
                },
            )
            .await?;

        let msgs = self.store.messages().get_by_ids(&ids).await?;
        Ok(msgs)
    }

    /// Replay an archived DLQ message back into the queue.
    pub async fn replay_dlq(
        &self,
        archived_msg_id: i64,
    ) -> crate::error::Result<Option<QueueMessage>> {
        let out = self.store.messages().replay_dlq(archived_msg_id).await?;
        Ok(out)
    }

    /// Return the validation config for this producer.
    pub fn validation_config(&self) -> &ValidationConfig {
        self.validator.config()
    }

    /// Return the current rate limit status, if enabled.
    pub fn rate_limit_status(&self) -> Option<RateLimitStatus> {
        self.validator.rate_limit_status()
    }
}

/// Consumer for dequeueing and managing messages.
#[derive(Clone, Debug)]
pub struct Consumer {
    store: AnyStore,
    queue_info: QueueRecord,
    worker_record: WorkerRecord,
    current_time: Option<DateTime<Utc>>,
}

impl Consumer {
    /// Create a consumer bound to a queue and worker record.
    pub fn new(store: AnyStore, queue_info: QueueRecord, worker_record: WorkerRecord) -> Self {
        Self {
            store,
            queue_info,
            worker_record,
            current_time: None,
        }
    }

    /// Set the current time used for dequeue timestamps.
    pub fn with_time(mut self, time: DateTime<Utc>) -> Self {
        self.current_time = Some(time);
        self
    }

    /// Return the current time used for dequeue timestamps.
    pub fn current_time(&self) -> DateTime<Utc> {
        self.current_time.unwrap_or_else(Utc::now)
    }

    /// Return the worker id for this consumer.
    pub fn worker_id(&self) -> i64 {
        self.worker_record.id
    }

    pub(crate) fn store(&self) -> &AnyStore {
        &self.store
    }

    /// Return the worker record for this consumer.
    pub fn worker_record(&self) -> &WorkerRecord {
        &self.worker_record
    }

    /// Fetch the current worker status.
    pub async fn status(&self) -> crate::error::Result<WorkerStatus> {
        self.store.workers().get_status(self.worker_record.id).await
    }

    /// Suspend this worker.
    pub async fn suspend(&self) -> crate::error::Result<()> {
        self.store.workers().suspend(self.worker_record.id).await?;
        Ok(())
    }

    /// Mark this consumer as polling.
    pub async fn poll(&self) -> crate::error::Result<()> {
        self.store.workers().poll(self.worker_record.id).await?;
        Ok(())
    }

    /// Interrupt this consumer's poll loop.
    pub async fn interrupt(&self) -> crate::error::Result<()> {
        self.store
            .workers()
            .interrupt(self.worker_record.id)
            .await?;
        Ok(())
    }

    /// Resume this worker.
    pub async fn resume(&self) -> crate::error::Result<()> {
        self.store.workers().resume(self.worker_record.id).await?;
        Ok(())
    }

    /// Shut down this worker if no messages are pending.
    pub async fn shutdown(&self) -> crate::error::Result<()> {
        let pending = self
            .store
            .messages()
            .count_pending_for_queue_and_worker(self.queue_info.id, self.worker_record.id)
            .await?;

        if pending > 0 {
            return Err(crate::error::Error::WorkerHasPendingMessages {
                count: pending as u64,
                reason: format!("Consumer has {} pending messages", pending),
            });
        }
        self.store.workers().shutdown(self.worker_record.id).await?;
        Ok(())
    }

    /// Record a heartbeat for this worker.
    pub async fn heartbeat(&self) -> crate::error::Result<()> {
        self.store
            .workers()
            .heartbeat(self.worker_record.id)
            .await?;
        Ok(())
    }

    /// Check if the worker heartbeat is within the given age.
    pub async fn is_healthy(&self, max_age: Duration) -> crate::error::Result<bool> {
        self.store
            .workers()
            .is_healthy(self.worker_record.id, max_age)
            .await
    }

    /// Dequeue a single message.
    pub async fn dequeue(&self) -> crate::error::Result<Vec<QueueMessage>> {
        self.dequeue_many(1).await
    }

    /// Dequeue multiple messages.
    pub async fn dequeue_many(&self, limit: usize) -> crate::error::Result<Vec<QueueMessage>> {
        self.dequeue_many_with_delay(limit, 30).await
    }

    /// Dequeue a message with a custom visibility timeout.
    pub async fn dequeue_delay(&self, vt: u32) -> crate::error::Result<Vec<QueueMessage>> {
        self.dequeue_many_with_delay(1, vt).await
    }

    /// Dequeue multiple messages with a visibility timeout.
    pub async fn dequeue_many_with_delay(
        &self,
        limit: usize,
        vt: u32,
    ) -> crate::error::Result<Vec<QueueMessage>> {
        self.dequeue_at(limit, vt, self.current_time()).await
    }

    /// Dequeue messages using an explicit time reference.
    pub async fn dequeue_at(
        &self,
        limit: usize,
        vt: u32,
        now: chrono::DateTime<chrono::Utc>,
    ) -> crate::error::Result<Vec<QueueMessage>> {
        let msgs = self
            .store
            .messages()
            .dequeue_at(
                self.queue_info.id,
                limit,
                vt,
                self.worker_record.id,
                now,
                self.store.config().max_read_ct,
            )
            .await?;
        Ok(msgs)
    }

    /// Extend the visibility timeout for a message.
    pub async fn extend_vt(&self, message_id: i64, seconds: u32) -> crate::error::Result<bool> {
        let count = self
            .store
            .messages()
            .extend_visibility(message_id, self.worker_record.id, seconds)
            .await?;
        Ok(count > 0)
    }

    /// Delete a message owned by this consumer.
    pub async fn delete(&self, message_id: i64) -> crate::error::Result<bool> {
        let count = self
            .store
            .messages()
            .delete_owned(message_id, self.worker_record.id)
            .await?;
        Ok(count > 0)
    }

    /// Delete multiple messages owned by this consumer.
    pub async fn delete_many(&self, message_ids: Vec<i64>) -> crate::error::Result<Vec<bool>> {
        let out = self
            .store
            .messages()
            .delete_many_owned(&message_ids, self.worker_record.id)
            .await?;
        Ok(out)
    }

    /// Archive a message owned by this consumer.
    pub async fn archive(&self, msg_id: i64) -> crate::error::Result<Option<QueueMessage>> {
        let out = self
            .store
            .messages()
            .archive(msg_id, self.worker_record.id)
            .await?;
        Ok(out)
    }

    /// Archive multiple messages owned by this consumer.
    pub async fn archive_many(&self, msg_ids: Vec<i64>) -> crate::error::Result<Vec<bool>> {
        let out = self
            .store
            .messages()
            .archive_many(&msg_ids, self.worker_record.id)
            .await?;
        Ok(out)
    }

    /// Release messages back to the queue.
    pub async fn release_messages(&self, message_ids: &[i64]) -> crate::error::Result<u64> {
        let res = self
            .store
            .messages()
            .release_messages_by_ids(message_ids, self.worker_record.id)
            .await?;
        Ok(res.iter().filter(|&&x| x).count() as u64)
    }

    /// Release a message with a custom visibility time.
    pub async fn release_with_visibility(
        &self,
        message_id: i64,
        visible_at: chrono::DateTime<chrono::Utc>,
    ) -> crate::error::Result<bool> {
        let count = self
            .store
            .messages()
            .release_with_visibility(message_id, self.worker_record.id, visible_at)
            .await?;
        Ok(count > 0)
    }
}

/// Workflow execution run handle.
///
/// Use this to acquire steps and complete or pause a workflow run.
#[derive(Clone, Debug)]
pub struct Run {
    store: AnyStore,
    record: RunRecord,
    current_time: Option<DateTime<Utc>>,
}

impl Run {
    /// Create a run handle from a run record.
    pub fn new(store: AnyStore, record: RunRecord) -> Self {
        Self {
            store,
            record,
            current_time: None,
        }
    }

    /// Set the current time used for step acquisition.
    pub fn with_time(mut self, time: DateTime<Utc>) -> Self {
        self.current_time = Some(time);
        self
    }

    /// Return the current time override, if any.
    pub fn current_time(&self) -> Option<DateTime<Utc>> {
        self.current_time
    }

    /// Return the run id.
    pub fn id(&self) -> i64 {
        self.record.id
    }

    /// Return the run record.
    pub fn record(&self) -> &RunRecord {
        &self.record
    }

    fn with_record(&self, record: RunRecord) -> Self {
        Self {
            store: self.store.clone(),
            record,
            current_time: self.current_time,
        }
    }

    /// Refresh the run record from storage.
    pub async fn refresh(&self) -> crate::error::Result<Run> {
        let record = self.store.workflow_runs().get(self.record.id).await?;
        Ok(self.with_record(record))
    }

    /// Mark the run as started.
    pub async fn start(&self) -> crate::error::Result<Run> {
        let record = self.store.workflow_runs().start_run(self.record.id).await?;
        Ok(self.with_record(record))
    }

    /// Complete the run with output.
    pub async fn complete(&self, output: serde_json::Value) -> crate::error::Result<Run> {
        let record = self
            .store
            .workflow_runs()
            .complete_run(self.record.id, output)
            .await?;
        Ok(self.with_record(record))
    }

    /// Pause the run until a resume time.
    pub async fn pause(
        &self,
        message: String,
        resume_after: std::time::Duration,
    ) -> crate::error::Result<Run> {
        let record = self
            .store
            .workflow_runs()
            .pause_run(self.record.id, message, resume_after)
            .await?;
        Ok(self.with_record(record))
    }

    /// Fail the run with a structured error payload.
    pub async fn fail_with_json(&self, error: serde_json::Value) -> crate::error::Result<Run> {
        let record = self
            .store
            .workflow_runs()
            .fail_run(self.record.id, error)
            .await?;
        Ok(self.with_record(record))
    }

    /// Complete the run with a serializable payload.
    pub async fn success<T: serde::Serialize + Send + Sync>(
        &self,
        output: &T,
    ) -> crate::error::Result<Run> {
        let value = serde_json::to_value(output).map_err(crate::error::Error::Serialization)?;
        self.complete(value).await
    }

    /// Fail the run with a serializable payload.
    pub async fn fail<T: serde::Serialize + Send + Sync>(
        &self,
        error: &T,
    ) -> crate::error::Result<Run> {
        let value = serde_json::to_value(error).map_err(crate::error::Error::Serialization)?;
        self.fail_with_json(value).await
    }

    /// Acquire a step for execution or replay.
    pub async fn acquire_step(
        &self,
        step_name: &str,
        current_time: chrono::DateTime<chrono::Utc>,
    ) -> crate::error::Result<Step> {
        let step_name_string = step_name.to_string();
        let row = self
            .store
            .workflow_steps()
            .acquire_step(self.record.id, &step_name_string)
            .await
            .map_err(|e| crate::error::Error::QueryFailed {
                query: "SQL_ACQUIRE_STEP".into(),
                source: Box::new(e),
                context: format!(
                    "Failed to acquire step {} for run {}",
                    step_name_string, self.record.id
                ),
            })?;

        let mut status = row.status;
        let retry_count = row.retry_count;
        let retry_at = row.retry_at;

        if status == crate::types::WorkflowStatus::Error {
            if let Some(retry_at) = retry_at {
                if current_time < retry_at {
                    return Err(crate::error::Error::StepNotReady {
                        retry_at,
                        retry_count: retry_count as u32,
                    });
                }

                self.store
                    .workflow_steps()
                    .clear_retry(row.id)
                    .await
                    .map(|_| ())
                    .map_err(|e| crate::error::Error::QueryFailed {
                        query: "SQL_CLEAR_RETRY".into(),
                        source: Box::new(e),
                        context: format!("Failed to clear retry_at for step {}", row.id),
                    })?;

                status = crate::types::WorkflowStatus::Running;
            } else {
                let error_val = row.error.unwrap_or_else(|| {
                    serde_json::json!({
                        "is_transient": false,
                        "message": "Unknown error"
                    })
                });

                return Err(crate::error::Error::RetriesExhausted {
                    error: error_val,
                    attempts: retry_count as u32,
                });
            }
        }

        let record = StepRecord { status, ..row };
        Ok(Step::new(self.store.clone(), record))
    }

    /// Complete a step by name.
    pub async fn complete_step(
        &self,
        step_name: &str,
        output: serde_json::Value,
    ) -> crate::error::Result<()> {
        let current_time = self.current_time().unwrap_or_else(chrono::Utc::now);
        let mut step = self.acquire_step(step_name, current_time).await?;
        step.complete(output).await
    }

    /// Fail a step by name with a structured error payload.
    pub async fn fail_step(
        &self,
        step_name: &str,
        error: serde_json::Value,
        current_time: chrono::DateTime<chrono::Utc>,
    ) -> crate::error::Result<()> {
        let mut step = self.acquire_step(step_name, current_time).await?;
        step.fail_with_json(error, current_time).await
    }
}

/// Workflow step execution handle.
#[derive(Clone, Debug)]
pub struct Step {
    store: AnyStore,
    record: StepRecord,
    current_time: Option<DateTime<Utc>>,
}

impl Step {
    /// Create a step handle from a step record.
    pub fn new(store: AnyStore, record: StepRecord) -> Self {
        Self {
            store,
            record,
            current_time: None,
        }
    }

    /// Set the current time used for retry calculations.
    pub fn with_time(mut self, time: DateTime<Utc>) -> Self {
        self.current_time = Some(time);
        self
    }

    /// Return the step id.
    pub fn id(&self) -> i64 {
        self.record.id
    }

    /// Return the step record.
    pub fn record(&self) -> &StepRecord {
        &self.record
    }

    /// Return the step status.
    pub fn status(&self) -> crate::types::WorkflowStatus {
        self.record.status
    }

    /// Return the step output, if available.
    pub fn output(&self) -> Option<&serde_json::Value> {
        self.record.output.as_ref()
    }

    /// Complete the step with an output payload.
    pub async fn complete(&mut self, output: serde_json::Value) -> crate::error::Result<()> {
        self.store
            .workflow_steps()
            .complete_step(self.record.id, output)
            .await
            .map(|_| ())
    }

    /// Fail the step with a structured error payload.
    pub async fn fail_with_json(
        &mut self,
        error: serde_json::Value,
        current_time: DateTime<Utc>,
    ) -> crate::error::Result<()> {
        let error_record = if error.get("is_transient").is_some() {
            error
        } else {
            serde_json::json!({
                "is_transient": false,
                "code": "NON_RETRYABLE",
                "message": error.to_string(),
            })
        };

        let is_transient = error_record
            .get("is_transient")
            .and_then(|v| v.as_bool())
            .unwrap_or(false);

        if is_transient {
            let policy = crate::StepRetryPolicy::default();
            if !policy.should_retry(self.record.retry_count as u32) {
                return self
                    .store
                    .workflow_steps()
                    .fail_step(self.record.id, error_record, None, self.record.retry_count)
                    .await
                    .map(|_| ());
            }

            let delay_seconds =
                policy.extract_retry_delay(&error_record, self.record.retry_count.max(0) as u32);
            let delay_i64: i64 = delay_seconds.into();

            let retry_at = current_time + chrono::Duration::seconds(delay_i64);
            let new_retry_count = self.record.retry_count + 1;

            return self
                .store
                .workflow_steps()
                .fail_step(
                    self.record.id,
                    error_record,
                    Some(retry_at),
                    new_retry_count,
                )
                .await
                .map(|_| ());
        }

        self.store
            .workflow_steps()
            .fail_step(self.record.id, error_record, None, self.record.retry_count)
            .await
            .map(|_| ())
    }

    /// Complete the step with a serializable payload.
    pub async fn success<T: serde::Serialize + Send + Sync>(
        &mut self,
        output: &T,
    ) -> crate::error::Result<()> {
        let value = serde_json::to_value(output).map_err(crate::error::Error::Serialization)?;
        self.complete(value).await
    }

    /// Fail the step with a serializable payload.
    pub async fn fail<T: serde::Serialize + Send + Sync>(
        &mut self,
        error: &T,
    ) -> crate::error::Result<()> {
        let value = serde_json::to_value(error).map_err(crate::error::Error::Serialization)?;
        self.fail_with_json(value, chrono::Utc::now()).await
    }
}