Skip to main content

bunqueue_client/
queue_admin.rs

1use rmpv::Value;
2
3use crate::queue::job_payload;
4use crate::wire::{Map, as_map, command, get, map};
5use crate::{JobOptions, Queue, Result};
6
7#[derive(Clone, Debug, Default)]
8pub struct SchedulerRepeat {
9    pub pattern: Option<String>,
10    pub every_ms: Option<i64>,
11    pub limit: Option<i64>,
12    pub timezone: Option<String>,
13    pub immediately: bool,
14    pub skip_if_no_worker: bool,
15}
16
17#[derive(Clone, Debug)]
18pub struct SchedulerTemplate {
19    pub name: Option<String>,
20    pub data: Value,
21    pub options: JobOptions,
22}
23
24impl Default for SchedulerTemplate {
25    fn default() -> Self {
26        Self {
27            name: None,
28            data: Value::Nil,
29            options: JobOptions::default(),
30        }
31    }
32}
33
34impl Queue {
35    pub fn get_dlq(&self, count: Option<i64>) -> Result<Vec<Map>> {
36        let response = self.call(command(
37            "Dlq",
38            map([
39                ("queue", Value::from(self.name.clone())),
40                ("count", count.map(Value::from).unwrap_or(Value::Nil)),
41            ]),
42        ))?;
43        Ok(get(&response, "jobs")
44            .and_then(Value::as_array)
45            .map(|items| {
46                items
47                    .iter()
48                    .filter_map(|item| as_map(item.clone()).ok())
49                    .collect()
50            })
51            .unwrap_or_default())
52    }
53
54    pub fn retry_dlq(&self, job_id: Option<&str>, count: Option<i64>) -> Result<i64> {
55        let response = self.call(command(
56            "RetryDlq",
57            map([
58                ("queue", Value::from(self.name.clone())),
59                ("jobId", job_id.map(Value::from).unwrap_or(Value::Nil)),
60                ("count", count.map(Value::from).unwrap_or(Value::Nil)),
61            ]),
62        ))?;
63        Ok(get(&response, "count").and_then(Value::as_i64).unwrap_or(0))
64    }
65
66    pub fn purge_dlq(&self) -> Result<i64> {
67        let response = self.call(command(
68            "PurgeDlq",
69            map([("queue", Value::from(self.name.clone()))]),
70        ))?;
71        Ok(get(&response, "count").and_then(Value::as_i64).unwrap_or(0))
72    }
73
74    pub fn upsert_job_scheduler(
75        &self,
76        id: &str,
77        repeat: SchedulerRepeat,
78        template: SchedulerTemplate,
79    ) -> Result<()> {
80        let name = template.name.as_deref().unwrap_or(id);
81        let mut fields = map([
82            ("name", Value::from(id)),
83            ("queue", Value::from(self.name.clone())),
84            ("data", job_payload(name, template.data)),
85            (
86                "schedule",
87                repeat.pattern.map(Value::from).unwrap_or(Value::Nil),
88            ),
89            (
90                "repeatEvery",
91                repeat.every_ms.map(Value::from).unwrap_or(Value::Nil),
92            ),
93            (
94                "maxLimit",
95                repeat.limit.map(Value::from).unwrap_or(Value::Nil),
96            ),
97            (
98                "timezone",
99                repeat.timezone.map(Value::from).unwrap_or(Value::Nil),
100            ),
101            ("immediately", Value::from(repeat.immediately)),
102            ("skipIfNoWorker", Value::from(repeat.skip_if_no_worker)),
103        ]);
104        let cron_options = template.options.cron_options();
105        if cron_options.as_map().is_some_and(|map| !map.is_empty()) {
106            fields.push((Value::from("jobOptions"), cron_options));
107        }
108        self.unit("Cron", fields)
109    }
110
111    pub fn get_job_scheduler(&self, id: &str) -> Result<Option<Map>> {
112        match self.call(command("CronGet", map([("name", Value::from(id))]))) {
113            Ok(response) => match get(&response, "cron") {
114                None | Some(Value::Nil) => Ok(None),
115                Some(value) => Ok(Some(as_map(value.clone())?)),
116            },
117            Err(error) if error.is_not_found() => Ok(None),
118            Err(error) => Err(error),
119        }
120    }
121
122    pub fn remove_job_scheduler(&self, id: &str) -> Result<()> {
123        self.unit("CronDelete", map([("name", Value::from(id))]))
124    }
125
126    pub fn set_rate_limit(
127        &self,
128        limit: i64,
129        duration_ms: Option<i64>,
130        ttl_ms: Option<i64>,
131    ) -> Result<()> {
132        self.unit(
133            "RateLimit",
134            map([
135                ("queue", Value::from(self.name.clone())),
136                ("limit", Value::from(limit)),
137                (
138                    "duration",
139                    duration_ms.map(Value::from).unwrap_or(Value::Nil),
140                ),
141                ("ttl", ttl_ms.map(Value::from).unwrap_or(Value::Nil)),
142            ]),
143        )
144    }
145
146    pub fn clear_rate_limit(&self) -> Result<()> {
147        self.unit(
148            "RateLimitClear",
149            map([("queue", Value::from(self.name.clone()))]),
150        )
151    }
152
153    pub fn ping(&self) -> Result<bool> {
154        self.connection.ping()
155    }
156}