1use std::collections::HashMap;
6
7use serde_json::{Map, Value};
8
9use crate::journal::{Journal, Record, apply_changes};
10use crate::tree::{detach, find, flatten, get_mut, group_list, id_of, place};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum Owner {
15 File,
16 Patch(usize),
18 Embedded(usize, &'static str),
20}
21
22#[derive(Debug, Clone, Default)]
24pub struct PatchIndex {
25 owners: HashMap<String, Owner>,
26 keys: HashMap<String, HashMap<String, usize>>,
27}
28
29impl PatchIndex {
30 pub fn entry(&self, id: Option<&str>) -> Owner {
31 id.and_then(|id| self.owners.get(id)).copied().unwrap_or(Owner::File)
32 }
33
34 pub fn key(&self, id: &str, key: &str) -> Owner {
35 match self.keys.get(id).and_then(|keys| keys.get(key)) {
36 Some(index) => Owner::Patch(*index),
37 None => self.entry(Some(id)),
38 }
39 }
40
41 pub fn file_owned(&self, id: &str, key: Option<&str>) -> bool {
42 match key {
43 None => self.entry(Some(id)) == Owner::File,
44 Some(key) => self.key(id, key) == Owner::File,
45 }
46 }
47}
48
49pub fn ensure_ids(entries: &mut [Value], used: &mut dyn FnMut(&str) -> bool) {
51 for entry in entries {
52 if id_of(entry).is_none()
53 && let Some(map) = entry.as_object_mut()
54 {
55 let id = random_id(used);
56 let rest = std::mem::take(map);
57 map.insert("id".into(), Value::String(id));
58 map.extend(rest);
59 }
60 if entry.get("group") == Some(&Value::Bool(true))
61 && let Some(Value::Array(list)) = entry.get_mut("config")
62 {
63 ensure_ids(list, used);
64 }
65 }
66}
67
68pub fn ensure_insert_ids(patches: &mut [Value], used: &mut dyn FnMut(&str) -> bool) {
70 for patch in patches {
71 if let Some(Value::Array(insert)) = patch.get_mut("insert") {
72 ensure_ids(insert, used);
73 }
74 }
75}
76
77pub(crate) fn random_id(used: &mut dyn FnMut(&str) -> bool) -> String {
78 use std::hash::{BuildHasher, RandomState};
79 loop {
80 let id = format!("{:08x}", RandomState::new().hash_one(0u8) as u32);
81 if !used(&id) {
82 return id;
83 }
84 }
85}
86
87pub struct Patched {
88 pub data: Vec<Value>,
89 pub index: PatchIndex,
90}
91
92pub fn apply_patches(data: &[Value], patches: &mut [Value], warn: &dyn Fn(String)) -> Patched {
97 let mut data = data.to_vec();
98 let mut index = PatchIndex::default();
99 let mut paths: HashMap<String, Vec<usize>> = HashMap::new();
101 mount(&data, &[], Owner::File, &mut index, &mut paths);
102
103 for (position, raw) in patches.iter_mut().enumerate() {
104 let Some(patch) = raw.as_object() else { continue };
105 let id = patch.get("id").and_then(Value::as_str);
106 let target = id.and_then(|id| paths.get(id).cloned());
107
108 if let Some(insert) = patch.get("insert") {
109 let insert = insert.as_array().cloned().unwrap_or_default();
110 let list_path = match (id, &target) {
111 (Some(id), None) => {
112 warn(format!("patch insert: entry {id} not found"));
113 continue;
114 }
115 (Some(id), Some(path)) => {
116 let group = get_mut(&mut data, path).expect("mounted");
117 if group.get("group") != Some(&Value::Bool(true)) {
118 warn(format!("patch insert: entry {id} is not a group"));
119 continue;
120 }
121 let config =
122 group.as_object_mut().expect("object").entry("config").or_insert(Value::Array(Vec::new()));
123 if !config.is_array() {
124 *config = Value::Array(Vec::new());
125 }
126 let list = config.as_array_mut().expect("array");
127 let start = list.len();
128 list.extend(insert.iter().cloned());
129 Some((path.clone(), start))
130 }
131 (None, _) => {
132 let start = data.len();
133 data.extend(insert.iter().cloned());
134 Some((Vec::new(), start))
135 }
136 };
137 if let Some((parent, start)) = list_path {
138 for (offset, options) in insert.iter().enumerate() {
139 let mut path = parent.clone();
140 path.push(start + offset);
141 mount(
142 std::slice::from_ref(options),
143 &path[..path.len() - 1],
144 Owner::Embedded(position, "insert"),
145 &mut index,
146 &mut paths,
147 );
148 remap(&mut paths, options, &path);
149 }
150 }
151 continue;
152 }
153
154 let Some(id) = id.map(String::from) else {
155 warn("patch: id is required for non-insert patches".into());
156 continue;
157 };
158 let Some(path) = target else {
159 warn(format!("patch: entry {id} not found"));
160 continue;
161 };
162 let options = get_mut(&mut data, &path).expect("mounted");
163 if let Some(name) = patch.get("name").and_then(Value::as_str)
164 && options.get("name").and_then(Value::as_str) != Some(name)
165 {
166 let actual = options.get("name").and_then(Value::as_str).unwrap_or_default().to_string();
167 warn(format!("patch: name mismatch for {id} (expected {actual}, got {name}), skipping"));
168 continue;
169 }
170 let replaces_config = patch.contains_key("config") && group_list(options).is_some();
171 if replaces_config {
173 for member in flatten(group_list(options).expect("checked")).keys() {
174 index.owners.remove(member);
175 index.keys.remove(member);
176 paths.remove(member);
177 }
178 if let Some(Value::Array(list)) = raw.get_mut("config") {
179 ensure_ids(list, &mut |id| paths.contains_key(id));
180 }
181 }
182 let patch = raw.as_object().expect("checked above");
183 let overridden = index.keys.entry(id).or_default();
184 let map = options.as_object_mut().expect("object");
185 for (key, value) in patch.iter().filter(|(key, _)| *key != "id" && *key != "name" && *key != "insert") {
186 map.insert(key.clone(), value.clone());
187 overridden.insert(key.clone(), position);
188 }
189 if patch.contains_key("config") && group_list(options).is_some() {
191 let members = group_list(options).expect("checked").clone();
192 let mut member_path = path.clone();
193 member_path.push(0);
194 for (offset, member) in members.iter().enumerate() {
195 *member_path.last_mut().expect("pushed") = offset;
196 mount(std::slice::from_ref(member), &path, Owner::Embedded(position, "config"), &mut index, &mut paths);
197 remap(&mut paths, member, &member_path);
198 }
199 }
200 }
201 Patched { data, index }
202}
203
204fn mount(
206 list: &[Value],
207 parent: &[usize],
208 owner: Owner,
209 index: &mut PatchIndex,
210 paths: &mut HashMap<String, Vec<usize>>,
211) {
212 for (position, options) in list.iter().enumerate() {
213 let mut path = parent.to_vec();
214 path.push(position);
215 if let Some(id) = id_of(options) {
216 index.owners.insert(id.to_string(), owner);
217 index.keys.remove(id);
219 paths.insert(id.to_string(), path.clone());
220 }
221 if let Some(members) = group_list(options) {
222 mount(members, &path, owner, index, paths);
223 }
224 }
225}
226
227fn remap(paths: &mut HashMap<String, Vec<usize>>, options: &Value, path: &[usize]) {
229 if let Some(id) = id_of(options) {
230 paths.insert(id.to_string(), path.to_vec());
231 }
232 if let Some(members) = group_list(options) {
233 for (position, member) in members.iter().enumerate() {
234 let mut member_path = path.to_vec();
235 member_path.push(position);
236 remap(paths, member, &member_path);
237 }
238 }
239}
240
241pub fn route_journal(journal: &Journal, data: &mut Vec<Value>, patches: &mut [Value], warn: &dyn Fn(String)) -> bool {
244 let mut index = apply_patches(data, patches, &|_| {}).index;
245 let mut patched = false;
246 for (id, record) in journal {
247 let owner = index.entry(Some(id));
248 let embedded = matches!(owner, Owner::Embedded(..));
249 let base = match owner {
250 Owner::Embedded(i, _) => patches[i].get("id").and_then(Value::as_str).map(String::from),
251 _ => None,
252 };
253 let Record::Upsert { parent, position, changes, .. } = record else {
254 detach(container(data, patches, owner), id);
255 patched |= embedded;
256 index = apply_patches(data, patches, &|_| {}).index;
257 continue;
258 };
259 let current = flatten(container(data, patches, owner)).shift_remove(id);
260 let Some(current) = current else {
261 let mut options = Value::Object(Map::from_iter([("id".to_string(), Value::String(id.clone()))]));
262 apply_changes(&mut options, changes, |_| true);
263 patched |= place_at(data, patches, &index, options, parent.clone().flatten(), *position, warn);
264 index = apply_patches(data, patches, &|_| {}).index;
265 continue;
266 };
267 let effective = current.parent.clone().or(base);
269 if let Some(target) = parent
270 && effective != *target
271 {
272 let mut options = detach(container(data, patches, owner), id).expect("found above");
274 patched |= embedded;
275 apply_changes(&mut options, changes, |_| true);
276 patched |= place_at(data, patches, &index, options, target.clone(), *position, warn);
277 index = apply_patches(data, patches, &|_| {}).index;
278 continue;
279 }
280 let mut patch_changes: HashMap<usize, Map<String, Value>> = HashMap::new();
281 let list = container(data, patches, owner);
282 let path = find(list, id).expect("found above");
283 let options = get_mut(list, &path).expect("found above");
284 apply_changes(options, changes, |key| match index.key(id, key) {
285 Owner::Patch(i) => {
286 let value = changes[key].clone().unwrap_or(Value::Null);
287 patch_changes.entry(i).or_default().insert(key.to_string(), value);
288 false
289 }
290 _ => true,
291 });
292 patched |= embedded;
293 for (i, changes) in patch_changes {
294 if let Some(patch) = patches[i].as_object_mut() {
295 for (key, value) in changes {
296 if value.is_null() {
297 patch.shift_remove(&key);
298 } else {
299 patch.insert(key, value);
300 }
301 }
302 }
303 patched = true;
304 }
305 }
306 patched
307}
308
309fn container<'a>(data: &'a mut Vec<Value>, patches: &'a mut [Value], owner: Owner) -> &'a mut Vec<Value> {
311 match owner {
312 Owner::Embedded(i, key) => {
313 let patch = patches[i].as_object_mut().expect("patches are objects");
314 let list = patch.entry(key).or_insert(Value::Array(Vec::new()));
315 if !list.is_array() {
316 *list = Value::Array(Vec::new());
317 }
318 list.as_array_mut().expect("array")
319 }
320 _ => data,
321 }
322}
323
324fn place_at(
327 data: &mut Vec<Value>,
328 patches: &mut [Value],
329 index: &PatchIndex,
330 options: Value,
331 parent: Option<String>,
332 position: usize,
333 warn: &dyn Fn(String),
334) -> bool {
335 if let Some(parent) = &parent {
336 match index.key(parent, "config") {
337 Owner::File => {}
338 Owner::Patch(i) => {
339 if let Some(Value::Array(list)) = patches[i].get_mut("config") {
340 list.insert(position.min(list.len()), options);
341 return true;
342 }
343 }
344 owner @ Owner::Embedded(..) => {
345 let list = container(data, patches, owner);
346 if place(list, options.clone(), Some(parent), position) {
347 return true;
348 }
349 }
350 }
351 }
352 if !place(data, options, parent.as_deref(), position) {
353 warn(format!("cannot place entry: group {} not found", parent.unwrap_or_default()));
354 }
355 false
356}
357
358#[cfg(test)]
359mod tests {
360 use serde_json::json;
361
362 use super::*;
363
364 #[test]
365 fn inserts_and_overrides() {
366 let data = vec![
367 json!({ "id": "a", "name": "foo" }),
368 json!({ "id": "g", "name": "group", "group": true, "config": [] }),
369 ];
370 let mut patches = vec![
371 json!({ "insert": [{ "id": "x", "name": "bar" }] }),
372 json!({ "id": "g", "insert": [{ "id": "y", "name": "baz" }] }),
373 json!({ "id": "a", "config": { "k": 1 } }),
374 json!({ "id": "y", "disabled": true }),
375 json!({ "id": "a", "name": "wrong", "config": 2 }),
376 ];
377 let warnings = std::sync::Mutex::new(Vec::new());
378 let Patched { data, index } = apply_patches(&data, &mut patches, &|w| warnings.lock().unwrap().push(w));
379 assert_eq!(
380 data,
381 vec![
382 json!({ "id": "a", "name": "foo", "config": { "k": 1 } }),
383 json!({ "id": "g", "name": "group", "group": true, "config": [{ "id": "y", "name": "baz", "disabled": true }] }),
384 json!({ "id": "x", "name": "bar" }),
385 ]
386 );
387 assert_eq!(warnings.lock().unwrap().len(), 1);
388 assert_eq!(index.entry(Some("a")), Owner::File);
389 assert_eq!(index.key("a", "config"), Owner::Patch(2));
390 assert_eq!(index.entry(Some("x")), Owner::Embedded(0, "insert"));
391 assert_eq!(index.key("y", "disabled"), Owner::Patch(3));
392 assert!(index.file_owned("a", Some("name")) && !index.file_owned("x", None));
393 }
394
395 #[test]
396 fn routes_changes_to_their_owners() {
397 let mut data = vec![json!({ "id": "a", "name": "foo" })];
398 let mut patches = vec![json!({ "insert": [{ "id": "x", "name": "bar" }] }), json!({ "id": "a", "config": 1 })];
399 let mut journal = Journal::new();
400 let change = |changes: Value| Record::Upsert {
401 created: false,
402 parent: None,
403 position: 0,
404 changes: changes.as_object().unwrap().iter().map(|(k, v)| (k.clone(), Some(v.clone()))).collect(),
405 };
406 journal.insert("a".into(), change(json!({ "config": 2, "disabled": true })));
407 journal.insert("x".into(), change(json!({ "config": 3 })));
408 assert!(route_journal(&journal, &mut data, &mut patches, &|_| {}));
409 assert_eq!(data, vec![json!({ "id": "a", "name": "foo", "disabled": true })]);
410 assert_eq!(
411 patches,
412 vec![json!({ "insert": [{ "id": "x", "name": "bar", "config": 3 }] }), json!({ "id": "a", "config": 2 })]
413 );
414 }
415}