Skip to main content

bunqueue_client/
queue_query.rs

1use std::collections::BTreeMap;
2use std::time::Duration;
3
4use rmpv::Value;
5
6use crate::wire::{Map, as_map, command, get, map};
7use crate::{Error, Job, Queue, Result};
8
9impl Queue {
10    pub fn get_job(&self, id: &str) -> Result<Option<Job>> {
11        match self.call(command("GetJob", map([("id", Value::from(id))]))) {
12            Ok(response) => job_from(&response, "job", self),
13            Err(error) if error.is_not_found() => Ok(None),
14            Err(error) => Err(error),
15        }
16    }
17
18    pub fn get_job_by_custom_id(&self, custom_id: &str) -> Result<Option<Job>> {
19        match self.call(command(
20            "GetJobByCustomId",
21            map([
22                ("queue", Value::from(self.name.clone())),
23                ("customId", Value::from(custom_id)),
24            ]),
25        )) {
26            Ok(response) => job_from(&response, "job", self),
27            Err(error) if error.is_not_found() => Ok(None),
28            Err(error) => Err(error),
29        }
30    }
31
32    pub fn get_jobs(&self, state: Value, offset: i64, limit: i64) -> Result<Vec<Job>> {
33        let response = self.call(command(
34            "GetJobs",
35            map([
36                ("queue", Value::from(self.name.clone())),
37                ("state", state),
38                ("offset", Value::from(offset.max(0))),
39                ("limit", Value::from(limit.max(0))),
40            ]),
41        ))?;
42        Ok(get(&response, "jobs")
43            .and_then(Value::as_array)
44            .map(|jobs| {
45                jobs.iter()
46                    .filter_map(|raw| as_map(raw.clone()).ok())
47                    .map(|raw| Job::new(raw, self.connection.clone(), None))
48                    .collect()
49            })
50            .unwrap_or_default())
51    }
52
53    pub fn get_state(&self, id: &str) -> Result<String> {
54        let response = self.call(command("GetState", map([("id", Value::from(id))])))?;
55        Ok(get(&response, "state")
56            .and_then(Value::as_str)
57            .unwrap_or_default()
58            .to_owned())
59    }
60
61    pub fn get_result(&self, id: &str) -> Result<Value> {
62        let response = self.call(command("GetResult", map([("id", Value::from(id))])))?;
63        Ok(get(&response, "result").cloned().unwrap_or(Value::Nil))
64    }
65
66    pub fn wait_for_job(&self, id: &str, timeout_ms: i64) -> Result<Value> {
67        let timeout_ms = timeout_ms.clamp(0, 600_000);
68        let response = self.connection.call_timeout(
69            command(
70                "WaitJob",
71                map([
72                    ("id", Value::from(id)),
73                    ("timeout", Value::from(timeout_ms)),
74                ]),
75            ),
76            Duration::from_millis(timeout_ms as u64) + Duration::from_secs(5),
77        )?;
78        if get(&response, "completed").and_then(Value::as_bool) == Some(true) {
79            return Ok(get(&response, "result").cloned().unwrap_or(Value::Nil));
80        }
81        match self.get_state(id) {
82            Ok(state) if state == "failed" => {
83                return Err(Error::Command(format!("job {id} failed")));
84            }
85            Ok(_) => {}
86            Err(error) => return Err(error),
87        }
88        Err(Error::Timeout(format!(
89            "wait_for_job timed out after {timeout_ms}ms"
90        )))
91    }
92
93    pub fn get_job_counts(&self) -> Result<BTreeMap<String, i64>> {
94        let response = self.call(command(
95            "GetJobCounts",
96            map([("queue", Value::from(self.name.clone()))]),
97        ))?;
98        let mut counts = BTreeMap::new();
99        if let Some(entries) = get(&response, "counts").and_then(Value::as_map) {
100            for (key, value) in entries {
101                if let (Some(key), Some(value)) = (key.as_str(), value.as_i64()) {
102                    counts.insert(key.to_owned(), value);
103                }
104            }
105        }
106        Ok(counts)
107    }
108
109    pub fn count(&self) -> Result<i64> {
110        let response = self.call(command(
111            "Count",
112            map([("queue", Value::from(self.name.clone()))]),
113        ))?;
114        Ok(get(&response, "count").and_then(Value::as_i64).unwrap_or(0))
115    }
116
117    pub fn get_job_logs(&self, id: &str) -> Result<Vec<String>> {
118        let response = self.call(command("GetLogs", map([("id", Value::from(id))])))?;
119        Ok(get(&response, "data")
120            .and_then(Value::as_map)
121            .and_then(|data| {
122                data.iter()
123                    .find(|(key, _)| key.as_str() == Some("logs"))
124                    .map(|(_, logs)| crate::wire::strings(logs))
125            })
126            .unwrap_or_default())
127    }
128}
129
130fn job_from(response: &Map, key: &str, queue: &Queue) -> Result<Option<Job>> {
131    match get(response, key) {
132        None | Some(Value::Nil) => Ok(None),
133        Some(raw) => Ok(Some(Job::new(
134            as_map(raw.clone())?,
135            queue.connection.clone(),
136            None,
137        ))),
138    }
139}