khive_request/
conflict.rs1use std::collections::{BTreeMap, BTreeSet, HashMap};
2use std::ops::Range;
3
4use khive_types::EdgeRelation;
5use serde_json::Value;
6
7use crate::types::{ArgValue, ParsedOp};
8
9#[cfg(test)]
10use crate::types::{DslError, ExecutionMode, ParsedRequest};
11
12pub fn write_key_conflict_ops(ops: &[ParsedOp]) -> Vec<Vec<usize>> {
18 participants_for_keys(
19 ops.len(),
20 key_claims(ops)
21 .into_values()
22 .filter(|claims| claims.len() > 1),
23 )
24}
25
26pub fn unit_write_key_conflict_ops(ops: &[ParsedOp], ranges: &[Range<usize>]) -> Vec<Vec<usize>> {
33 let mut unit_of = vec![0; ops.len()];
34 for (unit, range) in ranges.iter().enumerate() {
35 for leaf in range.clone() {
36 unit_of[leaf] = unit;
37 }
38 }
39 participants_for_keys(
40 ops.len(),
41 key_claims(ops).into_values().filter(|claims| {
42 claims
43 .iter()
44 .any(|&leaf| unit_of[leaf] != unit_of[claims[0]])
45 }),
46 )
47}
48
49fn key_claims(ops: &[ParsedOp]) -> HashMap<String, Vec<usize>> {
50 let mut claims: HashMap<String, Vec<usize>> = HashMap::new();
51 for (index, op) in ops.iter().enumerate() {
52 for key in write_keys_for_op_pub(op) {
53 claims.entry(key).or_default().push(index);
54 }
55 }
56 claims
57}
58
59fn participants_for_keys(count: usize, keys: impl Iterator<Item = Vec<usize>>) -> Vec<Vec<usize>> {
60 let mut participants = vec![BTreeSet::new(); count];
61 for claims in keys {
62 let claims: BTreeSet<_> = claims.into_iter().collect();
63 for &index in &claims {
64 participants[index].extend(claims.iter().copied());
65 }
66 }
67 participants
68 .into_iter()
69 .map(|indices| indices.into_iter().collect())
70 .collect()
71}
72
73#[derive(Debug, Clone, PartialEq, Eq)]
77pub struct UnitKeyConflict {
78 pub key: String,
79 pub leaf: usize,
80 pub other_unit: usize,
81 pub other_leaf: usize,
82}
83
84pub fn unit_write_key_conflicts(
95 ops: &[ParsedOp],
96 ranges: &[Range<usize>],
97) -> BTreeMap<usize, Vec<UnitKeyConflict>> {
98 let mut per_unit_keys: Vec<HashMap<String, usize>> = Vec::with_capacity(ranges.len());
103 for range in ranges {
104 let mut keys: HashMap<String, usize> = HashMap::new();
105 for leaf in range.clone() {
106 for key in write_keys_for_op_pub(&ops[leaf]) {
107 keys.entry(key).or_insert(leaf);
108 }
109 }
110 per_unit_keys.push(keys);
111 }
112
113 let mut first_claim: HashMap<String, (usize, usize)> = HashMap::new();
114 let mut conflicts: BTreeMap<usize, Vec<UnitKeyConflict>> = BTreeMap::new();
115 for (unit_index, keys) in per_unit_keys.iter().enumerate() {
116 for (key, &leaf) in keys {
117 match first_claim.get(key) {
118 Some(&(other_unit, other_leaf)) if other_unit != unit_index => {
119 conflicts
120 .entry(unit_index)
121 .or_default()
122 .push(UnitKeyConflict {
123 key: key.clone(),
124 leaf,
125 other_unit,
126 other_leaf,
127 });
128 conflicts
129 .entry(other_unit)
130 .or_default()
131 .push(UnitKeyConflict {
132 key: key.clone(),
133 leaf: other_leaf,
134 other_unit: unit_index,
135 other_leaf: leaf,
136 });
137 }
138 Some(_) => {}
139 None => {
140 first_claim.insert(key.clone(), (unit_index, leaf));
141 }
142 }
143 }
144 }
145 for entries in conflicts.values_mut() {
146 entries.sort_by_key(|c| (c.leaf, c.other_leaf));
147 entries.dedup();
148 }
149 conflicts
150}
151
152pub fn write_keys_for_op_pub(op: &ParsedOp) -> Vec<String> {
158 let mut keys = Vec::new();
159 match op.tool.as_str() {
160 "update" | "delete" => {
161 if let Some(ArgValue::Value(Value::String(s))) = op.args.get("id") {
162 keys.push(format!("entity:{s}"));
163 }
164 }
165 "merge" => {
166 let previews_without_writing = matches!(
172 op.args.get("dry_run"),
173 Some(ArgValue::Value(Value::Bool(true)))
174 );
175 if !previews_without_writing {
176 for name in &["into_id", "from_id"] {
177 if let Some(ArgValue::Value(Value::String(s))) = op.args.get(*name) {
178 keys.push(format!("entity:{s}"));
179 }
180 }
181 }
182 }
183 "link" => {
184 let link_arg = |canonical: &str, alias: &str| {
192 op.args.get(canonical).or_else(|| op.args.get(alias))
193 };
194 if let (
195 Some(ArgValue::Value(Value::String(s))),
196 Some(ArgValue::Value(Value::String(t))),
197 Some(ArgValue::Value(Value::String(r))),
198 ) = (
199 link_arg("source_id", "source"),
200 link_arg("target_id", "target"),
201 link_arg("relation", "kind"),
202 ) {
203 push_link_key(&mut keys, s, t, r);
204 }
205
206 if let Some(ArgValue::Value(Value::Array(links))) = op.args.get("links") {
208 for link in links {
209 let Some(obj) = link.as_object() else {
210 continue;
211 };
212 let (Some(s), Some(t), Some(r)) = (
213 obj.get("source_id").and_then(Value::as_str),
214 obj.get("target_id").and_then(Value::as_str),
215 obj.get("relation").and_then(Value::as_str),
216 ) else {
217 continue;
218 };
219 push_link_key(&mut keys, s, t, r);
220 }
221 }
222 }
223 _ => {}
224 }
225 keys
226}
227
228fn push_link_key(keys: &mut Vec<String>, source: &str, target: &str, relation: &str) {
230 let parsed = relation.parse::<EdgeRelation>().ok();
231 let relation_key = parsed.as_ref().map_or(relation, |r| r.as_str());
232 let (source_key, target_key) =
233 parsed.map_or((source, target), |r| r.canonical_endpoints(source, target));
234 keys.push(format!(
235 "edge-natural:{source_key}:{target_key}:{relation_key}"
236 ));
237}
238
239#[cfg(test)]
241pub(crate) fn check_write_key_conflicts(req: &ParsedRequest) -> Result<(), DslError> {
242 if req.mode == ExecutionMode::Chain {
243 return Ok(());
244 }
245 let mut seen: std::collections::HashMap<String, String> = std::collections::HashMap::new();
246 for op in &req.ops {
247 let keys = write_keys_for_op_pub(op);
248 for key in keys {
249 if let Some(first) = seen.get(&key) {
250 return Err(DslError::WriteKeyConflict {
251 conflict_ops: key_claims(&req.ops)[&key]
252 .iter()
253 .copied()
254 .collect::<BTreeSet<_>>()
255 .into_iter()
256 .collect(),
257 id: key,
258 first_op: first.clone(),
259 second_op: op.tool.clone(),
260 });
261 }
262 seen.insert(key, op.tool.clone());
263 }
264 }
265 Ok(())
266}
267
268#[cfg(test)]
269#[path = "conflict_tests.rs"]
270mod tests;