1use rmpv::Value;
2
3use crate::wire::{Map, command, get, id_string, map, strings};
4use crate::{Connection, Result};
5
6#[derive(Clone)]
7pub struct Job {
8 raw: Map,
9 token: Option<String>,
10 connection: Connection,
11}
12
13impl Job {
14 pub(crate) fn new(raw: Map, connection: Connection, token: Option<String>) -> Self {
15 Self {
16 raw,
17 token,
18 connection,
19 }
20 }
21
22 pub fn id(&self) -> String {
23 get(&self.raw, "id").and_then(id_string).unwrap_or_default()
24 }
25
26 pub fn name(&self) -> String {
27 get(&self.raw, "data")
28 .and_then(Value::as_map)
29 .and_then(|data| {
30 data.iter()
31 .find(|(key, _)| key.as_str() == Some("name"))
32 .and_then(|(_, value)| value.as_str())
33 })
34 .unwrap_or_default()
35 .to_owned()
36 }
37
38 pub fn data(&self) -> Value {
40 match get(&self.raw, "data") {
41 Some(Value::Map(entries)) => Value::Map(
42 entries
43 .iter()
44 .filter(|(key, _)| key.as_str() != Some("name"))
45 .cloned()
46 .collect(),
47 ),
48 Some(value) => value.clone(),
49 None => Value::Nil,
50 }
51 }
52
53 pub fn raw(&self) -> &Map {
54 &self.raw
55 }
56
57 pub fn state(&self) -> Option<&str> {
58 get(&self.raw, "state").and_then(Value::as_str)
59 }
60
61 pub fn attempts_made(&self) -> i64 {
62 get(&self.raw, "attempts")
63 .and_then(Value::as_i64)
64 .unwrap_or(0)
65 }
66
67 pub fn stacktrace(&self) -> Vec<String> {
68 get(&self.raw, "stacktrace")
69 .map(strings)
70 .unwrap_or_default()
71 }
72
73 pub fn update_progress(&self, progress: f64, message: Option<&str>) -> Result<()> {
74 self.connection.call(command(
75 "Progress",
76 map([
77 ("id", Value::from(self.id())),
78 ("progress", Value::from(progress)),
79 ("message", message.map(Value::from).unwrap_or(Value::Nil)),
80 ]),
81 ))?;
82 Ok(())
83 }
84
85 pub fn log(&self, message: &str, level: Option<&str>) -> Result<()> {
86 self.connection.call(command(
87 "AddLog",
88 map([
89 ("id", Value::from(self.id())),
90 ("message", Value::from(message)),
91 ("level", level.map(Value::from).unwrap_or(Value::Nil)),
92 ]),
93 ))?;
94 Ok(())
95 }
96
97 pub fn extend_lock(&self, duration_ms: i64) -> Result<()> {
98 self.connection.call(command(
99 "ExtendLock",
100 map([
101 ("id", Value::from(self.id())),
102 (
103 "token",
104 self.token.clone().map(Value::from).unwrap_or(Value::Nil),
105 ),
106 ("duration", Value::from(duration_ms)),
107 ]),
108 ))?;
109 Ok(())
110 }
111}