1use rmpv::Value;
2
3use crate::{Connection, ConnectionOptions, JobOptions, Queue, Result};
4
5#[derive(Clone, Debug)]
6pub struct FlowJob {
7 pub name: String,
8 pub queue_name: String,
9 pub data: Value,
10 pub options: JobOptions,
11 pub children: Vec<FlowJob>,
12}
13
14#[derive(Clone, Debug)]
15pub struct ChainStep {
16 pub name: String,
17 pub queue_name: String,
18 pub data: Value,
19 pub options: JobOptions,
20}
21
22#[derive(Clone)]
23pub struct FlowNode {
24 pub job: crate::Job,
25 pub children: Vec<FlowNode>,
26}
27
28pub struct FlowProducer {
29 connection: Connection,
30}
31
32impl FlowProducer {
33 pub fn new(options: ConnectionOptions) -> Self {
34 Self {
35 connection: Connection::new(options),
36 }
37 }
38
39 pub fn add(&self, flow: FlowJob) -> Result<FlowNode> {
40 let mut created = Vec::new();
41 match self.add_node(flow, None, &mut created) {
42 Ok(node) => Ok(node),
43 Err(error) => {
44 self.rollback(&created);
45 Err(error)
46 }
47 }
48 }
49
50 pub fn add_chain(&self, steps: Vec<ChainStep>) -> Result<Vec<String>> {
51 let mut ids: Vec<String> = Vec::new();
52 for step in steps {
53 let mut options = step.options;
54 if let Some(previous) = ids.last() {
55 options.depends_on = vec![previous.clone()];
56 }
57 let data = if let Some(previous) = ids.last() {
58 with_fields(
59 step.data,
60 vec![("__flowParentId", Value::from(previous.clone()))],
61 )
62 } else {
63 step.data
64 };
65 match Queue::with_connection(step.queue_name, self.connection.clone())
66 .add(step.name, data, options)
67 {
68 Ok(job) => ids.push(job.id()),
69 Err(error) => {
70 self.rollback(&ids);
71 return Err(error);
72 }
73 }
74 }
75 Ok(ids)
76 }
77
78 pub fn close(&self) {
79 self.connection.close();
80 }
81
82 fn add_node(
83 &self,
84 node: FlowJob,
85 parent: Option<(String, String)>,
86 created: &mut Vec<String>,
87 ) -> Result<FlowNode> {
88 let mut children = Vec::new();
89 for child in node.children {
90 children.push(self.add_node(
91 child,
92 Some(("pending".into(), node.queue_name.clone())),
93 created,
94 )?);
95 }
96 let mut options = node.options;
97 let child_ids: Vec<String> = children.iter().map(|child| child.job.id()).collect();
98 options.children_ids = child_ids.clone();
99 options.depends_on = child_ids.clone();
100 if let Some((parent_id, _)) = &parent {
101 options.parent_id = Some(parent_id.clone());
102 }
103 let mut markers = Vec::new();
104 if let Some((parent_id, parent_queue)) = &parent {
105 markers.push(("__parentId", Value::from(parent_id.clone())));
106 markers.push(("__parentQueue", Value::from(parent_queue.clone())));
107 }
108 if !child_ids.is_empty() {
109 markers.push((
110 "__childrenIds",
111 Value::Array(child_ids.iter().cloned().map(Value::from).collect()),
112 ));
113 }
114 let queue = Queue::with_connection(node.queue_name, self.connection.clone());
115 let job = queue.add(node.name, with_fields(node.data, markers), options)?;
116 created.push(job.id());
117 for child in &children {
118 queue.unit(
119 "UpdateParent",
120 crate::wire::map([
121 ("childId", Value::from(child.job.id())),
122 ("parentId", Value::from(job.id())),
123 ]),
124 )?;
125 }
126 Ok(FlowNode { job, children })
127 }
128
129 fn rollback(&self, ids: &[String]) {
130 let queue = Queue::with_connection("", self.connection.clone());
131 for id in ids.iter().rev() {
132 let _ = queue.remove(id);
133 }
134 }
135}
136
137fn with_fields(data: Value, fields: Vec<(&str, Value)>) -> Value {
138 let mut entries = match data {
139 Value::Map(entries) => entries,
140 Value::Nil => Vec::new(),
141 other => vec![(Value::from("payload"), other)],
142 };
143 entries.extend(
144 fields
145 .into_iter()
146 .map(|(key, value)| (Value::from(key), value)),
147 );
148 Value::Map(entries)
149}