1use std::collections::{BTreeMap, BTreeSet};
11use std::fs;
12use std::io;
13use std::path::Path;
14use std::time::SystemTime;
15
16use nibkeep_base::{EntityId, SpaceId, StatementId};
17use nibkeep_log::ChangeId;
18use nibkeep_model::storage::Statements as _;
19use nibkeep_model::{Operation, Value};
20use nibkeep_std::{CONTENT, LINK_TARGET, SECRET_CONTENT};
21
22use super::compare::{same_content, still_competes};
23use super::history::READ_LIMIT;
24use super::index::{Conflict, Entry, Index, Version};
25use super::locate::{Located, located};
26use super::secrecy::{NIBSECRET, lines};
27use super::walk::{Found, FoundKind, look, nanos, open_found};
28use super::write::{Content, Place, copy_version, same_version, undo_moves_at};
29use super::{CutShort, TreeState, settle_tree, version_of};
30use crate::NodeError;
31use crate::library::Library;
32use crate::library::checkouts::sync_folder_of;
33
34#[derive(Clone, Debug, Default, PartialEq, Eq)]
36pub struct Updated {
37 pub written: Vec<String>,
39 pub moved: Vec<(String, String)>,
41 pub deleted: Vec<String>,
43 pub merged: Vec<String>,
46 pub conflicts: Vec<String>,
49 pub kept: Vec<(String, String)>,
52 pub contested: Vec<String>,
56 pub skipped: Vec<(String, String)>,
58 pub waiting: Vec<CutShort>,
61 pub held: Vec<String>,
68 pub sealed: Vec<String>,
71}
72
73#[derive(Clone)]
75struct Arriving {
76 path: String,
77 entity: EntityId,
78 base: Option<Version>,
80 version: Version,
82 competing: Vec<Version>,
84 written: BTreeSet<String>,
87 deletions: Vec<String>,
90 secret: bool,
92}
93
94impl Arriving {
95 fn nothing_new(&self) -> bool {
98 let versions = if self.competing.is_empty() {
99 self.base.as_ref() == Some(&self.version)
100 } else {
101 self.competing
102 .iter()
103 .all(|version| self.written.contains(&version.key()))
104 };
105 versions && self.deletions.iter().all(|key| self.written.contains(key))
106 }
107
108 fn competes(&self) -> bool {
110 !self.competing.is_empty() || !self.deletions.is_empty()
111 }
112
113 fn wrote_out(&self, updated: &mut Updated, changes: &mut Changes) {
117 if !self.competes() {
118 return;
119 }
120 let mut keys: BTreeSet<String> = self.competing.iter().map(Version::key).collect();
121 keys.insert(self.version.key());
122 keys.extend(self.deletions.iter().cloned());
123 changes.written_out.push((self.entity, keys));
124 if !self.deletions.is_empty() {
125 updated.contested.push(self.path.clone());
126 }
127 }
128}
129
130struct Here<'a> {
132 space: SpaceId,
133 tree: EntityId,
134 place: Place<'a>,
135 index: &'a Index,
136 whole: bool,
139 conflicts: BTreeMap<String, Conflict>,
141 read_at: i64,
142}
143
144#[derive(Default)]
146struct Changes {
147 set: Vec<(String, Entry)>,
148 removed: Vec<String>,
149 written_out: Vec<(EntityId, BTreeSet<String>)>,
151 unknown: bool,
153}
154
155impl Library {
156 pub fn update_tree(
169 &self,
170 space: SpaceId,
171 tree: EntityId,
172 partial: bool,
173 ) -> Result<Updated, NodeError> {
174 self.update_tree_with(space, tree, (partial, false), None)
175 }
176
177 pub fn update_tree_agreeing(
185 &self,
186 space: SpaceId,
187 tree: EntityId,
188 partial: bool,
189 ) -> Result<Updated, NodeError> {
190 self.update_tree_with(space, tree, (partial, true), None)
191 }
192
193 pub fn update_tree_cut_after(
201 &self,
202 space: SpaceId,
203 tree: EntityId,
204 written: usize,
205 ) -> Result<Updated, NodeError> {
206 self.update_tree_with(space, tree, (false, true), Some(written))
207 }
208
209 fn update_tree_with(
213 &self,
214 space: SpaceId,
215 tree: EntityId,
216 (partial, agreed): (bool, bool),
217 cut: Option<usize>,
218 ) -> Result<Updated, NodeError> {
219 let _locked = self.lock_trees()?;
220 let root = self.root_here(space, tree)?;
221 let mut index = self.index()?;
222 let purged = self.learn_purges(space, &index)?;
223 let apart = self.apart();
224 let place = Place {
225 root: &root,
226 apart: &apart,
227 };
228 let now = self.tree_state(space, tree)?;
229 settle_tree((tree, &root, &apart), &mut index, (&purged, &now))?;
230 self.follow_cut_short(space, (tree, &root, &apart), &mut index, &now)?;
231 let entries = index.entries(tree)?;
232 if !entries.is_empty()
235 && entries
236 .keys()
237 .all(|path| located(&root, path, &apart) == Located::Absent)
238 {
239 return Err(NodeError::TreeEmptied(root));
240 }
241 let mut updated = Updated::default();
242 let in_full: BTreeSet<EntityId> = now.by_entity.keys().copied().collect();
243 let sealed: Vec<String> = now.sealed.keys().cloned().collect();
246 let (state, taken) =
247 self.state_to_update(space, tree, (now, partial), (&index, &mut updated))?;
248 let here = Here {
249 space,
250 tree,
251 place,
252 index: &index,
253 whole: index.knows(tree)?,
254 conflicts: index.conflicts(tree)?,
255 read_at: nanos(SystemTime::now()).unwrap_or(0),
256 };
257 let by_entity: BTreeMap<EntityId, (String, Entry)> = entries
258 .iter()
259 .map(|(path, entry)| (entry.entity, (path.clone(), entry.clone())))
260 .collect();
261 let mut changes = Changes::default();
262 let written = index.written_out(tree)?;
263 let (mut deleted, mut moves, mut arriving) =
264 plan_update((&state, &in_full), &by_entity, &written);
265 updated.sealed = sealed;
266 if !agreed {
267 self.hold_back(
268 space,
269 (&state, &entries),
270 (&mut deleted, &mut moves, &mut arriving),
271 &mut updated,
272 )?;
273 }
274 tell_moved_apart(&state, &by_entity, &mut updated);
275 let noted = note_writing(&index, tree, &arriving)?;
276 for (path, entry) in &deleted {
277 delete_copy(place, (path, entry), &mut updated, &mut changes.removed);
279 }
280 let failed = carry_out_moves(place, (&entries, &moves), (&mut updated, &mut changes));
283 let held = held_paths(&entries, &changes);
284 self.arrive_all(
285 &here,
286 (&arriving, &failed, &held),
287 cut,
288 (&mut updated, &mut changes),
289 );
290 if cut.is_some() {
291 return Ok(updated);
292 }
293 let whole = here.whole;
294 index.change(tree, &changes.removed, &changes.set)?;
295 self.note_secrets(space, (tree, &index), &state, &changes.set)?;
296 for (entity, keys) in &changes.written_out {
297 index.write_out(tree, *entity, keys)?;
298 }
299 clear_obsolete((tree, place, &index), &state, &mut updated)?;
300 self.settle_repositories(space, (tree, &index), &mut updated)?;
301 if partial {
302 index.take_parts(tree, &taken)?;
303 }
304 if whole || (!changes.unknown && updated.skipped.is_empty()) {
306 index.know(tree)?;
307 }
308 if noted {
309 index.forget_writing(tree)?;
310 }
311 updated.written.sort();
312 updated.merged.sort();
313 updated.contested.sort();
314 updated.conflicts.sort();
315 updated.conflicts.dedup();
316 Ok(updated)
317 }
318
319 fn arrive_all(
323 &self,
324 here: &Here<'_>,
325 (arriving, failed, held): (
326 &[Arriving],
327 &BTreeSet<EntityId>,
328 &BTreeMap<String, EntityId>,
329 ),
330 cut: Option<usize>,
331 (updated, changes): (&mut Updated, &mut Changes),
332 ) {
333 for arrival in arriving {
334 if cut.is_some_and(|cut| updated.written.len() >= cut) {
335 return;
336 }
337 if failed.contains(&arrival.entity) {
338 let why = "it could not be moved where the tree has it".to_owned();
339 updated.skipped.push((arrival.path.clone(), why));
340 continue;
341 }
342 if goes_beside(held, here, arrival) {
343 self.write_beside(here, arrival, updated);
344 continue;
345 }
346 if let Err(error) = self.arrive(here, arrival, (updated, changes)) {
348 updated
349 .skipped
350 .push((arrival.path.clone(), error.to_string()));
351 }
352 }
353 }
354
355 fn state_to_update(
361 &self,
362 space: SpaceId,
363 tree: EntityId,
364 (now, partial): (TreeState, bool),
365 (index, updated): (&Index, &mut Updated),
366 ) -> Result<(TreeState, Vec<EntityId>), NodeError> {
367 let cut = self.cut_short(space, tree)?;
368 let revisions = cut.iter().map(|cut| cut.revision).collect();
369 if partial {
370 return Ok((now, revisions));
371 }
372 let this_replica = self.replica.signing.verifying_key();
373 let taken = index.taken_parts(tree)?;
374 let mut without = BTreeSet::new();
375 for cut in cut {
376 if taken.contains(&cut.revision) {
377 continue;
378 }
379 let changes = self.revision_changes(space, tree, cut.revision)?;
380 let log = self.space(space)?.stored.log();
381 let own = match changes.first() {
382 Some(first) => log
383 .change(*first)?
384 .is_some_and(|change| *change.author() == this_replica),
385 None => true,
386 };
387 if !own {
388 without.extend(changes);
389 updated.waiting.push(cut);
390 }
391 }
392 if without.is_empty() {
393 return Ok((now, revisions));
394 }
395 Ok((self.tree_state_without(space, tree, &without)?, revisions))
396 }
397
398 fn arrive(
404 &self,
405 here: &Here<'_>,
406 arrival: &Arriving,
407 (updated, changes): (&mut Updated, &mut Changes),
408 ) -> Result<(), NodeError> {
409 let path = &arrival.path;
410 let nothing_new = arrival.nothing_new();
411 let entry = |found: &Found, version: &Version, known: bool| {
412 entry_for(arrival.entity, (found, version, known), here.read_at)
413 };
414 let on_disk = match located(here.place.root, path, here.place.apart) {
415 Located::Here(on_disk) => on_disk,
416 Located::Absent
420 if !arrival.deletions.is_empty()
421 && arrival.competing.is_empty()
422 && arrival.base.as_ref() == Some(&arrival.version) =>
423 {
424 arrival.wrote_out(updated, changes);
425 return Ok(());
426 }
427 Located::Absent if arrival.base.is_some() => {
428 if !nothing_new {
429 let why = "deleted or moved here, and changed elsewhere: restore it, or \
430 commit with force to delete it"
431 .to_owned();
432 updated.kept.push((path.clone(), why));
433 }
434 return Ok(());
435 }
436 Located::Absent => {
437 let content = Content::of(&arrival.version, arrival.secret);
438 match self.write_new(here.space, here.place, path, &content) {
439 Ok(found) if arrival.competing.is_empty() => {
440 updated.written.push(path.clone());
441 let written = entry(&found, &arrival.version, true);
442 changes.set.push((path.clone(), written));
443 arrival.wrote_out(updated, changes);
444 }
445 Ok(found) => {
447 updated.written.push(path.clone());
448 let written = Arriving {
449 base: Some(arrival.version.clone()),
450 ..arrival.clone()
451 };
452 return self.arrive_at_copy(
453 here,
454 &written,
455 &found.on_disk,
456 (updated, changes),
457 );
458 }
459 Err(why) => updated.skipped.push((path.clone(), why)),
460 }
461 return Ok(());
462 }
463 Located::Unknown(why) => {
464 updated.skipped.push((path.clone(), why));
465 return Ok(());
466 }
467 };
468 if nothing_new {
469 return Ok(());
470 }
471 self.arrive_at_copy(here, arrival, &on_disk, (updated, changes))
472 }
473
474 fn arrive_at_copy(
477 &self,
478 here: &Here<'_>,
479 arrival: &Arriving,
480 on_disk: &Path,
481 (updated, changes): (&mut Updated, &mut Changes),
482 ) -> Result<(), NodeError> {
483 let path = &arrival.path;
484 let entry = |found: &Found, version: &Version, known: bool| {
485 entry_for(arrival.entity, (found, version, known), here.read_at)
486 };
487 let found = look(on_disk).ok();
489 let Some((found, holds)) =
490 found.and_then(|found| copy_version(&found).map(|holds| (found, holds)))
491 else {
492 updated
493 .skipped
494 .push((path.clone(), "it cannot be read".to_owned()));
495 return Ok(());
496 };
497 if arrival.base.is_none() {
498 if same_version(&found, &holds, &arrival.version) {
500 changes
501 .set
502 .push((path.clone(), entry(&found, &arrival.version, true)));
503 } else {
504 changes.unknown = true;
505 let why = "which version it holds is not known, as the index of copies was \
506 lost: commit it, or restore it"
507 .to_owned();
508 updated.kept.push((path.clone(), why));
509 }
510 return Ok(());
511 }
512 let candidates: Vec<&Version> = if arrival.competing.is_empty() {
515 vec![&arrival.version]
516 } else {
517 arrival
518 .competing
519 .iter()
520 .filter(|version| !arrival.written.contains(&version.key()))
521 .collect()
522 };
523 let others: Vec<&Version> = candidates
524 .into_iter()
525 .filter(|other| !same_version(&found, &holds, other))
526 .filter(|other| arrival.base.as_ref() != Some(*other))
527 .collect();
528 let unedited = arrival
529 .base
530 .as_ref()
531 .is_some_and(|base| same_version(&found, &holds, base));
532 if others.is_empty() {
533 let known = arrival.competing.is_empty() && unedited;
534 changes
535 .set
536 .push((path.clone(), entry(&found, &arrival.version, known)));
537 arrival.wrote_out(updated, changes);
538 return Ok(());
539 }
540 if unedited && arrival.competing.is_empty() {
541 let content = Content::of(&arrival.version, arrival.secret);
542 match self.write_over(here.space, &found, &content) {
543 Ok(()) => {
544 updated.written.push(path.clone());
545 if let Ok(now) = look(on_disk) {
546 let written = entry(&now, &arrival.version, true);
547 changes.set.push((path.clone(), written));
548 arrival.wrote_out(updated, changes);
549 }
550 }
551 Err(why) => updated.skipped.push((path.clone(), why)),
552 }
553 return Ok(());
554 }
555 let Some(clashed) = self.merge_arrival(here, (arrival, &found), others, updated)? else {
556 return Ok(());
557 };
558 if clashed {
559 updated.conflicts.push(path.clone());
560 } else {
561 updated.merged.push(path.clone());
562 }
563 if let Ok(now) = look(on_disk) {
565 changes
566 .set
567 .push((path.clone(), entry(&now, &arrival.version, false)));
568 arrival.wrote_out(updated, changes);
569 }
570 Ok(())
571 }
572
573 fn merge_arrival(
579 &self,
580 here: &Here<'_>,
581 (arrival, found): (&Arriving, &Found),
582 others: Vec<&Version>,
583 updated: &mut Updated,
584 ) -> Result<Option<bool>, NodeError> {
585 let path = &arrival.path;
586 let space = here.space;
587 let base = if arrival.competing.is_empty() {
590 arrival.base.clone()
591 } else {
592 let written = matches!(
594 arrival.base,
595 Some(Version::File {
596 executable: true,
597 ..
598 })
599 );
600 self.common_base(space, arrival.entity)?
601 .map(|base| match base {
602 Version::File { content, .. } => Version::File {
603 content,
604 executable: written,
605 },
606 link @ Version::Link { .. } => link,
607 })
608 };
609 let mut ours = match &found.kind {
610 FoundKind::File => {
611 let mut bytes = Vec::new();
612 let read = open_found(found)
613 .and_then(|file| {
614 io::Read::read_to_end(&mut io::Read::take(file, READ_LIMIT + 1), &mut bytes)
615 })
616 .map_err(NodeError::file(&found.on_disk))?;
617 (read as u64 <= READ_LIMIT).then_some(bytes)
618 }
619 FoundKind::Link(_) => None,
620 };
621 let secret = arrival.secret;
622 let base_bytes = match &base {
623 Some(Version::File { content, .. }) => self.version_bytes(space, content, secret)?,
624 Some(Version::Link { .. }) => None,
625 None => Some(Vec::new()),
626 };
627 let mut clashed = false;
628 let mut merged_any = false;
629 for other in others {
630 let other_bytes = match other {
631 Version::File { content, .. } => self.version_bytes(space, content, secret)?,
632 Version::Link { .. } => None,
633 };
634 let text = match (&ours, &base_bytes, &other_bytes) {
635 (Some(ours), Some(base), Some(other)) => [ours, base, other]
636 .iter()
637 .all(|bytes| super::diff::is_text(bytes))
638 .then(|| (ours.clone(), base.clone(), other.clone())),
639 _ => None,
640 };
641 if let Some((mine, from, theirs)) = text {
642 match diffy::merge_bytes(&from, &mine, &theirs) {
643 Ok(merged) => ours = Some(merged),
644 Err(marked) => {
645 ours = Some(marked);
646 clashed = true;
647 }
648 }
649 merged_any = true;
650 continue;
651 }
652 let device = self.device_of(space, arrival.entity, other);
653 let Some((beside, there)) = place_beside(here, (path, &device), other) else {
654 let why = format!("{path}.conflict-{device} and the names after it are taken");
655 updated.skipped.push((path.clone(), why));
656 return Ok(None);
657 };
658 clashed = true;
659 if there {
660 continue;
661 }
662 here.index.mark(
664 here.tree,
665 &beside,
666 "NibKeep wrote it, the other version of a file, from another device",
667 )?;
668 if let Err(why) =
669 self.write_new(space, here.place, &beside, &Content::of(other, secret))
670 {
671 here.index
672 .unmark(here.tree, std::slice::from_ref(&beside))?;
673 updated.skipped.push((path.clone(), why));
674 return Ok(None);
675 }
676 }
677 if merged_any && let Some(bytes) = &ours {
678 let executable = merged_executable(found, base.as_ref(), &arrival.version);
679 let merged = Content::bytes(bytes, executable, secret);
680 if let Err(why) = self.write_over(space, found, &merged) {
681 updated.skipped.push((path.clone(), why));
682 return Ok(None);
683 }
684 }
685 Ok(Some(clashed))
686 }
687
688 fn write_beside(&self, here: &Here<'_>, arrival: &Arriving, updated: &mut Updated) {
694 let device = self.device_of(here.space, arrival.entity, &arrival.version);
695 let named = (1..=99)
698 .map(|number| match number {
699 1 => format!("{}.conflict-{device}", arrival.path),
700 _ => format!("{}.conflict-{device}-{number}", arrival.path),
701 })
702 .find(|beside| match here.conflicts.get(beside) {
703 Some(conflict) => conflict.entity == arrival.entity,
704 None => located(here.place.root, beside, here.place.apart) == Located::Absent,
705 });
706 let Some(beside) = named else {
707 let why = format!(
708 "{}.conflict-{device} and the names after it are taken",
709 arrival.path
710 );
711 updated.skipped.push((arrival.path.clone(), why));
712 return;
713 };
714 let content = Content::of(&arrival.version, arrival.secret);
715 let written = match located(here.place.root, &beside, here.place.apart) {
716 Located::Absent
718 if here.conflicts.get(&beside).is_some_and(|conflict| {
719 conflict.entity == arrival.entity
720 && conflict
721 .written
722 .as_ref()
723 .is_some_and(|written| same_content(written, &arrival.version))
724 }) =>
725 {
726 let why = "the other file at this path, settled here: commit to record it";
727 updated.kept.push((beside, why.to_owned()));
728 return;
729 }
730 Located::Absent => {
731 let why = "NibKeep wrote it, the file of another device at the same path";
732 match here.index.mark(here.tree, &beside, why) {
733 Ok(()) => match self.write_new(here.space, here.place, &beside, &content) {
734 Ok(_) => Ok(()),
735 Err(why) => {
736 let _ = here.index.unmark(here.tree, std::slice::from_ref(&beside));
737 Err(why)
738 }
739 },
740 Err(error) => Err(error.to_string()),
741 }
742 }
743 Located::Here(on_disk) => match look(&on_disk) {
744 Ok(found) => {
745 let holds = copy_version(&found);
746 let before = here
747 .conflicts
748 .get(&beside)
749 .filter(|conflict| conflict.entity == arrival.entity)
750 .and_then(|conflict| conflict.written.clone());
751 let holding = |version: &Version| {
752 holds
753 .as_ref()
754 .is_some_and(|holds| same_content(holds, version))
755 };
756 if holding(&arrival.version) {
757 Ok(())
758 } else if before.as_ref().is_some_and(holding) {
759 self.write_over(here.space, &found, &content)
760 } else {
761 Err(format!("{beside} is in the way"))
762 }
763 }
764 Err(why) => Err(why),
765 },
766 Located::Unknown(why) => Err(why),
767 };
768 let marked = written.and_then(|()| {
769 here.index
770 .mark_conflict(
771 here.tree,
772 (&beside, &arrival.path),
773 (arrival.entity, &arrival.version),
774 )
775 .map_err(|error| error.to_string())
776 });
777 match marked {
778 Ok(()) => updated.conflicts.push(arrival.path.clone()),
779 Err(why) => updated.skipped.push((arrival.path.clone(), why)),
780 }
781 }
782
783 fn settle_repositories(
788 &self,
789 space: SpaceId,
790 (tree, index): (EntityId, &Index),
791 updated: &mut Updated,
792 ) -> Result<(), NodeError> {
793 let recorded: BTreeMap<EntityId, String> = self
794 .recorded_repositories(space, tree)?
795 .into_iter()
796 .map(|recorded| (recorded.entity, recorded.path))
797 .collect();
798 let mut gone = Vec::new();
799 for (path, (entity, _)) in index.repositories(tree)? {
800 match recorded.get(&entity) {
801 Some(now) if *now == path => {}
802 Some(now) => {
803 let why =
804 format!("a Git repository moved elsewhere to {now}: move its folder there");
805 updated.kept.push((path, why));
806 }
807 None => {
808 let why = "a Git repository deleted from the tree elsewhere, whose folder stays \
809 with its work until you delete it";
810 index.mark(tree, &path, why)?;
811 updated.kept.push((path.clone(), why.to_owned()));
812 gone.push(path);
813 }
814 }
815 }
816 index.forget_repositories(tree, &gone)
817 }
818
819 fn device_of(&self, space: SpaceId, entity: EntityId, version: &Version) -> String {
823 let (fields, value) = match version {
824 Version::File { content, .. } => {
825 (&[CONTENT, SECRET_CONTENT][..], Value::Blob(*content))
826 }
827 Version::Link { target } => (&[LINK_TARGET][..], Value::Text(target.clone())),
828 };
829 let name = {
830 let open = self.space(space).ok();
831 let statement = open.and_then(|open| {
832 let state = open.stored.log().state();
833 fields.iter().find_map(|field| {
834 state
835 .current(entity, field)
836 .ok()?
837 .into_iter()
838 .find(|statement| statement.value == value)
839 .map(|statement| statement.id)
840 })
841 });
842 statement
843 .and_then(|statement| self.device_name_of(space, statement))
844 .unwrap_or_else(|| "elsewhere".to_owned())
845 };
846 let kept: String = name
847 .chars()
848 .take(40)
849 .map(|character| {
850 if character.is_alphanumeric() || matches!(character, '-' | '_') {
851 character
852 } else {
853 '-'
854 }
855 })
856 .collect();
857 if kept.trim_matches('-').is_empty() {
858 "elsewhere".to_owned()
859 } else {
860 kept
861 }
862 }
863
864 fn common_base(&self, space: SpaceId, entity: EntityId) -> Result<Option<Version>, NodeError> {
868 let open = self.space(space)?;
869 let state = open.stored.log().state();
870 let storage = state.storage();
871 let mut competing = Vec::new();
872 for field in [CONTENT, SECRET_CONTENT, LINK_TARGET] {
873 for id in storage.of_field(entity, &field)? {
874 if state.is_current(id)? {
875 competing.push(id);
876 }
877 }
878 }
879 let mut common: Option<BTreeSet<StatementId>> = None;
880 for id in competing {
881 let before = self.superseded_through(space, id)?;
882 common = Some(match common {
883 Some(common) => common.intersection(&before).copied().collect(),
884 None => before,
885 });
886 }
887 let mut last: Option<(nibkeep_time::Timestamp, Version)> = None;
888 for id in common.unwrap_or_default() {
889 let Some(recorded) = storage.get(id)? else {
890 continue;
891 };
892 let version = match recorded.statement.value.clone() {
893 Value::Blob(content) => Version::File {
894 content,
895 executable: false,
896 },
897 Value::Text(target) => Version::Link { target },
898 _ => continue,
899 };
900 if last.as_ref().is_none_or(|(at, _)| recorded.at > *at) {
901 last = Some((recorded.at, version));
902 }
903 }
904 Ok(last.map(|(_, version)| version))
905 }
906
907 fn superseded_through(
910 &self,
911 space: SpaceId,
912 statement: StatementId,
913 ) -> Result<BTreeSet<StatementId>, NodeError> {
914 let open = self.space(space)?;
915 let log = open.stored.log();
916 let mut seen = BTreeSet::new();
917 let mut waiting = vec![statement];
918 while let Some(id) = waiting.pop() {
919 let change = log
920 .state()
921 .storage()
922 .get(id)?
923 .and_then(|recorded| recorded.change);
924 let Some(change) = change else {
925 continue;
926 };
927 let Some(payload) = log.payload(ChangeId::from_hash(change), &open.keys)? else {
928 continue;
929 };
930 for operation in &payload.operations {
931 if let Operation::Assert {
932 statement,
933 supersedes,
934 ..
935 } = operation
936 && statement.id == id
937 {
938 for before in supersedes {
939 if seen.insert(*before) {
940 waiting.push(*before);
941 }
942 }
943 }
944 }
945 }
946 Ok(seen)
947 }
948
949 #[allow(
955 clippy::type_complexity,
956 reason = "the three lists of an update, changed in place"
957 )]
958 fn hold_back(
959 &self,
960 space: SpaceId,
961 (state, entries): (&TreeState, &BTreeMap<String, Entry>),
962 (deleted, moves, arriving): (
963 &mut Vec<(String, Entry)>,
964 &mut Vec<(String, String)>,
965 &mut Vec<Arriving>,
966 ),
967 updated: &mut Updated,
968 ) -> Result<(), NodeError> {
969 let is_nibsecret =
970 |path: &str| path == NIBSECRET || path.ends_with(&format!("/{NIBSECRET}"));
971 let mut held: BTreeSet<EntityId> = BTreeSet::new();
972 moves.retain(|(from, to)| {
973 let Some(entry) = entries.get(from) else {
974 return true;
975 };
976 if state.is_secret(entry.entity) || is_nibsecret(from) {
977 updated.held.push(format!("{from} -> {to}"));
978 held.insert(entry.entity);
979 return false;
980 }
981 true
982 });
983 deleted.retain(|(path, entry)| {
984 if is_nibsecret(path) {
985 updated.held.push(path.clone());
986 held.insert(entry.entity);
987 return false;
988 }
989 true
990 });
991 for arrival in arriving.iter() {
992 if held.contains(&arrival.entity) || !is_nibsecret(&arrival.path) {
993 continue;
994 }
995 let (
996 Some(Version::File { content: was, .. }),
997 Version::File {
998 content: becomes, ..
999 },
1000 ) = (&arrival.base, &arrival.version)
1001 else {
1002 continue;
1003 };
1004 if was == becomes {
1005 continue;
1006 }
1007 let was = self.content_bytes(space, was)?.unwrap_or_default();
1008 let becomes = self.content_bytes(space, becomes)?.unwrap_or_default();
1009 let was = String::from_utf8_lossy(&was);
1010 let becomes = String::from_utf8_lossy(&becomes);
1011 if !lines(&was).is_subset(&lines(&becomes)) {
1012 updated.held.push(arrival.path.clone());
1013 held.insert(arrival.entity);
1014 }
1015 }
1016 arriving.retain(|arrival| !held.contains(&arrival.entity));
1017 updated.held.sort();
1018 Ok(())
1019 }
1020}
1021
1022fn held_paths(entries: &BTreeMap<String, Entry>, changes: &Changes) -> BTreeMap<String, EntityId> {
1025 let mut held: BTreeMap<String, EntityId> = entries
1026 .iter()
1027 .filter(|(path, _)| !changes.removed.contains(path))
1028 .map(|(path, entry)| (path.clone(), entry.entity))
1029 .collect();
1030 held.extend(
1031 changes
1032 .set
1033 .iter()
1034 .map(|(path, entry)| (path.clone(), entry.entity)),
1035 );
1036 held
1037}
1038
1039fn tell_moved_apart(
1042 state: &TreeState,
1043 by_entity: &BTreeMap<EntityId, (String, Entry)>,
1044 updated: &mut Updated,
1045) {
1046 for (entity, paths) in &state.paths {
1047 if let Some((here_at, _)) = by_entity.get(entity)
1048 && paths.contains(here_at)
1049 {
1050 let elsewhere: Vec<&str> = paths
1051 .iter()
1052 .filter(|path| *path != here_at)
1053 .map(String::as_str)
1054 .collect();
1055 let why = format!(
1056 "moved apart, also to {}: commit to keep it here",
1057 elsewhere.join(", ")
1058 );
1059 updated.kept.push((here_at.clone(), why));
1060 }
1061 }
1062}
1063
1064fn place_beside(
1069 here: &Here<'_>,
1070 (path, device): (&str, &str),
1071 other: &Version,
1072) -> Option<(String, bool)> {
1073 for number in 1..=99 {
1074 let beside = if number == 1 {
1075 format!("{path}.conflict-{device}")
1076 } else {
1077 format!("{path}.conflict-{device}-{number}")
1078 };
1079 match located(here.place.root, &beside, here.place.apart) {
1080 Located::Absent => return Some((beside, false)),
1081 Located::Here(on_disk) => {
1082 let holds = look(&on_disk).ok().and_then(|found| copy_version(&found));
1083 if holds.is_some_and(|holds| same_content(&holds, other)) {
1084 return Some((beside, true));
1085 }
1086 }
1087 Located::Unknown(_) => {}
1088 }
1089 }
1090 None
1091}
1092
1093fn entry_for(
1097 entity: EntityId,
1098 (found, version, known): (&Found, &Version, bool),
1099 read_at: i64,
1100) -> Entry {
1101 Entry {
1102 entity,
1103 version: version.clone(),
1104 size: found.size,
1105 modified: if known { found.modified } else { None },
1106 read_at,
1107 }
1108}
1109
1110fn merged_executable(found: &Found, base: Option<&Version>, arrived: &Version) -> bool {
1113 let is = |version: Option<&Version>| {
1114 matches!(
1115 version,
1116 Some(Version::File {
1117 executable: true,
1118 ..
1119 })
1120 )
1121 };
1122 match found.executable {
1123 Some(here) if here != is(base) => here,
1124 _ => is(Some(arrived)),
1125 }
1126}
1127
1128fn delete_copy(
1132 place: Place<'_>,
1133 (path, entry): (&String, &Entry),
1134 updated: &mut Updated,
1135 removed: &mut Vec<String>,
1136) {
1137 let on_disk = match located(place.root, path, place.apart) {
1138 Located::Here(on_disk) => on_disk,
1139 Located::Absent => {
1140 removed.push(path.clone());
1141 return;
1142 }
1143 Located::Unknown(why) => {
1144 updated.skipped.push((path.clone(), why));
1145 return;
1146 }
1147 };
1148 let Ok(found) = look(&on_disk) else {
1149 updated
1150 .skipped
1151 .push((path.clone(), "it cannot be read".to_owned()));
1152 return;
1153 };
1154 let unedited =
1155 copy_version(&found).is_some_and(|holds| same_version(&found, &holds, &entry.version));
1156 if !unedited {
1157 let why = "deleted elsewhere, and edited here".to_owned();
1158 updated.kept.push((path.clone(), why));
1159 return;
1160 }
1161 if !super::write::still_the_copy(&found) {
1163 updated
1164 .kept
1165 .push((path.clone(), "it changed meanwhile".to_owned()));
1166 return;
1167 }
1168 match fs::remove_file(&on_disk) {
1169 Ok(()) => {
1170 sync_folder_of(&on_disk);
1171 updated.deleted.push(path.clone());
1172 removed.push(path.clone());
1173 }
1174 Err(error) => updated.skipped.push((path.clone(), error.to_string())),
1175 }
1176}
1177
1178fn carry_out_moves(
1181 place: Place<'_>,
1182 (entries, moves): (&BTreeMap<String, Entry>, &[(String, String)]),
1183 (updated, changes): (&mut Updated, &mut Changes),
1184) -> BTreeSet<EntityId> {
1185 let at = undo_moves_at(place, moves, &mut updated.skipped);
1186 let mut failed = BTreeSet::new();
1187 for (from, to) in moves {
1188 let Some(entry) = entries.get(from) else {
1189 continue;
1190 };
1191 if at.get(from) == Some(to) {
1192 updated.moved.push((from.clone(), to.clone()));
1193 changes.removed.push(from.clone());
1194 changes.set.push((to.clone(), entry.clone()));
1195 } else {
1196 failed.insert(entry.entity);
1197 }
1198 }
1199 failed
1200}
1201
1202fn note_writing(index: &Index, tree: EntityId, arriving: &[Arriving]) -> Result<bool, NodeError> {
1206 let secrets: Vec<(String, EntityId, Version)> = arriving
1207 .iter()
1208 .filter(|arrival| arrival.secret && !arrival.nothing_new())
1209 .map(|arrival| {
1210 (
1211 arrival.path.clone(),
1212 arrival.entity,
1213 arrival.version.clone(),
1214 )
1215 })
1216 .collect();
1217 if secrets.is_empty() {
1218 return Ok(false);
1219 }
1220 index.about_to_write(tree, &secrets)?;
1221 Ok(true)
1222}
1223
1224#[allow(clippy::type_complexity, reason = "three lists, made once")]
1227fn plan_update(
1228 (state, in_full): (&TreeState, &BTreeSet<EntityId>),
1229 by_entity: &BTreeMap<EntityId, (String, Entry)>,
1230 written: &BTreeMap<EntityId, BTreeSet<String>>,
1231) -> (Vec<(String, Entry)>, Vec<(String, String)>, Vec<Arriving>) {
1232 let mut deleted = Vec::new();
1233 let mut moves = Vec::new();
1234 let mut arriving = Vec::new();
1235 let entities: BTreeSet<EntityId> = state
1236 .by_entity
1237 .keys()
1238 .chain(by_entity.keys())
1239 .copied()
1240 .collect();
1241 for entity in entities {
1242 match (by_entity.get(&entity), version_of(state, entity)) {
1243 (Some(_), None) if in_full.contains(&entity) => {}
1245 (Some((path, entry)), None) => deleted.push((path.clone(), entry.clone())),
1246 (ours, Some((path, version))) => {
1247 let Some(version) = version else {
1249 continue;
1250 };
1251 let path = match ours {
1253 Some((from, _)) if state.at(entity, from) => from.clone(),
1254 _ => path,
1255 };
1256 if let Some((from, _)) = ours
1257 && *from != path
1258 {
1259 moves.push((from.clone(), path.clone()));
1260 }
1261 arriving.push(Arriving {
1262 path,
1263 entity,
1264 base: ours.map(|(_, entry)| entry.version.clone()),
1265 version,
1266 competing: state.versions.get(&entity).cloned().unwrap_or_default(),
1267 written: written.get(&entity).cloned().unwrap_or_default(),
1268 deletions: state.contested.get(&entity).cloned().unwrap_or_default(),
1269 secret: state.is_secret(entity),
1270 });
1271 }
1272 (None, None) => {}
1273 }
1274 }
1275 (deleted, moves, arriving)
1276}
1277
1278fn goes_beside(held: &BTreeMap<String, EntityId>, here: &Here<'_>, arrival: &Arriving) -> bool {
1283 match held.get(&arrival.path) {
1284 Some(entity) => *entity != arrival.entity,
1285 None if arrival.base.is_some() || !here.whole => false,
1286 None => match located(here.place.root, &arrival.path, here.place.apart) {
1287 Located::Here(on_disk) => look(&on_disk)
1288 .ok()
1289 .and_then(|found| copy_version(&found).map(|holds| (found, holds)))
1290 .is_none_or(|(found, holds)| !same_version(&found, &holds, &arrival.version)),
1291 Located::Absent | Located::Unknown(_) => false,
1292 },
1293 }
1294}
1295
1296fn clear_obsolete(
1300 (tree, place, index): (EntityId, Place<'_>, &Index),
1301 state: &TreeState,
1302 updated: &mut Updated,
1303) -> Result<(), NodeError> {
1304 let placed: BTreeSet<EntityId> = index
1305 .entries(tree)?
1306 .values()
1307 .map(|entry| entry.entity)
1308 .collect();
1309 for (beside, conflict) in index.conflicts(tree)? {
1310 if still_competes(state, &placed, &conflict) {
1311 continue;
1312 }
1313 let on_disk = match located(place.root, &beside, place.apart) {
1314 Located::Here(on_disk) => on_disk,
1315 Located::Absent => {
1316 index.unmark(tree, std::slice::from_ref(&beside))?;
1317 continue;
1318 }
1319 Located::Unknown(_) => continue,
1320 };
1321 let found = look(&on_disk).ok();
1322 let as_written = found.as_ref().is_some_and(|found| {
1323 copy_version(found)
1324 .zip(conflict.written.as_ref())
1325 .is_some_and(|(holds, written)| same_content(&holds, written))
1326 });
1327 let still = found.is_some_and(|found| {
1328 look(&on_disk).is_ok_and(|now| {
1329 now.identity == found.identity
1330 && now.size == found.size
1331 && now.modified == found.modified
1332 })
1333 });
1334 if as_written && still && fs::remove_file(&on_disk).is_ok() {
1335 sync_folder_of(&on_disk);
1336 index.unmark(tree, std::slice::from_ref(&beside))?;
1337 updated.deleted.push(beside);
1338 } else {
1339 index.forget_conflict(tree, &beside)?;
1340 }
1341 }
1342 Ok(())
1343}